Javascript Tricky Questions — Functions
1. Guess the output
Answer: my@email.com
Why ? => using a arrow function => this does not point to the user object but the execution context in which user lies.
Here , this points to Window
This can be solved by using a normal function instead of the arrow function.
2. Guess the output
Answer:
Second Greetings (because of the hpisting of function declaration)
First Greetings (initialisation at line 2 overrides the hoisted definition)
First Greetings
3. Guess the output
Answer:
10
20
20
30
4. Guess the output
Answer:
undefined
20
10
30
5. Guess the output
Answer:
35 (var3 is hoisted and initiased at line 3 in the IIFE scope)
10 (global variable)
15 (global variable)
Uncaught ReferenceError: var3 is not defined
(trying to access the variable that is accessible only in IIFE scope)
6. Guess the output
Answer:
0
1
2
7. Guess the ouput
Answer:
Aurelio de Rose
John
Colin Ihrig
Doe
8. Guess the output
Answer:
SyntaxError: Rest parameter must be last formal parameter
9. Guess the output
Answer:
undefined
John Doe
10. Guess the output
Answer:
Tom Cruise
Tom Cruise
(Binding an already bound function does not change the execution context.)
11. Guess the output
Answer:
undefined
12. Guess the output
Answer:
Daniel Craig
13. Guess the output
Answer:
undefined
14. Guess the output
Answer:
Jason
15. Guess the output
Answer:
JS
var
Why ?
1. Creation phase-
On line 2, display gets stored as a var variable and initialised with undefined.
VO : {
display : undefined;
}
On line 5, display is set a function declaration, overrides undefined with the function definition.
VO : {
display : function(){ console.log('JS')};
}
2. Execution Phase-
Line 1 — display stores the function definition from line 5 , logs — JS
Line 2 — display value gets overwritten and now the function stored in display is -
VO : {
display : function(){ console.log('var')};
}
Line 5- skipped the function declaration
Line 8— display() — logs var
Sources:
https://codeburst.io/javascript-interview-questions-functions-5a3081c1f3f5