For the most part, yes. With two main exceptions (leaving aside the obvious "definition of a function", call the function "which effectively" returns "to the body of the function):
1: Rise. var statements are raised, so if you write
alert(a); var a = 123;
You get undefined , not an error message. This is because he is raised to
var a; alert(a); a = 123;
Similarly, function definitions also rise. If you write:
foo(123); function foo(num) {alert(num);}
It will work because the function is raised. However, this does NOT work if you wrote
foo(123); foo = function(num) {alert(num);}
Because it is the purpose of an anonymous function, not the definition of a function.
2: Asynchronous functions.
A common mistake among beginners is to write the following:
var a = new XMLHttpRequest(); a.open("GET","sompage.php",true); a.onreadystatechange = function() { if( a.readyState == 4 && a.status == 200) { myvar = "Done!"; } }; a.send(); alert(myvar);
They expect a warning to tell Done! but instead they will get an inexplicable error because it is not defined. This is because myvar = "Done!" not yet run, despite appearing earlier in the script.
See also this joke from Computer nonsense :
An introductory student programmer once asked me to look at his program and find out why it always knocked out zeros as a result of a simple calculation. I looked at the program, and it was pretty obvious:
begin readln("Number of Apples", apples); readln("Number of Carrots", carrots); readln("Price for 1 Apple", a_price); readln("Price for 1 Carrot", c_price); writeln("Total for Apples", a_total); writeln("Total for Carrots", c_total); writeln("Total", total); total := a_total + c_total; a_total := apples * a_price; c_total := carrots + c_price; end;
- Me: "Well, your program cannot print the correct results before they are calculated."
- He: "Yeah, itβs logical that this is the right decision, and the computer must correctly reorder the instructions."