Showing posts with label function scope. Show all posts
Showing posts with label function scope. Show all posts

Thursday, 8 June 2023

Variable Scope in JavaScript: var vs let

In JavaScript, the way variables work in different parts of your code is essential. JavaScript has two keywords for declaring variables "var" and "let". These keywords behave differently in terms of scope. The purpose of this article is to clarify the difference between var and let scoping with an example.

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.