Skip to content

Commit 46a0fdd

Browse files
committed
adding tricky questions
1 parent 0ad12bd commit 46a0fdd

9 files changed

+14
-5
lines changed
Loading
Loading

Javascript/Tricky-JS-Problems/what-below-code-will-output.md renamed to Javascript/Tricky-JS-Problems/what-below-code-will-output-1.md

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,26 @@
1-
![](2020-10-08-16-50-10.png)
1+
#### Q - What will be the output of the below code and why
2+
3+
![](assets/2020-10-08-16-50-10.png)
24

35
#### Ans - if you are not using strict mode), the output of the code snippet would be:
46

5-
![](2020-10-08-16-51-07.png)
7+
![](assets/2020-10-08-16-51-07.png)
68

79
### Explanations
810

911
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.
1012

1113
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:
1214

13-
![](2020-10-08-16-59-10.png)
15+
![](assets/2020-10-08-16-59-10.png)
1416

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

17-
![](2020-10-08-16-59-22.png)
19+
![](assets/2020-10-08-16-59-22.png)
1820

1921
As a result (if you are not using strict mode), the output of the code snippet would be:
2022

21-
![](2020-10-08-16-59-37.png)
23+
![](assets/2020-10-08-16-59-37.png)
2224

2325
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.
2426

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#### Q - What will be the output of the below code and why
2+
3+
![](2020-10-08-17-02-25.png)
4+
5+
### Ans - The above code will output the following to the console:
6+
7+
![](2020-10-08-17-02-51.png)

0 commit comments

Comments
 (0)