04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5: Reference Types<br />

In this example, it ’ s clear that declaring two functions with the same name always results in the last<br />

function overwriting the previous one. This code is almost exactly equivalent to the following:<br />

var addSomeNumber = function (num){<br />

return num + 100;<br />

}<br />

addSomeNumber = function (num) {<br />

return num + 200;<br />

}<br />

var result = addSomeNumber(100); //300<br />

In this rewritten code, it ’ s much easier to see exactly what is going on. The variable addSomeNumber is<br />

simply being overwritten when the second function is created.<br />

Function Declarations vs. Function Expressions<br />

Throughout this section, the function declaration and function expression have been referred to as being<br />

almost equivalent. This hedging is due to one major difference in the way that an interpreter loads data<br />

into the execution context. Function declarations are read and available in an execution context before<br />

any code is executed, whereas function expressions aren ’ t complete until the execution reaches that line<br />

of code. Consider the following:<br />

alert(sum(10,10));<br />

function sum(num1, num2){<br />

return num1 + num2;<br />

}<br />

This code runs perfectly because function declarations are read and added to the execution context<br />

before the code begins running. Changing the function declaration to an initialization, as in the following<br />

example, will cause an error during execution:<br />

alert(sum(10,10));<br />

var sum = function(num1, num2){<br />

return num1 + num2;<br />

};<br />

This updated code will cause an error because the function is part of an initialization statement, not part<br />

of a function declaration. That means the function isn ’ t available in the variable sum until the<br />

highlighted line has been executed, which won ’ t happen, because the first line causes an “ unexpected<br />

identifier ” error.<br />

Aside from this difference in when the function is available by the given name, the two syntaxes are<br />

equivalent.<br />

It is possible to use function declaration and initialization together, such as<br />

var sum = function sum() {} . However this syntax will cause an error in Safari.<br />

124

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!