var:
Variables declared with "var" are function-scoped. They are accessible throughout the function regardless of where they are declared within the function.
<!DOCTYPE html>
<html>
<head>
<title>"var" keyword example</title>
<script>
function exampleVar() {
if (true) {
var x = 10;
console.log(x); // Output: 10
}
console.log(x); // Output: 10
}
exampleVar();
console.log(x); // Output: ReferenceError: x is not defined
</script>
</head>
<body>
</body>
</html>
In this example, the variable x declared with var inside the if block is accessible both inside and outside the block because of its function scope.
let:
Variables declared with let are block-scoped. They are accessible only within the code block in which they are defined, such as within a loop or conditional statement.
<!DOCTYPE html>
<html>
<head>
<title>"let" keyword example</title>
<script>
function exampleLet() {
if (true) {
let y = 20;
console.log(y); // Output: 20
}
console.log(y); // Output: ReferenceError: y is not defined
}
exampleLet();
console.log(y); // Output: ReferenceError: y is not defined
</script>
</head>
<body>
</body>
</html>
In this example, the variable y declared with let inside the if block is only accessible within that block. Trying to access it outside the block will result in a ReferenceError.