Ways of declaring JavaScript Variables and their differences

There are 4 ways of declaring a JavaScript variable:

  1. var keyword
  2. let keyword
  3. const keyword
  4. Automatic declaration

1. var keyword

A variable declared with the var keyword is function-scoped, which means if the variable is declared within a function, you cannot access it from outside of the function.

Here is an example:

This example will throw an error because the variable ‘x’ is declared inside the example1() function using the var keyword, so you cannot access it from the global scope.

Try this example:

This code will print 10.

However, variables created with the var keyword are not block-scoped. This means you can access a variable created using the var keyword from the global scope even if it is declared inside a code block like if, for, or while (except for functions).

Example:

This example will not throw an error.

Note: It is not recommended anymore to use the var keyword.

2. let keyword

The let keyword is block-scoped, meaning if you declare a variable using the let keyword inside any code block (including if, for, while, or functions), you cannot access the variable from outside that block.

Try this example:

This code will throw an error because the x variable was created inside the if block, so you cannot access it from outside.

The value of a variable created with the let keyword can be changed.

3. const keyword

The const keyword is also block-scoped, just like the let keyword. The difference is that the value of a const variable cannot be changed after it is set for the first time.

Try this example:

This code will throw an error because the x variable was created inside the if block, so you cannot access it from outside.

Another example:

This example will throw an error because the value of a const variable cannot be reassigned after declaration. You must assign the value of a const variable at the time of declaration.

However, if a const variable holds an object or array, the elements/properties of the array or object can be changed or mutated. But you cannot change the reference value.

4. Automatic declaration

A variable can be created without using any keyword like var, let, or const.

Here is an example:

This code snippet will work fine.

Auto-assigned variables are function-scoped, like var variables, and their values can be changed. However, it is not recommended to use automatic assignment in JavaScript.

Leave a Comment