Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables undefined when referencing them via window object

I'm fairly new to declaring variables globally via window, so I was a bit surprised that the following snippet behaves differently depending on the browser.

window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);​

Firefox, IE, Opera

Good

undefined

Good

Chrome and Safari

Good

Good

Good

My initial belief was that it should behave the way Chrome and Safari does, but I realize I might not have a proper understanding of the window object, so would anyone more knowledgeable explain this?

I realize I can just use var test = "Good"; for that scope, but I'm interested in why the browsers handle it differently.

http://jsfiddle.net/WHYFc/

like image 737
Michael Theriot Avatar asked Oct 19 '12 05:10

Michael Theriot


People also ask

Is window a global variable?

In HTML, the global scope is the window object. All global variables belong to the window object.

What is global window object?

In a web browser, any code which the script doesn't specifically start up as a background task has a Window as its global object.

What is window variable in JavaScript?

window. variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.

Can we declare global variable in JavaScript?

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable. Global Variables are the variables that can be accessed from anywhere in the program.


Video Answer


1 Answers

Your JSFiddle is using window.load to create the script.

document.write after load CLEARS/WIPES the document so what you are seeing is normal for those browsers and webkit simply is more lenient

Here is the code you produce in jsfiddle:

window.addEvent('load', function() {
window.test = "Good";
document.write(window.test);
document.write('<br>');
document.write(window.test);
document.write('<br>');
document.write(test);
});

Change your fiddle to head or body and it will work as expected

DEMO

like image 199
mplungjan Avatar answered Sep 28 '22 08:09

mplungjan