Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 declaring variables before or in loop

Where and how should I declare new variables used in loops?

A:

const map = new Map(Object.entries(columns));
let cols;
for (let [key, value] of map)
{
    cols = value.split('|');
    //...
}

B:

const map = new Map(Object.entries(columns));
for (let [key, value] of map)
{
    let cols = value.split('|');
    //...
}

C:

const map = new Map(Object.entries(columns));
var cols;
for (let [key, value] of map)
{
    cols = value.split('|');
    //...
}

Probably A or B since everyone says let is the new var, but is there any difference between A and B?

Edited:
The variable cols will be used only inside for. I was wondering if there are some issues if variable is initialized inside loop (for example 100 times). So I wondered if it should be initialized outside loop. (A or B example)

The purpose is not to get access outside loop, but prevent (for example) 100 initialization variable cols inside loop (because let is used inside loop - case B).

like image 324
Makla Avatar asked Jul 28 '16 10:07

Makla


People also ask

How do I declare variables in ES6?

A variable can be initialized at any time before its use. The ES6 syntax used the keyword var to declare a variable. In ES5, we declare the variable like this: var x //Declaration of a variable by using the var keyword.

Can we declare variable inside for loop in JavaScript?

If a variable is declared inside a loop, JavaScript will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

What is the correct way to declare a variable in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browsers, you must use var .

How many ways of defining your variables in ES6?

Now, with ES6, there are three ways of defining your variables: var , let , and const .


1 Answers

In code snippet A, cols is accessible outside of the for too. As let variables are block-scoped, when used let to define variable inside for, the scope of the variable is for that block only. So, in B, the variable cols will not be accessible outside of the for.

C, is similar to A if cols is defined only once. If col is defined twice in the same scope using let will result in error.

Which one to use depends on the use-case.

  1. If cols is needed inside for only, then use let cols = ...
  2. If cols is needed outside of for too, use let cols; before for and then it can be used after for too in the same enclosing scope. Note that, in this case, cols will be the last value assigned in the loop.
like image 170
Tushar Avatar answered Oct 17 '22 01:10

Tushar