let, var, and const: Differences & Examples in JS

Author: neptune | 10th-Apr-2023
#JavaScript

In JavaScript, let, var, and const are used to declare variables to store values or data. These three keywords have different behaviours and usage, and it's important to understand them to write correct and efficient code.


var

The var keyword is used for variable declaration in JavaScript, and it has function-level scope, meaning that the variable can be accessed within the entire function, even if it is declared inside a block. However, if it is declared outside of any function, it becomes a global variable and can be accessed throughout the entire program.

Example:

 

 function testVar() {

    var a = 10;

    if (true) {

        var a = 20;

        console.log(a); // Output: 20

    }

    console.log(a); // Output: 20

 }


In this example, the variable a is declared inside the testVar function with the var keyword. It is then declared again inside the if block, which should create a new variable with a different scope, but because var has function-level scope, the second declaration overrides the first one. Thus, both console.log statements output 20.

Valid cases:

1. Use var to declare global variables or function-scoped variables that need to be accessible throughout the function.

2. Use var to declare variables in legacy code or in specific situations where the behaviour of var is required.


Not valid cases:

1. Avoid using var for block-scoped variables, as it can lead to unexpected behavior.

Example:

 

 if (true) {

    console.log(a); // Error: Cannot access 'a' before initialization

    var a = 10;

 }


2. Avoid redeclaring the same variable with var in the same scope, as it can lead to variable shadowing and unexpected changes in variable values.

Example:


 function testVar() {

    var a = 10;

    if (true) {

        var a = 20;

    }

    var a = 30; // Error: Identifier 'a' has already been declared

 }


In this example, the same variable ‘a’ is declared three times in the same scope, which leads to an error. This is not a valid case for using the var keyword.


let

The let keyword is used to declare block-scoped variables. It was introduced in ES6 and is preferred over var in modern JavaScript code. The variable declared with let is accessible only within the block in which it is defined.

Example:

 

 function testLet() {

    let a = 10;

    if (true) {

        let a = 20;

        console.log(a); // Output: 20

    }

    console.log(a); // Output: 10

 }



In this example, the variable a is declared with let inside the testLet function. The variable is also declared inside the if block, but because let has block-level scope, the two variables are distinct and do not affect each other.

Valid cases:

1. Use let to declare variables that are only needed within a block or a function scope.

Example:

 

 function testLet() {

    let a = 10;

    if (true) {

        console.log(a); // Output: 10

    }

    console.log(a); // Error: a is not defined

}


In this example, let is used to declare a variable inside a block, but the variable is not accessible outside the block. 

2. Use let to avoid variable shadowing and unexpected changes in variable values.


Not valid cases:

1. Avoid using let to declare global variables, as it can lead to unexpected behaviour.

2. Avoid using let to declare variables that need to be accessed throughout the entire function or program, as it has block-level scope.

Example:


 let a = 10;

 let a = 20; // Error: Identifier 'a' has already been declared


In this example, the same variable ‘a’ is declared twice in the same scope, which leads to an error. This is not a valid case for using the let keyword.


const

The const keyword is used to declare constant variables that cannot be reassigned a new value. Like let, it has block-level scope.

Example:

 

 function testConst() {

    const a = 10;

    if (true) {

        const a = 20;

        console.log(a); // Output: 20

    }

    console.log(a); // Output: 10

 }



In this example, the variable a is declared with const inside the testConst function. The variable is also declared inside the if block, but because const variables cannot be reassigned, the second declaration creates a new variable that does not affect the first one.

Valid cases:

1. Use const to declare variables that should not be reassigned a new value, such as constants or values that should remain consistent throughout the program.

2. Use const to declare variables with block-level scope.

Not valid cases:

1. Avoid using const to declare variables that need to be reassigned a new value, as it will result in a TypeError.

Example: 

 

 const a = 10;

 a = 20; // Error: Assignment to constant variable


In this example, const is used to declare a variable that is then reassigned a new value, which is not allowed. This leads to an error and is not a valid case for using the const keyword.


2. Avoid using const to declare variables that need to be initialised with a value later, as it requires a value to be assigned during declaration.

Example:


 const a; // Error: Missing initializer in const declaration

 a = 10;


In this example, const is used to declare a variable without initialising it with a value. Const requires a value to be assigned during declaration, so this leads to an error.

Conclusion

In conclusion, var, let, and const are keywords used to declare variables in JavaScript. Var has function-level scope and can be redeclared and reassigned, while let and const have block-level scope and cannot be redeclared but can be reassigned. Const requires a value to be assigned during declaration and cannot be reassigned later. It's important to choose the right keyword based on the scope and mutability requirements of the variable to avoid errors and ensure proper functionality.




Related Blogs
Generate Fibonacci Sequence - JavaScript | Hackerank
Author: neptune | 07th-Apr-2023
#JavaScript #Hackerrank
Write a JavaScript function fibonacciSequence() to generate a FIbonacci sequence...

Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

To Be Or Not To Be | #2704 | LeetCode Solution
Author: neptune | 03rd-Sep-2023
#JavaScript #LeetCode
Write a function that helps developers test their code. It should take in any value and return an object with the following two functions...

Apply Transform Over Each Element in Array | #2635 | LeetCode Solution
Author: neptune | 05th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a mapping function `fn`, return a new array with a transformation applied to each element...

Function Composition | #2629 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the function composition of the array of functions...

Counter | #2620 | LeetCode Solution
Author: neptune | 02nd-Sep-2023
#JavaScript #LeetCode
Given an integer n, return a counter function. This counter function returns n and then n + 1, n + 2, etc...

Chunk Array | #2677 | LeetCode Solution
Author: neptune | 19th-Sep-2023
#JavaScript #LeetCode
Given an array arr and a chunk `size`, return a `chunked` array...

Counter 2 | #2665 | LeetCode Solution
Author: neptune | 04th-Sep-2023
#JavaScript #LeetCode
Write function 'createCounter' It accept an initial integer 'init' It should return an object with three functions- increment() , decrement(), reset()...

Different ways to handle state in React applications
Author: neptune | 21st-Jun-2023
#JavaScript #React.js
This article explores different ways to manage states in React, including local component state, context API, and state management libraries like Redux...

Array Reduce Transformation | #2626 | LeetCode Solution
Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode
Given an integer array `nums` and a reducer function `fn`, and an initial value `init`, return a reduced array...

Add Two Promises | #2723 | LeetCode Solution
Author: neptune | 12th-Sep-2023
#JavaScript #LeetCode
Given two promises `promise1` and `promise2`, return a new `promise`. `promise1` and `promise2` will both resolve with a number...

Filter Elements from Array | #2634 | LeetCode Solution
Author: neptune | 06th-Sep-2023
#JavaScript #LeetCode
Given an integer array `arr` and a filtering function `fn`, return a filtered array `filteredArr`...

Arrow Functions in JavaScript | ES6
Author: neptune | 26th-Mar-2023
#JavaScript #React.js
In this article, we will explore the syntax and usage of arrow functions in detail, along with some examples...

Is Object Empty | #2727 | LeetCode | JavaScript Solution
Author: neptune | 01st-Sep-2023
#JavaScript #LeetCode
Given an object or an array, return if it is empty...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 31st-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

View More