Question 1
function priority() {
var a = 10;
function a() {};
return a;
}
console.log(typeof priority(), priority());
Answer:
The result will be number
and 10
.
Explanation:
This is because of hoisting. Because of hoisting, the function declaration moves to the top. This is followed by the var declaration. And then the value is assigned. Here 10 will be assigned.
Here is what the hoisted code would look like
function priority() {
function a() {}; // Function declaration for 'a' (hoisted)
var a; // Variable declaration for 'a' (hoisted)
a = 10; // Assignment to 'a'
return a; // Return 'a'
}
Question 2:
function priority() {
a = 10;
function a() {};
var a;
a = 11;
return a;
}
Answer
The result will be number
and 11
Explanation:
Again because of hoisting. First the function will be hoisted. Followed by the var. Then var will be assigned a followed by 11. Hence 11 will be returned. Below is how the hoisted code would look like.
function priority() {
function a() {}; // Function declaration for 'a' (hoisted)
var a; // Variable declaration for 'a' (hoisted)
a = 10; // Assignment to 'a'
a = 11; // Assignment to 'a'
return a; // Return 'a'
}
Question 3:
function priority() {
return test;
console.log('hello');
test = 10;
function test() {};
var test = '11';
}
Answer:
The answer will be function
and [Function: test]
Explanation
This is how the code will be hoisted.
function priority() {
function test() {}; // Function declaration for 'test' (hoisted)
var test; // Variable declaration for 'test' (hoisted)
return test; // Return 'test'
// The rest of the code is not executed due to the early return
console.log('hello'); // This line is never executed
test = 10; // This line is never executed
var test = '11'; // This line is never executed
}
If we have a function and variable with same name and the variable is not assigned with any value, then the variable will have the function and not an undefined value.