The second function is more efficient in terms of parsing and execution time compared to the first one, both during page load and when the function is called.
During page load, the interpreter needs to validate the syntax of all the text, create an Abstract Syntax Tree from it, and potentially compile it into machine code on newer engines. Even if most of the code inside function a
is not executed, it still needs to be parsed. Parsing a million lines of JavaScript is a challenging task.
When each function is executed, function a
may take longer to run than function b
, especially if function a
defines many variables within its scope:
function a() {
var a = false;
if(a) {
var b = 'b';
var c = 'c';
// more lines
}
}
During execution, the interpreter has to process all the variables defined within the if
block, even though that block may never execute. This results in hoisting the variable declarations like var b;
and var c
; along with any other var
s to the top:
function a() {
var a;
var b;
var c;
// initialize any other variables local to this function
a = false;
if(a) {
b = 'b';
c = 'c';
// more lines
}
}
If there are many variables to initialize, this process can make the function take slightly longer to execute.
In contrast, a function without unnecessary variable initialization or extra lines to parse like:
function b() {
var a = false;
if (a != true) {
return;
}
}
will have quicker parsing, compilation, and execution times.