0

I'm in javascript for a quite long time now, but i'm not able to understand the following case:

var a = "test1";

var c = function()
{
    console.log("2/ "+a)
    if(true)
    {
        console.log("3/ "+a);
    }
    else
    {
        var a = "test2";
        console.log("3/ "+a);
    }
}
    
console.log("1/ "+a);
c();

=> 1/ test1
=> 2/ undefined
=> 3/ undefined

Why the variable become unavailable on the line 'console.log("2/ "+a)', and 'console.log("3/ "+a);' ?

I understand that once we reach the "else" the global scope of "a" inside function c() is "destroyed", but in my mind, as javascript is "scripted" we must be able to use a before the redefinition in the function scope.

Which mecanism is responsible of that ?

Daphoque
  • 4,421
  • 1
  • 20
  • 31
  • 2
    **var** gets [hoisted](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var/11444416#11444416). – Lain Jul 12 '21 at 14:19
  • "var hoisting was thus [an] unintended consequence of function hoisting, no block scope, [and] JS as a 1995 rush job." – Daphoque Jul 12 '21 at 14:29

1 Answers1

1

Variables defined using the var keyword in JavaScript will have their declarations hoisted. See https://www.w3schools.com/js/js_hoisting.asp

When you included the line var a = "test2"; in your function c, you redeclared the variable a in the scope of the function c. All references to the variable a within the function c, before a has been initialized, will have the value undefined since this is the value of an uninitialized variable.