JavaScript Variables

JavaScript Variables

Published by: Anil K. Panta

JavaScript Variables

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.


Before you use a variable in a JavaScript program, you must declare it. JavaScript Variables can be declared in 4 ways:

  • Automatically

  • Using var

  • Using let

  • Using const


Let

The let keyword was introduced in ES6 (2015)

Variables declared with let have Block Scope

Variables declared with let must be Declared before use

Variables declared with let cannot be Redeclared in the same scope


Block Scope

Variables declared inside a { } block cannot be accessed from outside the block:



Before ES6 (2015), JavaScript did not have Block Scope. JavaScript had Global Scope and Function Scope.

ES6 introduced the two new JavaScript keywords: let and const. These two keywords provided Block Scope in JavaScript.


Global Scope

Variables declared with var inside a { } block can be accessed from outside the block:



Variables declared with the var always have Global Scope. Variables declared with the var keyword cannot have block scope.


Const

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope


We will get back to you via email or phone call