1

Why do declarations return undefined? Is there any technical reason for them to?

A benefit if declaration returned the values of their variables would be that I could write something like:

while((var next = generator.next())) doSomething(next);

Because of the specification, I need to declare next in a scope it doesn't belong.

(Note: is there somewhere better to ask this question? It's possible this question is controversial and not just technical.)

Sophie McCarrell
  • 2,831
  • 8
  • 31
  • 64
  • They do return the value as far as I know, otherwise you wouldn't be able to do `a = b = c = 5` – Bálint Jul 29 '17 at 21:47
  • 1
    _"Because of the specification, I need to declare next in a scope it doesn't belong."_ You can use block scope, see [Prevent JavaScript closure from inheriting scope](https://stackoverflow.com/q/45260308/) – guest271314 Jul 29 '17 at 22:12
  • Balint that's assignment, not declaration. Unfortunately they are different things, which creates this complicated problem. – Sophie McCarrell Aug 01 '17 at 17:43

2 Answers2

3

This question is duplicate of Value returned by the assignment, although there is not much of an answer to give other than it is like that because it has been specified like that (how disappointing). var is not part of an expression.

But since you ask about a while loop, I would like to offer this alternative:

for(let next; next = generator.next();) doSomething(next);
trincot
  • 317,000
  • 35
  • 244
  • 286
  • `var` does not even *make sense* as part of an expression. It would get hoisted out to the function scope anyway. – Bergi Jul 29 '17 at 22:44
  • But most languages wouldn't hoist it out, it would be part of the for loop scope. With Javascript we tend to write code that would be hypothetically correct in other languages, even if it's meaningless in JS. It just makes the code saner, IMO. – Sophie McCarrell Aug 01 '17 at 17:38
  • This answer looks better than having a block scope as Guest271314 suggested, even if it won't technically scope the variable in the for loop. – Sophie McCarrell Aug 01 '17 at 17:42
  • 1
    @JasonMcCarrell, the variable *is* scoped to the `for` loop: every iteration [will have its own instance](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let#Cleaner_code_in_inner_functions) of the `next` variable. – trincot Aug 01 '17 at 17:55
  • You're correct, my bad. Thanks for the clear and well supported answer! – Sophie McCarrell Aug 17 '17 at 21:06
1

I need to declare next in a scope it doesn't belong.

You can use block scope to perform tasks, where previously defined variable declaration will retain the original value assigned outside of the block scope

const next = "abc";

const doSomething = prop => console.log(prop);

{
  let next = 10;
  while (next = --next) doSomething(next)
}

console.log(next); // `"abc"`
guest271314
  • 1
  • 15
  • 104
  • 177