In this post,I have tried to cover all the types of possible interview questions and answers on hoisting.
If you are not familiar with the hoisting, I would highly recommend you to go to my post on hoisting. Once you are comfortable with the topic, you can attempt these questions. Understanding the type of question will help you to answer. I have provided the hint after each question. All the answers are given at the end of the post.
//Question 1
console.log('bar:', bar)
bar = 15
var foo = 1
console.log(foo, bar)
var bar
Hint: Basics of hoisting
//Question 2
var foo = 5
console.log('foo:', foo)
var foo;
var bar = 10;
var bar;
console.log('bar:', bar)
var baz = 10
var baz = 12
console.log('baz:', baz)
Hint: Basics of hoisting
//Question 3
function foo() {
function bar() {
return 5
}
return bar()
function bar() {
return 10
}
}
console.log(foo());
Hint: Think what happens if two functions with same name are hoisted.
//Question 4
function foo() {
var bar = "I'm a bar variable"
function bar() {
return "I'm a bar function"
}
return bar()
}
console.log(foo())
function foo() {
var bar = "I'm a bar variable"
function bar() {
return "I'm a bar function"
}
return bar()
}
console.log(foo())
Hint: Think what is the preference given if a function and variable has same name.
//Question 5
greeting()
var greeting = function() {
console.log('Good morning')
}
greeting()
function greeting() {
console.log('Good evening')
}
greeting()
Hint: Precedence of function expressions and function declaration and also how these are hoisted.
//Question 6
var foo = 5
console.log('foo:', foo)
var foo = 10
console.log('foo:', foo)
Hint: Basics of hoisting.
//Question 7
console.log(foo());
function foo() {
var bar = function() {
return 3
}
return bar()
var bar = function() {
return 8
}
}
Hint: how hoisting works happens when two function exression has same name.
// Question 8
var x = 'foo';
(function() {
console.log('x: ' + x)
var x = 'bar'
console.log('x: ' + x)
})()
var x = 'foo';
(function() {
console.log('x: ' + x)
var x = 'bar'
console.log('x: ' + x)
})()
Hint: Stick to the basics of hoisting
//Question 9
function foo() {
console.log('First')
}
foo()
function foo() {
console.log('Second')
}
Hint: Similar to question No 3
//Question 10
var foo = 5
function baz() {
foo = 10
return
function foo() {}
}
baz()
console.log(foo)
Output 1:
'bar:' undefined
1 15
Output 2:
'foo:'5
'bar:'10
'baz:'12
Output 3:
10
Output 4:
error: bar is not a function
Output 5:
Good evening
Good morning
Good morning
Output 6:
'foo:'5
'foo:'10
'foo:'10
Output 7:
3
Output 8:
'x: undefined
'x: bar'
Output 9:
'Second'
Output 10:
5
Hope this was helpful. Comment me how much you scored. Let me know if any other question you encounter. Subscribe and leave your comments to support.
Thank you !!
Awesome questions.
ReplyDeleteI was actually asked two of these question in an interview.
☝��