English 中文(简体)
ES6 - Variables
  • 时间:2024-11-03

ES6 - Variables


Previous Page Next Page  

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 can contain alphabets and numbers.

    Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.

    Variable names cannot begin with a number.

Type Syntax

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 initiapzation refers to the process of storing a value in the variable. A variable may be initiapzed either at the time of its declaration or at a later point in time.

The traditional ES5 type syntax for declaring and initiapzing a variable is as follows −


//Declaration using var keyword 
var variable_name = value

Example : Using Variables


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 and Dynamic Typing

JavaScript is an un-typed language. This means that a JavaScript variable can hold a value of any data type. Unpke 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.

JavaScriptVariable Scope

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.

    Local Scope − A variable with a local scope can be accessed from within a function where it is declared.

Example : Global vs. Local Variable

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 Let and 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. Unpke 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

Example: let v/s var


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.

let and block level safety

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

let and multiple blocks

However, the same let variable can be used in different block level scopes without any syntax errors.

Example


<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

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 pke 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 initiapzer. This means constants must be initiapzed during its declaration.

    The value assigned to a const variable is mutable.

Example


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.

Constants are Immutable

Unpke 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

const and arrays

The following example shows how to create an immutable array. New elements can be added to the array. However, reinitiapzing 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.

The var keyword

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.

var and hoisting

Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initiapzed 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 initiapzed here
   console.log(company);
</script>

The output of the above code will be as shown below −


undefined
TutorialsPoint

var and 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. 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 pmitation.

var and block level safety

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
Advertisements