javascript - ES6 declaring variables before or in loop -


where , how should declare new variables used in loops?

a:

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

b:

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

c:

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

probably or b since says let new var, there difference between , b?

edited:
variable cols used inside for. wondering if there issues if variable initialized inside loop (for example 100 times). wondered if should initialized outside loop. (a or b example)

the purpose not access outside loop, prevent (for example) 100 initialization variable cols inside loop (because let used inside loop - case b).

in code snippet a, cols accessible outside of for too. let variables block-scoped, when used let define variable inside for, scope of variable block only. so, in b, variable cols not accessible outside of for.

c, similar if cols defined once. if col defined twice in same scope using let result in error.

which 1 use depends on use-case.

  1. if cols needed inside for only, use let cols = ...
  2. if cols needed outside of for too, use let cols; before for , can used after for in same enclosing scope. note that, in case, cols last value assigned in loop.

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -