According to the provided documentation, hoisting impacts variable declaration but not its value initialization. The value is assigned only when the assignment statement is encountered.
Within the function displayInstructor
, the variable instructor
is hoisted to the top, yet its value is set only upon reaching the line var instructor = "Loser";
. When the return
statement is executed before the assignment, the variable instructor
remains undefined
.
function displayInstructor(){
console.log(instructor) // undefined
return instructor;
var instructor = "Loser";
}
console.log(displayInstructor());
To address this issue, it is recommended to assign the value first and then return the variable.
function displayInstructor() {
var instructor = "Loser";
return instructor;
}
console.log(displayInstructor());