1
(function foo() { var a=b=c=1 }())

When I try to log a will return a not defined err, however, when I try to log b or c will return the value 1. It's wicked.

2
  • 4
    You have not asked a question. Commented Mar 6, 2018 at 10:42
  • Always use strict mode to prevent mistakes like this from happening. (function foo() { "use strict"; var a=b=c=1 }()) Commented Mar 6, 2018 at 13:28

3 Answers 3

4

b and c are added into the window object and get their values as 1. But a is declared via var. This means that a is visible only in the function context and not outside from it.

Your code is equivalent

(function foo() { 
   c = 1;
   b = c;
   var a = b;
}())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I will guess the js interpreter will do this under the scene.Still it kind of weird.
0

however, when I try to log b or c will return the value 1.

Because you didn't localized the scope (inside the function) of b and c by using var or let or const.

Without var, let or const, these variable will take the scope in which this function is defined.

If the outer scope (not outermost) also doesn't localize those variables, then parent scope is checked again till the outermost scope (window). And the variable gets added to outermost scope if no local scope is defined for them. for example

function a() {
  (function foo() {
    var a = b = c = 1;
  }());
  console.log(b, c); //print 1,1
}
a();
console.log(b, c); //print 1,1

However, if these variables are defined in outer scope, then they don't get added to the outermost (window) scope. For example, following will throw an error.

function a() {
  var b,c;
  (function foo() {
    var a = b = c = 1;
  }());
  a();
  console.log(b, c); 
}
console.log(b, c); 

11 Comments

'scope in which this function is specified' described clearly. I thought the leading var has confined the scope of those three variables.
No, leading var is only for a since you are using an assignment expression. You meant var a = 1, b = 1?
@BlakeWoo Also, I meant defined, rather than specified. I have made the changes.
Yes, I didn't realize assignment expression is operating like this.
@BlakeWoo ohh, is your question/doubt answered now?
|
0

If you have lots of constructs where you want to initialise to some constants and you can use ES6 features the following is a nice way to do it.

//store function in your lib
function* initVar(value) {
  while (true) yield value;
}

//using function
let 
  [a,b,c] = initVar(0),
  [d,e,f] = initVar("xyz"); //not just limited to numbers.

console.log(a,b,c,d,e,f);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.