Why a is undefined while b is 3 in var a=b=3?

Why a is undefined while b is 3 in var a=b=3?

In the following code, I expected both a and b to be 3. However, a is undefined and b is 3. Why?

(function(){
    var a = b = 3;
})();

console.log(typeof a);//"undefined"
console.log(b);//3

 

回答1

The issue here is that most developers understand the statement var a = b = 3; to be shorthand for:

var b = 3;
var a = b;

But in fact, var a = b = 3; is actually shorthand for:

b = 3;
var a = b;

Therefore, b ends up being a global variable (since it is not preceded by the var keyword) and is still in scope even outside of the enclosing function.

The reason a is undefined is that a is a local variable to that self-executing anonymous function

(function(){
    var a = b = 3;
})();

 

回答2

var a=b=3 

Is the same as:

var a = (b = 3) 

And var statement applies only to a, and not to b. You can check the syntax of var statement here.

Therefore a will be defined in local scope and b will be defined in global scope. Inside function both a and b are 3 but after function returns registered local variable (a) is deleted. Since b is defined in global scope it is not deleted.

 

In Javascript: why does var a, b = 3 return undefined while b = 3 does not?

In the MDN the comma operator is described:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

But why does

var a, b = 3

return undefined, while the expression

b = 3

will return 3, doesn't it?

回答1

This:

var a, b = 3;

is a VariableStatement. VariableStatement evaluation in "normal completion" to empty:

  1. Let next be the result of evaluating VariableDeclarationList.
  2. ReturnIfAbrupt(next).
  3. Return NormalCompletion(empty).

This:

b = 3;

is an ExpressionStatement. ExpressionStatement evaluates to the result of the evaluating expression:

  1. Let exprRef be the result of evaluating Expression.
  2. Return ? GetValue(exprRef).

 

回答2

var a, b = 3;

Is the same as the following:

var a;
var b = 3;

Variable declaration (the var keyword) is not an expression. The commas in variable declarations are more akin to the commas in function argument lists. They do not return anything.

It is true that the comma operator returns the last item, but I am not sure if it has any practical use cases (outside the for loop's initialization).

> 1, 2, 3
< 3

The page you linked to actually explains it pretty well.

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(97)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-12-29 Date and time types
点击右上角即可分享
微信分享提示