Skip to content

Commit 0ad12bd

Browse files
committed
adding tricky questions
1 parent c40cfdd commit 0ad12bd

6 files changed

+25
-0
lines changed
Loading
Loading
Loading
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
![](2020-10-08-16-50-10.png)
2+
3+
#### Ans - if you are not using strict mode), the output of the code snippet would be:
4+
5+
![](2020-10-08-16-51-07.png)
6+
7+
### Explanations
8+
9+
Since both a and b are defined within the enclosing scope of the function, and since the line they are on begins with the var keyword, most JavaScript developers would expect typeof a and typeof b to both be undefined in the above example.
10+
11+
However, that is not the case. The issue here is that most developers incorrectly understand the statement var a = b = 3; to be shorthand for:
12+
13+
![](2020-10-08-16-59-10.png)
14+
15+
But in fact, var a = b = 3; is actually shorthand for:
16+
17+
![](2020-10-08-16-59-22.png)
18+
19+
As a result (if you are not using strict mode), the output of the code snippet would be:
20+
21+
![](2020-10-08-16-59-37.png)
22+
23+
But how can b be defined outside of the scope of the enclosing function? Well, since the statement var a = b = 3; is shorthand for the statements b = 3; and var a = b;, b ends up being a global variable (since it is not preceded by the var keyword) and is therefore still in scope even outside of the enclosing function.
24+
25+
Note that, in strict mode (i.e., with use strict), the statement var a = b = 3; will generate a runtime error of ReferenceError: b is not defined, thereby avoiding any headfakes/bugs that might othewise result. (Yet another prime example of why you should use use strict as a matter of course in your code!)

0 commit comments

Comments
 (0)