425nesp
425nesp

Reputation: 7583

Declaring Variables Outside of Functions

What kind of variables can be declared outside of functions in JavaScript? I'm having a bit of trouble understanding the following code.

This code doesn't affect subtitle.

var element = window.document.getElementById("subtitle");
var test = "Changed!";

function check(){
    element.innerHTML = test;
}

However, if I move element inside the function, then the subtitle element changes to "Changed!".

var test = "Changed!";

function check()
{
    var element = window.document.getElementById("subtitle");
    element.innerHTML = test;
}

Is there a rule that says window objects can't be assigned to var outside of a function, is there a mistaken in the code, or am I just not understanding JavaScript variables?

Upvotes: 1

Views: 1437

Answers (1)

jeff
jeff

Reputation: 8338

Global variables can contain any data type. The first shown code is likely not working because the document isn't loaded when you fetch the value for element, while the second code is working because the document is loaded by the time check() is called.

If you want to use global variables, try this:

var element;
var test = "Changed!";

window.onload = function() {
    element = window.document.getElementById("subtitle");
    check();
}

Upvotes: 2

Related Questions