JavaScript Variables

JavaScript variables: In this tutorial, we are going to learn about the variables, declaration of the variables in JavaScript, accessing, updating the variables with examples, etc.
Submitted by Siddhant Verma, on September 26, 2019

One of the most fundamental topics in any language is variables. Variables are the most primitive containers that hold our data. They allow us to store a value like a name, number, etc that we can use anytime later in the program. There are three ways to declare variables in JavaScript: using the let keyword, var keyword, and const keyword.

Open the chrome dev console to try out the examples by right-clicking on the browserselecting inspectselecting console or simply press f12.

Here you can define variables in JavaScript using the following syntax:

    let variable_name = value 
Variables in JavaScrpt | 1

If we want to change the value assigned to a variable, we avoid the use of let keyword again. We simply use the assignment operator (=) and the variable takes the newly assigned value.

Syntax:

    variable_name = new_value; 

We use the const keyword to declare constant. A constant is quite literally a value that is fixed or wouldn't change during the program. If we declare a variable as constant, we cannot and should not reassign a value to it.

Variables in JavaScrpt | 2

Here we get an error because assigning a new value to a const is not allowed. Both the above keywords were added by ES16 update to the language and are fairly new. The old way of declaring variables is using the var keyword.

Variables in JavaScrpt | 3

The major difference between let and var are their scopes. Variable declared with let has a block scope whereas var has function scope.

Variables in JavaScrpt | 4

Redeclaring let variables gives an error because it is hoisted in a temporal dead zone unlike var is hoisted normally.

Writing async functions using let is quite different. Look at the following example,

for(var i=0; i<3; i++ ){
	setTimeout(function(){
		console.log(i);
	},1000)
}

for(var i=0; i<3; i++){
   setTimeout(function(){
       console.log(i);
   },1000)
}
//Output is 3

for(let i=0; i<3; i++){
   setTimeout(function(){
       console.log(i);
   },1000)
}
//Output is 0,1,2

Due to hoisting in the temporal dead zone, we get all the values of let barring the last value on the console. Whereas in the case of using var, we only get it's final value after the setTimeout() function executes (i.e. after 1 sec).

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.