ES6 - Variables

A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier −
Identifiers cannot be keywords.
Identifiers cannot be keywords.
Identifiers can contain alphabets and numbers.
Identifiers can contain alphabets and numbers.
Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
Variable names cannot begin with a number.
Variable names cannot begin with a number.
A variable must be declared before it is used. ES5 syntax used the var keyword to achieve the same. The ES5 syntax for declaring a variable is as follows.
//Declaration using var keyword 
var  variable_name

ES6 introduces the following variable declaration syntax −
Using the let.
Using the const.
Variable initialization refers to the process of storing a value in the variable. A variable may be initialized either at the time of its declaration or at a later point in time.
The traditional ES5 type syntax for declaring and initializing a variable is as follows −
//Declaration using var keyword 
var variable_name = value

var name = "Tom" 
console.log("The value in the variable is: "+name)
The above example declares a variable and prints its value.
The following output is displayed on successful execution.
The value in the variable is Tom

JavaScript is an un-typed language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically. This feature is termed as dynamic typing.
The scope of a variable is the region of your program in which it is defined. Traditionally, JavaScript defines only two scopes-global and local.
Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code.
Global Scope − A variable with global scope can be accessed from within any part of the JavaScript code.
Local Scope − A variable with a local scope can be accessed from within a function where it is declared.
Local Scope − A variable with a local scope can be accessed from within a function where it is declared.
The following example declares two variables by the name num - one outside the function (global scope) and the other within the function (local scope).
var num = 10 
function test() { 
   var num = 100 
   console.log("value of num in test() "+num) 
} 
console.log("value of num outside test() "+num) 
test()
The variable when referred to within the function displays the value of the locally scoped variable. However, the variable num when accessed outside the function returns the globally scoped instance.
The following output is displayed on successful execution.
value of num outside test() 10
value of num in test() 100

ES6 defines a new variable scope - The Block scope.
The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Unlike the var keyword, the let keyword allows the script to restrict access to the variable to the nearest enclosing block.
"use strict" 
function test() { 
   var num = 100 
   console.log("value of num in test() "+num) { 
      console.log("Inner Block begins") 
      let num = 200 
      console.log("value of num : "+num)  
   } 
} 
test()
The script declares a variable num within the local scope of a function and re-declares it within a block using the let keyword. The value of the locally scoped variable is printed when the variable is accessed outside the inner block, while the block scoped variable is referred to within the inner block.
Note − The strict mode is a way to opt in to a restricted variant of JavaScript.
The following output is displayed on successful execution.
value of num in test() 100 
Inner Block begins 
value of num : 200

var no = 10; 
var no = 20; 
console.log(no);
The following output is displayed on successful execution of the above code.
20

Let us re-write the same code using the let keyword.
let no = 10; 
let no = 20; 
console.log(no);

The above code will throw an error: Identifier 'no' has already been declared. Any variable declared using the let keyword is assigned the block scope.
If we try to declare a let variable twice within the same block, it will throw an error. Consider the following example −
<script>
   let balance = 5000 // number type
   console.log(typeof balance)
   let balance = {message:"hello"} // changing number to object type
   console.log(typeof balance)
</script>
The above code will result in the following error −
Uncaught SyntaxError: Identifier 'balance' has already been declared

However, the same let variable can be used in different block level scopes without any syntax errors.
<script>
   let count = 100
   for (let count = 1;count <= 10;count++){
      //inside for loop brackets ,count value starts from 1
      console.log("count value inside loop is ",count);
   }
   //outside for loop brackets ,count value is 100
   console.log("count value after loop is",count);

   if(count == 100){
      //inside if brackets ,count value is 50
      let count = 50;
      console.log("count inside if block",count);
   }
   console.log(count);
</script>
The output of the above code will be as follows −
count value inside loop is 1
count value inside loop is 2
count value inside loop is 3
count value inside loop is 4
count value inside loop is 5
count value inside loop is 6
count value inside loop is 7
count value inside loop is 8
count value inside loop is 9
count value inside loop is 10
count value after loop is 100
count inside if block 50
100

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be re-declared.
The following rules hold true for a variable declared using the const keyword −
Constants cannot be reassigned a value.
A constant cannot be re-declared.
A constant requires an initializer. This means constants must be initialized during its declaration.
The value assigned to a const variable is mutable.
const x = 10
x = 12 // will result in an error!!

The above code will return an error since constants cannot be reassigned a value. Constants variable are immutable.
Unlike variables declared using let keyword, constants are immutable. This means its value cannot be changed. For example, if we try to change value of the constant variable, an error will be displayed.
<script>
   let income = 100000
   const INTEREST_RATE = 0.08
   income += 50000 // mutable
   console.log("changed income value is ",income)
   INTEREST_RATE += 0.01
   console.log("changed rate is ",INTEREST_RATE) //Error: not mutable
</script>
The output of the above code will be as follows −
changed income value is 150000
Uncaught TypeError: Assignment to constant variable
The following example shows how to create an immutable array. New elements can be added to the array. However, reinitializing the array will result in an error as shown below −
<script>
   const DEPT_NOS = [10,20,30,50]
   DEPT_NOS.push(40)
   console.log('dept numbers is ',DEPT_NOS)

   const EMP_IDS = [1001,1002,1003]
   console.log('employee ids',EMP_IDS)
   //re assigning variable employee ids
   EMP_IDS = [2001,2002,2003]
   console.log('employee ids after changing',EMP_IDS)
</script>
The output of the above code will be as shown below −
dept numbers is (5) [10, 20, 30, 50, 40]
employee ids (3) [1001, 1002, 1003]
Uncaught TypeError: Assignment to constant variable.

Prior to ES6, the var keyword was used to declare a variable in JavaScript. Variables declared using var do not support block level scope. This means if a variable is declared in a loop or if block it can be accessed outside the loop or the if block. This is because the variables declared using the var keyword support hoisting.
Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top. Consider the following example −
<script>
   variable company is hoisted to top , var company = undefined
   console.log(company); // using variable before declaring
   var company = "TutorialsPoint"; // declare and initialized here
   console.log(company);
</script>
The output of the above code will be as shown below −
undefined
TutorialsPoint

The block scope restricts a variable’s access to the block in which it is declared. The var keyword assigns a function scope to the variable. Variables declared using the var keyword do not have a block scope. Consider the following example −
<script>
   //hoisted to top ; var i = undefined
   for (var i = 1;i <= 5;i++){
      console.log(i);
   }
   console.log("after the loop i value is "+i);
</script>
The output of the above code will be as follows −
1
2
3
4
5
after the loop i value is 6

The variable i is declared inside the for loop using the var keyword. The variable i is accessible outside the loop. However, at times, there might be a need to restrict a variable's access within a block. We cannot use the var keyword in this scenario. ES6 introduces the let keyword to overcome this limitation.
If we declare the same variable twice using the var keyword within a block, the compiler will not throw an error. However, this may lead to unexpected logical errors at runtime.
<script>
   var balance = 5000
   console.log(typeof balance)
   var balance = {message:"hello"}
   console.log(typeof balance)
</script>
The output of the above code is as shown below −
number
object


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page