1

In JavaScript, by definition a block is defined by a pair of curly brackets, but are parenthesis also considered as blocks?

for (var i = 0; i < 5; i++) {
  //some code
}

console.log(i) // outputs 5;

for (let j = 0; j < 5; j++) {
  //some code
}

console.log(j) // ReferenceError
nick zoum
  • 7,216
  • 7
  • 36
  • 80
Mailinator
  • 53
  • 3
  • 6
    The `for` loop is a special case. The variables declared with `let` are considered to be scoped to the body of the loop – Pointy Nov 08 '19 at 12:42
  • 1
    Another relevant bit is that [*var* definitions are hoisted to the top of the function or global code](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting). – 3limin4t0r Nov 08 '19 at 12:49
  • 1
    *"This expression may optionally declare new variables with `var` or `let` keywords. Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for` loop is in. Variables declared with let are local to the statement."* - [MDN for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#Syntax) – 3limin4t0r Nov 08 '19 at 12:55

1 Answers1

1

This is how let and var works in for statement.

As mdn says:

This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.

let k = 15;
for (let k = 0; k < 5; k++) {
  console.log(`k is ${k}`);
}

// Here k is 15
console.log(`variable k which is declared above the loop ${k}`)
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • However in the posted code, the `let` is *outside* the `{ }` body of the `for` loop. – Pointy Nov 08 '19 at 12:43
  • I think the OP knows that bit, he's pointing out the `let` is in fact outside the `{}`,. but like Pointy has pointed out the for is a special case. – Keith Nov 08 '19 at 12:44
  • @Pointy oops, I've edited my answer. Please, see my updated reply – StepUp Nov 08 '19 at 12:56
  • @Keith thanks for the great comment! I've edited the answer. Please, see my updated answer – StepUp Nov 08 '19 at 12:56
  • @downvoter I believe that there is no reason to downvote now. I've edited the answer. Please, see my updated answer:) – StepUp Nov 08 '19 at 12:57
  • 1
    Not me either, but I do know w3schools has a bad rep here. :), maybe an mdn link -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for The part that relevant here -> `Variables declared with let are local to the statement.` – Keith Nov 08 '19 at 13:04