I've added comments to your code inline to show what's happening:
var a = 45; // declare a global variable
function temp() {
b = 34; // declare a unscoped / global variable (you're missing the "var" in your declaration
}
alert(b); // attempts to print "b" but "temp" function hasn't been declared. Results in undefined
var a = 45; // redeclare does nothing
function temp() { // overrides previous declaration of "temp" function
a = 34; // update the global variable - when the function is called
}
alert(a); // print the function. It's 45 because you haven't called temp()
If b=34
had been written as var b=34;
then when you try to access b
you'd get an undefined error. This is the reason that you should usually run your code through a JSLint check before going to publish. It checks for undeclared variables and other common mistakes. You can also force your browser to be more rigorous in its checks by using strict mode
http://www.jslint.com/
Edit:
As noted by @Spencer Wieczorek the temp
function that contains the variable declaration is never actually called. Because of this, the variable is never defined (in any scope) so when attempting to access it afterwards, it will always return undefined
In this example:
var a = 45;
function temp() {
a = 34;
}
alert(a);
the reason the value of a
doesn't change is that the temp
function was never executed. There are a couple of ways you can change this. The easiest is just to call temp
var a = 45;
function temp() {
a = 34;
}
temp(); // call temp()
alert(a); // prints "34"