JavaScript: Variations Between Utilizing var, let, and const Key phrases for Variable Declaration




The var key phrase was the unique key phrase used to declare variables in JavaScript.

Launched in ES2016, let and const are two new key phrases used for declaring variables. This text will clarify the variations between how the var, let, and const key phrases work.

Earlier than we leap into the variations between let, var and const, it is vital to grasp how scope and hoisting works.



Scope

Scope is the area the place the worth of a variable is outlined and accessible.

There are 3 forms of scope in JavaScript:

  • International Scope
  • Operate Scope
  • Block Scope

Variables outlined with the var key phrase have both world or perform scope.

Variables outlined with the let or const key phrase have block scope.

For a extra in-depth rationalization of scope, see my different submit titled Scope in JavaScript.



Hoisting

When a JavaScript program runs, it’ll first parse the script and search for any variable declarations or perform declarations. If it finds any variable or perform declarations, it’ll “hoist” these to the highest their respective scopes and course of them first earlier than continuing to judge the remainder of the JavaScript code. This course of is named “Hoisting”

Hoisting impacts variable declaration however NOT worth INITIALIZATION / ASSIGNMENT.

Examples of Hoisting in JS

x = 1; // Assign the variable x a worth of 1
console.log(x); // 1;

// Declare a variable x
// This declaration will probably be "hoisted" by JS when this system runs
var x;
Enter fullscreen mode

Exit fullscreen mode

x = 1;
var x; // This will get hoisted

// similar as

var x;
x = 1;
Enter fullscreen mode

Exit fullscreen mode

Keep in mind, hoisting solely applies to variable declarations, not variable initialization. The beneath instance will return “undefined” as x is initialized and never outlined within the second line and due to this fact, it isn’t hoisted above the console.log() name.

console.log(x); // returns undefined
var x = 1;
Enter fullscreen mode

Exit fullscreen mode

The code beneath will print 2. Because the variable y is said on line 3, however not initialized, it is going to be hoisted as much as the highest of this system, above the y = 2 initialization. So by the point console.log(y) is definitely known as, a worth of two will probably be outlined for y.

y = 2;
console.log(y); // Returns 2
var y;

// Similar As
var y;
y = 2;
console.log(y);
Enter fullscreen mode

Exit fullscreen mode

NOTE: Whereas hoisting applies to variables declared with var, let, or const, hoisting actually solely helps variables declared with var. Variables declared with the let key phrase return ReferenceError if they’re un-initialized (see TDZ part additional down for extra element). You additionally can not declare a variable with the const key phrase with out additionally initializing it is worth straight away. In the event you attempt to do that, you’ll get hold of a “SyntaxError: Lacking initializer in const declaration”.



Variations between var, let, and const



var

A variable which is said (however not initialized) utilizing the var key phrase returns a worth of undefined whether it is accessed earlier than it’s initialized (see part about hoisting).

console.log(x); // Returns undefined
var x = 1; // variable declaration and initialization
console.log(x); // Returns 1
Enter fullscreen mode

Exit fullscreen mode

Variables declared with var will be both perform or world scoped.

// Variable declared in world scope
var globalVariable = "This variable was declared within the world scope";

perform myFunc() {
  // Variable declared in perform scope
  var funcVariable = "This variable was declared within the perform scope";
}
Enter fullscreen mode

Exit fullscreen mode

Variables declared with var will be re-declared.

var x = 1;
console.log(x); // 1

var x = 2;
console.log(x); // 2
Enter fullscreen mode

Exit fullscreen mode



let

Variables declared with let are block scoped. We will solely declare variables with the identical identify so long as they’re in several block scopes utilizing let.

{
  // This x variable doesn't exist outdoors of the present block scope
  let x = 1;
  console.log(x); // 1
}
// Attempting to entry x outdoors of its perform block
console.log(x); // Uncaught ReferenceError: x shouldn't be outlined

{
  // Since we at the moment are in a brand new block scope, we are able to declare a variable named x (observe that that is NOT the identical variable as what was declared within the block above)
  let x = 2;
  console.log(x); // 2
}
// Attempting to entry x outdoors of its perform block (nonetheless doesn't exist)
console.log(x); // Uncaught ReferenceError: x shouldn't be outlined
Enter fullscreen mode

Exit fullscreen mode

Not like var, variables declared with the let key phrase can’t be re-declared inside the similar scope

let x = 1;
let x = 2; // Uncaught SyntaxError: Identifier 'x' has already been declared
Enter fullscreen mode

Exit fullscreen mode

You’ll be able to nonetheless, nonetheless redefine (reassign) a variable declared with let.

let x = 1;
console.log(x); // 1

x = 2; // That is okay as a result of you aren't making an attempt to redeclare x, simply redefine its worth
console.log(x); // 2
Enter fullscreen mode

Exit fullscreen mode



The Temporal Lifeless Zone

The Temporal Lifeless Zone (TDZ) is the world within the present scope between the beginning of the scope and the place the variable is lastly initialized. The TDZ applies to variables declared with the let key phrase. A variable declared with let can’t be accessed (will return “ReferenceError”) inside the TDZ.

{
  // Begin of Temporal Lifeless Zone for variable x
  console.log(x); // ReferenceError, nonetheless in TDZ for x
  var y = "hello"; // Nonetheless in TDZ for x
  let x; // x declared, however not initialized with worth, nonetheless in TDZ for x
  x = 10; // TDZ for x ended as x is initialized to a worth of 10
}
Enter fullscreen mode

Exit fullscreen mode



const

Much like variables declared with let, variables declared with the const key phrase are block scoped.

Additionally much like let, variables declared with const can’t be redeclared.

Not like variables declared with let nonetheless, variables declared with const MUST be initialized straight away. If not, you’ll find yourself with a “SyntaxError: Lacking initializer in const declaration” error.

Most significantly, variables declared and initialized with the const key phrase can not have their worth modified via reassignment (see observe beneath). It’s because the const key phrase causes the identify of the variable to be read-only, stopping write entry to the worth saved in reminiscence via the assigned variable. If you consider it, it is smart why that is. If you wish to create a variable that may’t be modified simply, you must know it is worth, in any other case, you’d simply find yourself with a continuing variable with an “undefined” worth.

NOTE: Discover that variables initialized with the const key phrase can not have their worth modified via reassignment. This doesn’t imply that the worth of a continuing worth can not change, it solely means you may’t change it utilizing the variable identify straight. Whereas there is not one other solution to change a string or quantity variable aside from reassignment for instance, you may change the properties of an object.

// Create a variable utilizing the const key phrase and assign it a worth of 1 (quantity)
const x = 1;
x = 2; // SyntaxError: Lacking initializer in const declaration

// Create aa variable utilizing the const key phrase
// and assign it to an object
const myObj = {
  favoriteFood: "Pizza",
  favoriteLanguage: "JavaScript",
  favoriteHobby: "coding",
};

// Print out the worth of favoriteFood
console.log(myObj.favoriteFood);

// Change the worth of favoriteFood
// This works as a result of we aren't accessing the worth straight via using the worth identify
myObj.favoriteFood = "Brocolli";
console.log(myObj.favoriteFood);
Enter fullscreen mode

Exit fullscreen mode



Which variable declaration is greatest and which ought to I exploit?

I learn an article from Wes Bos and I like his recommendation:

  1. Use the const key phrase to declare variables by default until you already know that your variable might want to have its worth modified (use let in that case).
  2. Use the let key phrase to declare a variable if you already know its worth will change (like an iterator for instance).
  3. Until vital for a particular case, keep away from utilizing the var key phrase for variable declaration.



Abstract: Distinction between variables declared with “var”, “let”, and “const” key phrases:

var

  • Scope:
  • Capable of be redeclared?
  • Capable of be reinitialized?

let

  • Scope:
  • Capable of be redeclared?
  • Capable of be reinitialized?

const

  • Scope:
  • Capable of be redeclared?
  • Capable of be reinitialized?



Sources



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#JavaScript #Variations #var #const #Key phrases #Variable #Declaration