Variables and Scope

Variables

When a value is assigned to a variable, the JavaScript engine must determine if it’s a primitive or a reference.

The five primitive types: Undefined,Null, Boolean, Number, and String. These variables are said to be accessed by value, because you are manipulating the actual value stored in the variable.

Reference values are objects stored in memory. Unlike other languages, JavaScript does not permit direct access of memory locations, so direct manipulation of the object’s memory space is not allowed. When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference.

Aside from differences in how they are stored, primitive and reference values act differently when copied from one variable to another. When a primitive value is assigned from one variable to another, the value stored on the variable object is created and copied into the location for the new variable.

When a reference value is assigned from one variable to another, the value stored on the variable object is also copied into the location for the new variable. The difference is that thisvalue is actually a pointerto an object stored on the heap. Once the operation is complete, two variables point to exactly the same object, so changes to one are reflected on the other.

Argument Passing

All function arguments in ECMAScript are passed by value. This means that the value outside of the function is copied into an argument on the inside of the function the same way a value is copied from one variable to another. If the value is primitive, then it acts just like a primitive variable copy, and if the value is a reference, it acts just like a reference variable copy.

When an argument is passed by value, the value is copied into a local variable (a named argument and, in ECMAScript, a slot in the arguments object). When an argument is passed by reference, the location of the value in memory is stored into a local variable, which means that changes to the local variable are reflected outside of the function.

// pass by value 
function addTen(num) {
   num += 10;
   return num;
}
var count = 20;
var result = addTen(count);
alert(count); //20 - no change
alert(result); //30

// pass by value (not reference)

function setName(obj) {
 obj.name = 'Nicholas';
}

var person = new Object();
setName(person);
alert(person.name); // "Nicholas"

// proved pass by value

function setName(obj) {
 obj.name = 'Nicholas';

 // obj is replaced by a new local object 
 obj = new Object();
 obj.name = 'Greg';
}

/*

In this code, an object is created and stored in the 
variable person. This object is then passed into
the setName()  method, where it is copied into obj . 
when the property of obj is changed, it reflects person object. 

But when it is replaced by a local object, 
it won't reflect the change of person object. 

*/
var person = new Object();
setName(person);
alert(person.name); // 'Nicholas'

Put another way, in JavaScript, you cannot pass parameters by reference; that is, if you pass a variable to a function, its value is copied and handled to the function (pass by value). Therefore, the function can't change the variable. If you need to do so, you must wrap the value of the variable in an array.

 function incRef(numberRef) {
  numberRef[0] ++;
 }
 var n = [7];
 incRef(n);
 console. log(n[0]);  // 8

Scope

The execution context of a variable or function defi nes what other data it has access to, as well as how it should behave. Each execution context has an associated variable object upon which all of its defi ned variables and functions exist. This object is not accessible by code but is used behind the scenes to handle data.

The global execution context is the outermost one. In web browsers, the global context is said to be that of the window object. so all global variables and functions are created as properties and methods on the window object.

Each function call has its own execution context. Whenever code execution fl ows into a function, the function’s context is pushed onto a context stack. After the function has fi nished executing, the stack is popped, returning control to the previously executing context. This facility controls execution fl ow throughout an ECMAScript program.

When code is executed in a context, a scope chain of variable objects is created. The purpose of the scope chain is to provide ordered access to all variables and functions that an execution context has access to. The front of the scope chain is always the variable object of the context whose code is executing. If the context is a function, then the activation object is used as the variable object. An activation object starts with a single defi ned variable called arguments. (This doesn’t exist for the global context.) The next variable object in the chain is from the containing context, and the next after that is from the next containing context. This pattern continues until the global context is reached; the global context’s variable object is always the last of the scope chain.

An inner context can access everything from all outer contexts through the scope chain, but the outer contexts cannot access anything within an inner context. The connection between the contexts is linear and ordered. Each context can search up the scope chain for variables and functions, but no context can search down the scope chain into another execution context.

Local object is destroyed as soon as the function fi nishes executing.

No Block-Level Scopes

JavaScript’s lack of block-level scopes is a common source of confusion.

Variable Declaration

When a variable is declared using var, it is automatically added to the most immediate context available. In a function, the most immediate one is the function’s local context;

Garbage Collection

JavaScript is a garbage-collected language, meaning that the execution environment is responsible for managing the memory required during code execution.

Consider the normal life cycle of a local variable in a function. The variable comes into existence during the execution of the function. At that time, memory is allocated on the stack (and possibly on the heap) to provide storage space for the value. The variable is used inside the function and then the function ends. At that point this variable is no longer needed, so its memory can be reclaimed for later use. In this situation, it’s obvious that the variable isn’t needed, but not all situations are as obvious. The garbage collector must keep track of which variables can and can’t be used so it can identify likely candidates for memory reclamation. The strategy for identifying the unused variables may differ on an implementation basis, though two strategies have traditionally been used in browsers.

results matching ""

    No results matching ""