avatarRavi Sharma

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5008

Abstract

a variable's value to change, consider using <code>let</code> or <code>var</code> instead of <code>const</code>.</li></ol><h1 id="1030">Problems Set:</h1><ol><li>let and var scope:</li></ol><div id="8ce5"><pre><span class="hljs-comment">// Using 'var' inside a function</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">varExample</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) { <span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>; <span class="hljs-comment">// 'var' is function-scoped</span> } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 'x' is accessible outside the if block</span> }

<span class="hljs-comment">// Using 'let' inside a block</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">letExample</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) { <span class="hljs-keyword">let</span> y = <span class="hljs-number">20</span>; <span class="hljs-comment">// 'let' is block-scoped</span> } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(y); <span class="hljs-comment">// 'y' is not accessible outside the if block</span> }

<span class="hljs-title function_">varExample</span>(); <span class="hljs-comment">// Outputs: 10</span> <span class="hljs-title function_">letExample</span>(); <span class="hljs-comment">// Throws an error: ReferenceError: y is not defined</span></pre></div><p id="2aec">2. Hoisting with var and let:</p><div id="edbe"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">hoistingExample</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a); <span class="hljs-comment">// Outputs: undefined</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b); <span class="hljs-comment">// Throws an error: Cannot access 'b' before initialization</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// Variable 'a' is hoisted but initialized with 'undefined'</span> <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>; <span class="hljs-comment">// Variable 'b' is hoisted but remains uninitialized until this line</span> }

<span class="hljs-title function_">hoistingExample</span>();</pre></div><p id="85bf">3. Pass by value with var and let:</p><div id="cf7f"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">modify</span>(<span class="hljs-params">x, y</span>) { x = <span class="hljs-number">20</span>; <span class="hljs-comment">// This does not change the original variable</span> y = <span class="hljs-number">20</span>; <span class="hljs-comment">// This does not change the original variable</span> }

<span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>; <span class="hljs-keyword">let</span> y = <span class="hljs-number">10</span>;

<span class="hljs-title function_">modify</span>(x, y); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// Outputs: 10 (unchanged)</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(y); <span class="hljs-comment">// Outputs: 10 (unchanged)</span></pre></div><p id="3da4">4. Pass by reference with var and let:</p><div id="c168"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">modifyArray</span>(<span class="hljs-params">arrV, arrL</span>) { arrV.<span class="hljs-title function_">push</span>(<span class="hljs-number">4</span>); <span class="hljs-comment">// This modifies the original array</span> arrL.<span class="hljs-title function_">push</span>(<span class="hljs-number">4</span>); <span class="hljs-comment">// This modifies the original array</span> }

<span class="hljs-keyword">var</span> arrVar = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]; <span class="hljs-keyword">let</span> arrLet = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-title function_">modifyArray</span>(arrVar, arrVar); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrVar); <span class="hljs-comment">// Outputs: [1, 2, 3, 4]</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrLet); <span class="hljs-comment">// Outputs: [1, 2, 3, 4]</span></pre></div><p id="c9cf">5. Redeclaration

Options

of the variable with let, const, and var in the same scope:</p><div id="5ec4"><pre><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>; <span class="hljs-keyword">var</span> x = <span class="hljs-number">20</span>; <span class="hljs-comment">// Redeclaring 'x' in the same scope is allowed</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// Outputs: 20</span>

<span class="hljs-keyword">let</span> y = <span class="hljs-number">10</span>; <span class="hljs-keyword">let</span> y = <span class="hljs-number">20</span>; <span class="hljs-comment">// Throws an error: Identifier 'y' has already been declared</span>

<span class="hljs-keyword">const</span> z = <span class="hljs-number">10</span>; <span class="hljs-keyword">const</span> z = <span class="hljs-number">20</span>; <span class="hljs-comment">// Throws an error: Identifier 'z' has already been declared</span></pre></div><p id="0c23">6. Redeclaration of the variable with let, const, and var in the different scope:</p><div id="94dc"><pre><span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// a becomes a property of the global object</span> <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) { <span class="hljs-keyword">var</span> a = <span class="hljs-number">20</span>; <span class="hljs-comment">// This modifies the original 'a' in the outer scope</span> } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a); <span class="hljs-comment">// Outputs: 20</span></pre></div><div id="808b"><pre><span class="hljs-keyword">let</span> b = <span class="hljs-number">10</span>; <span class="hljs-comment">// b do not become properties of the global object,</span> <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) { <span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>; <span class="hljs-comment">// This creates a new 'b' in the inner scope</span> } <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b); <span class="hljs-comment">// Outputs: 10 (unchanged)</span></pre></div><div id="d938"><pre><span class="hljs-keyword">const</span> c = <span class="hljs-number">10</span>; <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) { <span class="hljs-keyword">const</span> c = <span class="hljs-number">20</span>; <span class="hljs-comment">// Throws an error: Identifier 'c' has already been declared</span> <span class="hljs-comment">// JavaScript does not allow redeclaration of variables with the const keyword in the same or inner scope.</span>

}</pre></div><p id="a071">7. Use of let and var variables inside the loop:</p><div id="3257"><pre><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">5</span>; i++) { <span class="hljs-comment">// with let i</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i); <span class="hljs-comment">// 0,1,2,3,4</span> }, <span class="hljs-number">1000</span>); }

<span class="hljs-comment">// Explanation: When let is used in the loop, it creates a new variable i </span> <span class="hljs-comment">// for each iteration, (have block scope) preserving its value for the setTimeout callback. </span> <span class="hljs-comment">// This will correctly log values (0,1,2,3,4) each after a 1-second delay.</span></pre></div><div id="e4ad"><pre><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">5</span>; i++) {. <span class="hljs-comment">// with var i</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i); <span class="hljs-comment">// 5,5,5,5,5</span> }, <span class="hljs-number">1000</span>); }

<span class="hljs-comment">// Explanation: When var is used, it doesn't create a new variable for each iteration.</span> <span class="hljs-comment">// Instead, it declares a single variable i that is function-scoped and shared across all iterations</span> <span class="hljs-comment">// As a result, by the time the setTimeout callbacks execute, </span> <span class="hljs-comment">// i will be equal to 5 for all of them. So, it will log values 5 five times.</span></pre></div><p id="b23e">Hope you like this article. If you find this article helpful then like it and share it with others.</p><p id="3378">Thanks for reading.</p></article></body>

JavaScript Interview Preparation: let, const, and var

In this article, we’ll dive into the differences between let, const, and var in JavaScript and cover many important problems based on block scope and function scope also explore best practices for their usage.

Read the full article it will definitely help you in your JavaScript interview.

When working with JavaScript, you’ll frequently encounter three keywords for declaring variables: let, const, and var. Each of these has a distinct purpose and scope, and understanding when and how to use them is essential for writing clean and maintainable code.

Points related to var variables:

  1. Function Scope: Variables declared with var are function-scoped, which means they are accessible within the function in which they are defined.
  2. Hoisting: Declarations made with var are hoisted to the top of their containing function or global scope. This means you can use a variable before it's declared, but it will be undefined until the declaration is reached in the code.
  3. No Block Scope: Unlike let and const, variables declared with var do not have block scope. They are visible throughout the entire function, even if they are defined within a block (such as an if statement).
  4. Global Scope: If a var variable is declared outside of any function or block, it becomes a property of the global object (e.g., window in a browser environment).
  5. Redeclaration: You can redeclare a variable using var in the same scope without any errors. This can lead to unexpected behavior and bugs.
  6. Considered Outdated: With the introduction of let and const in ES6, the use of var is generally discouraged in modern JavaScript development due to its scope quirks and potential issues.

Points related to let variables:

  1. Block Scope: Variables declared with let are block-scoped, meaning they are only accessible within the block or function where they are defined.
  2. No Redeclaration: Unlike var, you cannot redeclare a variable using let in the same scope. Attempting to do so will result in an error.
  3. Temporal Dead Zone (TDZ): Variables declared with let are hoisted to the top of their containing block or function but remain in an uninitialized state until they are assigned a value. Accessing them before initialization results in a ReferenceError.
  4. Global Object Property: Variables declared with let do not become properties of the global object, unlike var, which adds properties to the window object in a browser environment.
  5. For Loops: let is often used in for loops to create a new variable for each iteration, preventing issues with closures and variable sharing.
  6. Preferred over var: Due to its block scope and improved scoping behavior, let is generally preferred over var for declaring variables in modern JavaScript.

Points related to const variables:

  1. Constant Value: Variables declared with const are constants, meaning their values cannot be changed or reassigned after they are initially set. This makes const suitable for values that should remain constant throughout your code.
  2. Block Scope: Like let, const is block-scoped, meaning it is only accessible within the block or function where it is defined.
  3. No Redeclaration: You cannot redeclare a variable using const in the same scope. Once assigned, a const variable's name is locked to the value it holds.
  4. Must Be Initialized: A const variable must be initialized (given a value) when it is declared; otherwise, it will result in an error.
  5. Immutable Reference: While the value of a const variable is immutable, if it holds a reference to an object (e.g., an array or an object), the properties or elements of that object can still be modified.
  6. Preferred for Constants: Use const for values that should not change during the execution of your program, such as mathematical constants or configuration settings.
  7. Consider Using let or var for Mutable Variables: If you expect a variable's value to change, consider using let or var instead of const.

Problems Set:

  1. let and var scope:
// Using 'var' inside a function
function varExample() {
  if (true) {
    var x = 10; // 'var' is function-scoped
  }
  console.log(x); // 'x' is accessible outside the if block
}

// Using 'let' inside a block
function letExample() {
  if (true) {
    let y = 20; // 'let' is block-scoped
  }
  console.log(y); // 'y' is not accessible outside the if block
}

varExample(); // Outputs: 10
letExample(); // Throws an error: ReferenceError: y is not defined

2. Hoisting with var and let:

function hoistingExample() {
  console.log(a); // Outputs: undefined
  console.log(b); // Throws an error: Cannot access 'b' before initialization

  var a = 10; // Variable 'a' is hoisted but initialized with 'undefined'
  let b = 20; // Variable 'b' is hoisted but remains uninitialized until this line
}

hoistingExample();

3. Pass by value with var and let:

function modify(x, y) {
  x = 20; // This does not change the original variable
  y = 20; // This does not change the original variable
}

var x = 10;
let y = 10;

modify(x, y);
console.log(x); // Outputs: 10 (unchanged)
console.log(y); // Outputs: 10 (unchanged)

4. Pass by reference with var and let:

function modifyArray(arrV, arrL) {
  arrV.push(4); // This modifies the original array
  arrL.push(4); // This modifies the original array
}

var arrVar = [1, 2, 3];
let arrLet = [1, 2, 3];

modifyArray(arrVar, arrVar);
console.log(arrVar); // Outputs: [1, 2, 3, 4]
console.log(arrLet); // Outputs: [1, 2, 3, 4]

5. Redeclaration of the variable with let, const, and var in the same scope:

var x = 10;
var x = 20; // Redeclaring 'x' in the same scope is allowed
console.log(x); // Outputs: 20

let y = 10;
let y = 20; // Throws an error: Identifier 'y' has already been declared

const z = 10;
const z = 20; // Throws an error: Identifier 'z' has already been declared

6. Redeclaration of the variable with let, const, and var in the different scope:

var a = 10; // a becomes a property of the global object
if (true) {
  var a = 20; // This modifies the original 'a' in the outer scope
}
console.log(a); // Outputs: 20
let b = 10; // b do not become properties of the global object,
if (true) {
  let b = 20; // This creates a new 'b' in the inner scope
}
console.log(b); // Outputs: 10 (unchanged)
const c = 10;
if (true) {
  const c = 20; // Throws an error: Identifier 'c' has already been declared
  // JavaScript does not allow redeclaration of variables with the const keyword in the same or inner scope.
  
}

7. Use of let and var variables inside the loop:

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

// Explanation: When let is used in the loop, it creates a new variable i 
// for each iteration, (have block scope) preserving its value for the setTimeout callback. 
// This will correctly log values (0,1,2,3,4) each after a 1-second delay.
for (var i = 0; i < 5; i++) {. // with var i
  setTimeout(function () {
    console.log(i); // 5,5,5,5,5
  }, 1000);
}

// Explanation: When var is used, it doesn't create a new variable for each iteration.
// Instead, it declares a single variable i that is function-scoped and shared across all iterations
// As a result, by the time the setTimeout callbacks execute, 
// i will be equal to 5 for all of them. So, it will log values 5 five times.

Hope you like this article. If you find this article helpful then like it and share it with others.

Thanks for reading.

JavaScript
Javascript Tips
Web Development
Programming
Coding
Recommended from ReadMedium