04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4: Variables, Scope, and Memory<br />

There is a deviation in the Internet Explorer (IE) implementation of JavaScript,<br />

where the error caught in a catch statement is added to the execution context ’s<br />

variable object, making it accessible even outside the catch block.<br />

No Block - Level Scopes<br />

JavaScript ’ s lack of block - level scopes is a common source of confusion. In other C - like languages, code<br />

blocks enclosed by brackets have their own scope (more accurately described as their own execution<br />

context in ECMAScript), allowing conditional definition of variables. For example, the following code<br />

may not act as expected:<br />

if (true) {<br />

var color = “blue”;<br />

}<br />

alert(color);<br />

//”blue”<br />

Here, the variable color is defined inside an if statement. In languages such as C, C++, and Java, that<br />

variable would be destroyed after the if statement is executed. In JavaScript, however, the variable<br />

declaration adds a variable into the current execution context (the global context, in this case). This is<br />

important to keep in mind when dealing with the for statement, which is typically written like this:<br />

for (var i=0; i < 10; i++){<br />

doSomething(i);<br />

}<br />

alert(i); //10<br />

In languages with block - level scoping, the initialization part of the for statement defines variables that<br />

exist only within the context of the loop. In JavaScript, the i variable is created by the for statement and<br />

continues to exist outside the loop after the statement executes.<br />

Variable Declaration<br />

When a variable is declared using var , it is automatically added to the most immediate context<br />

available. In a function, the most immediate one is the function ’ s local context; in a with statement, the<br />

most immediate is the function context. If a variable is initialized without first being declared, it gets<br />

added to the global context automatically, as in this example:<br />

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

var sum = num1 + num2;<br />

return sum;<br />

}<br />

var result = add(10, 20); //30<br />

alert(sum);<br />

//causes an error since sum is not a valid variable<br />

88

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

Saved successfully!

Ooh no, something went wrong!