Javascript ES6: Let, Const, and Var-

Javascript ES6: Let, Const, and Var- Choosing the Right Variable Declaration

Javascript is a dynamic programming language that provides browser compilation for the developer which helps in step-by-step debugging of the function.

With the introduction of new ways to declare variables in ECMAScript 2015 (also known as ES6), one of the biggest advancements occurred. Let, const, and var are the three primary keywords for variable declaration in ES6.

Writing clean, manageable, and bug-free code requires selecting the best one for your purposes. It will help you in making wise choices, we will look at the difference between let, const, and var in this post and offer examples.

Javascript ES6: Let, Const, and Var- Choosing the Right Variable Declaration

The Old Way ‘Var’

The var keyword was the only way to declare variables in JavaScript prior to ES6. Although var is still valid, it has significant limitations that have caused confusion and errors in many codebases. The main features of var are as follows:

1. Function-Scoped: Var-declared variables are function-scoped. This implies that regardless of where the variable is declared, it is accessible throughout the entire function. This might cause unexpected behavior and make managing variables in bigger codebases difficult.

function exampleVarScope() {
  if (true) {
    var x = 10;
  }
  console.log(x); // Outputs 10
}

2. Hoisting: The global scope or the function that contains the variable receives the variable declared using the var keyword. This means that a variable can be used before it has been defined, which may result in undetectable problems.

console.log(y); // Outputs undefined
var y = 5;

3. Reassignment: Using the Var keyword we can reassign value to the variables that are already declared.

var age = 25; // Declare and initialize a variable with the value 25
console.log(age); // Output: 25

age = 30; // Reassign the variable's value to 30
console.log(age); /;/ Output: 30

4. Redeclaration: Using var in the same scope while in non-strict mode allows you to redeclare a variable without encountering an error, but using let and const does not.

Note: “Strict Mode in javascript is a method of writing code which follows strict rules of declaring functions and writing a clean code.

var x = 5;
console.log(x); // Output: 5

var x = 10; // This is a redeclaration
console.log(x); // Output: 10

Pros

  • Function Scope: Once a variable is declared, it is accessible throughout the entire function.
  • Hoisting: Variables are initialized with undefined and shifted to the top of their scope so they can be referenced before declaration.

Cons

  • Lack of Block Scope: Potential problems can occur when variables are accessed outside of the block they were declared in.
  • Hoisting Quirks: This can be confusing because variables are available before they are declared.

The New Way: Let and Const

Let and const are two new variable declaration keywords introduced with ES6. For better control over variable scoping and consistency, these keywords reduce many of the problems of var.

let

Let is comparable to var but has block-scoping, making it safer and more predictable to use. The main characteristics of let are as follows:

1. Block Scoped: Let variables are block-scoped, which means that only the block in which they are defined can access them. This reduces the possibility of random variable modifications

function exampleLetScope() {
  if (true) {
    let x = 10;
  }
  console.log(x); // ReferenceError: x is not defined
}

2. No Hoisting: Variables declared with let are not hoisted, in contrast to var. Variables cannot be utilized before they are declared as a result.

console.log(z); // ReferenceError: z is not defined
let z = 5;

3. Reassignment: Like the Var keyword we can reassign value using the let keyword to the variables that are already declared.

let x = 5;
console.log(x); // Output: 5

x = 10; // This is reassignment
console.log(x); // Output: 10

Pros

  • Block Scope: Restricting access to variables to the block in which they are declared, reduces the chances of error inside the function.
  • No Hoisting: The variables are initialized after the execution of the code reaches to the declaration to the declaration of the variable.

Cons:

  • More Limited Scope: It might be necessary to plan for the variable’s declaration position more carefully.

Const

Const stands for “constant” and is used to refer to variables that should not have their original values changed. The main characteristics of const are as follows:

1. Block-Scoped: Const, like let, is block-scoped, making block-level variable declarations safe.

2. Immutable: Variables declared with cons cannot be re-assigned. However, it’s essential to note that this applies to the variable itself, not necessarily the value it holds. Objects and arrays declared with const can have their properties or elements modified.

const pi = 3.14159;
pi = 42; // TypeError: Assignment to constant variable.
const person = { name: "Alice" };
person.name = "Bob"; // Allowed

3. No Reassignment: Once a variable has been assigned with const, it cannot be reassigned, unlike var and let. A TypeError will appear if you try to do this.

4. No Declaration: Const cannot be used to redeclare a variable inside the same scope.

Pros

  • Immutable Reference: Prevents reassignment, improving predictability of code.
  • Block Space: Variables are only accessible within the block in which they are declared, similar to how let works.

Cons

  • Not Fully Immutable: The object itself is not constant; just the reference is. The characteristics of a variable that is an object can still be changed.

Let VS Const VS Var

CharacteristicLetConstVar
ScopeBlock-scopedBlock-scopedFunction-scoped
HoistingNot hoistedNot hoistedHoisted to function or global scope
Re-assignment AllowedYesNo (for the variable itself)Yes
Value ImmutableNoYes (for the variable itself)No
TDZ (Temporal Dead Zone)Yes (variables declared with let have a TDZ)Yes (variables declared with const have a TDZ)No
Redeclaration AllowedNo (within the same scope)No (within the same scope)Yes (within the same scope)
Block-Level Function DeclarationsNoNoYes (function declarations are hoisted to the top of their containing function or global scope)
Examplelet x = 5;const pi = 3.14159;var y = 10;
Typical Use CasesMutable variablesConstantsLess common, legacy code

Choosing the right variable declaration

The choice between let, const, and var depends on your specific use case and the behavior you want for your variables. There is no one-size-fits-all answer, as each method serves a different purpose. Here’s a summary of when to use each method:

Const:

  • Best for variables that shouldn’t be changed after being initially assigned
  • Const provider immutability which helps prevent changes to the values.
  • Const variable is mostly used for representing variables that hold either mathematical values or other configuration settings where values are not changed.

Let:

  • It is appropriate to use these variables for variables that need to have their scope changed.
  • When compared to var, it is safer for variable declarations because it offers block-level scoping.
  • Useful for loop counters, temporary variables, or variables whose values change over time within a function or block.

Var:

ADVERTISEMENT

  • Generally, this should be avoided in modern JavaScript development.
  • It can be difficult to manage variables in bigger codebases because variables declared using var are function-scoped and can exhibit unexpected behavior.
  • Hoisting using var can produce subtle errors.
  • Var is not advised for new projects, even though it may still be used in some legacy codebases. For improved scope and predictability, use let and const.

In current JavaScript development, const is advised for variables that should remain constant, let is advised for mutable variables, and var should generally be avoided in favor of let or const to ensure safer and more predictable code.

ADVERTISEMENT

If you find this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

ADVERTISEMENT



Leave a Reply