Let Const Var Keyword in JavaScript – Learn How They Work – When To Use

'Let' 'Const' 'Var' Keyword in JavaScript - Learn How They Work - When To Use

In JavaScript, let, const, and var are used to declare variables, but they have different scopes and behaviors. Understanding when to use each one is important for writing clean and maintainable code. Let’s explore each one in detail with coding examples:

var:

  • var was the original way to declare variables in JavaScript.
  • Variables declared with var are function-scoped, meaning they are only available within the function in which they are declared or globally if declared outside of any function.
  • Variables declared with var can be redeclared and reassigned.
  • Example:
function varExample() {
if (true) {
var message = "Hello, var!";
}
console.log(message); // Output: Hello, var!
}
varExample();
console.log(message); // Output: Hello, var!

let:

  • let was introduced in ES6 and is preferred over var for variable declaration in modern JavaScript.
  • Variables declared with let are block-scoped, meaning they are only available within the block in which they are declared.
  • Variables declared with let can be reassigned but not redeclared within the same block.
  • Example:
function letExample() {
if (true) {
let message = "Hello, let!";
console.log(message); // Output: Hello, let!
}
console.log(message); // Error: message is not defined
}
letExample();

const:

  • const is also introduced in ES6 and is used to declare constants.
  • Variables declared with const are block-scoped like let.
  • Constants must be initialized at the time of declaration and cannot be reassigned.
  • Example:
function constExample() {
const message = "Hello, const!";
console.log(message); // Output: Hello, const!
// message = "Hello, const!"; // Error: Assignment to constant variable.
}
constExample();

When to use let, const, or var:

  • Use let when you need to reassign the variable.
  • Use const when you want to declare a variable that should not be reassigned.
  • Avoid using var unless you have a specific reason to use it, as it can lead to unexpected behavior due to its function scope.

Let’s see some more examples so that you can understand it properly

Using let in a for loop:

for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
console.log(i); // Error: i is not defined

Explanation:

  • for (let i = 0; i < 5; i++): This line declares a variable i using let and initializes it to 0. The loop will run as long as i is less than 5, and i will be incremented by 1 after each iteration.
  • console.log(i);: This line logs the current value of i to the console during each iteration of the loop.
  • console.log(i);: This line tries to log the value of i outside the loop, but since i was declared with let inside the loop, it is not accessible outside the loop’s block scope, resulting in an error.

Using const with an object:

const person = {
name: "Alice",
age: 30
};
person.age = 31; // Allowed
console.log(person); // Output: { name: "Alice", age: 31 }

Explanation:

  • const person = { name: "Alice", age: 30 };: This line declares a constant variable person and initializes it with an object containing name and age properties.
  • person.age = 31;: This line modifies the age property of the person object, which is allowed because const only prevents reassigning the variable person, not mutating its properties.
  • console.log(person);: This line logs the modified person object to the console.

Redeclaring a variable with var:

var count = 10;
var count = 20; // Redeclaration allowed
console.log(count); // Output: 20

Explanation:

  • var count = 10;: This line declares a variable count using var and initializes it to 10.
  • var count = 20;: This line redeclares the variable count with a new value of 20, which is allowed with var.
  • console.log(count);: This line logs the final value of count, which is 20.

Redeclaring a variable with let:

let count = 10;
// let count = 20; // Error: Identifier 'count' has already been declared
console.log(count); // Output: 10

Explanation:

  • let count = 10;: This line declares a variable count using let and initializes it to 10.
  • // let count = 20;: This line attempts to redeclare the variable count with a new value of 20, but it’s commented out to avoid the error.
  • console.log(count);: This line logs the initial value of count, which is 10.

Using let in a block scope:

let x = 10;
if (true) {
let x = 20;
console.log(x); // Output: 20
}
console.log(x); // Output: 10
  • let x = 10;: This line declares a variable x using let and initializes it to 10.
  • if (true) { let x = 20; ... }: This line creates a block scope with an if statement and declares a new variable x inside the block, which shadows the outer x variable.
  • console.log(x);: This line logs the outer x variable, which is 10, outside the block scope.

Using const with arrays:

const numbers = [1, 2, 3];
numbers.push(4); // Allowed
console.log(numbers); // Output: [1, 2, 3, 4]
// numbers = [4, 5, 6]; // Error: Assignment to constant variable.

Explanation:

  • const numbers = [1, 2, 3];: This line declares a constant variable numbers and initializes it with an array containing numbers 1, 2, and 3.
  • numbers.push(4);: This line modifies the numbers array by adding 4 to the end, which is allowed because const only prevents reassigning the variable numbers, not mutating its elements.
  • console.log(numbers);: This line logs the modified numbers array to the console.

Using var in a function scope:

function varFunction() {
if (true) {
var message = "Hello, var!";
}
console.log(message); // Output: Hello, var!
}
varFunction();
console.log(message); // Output: Hello, var!

Explanation:

function varFunction() { ... }: This line defines a function varFunction.
var message = "Hello, var!";: This line declares a variable message using var inside the if block, which is function-scoped.
console.log(message);: This line logs the message variable, which is accessible within the function scope.

Using let to avoid variable hoisting:

console.log(x); // Output: undefined
var x = 10;
console.log(y); // Error: Cannot access 'y' before initialization
let y = 20;

Explanation:

  • console.log(x);: This line logs undefined because var variables are hoisted to the top of their scope, but their initialization is not hoisted.
  • var x = 10;: This line declares and initializes a variable x using var.
  • console.log(y);: This line throws an error because let variables are not hoisted, and trying to access y before its initialization results in a ReferenceError.
  • let y = 20;: This line declares and initializes a variable y using let.

Using const for constants:

const PI = 3.14159;
// PI = 3; // Error: Assignment to constant variable.
console.log(PI); // Output: 3.14159

Explanation:

  • const PI = 3.14159;: This line declares a constant variable PI and initializes it with the value of 3.14159.
  • // PI = 3;: This line is commented out because it tries to reassign the constant PI, which is not allowed and would result in an error.
  • console.log(PI);: This line logs the value of PI to the console.

Using let in a nested block:

let a = 10;
{
let a = 20;
console.log(a); // Output: 20
}
console.log(a); // Output: 10

Explanation:

  • let a = 10;: This line declares a variable a and initializes it to 10.
  • let a = 20;: This line declares a new variable a in a nested block and initializes it to 20, which shadows the outer a variable.
  • console.log(a);: This line logs the inner a variable, which is 20, inside the nested block.
  • console.log(a);: This line logs the outer a variable, which is 10, outside the nested block.

In conclusion, let, const, and var are used for variable declaration in JavaScript, each with its own scope and behavior. let is preferred for most use cases due to its block scope and ability to reassign values. const should be used for variables that should not be reassigned. var should be used sparingly due to its function scope and potential for unexpected behavior. Understanding the differences between these keywords is essential for writing clean and maintainable JavaScript code.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>