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.
- if
cols
needed insidefor
only, uselet cols = ...
- if
cols
needed outside offor
too, uselet cols;
beforefor
, can used afterfor
in same enclosing scope. note that, in case,cols
last value assigned in loop.
Comments
Post a Comment