Back

Technologies:

javascriptjavascript
avatar
Tolerim
25 days ago

What causes a global variable to become undefined when redefined inside a function?

While I was studying JavaScript hoisting, I conducted a test using the provided code snippets. I was unable to deduce the reason why the first and second functions produced different outputs. It is uncertain whether this inconsistency is due to hoisting.

var me = 1;
function findme(){
   if(me){
    console.log( me );//output 1
    }
  console.log( me ); //output 1
}
findme();
However, the third function returns "undefined".

var me = 1;
function findme(){
 if(me){
    var me = 100;
    console.log(me); 
    }
  console.log(me); 
}
findme();
// undefined
Answers(2)
avatar
Vogi
24 days ago
Verified Answer
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their scope by the JavaScript engine. This means that you can use a variable or function before it has been declared in your code, and JavaScript will still understand what you mean. In the first two functions, the variable "me" is declared outside of the function and is therefore in the global scope. When the function is called, it looks for "me" in its local scope first. Since it doesn't find it there, it looks up to the global scope and finds "me" there. That's why both functions output 1. However, in the third function, "me" is declared inside the if statement block. This means that it is only available within that block. When you try to log "me" outside of that block, it is undefined because it was never assigned a value. I hope this helps! Let me know if you have any other questions.

Sources

Hoisting in JavascriptQuestions on JavaScript hoisting - Stack OverflowJavaScript Hoisting (with Examples) - ProgramizJavaScript Hoisting - W3SchoolHoisting - MDN Web Docs Glossary: Definitions of Web-related terms | MDNjavascript - Hoisting with var - Stack Overflow
avatar
Tolerim
25 days ago
This is related to hoisting. In the second example, the variable me is declared with the var keyword inside the findme() function. This means that the variable is hoisted to the top of the function, but it is not assigned a value until later in the function. So when the first console.log() statement is executed, me is still undefined. In contrast, in the first example, me is defined outside the findme() function, so it is available to the entire function and has a value of 1.
;