var, let, const

Declaring JavaScript Variables: Var, Let and Const

Posted by

You can define the variables in JavaScript using var, let, or const keywords. In this post, we will see the scope of variables and the difference between Var , Let , and Const .

VAR Keyword in Javascript

It is a keyword to declare variables in JavaScript. It can be function scoped or global scope. You can re-assign and re-declare it.

Example of variable declaration using var keyword:

Function Scoped

If you define the variable in the function then called function scoped and it will be accessible inside the function.

It will not be accessible outside the function. It will show the error “Uncaught ReferenceError: variableName is not defined”.

Global Scoped

A globally scoped variable can access outside the function and inside the function as well.

Re-assignable and Re-declaration

Any variable declared with the var keyword may be reassigned or re-declared at any time.

An example of reassigning:

An example of re-declared:

LET Keyword in Javascript

It is another keyword to declare a variable. It is a block scope and re-assignable but can not be re-declared.

Block Scoped

When a variable is declared within a function, it is scoped to that function:

When a variable is declared within a block, it is scoped to that block. Here’s an example of the block statement:

Re-assignable but not re-declared

The let variable can be reassigned but can not be re-declared. If you re-declare the let variable in block scoop then it will show the error “Uncaught SyntaxError: Identifier ‘price’ has already been declared”.

Here is an example of reassigning the value of the variable:

Re-declaring the let variable:

CONST Keyword in Javascript

It is another keyword to declare a variable in JavaScript. It is block-scoped and it can not be re-assignable and re-declarable.

Example of variable declaration using the const keyword:

Block Scoped

When a variable is declared within a function, it is scoped to that function:

When a variable is declared within a block, it is scoped to that block. Here’s an example of the block statement:

Not re-assignable, not re-declarable

You can not reassign and re-declare any variable that declares with the const keyword.

Here is the example of a re-declaration that throws the error:

An example of a re-assignable that throws the error:

Difference between VAR, LET, and CONST

var let const
Stored in Global Scope Yes No No
Function Scope Yes Yes Yes
Block Scope No Yes Yes
Reassignable? Yes Yes No
Redeclarable? Yes No No
Hoist? Yes No No

Conclusion

In this article, we have seen how to Declare JavaScript Variables using var, let, and const.

 

Leave a Reply

Your email address will not be published. Required fields are marked *