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.

Variables, Scope,<br />

and Memory<br />

The nature of variables in JavaScript, as defined in ECMA - 262 Third Edition, is quite unique<br />

compared to other languages. Being loosely typed, a variable is literally just a name for a particular<br />

value at a particular time. Because there are no rules defining the type of data that a variable must<br />

hold, a variable ’ s value and data type can change during the lifetime of a script. Though this is an<br />

interesting, powerful, and problematic feature, there are many more complexities related to<br />

variables.<br />

Primitive and Reference Values<br />

ECMAScript variables may contain two different types of data: primitive values and reference<br />

values. Primitive values are simple pieces of data that are stored in memory on the stack , which is to<br />

say that the value is completely stored in one memory location. Reference values , on the other hand,<br />

are objects that are stored on the heap , meaning that the value stored in the variable is actually just<br />

a pointer to another memory location where the object is stored.<br />

When a value is assigned to a variable, the interpreter must determine if it ’ s a primitive or a<br />

reference. The five primitive types were discussed in the previous chapter: Undefined, Null,<br />

Boolean, Number, and String. Each of these data types takes up a fixed amount of space, so values<br />

can easily be stored on the stack. Doing so also allows for fast variable lookup. These variables are<br />

said to be accessed by value , because you are manipulating the actual value stored in the variable.<br />

In many languages, strings are represented by objects and are therefore considered to be reference<br />

types. ECMAScript breaks away from this tradition.<br />

If a reference value is assigned to a variable, space must be allocated on the heap. Reference values<br />

cannot be stored on the stack, because they don ’ t have fixed sizes. A memory address does

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

Saved successfully!

Ooh no, something went wrong!