简体   繁体   中英

Strange behavior with var in Chrome

I'm getting some very strange behavior in Chrome v57.0.2987.133 using JavaScript:

Here is my code:

var firstName = "Bob";
var lastName = "Smith";
var age = 29;

function happyBirthdayLocal(first, last, a) {
    a = a + 1;
    message = "Happy Birthday to " + first + " " + 
                last + " who just turned " + a;
    console.log(message);
}
happyBirthdayLocal(firstName, lastName, age);

As expected, because I did not use var in front of message in the function, message acts like a global variable, and I can access window.message in the developer console.

However, if I insert a line accessing message above the call to the function, like so:

var firstName = "Bob";
var lastName = "Smith";
var age = 29;

function happyBirthdayLocal(first, last, a) {
    a = a + 1;
    message = "Happy Birthday to " + first + " " + 
                last + " who just turned " + a;
    console.log(message);
}
console.log(message);
happyBirthdayLocal(firstName, lastName, age);

(no other changes!) now, I'm getting an uncaught reference error, and window.message is no longer defined.

My sense is that "failing to declare variables will very likely lead to unexpected results" is at play here and it seems Chrome is in an in-between place with regards to defaulting to global vs. local scope for undeclared variables depending on other use in the program? Can anyone confirm this?

I get similar results in Firefox. I've tried searching for specific information regarding what the default behavior is for undeclared variables in both Firefox and Chrome and didn't find anything more enlightening other than to potentially expect strange behavior.

(I'm a bit surprised this hasn't broken a bunch of people's code actually. Or maybe it has. My (mis)use of the variable here--not declaring it--is in the context of teaching about global vs. local scope; I wouldn't on purpose forget to declare a variable (and would lint my code anyway) so this is the first time I've noticed this behavior.)

Thank you in advance for any insight.

Step through it in order.

First, due to hoisting, the variables firstName , lastName , age are declared, and the function happyBirthdayLocal is also declared.

Then, firstName , lastName , age are all assigned their values.

Next you call console.log(message); . Uh-oh, message hasn't been defined yet. That doesn't happen until happyBirthdayLocal is actually called for the first time, which would be on the following line.

Due to the error, which is fatal, the function is never called, and message remains undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM