DEV Community

Mark Tony
Mark Tony

Posted on

Variables in JavaScript

Variables are containers that store data. In JavaScript a variable can be declared in three ways:

  1. let
  2. Const
  3. Var

The variable method was used earlier. The other two were added to simplify the coding.The Variable and let method are almost similar.

1.let:

  • let is a block-scoped variable that can be reassigned.
  • let prevents scope leakage and accidental redeclaration within the same scope.
  • Temporal Dead Zone (TDZ): Accessing a let variable before its declaration results in a ReferenceError, unlike var which hoists and initializes as undefined.
  • Global Scope Behavior: At the top level, let does not create a property on the global object.

Declaring the variable with value:

<body>
    <script>
        let a = 10
        console.log(a);
        </script>
</body>
Enter fullscreen mode Exit fullscreen mode

Reassigning the value:

<body>
    <script>
        let a = 10
        a = a+ 20
        console.log(a);
        </script>
</body>
Enter fullscreen mode Exit fullscreen mode

2. Const:

  • Const is a block-scoped variable that cannot be neither reassigned nor redeclared.
  • Like let, const is limited to the block in which it is defined, avoiding the hoisting and scoping issues associated with var.
  • A value must be provided at the time of declaration; attempting to declare const without initialization throws a syntax error.
<body>
    <script>
        const a = 10
        a = a+ 20
        console.log(a);
        </script>
</body>
Enter fullscreen mode Exit fullscreen mode

3. Var:

  • var is the original method used for declaring variables.
  • The same variables can be redeclared in Var.
  • Variables are scoped to the entire function they are declared in, or globally if declared outside any function, ignoring block boundaries like if statements or for loops.

Note

  1. Prefer const: Use const for all variables that are not intended to be reassigned, as it signals intent and helps prevent accidental bugs.
  2. Use let: Only use let for variables that require reassignment, such as loop counters or values that change based on user interaction.
  3. Avoid var: The var keyword is no longer in use due to its function scope and hoisting behavior, which can lead to unexpected bugs.

Top comments (0)