Javascript: Understanding the Weird Parts - function scope not working as described

591 views Asked by At

I have tried to rewrite this a million ways and can't figure out how Tony Alicea produces the outcome 1, 2, undefined, 1 from this code:

function b() {
    var myVar;
    console.log(myVar);
}

function a() {
    myVar = 2;
    console.log(myVar)
    b();
}

var myVar = 1;
console.log(myVar);
a();
console.log(myVar);

You can see the code and the video at https://www.youtube.com/watch?v=Bv_5Zv5c-Ts&t=74m30s where he executes this and produces 1, 2, undefined, 1. I keep running it and getting 1, 2, undefined, 2. Is there something I'm doing that is causing myVar to exist as 2 in both the global scope and the scope of a()? My code is currently posted at https://testing-mdmitchellnyc.c9.io/hello-world.html.

1

There are 1 answers

0
Craicerjack On BEST ANSWER

function a() should be

function a() {
    var myVar = 2;
    console.log(myVar)
    b();
} 

The way you have it now function a() is overwriting the global myVar instead of creating its own scoped myVar