Execution Context and Scope

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

EXECUTION CONTEXT AND SCOPE

Execution context refers to the data that a variable or function has access to.
Each context has a variable object, upon which all of its defined variables and
functions exist
This variable object cannot be accessed via code as this takes place behind the
scenes
The global context is the outermost context in web browsers, the global context
is the window object.
Each function call has its own execution context. When code execution flows into
a function, that functions context is pushed onto a context stack. After the
function is finished executing, the context stack is popped and the returning
control goes to the previous context.
A scope chain refers to such a hierarchy of different contexts, with the front of
the chain being the current active context, with the global context always being
last in the chain
Identifiers are resolved by traveling up this scope chain, starting with the current
context, searching for the identifier name until it is found (if the identifier is not
there, this usually results in an error). The opposite is not true; an outer context
CANNOT access identifiers in tiers below (e.g. context from window cannot
access any identifiers in functions, since they would be nested within this context
by definition) An inner context can access everything

Though there are two primary types of execution contexts, global and function
(and the third exists inside a call to eval()), we can augment the scope chain,
temporarily adding a context to the front of the scope chain the code within that
context is done executing. This is done by
o The catch block in a try-catch statement
o A with statement
Both of these statements add a variable object to the front of the scope chain.
For the with statement, the specified object is added to the scope chain. For the
catch statement, a new variable object is created and contains a declaration for
the thrown error object
JavaScript does not have block-level scoping meaning declarations inside of if,
while, for-loop statements do not affect the scope chain
for (var i=0; I < 10; i++) {
doSomething();
}
alert(i); //10 this is valid!

MEMORY AND GARBAGE COLLECTION


JavaScript utilizes garbage collection to manage memory, freeing this
responsibility from the developer. There are two methods of garbage collection:
o Mark-and-Sweep When a variable goes into context, it is flagged as
being in context, and likewise when it leaves context. The garbage
collector sweeps every set interval amount of time, marking these
variables stored in memory and clearing the variables that are marked out
of context.
o Reference counting less popular; every value has a counter that refers
to the number of references made to that variable. When a variable is
declared and reference value is assigned, it receives a reference count of
1. When the reference count is 0, this indicates that the variable is out of
context and can safely be removed and its memory freed. This method
has issues when dealing with circular references.
In a garbage-collected environment, developers typically do not need to worry
about memory management. However, since we are working in browsers and
memory is limited, a good practice is to dereference values when we are finished
with them. This advice typically applies to globals and properties of these global
values, since local variables are automatically dereferenced when they go out of
scope

********************************************************************************************

5 Reference Types
Reference values, also known as objects, is an instance of a specific reference
type. Since ECMAScript lacks constructs such as classes and interfaces, it is
incorrect to call reference values classes, though they are very similar.
Reference types are also sometimes called object definitions because they
describe the properties and methods that an object should have
Objects are considered to be instances of reference types
New objects are created using the new operator followed by a constructor.
A constructor is a function whose purpose is simply to create a new object.
var person = new Object();
The code above creates a new instance of the Object reference type and stores
it in the person variable

THE OBJECT TYPE


The object type is one of ECMAScripts many available native types.
Functionally, they are not very interesting but they are useful for storing and
transmitting data around an application
There are two ways to explicitly create an instance of an Object
o Using the new operator with the Object constructor
var person = new Object();
person.name = David;
person.age = 22;
o Using object literal notation. Object literal notation is a short-hand form of
object definition designed to simplify the creation of an object with
numerous properties.
var person = {
name: David,
age: 22
};
The left curly brace signifies the beginning of an object literal, because it
occurs in an expression context. We know this because it follows an
assignment operator. That same left curly brace would represent a
statement context if it were to appear following an if statement
Within the object literal notation, colons are used to designate property names with
their values. Commas separate each property in an object literal, but is not
necessary in the last property of an object
Property names can also be specified as strings or numbers in object literal notation
var person = {
name : David,
age : 22,
5: true
};
Note that numeric properties are automatically converted to strings in this format

var person = {}; can be used to rewrite new Object(), though this is
uncommon
Developers tend to favorite object literal notation since it is concise and
encapsulates all of the data. It is also a way to pass a large number of optional
arguments to a function

function displayInfo(args) {
var output = ;

if (typeof args.name == string){


output += Name: + args.name + \n;
}

if (typeof args.age == number) {


output += Age: + args.age + \n;
}

alert(output);
}

displayInfo({
name: Nicholas,
age: 29
});
displayInfo({
name: Greg
});
The function above accepts arguments that have a name property, age property,
both, or neither. This pattern of argument passing is best used whe there are a
large number of optional arguments. In other cases, named parameters work
fine, but can get unruly when a large number are present
Like many other OOP languages, dot notation is used to access object
properties, as well as bracket notation with strings. Both are identical. The
advantage to bracket notation is that it allows for named variables to access
properties, as well as reserved keywords and other illegal characters. Dot-
notation is preferred, unless something can only be accessed via bracket.

alert(person.name); //David
alert(person[name]); //David

var property = name


alert(person[property]) //David
THE ARRAY TYPE
ECMAScript arrays, unlike those of other languages, are not restricted to holding
just one data type in its contents
Arrays are dynamically sized, meaning they grow automatically to accommodate
data that is added
Arrays are created in two different ways
o The array constructor

var colors = new Array(20);

The parameter is optional to be used if you know ahead of time


how many entries the array will have. ECMAScript will give the
arrays length property 20 in this case
The array constructor can also directly accept the contents of the
array

var colors = new Array(red, blue, green);

The new keyword is completely optional when creating arrays

var colors = Array(3);

Do note that it is possible to initialize an Array with a single item,


but when the single argument is a number, it will only create an
empty array with that number initialized as the length property

var arr = new Array(David) //array with one


item, string David

var arr = new Array(5) //array with five items

o Array literal notation

var colors = [red, blue, green]; //create


an array with three strings

var names = []; //creates an empty array

Arrays are zero-based index and accessed through bracket notation


By altering the length property, we can truncate arrays if the new value is less
than the current length. If the new length value is greater, the remaining slots will
return undefined
Array.length can be used to append items to the end of an Array

var colors = [red, blue, green];


colors[colors.length] = white; //now at position 3
colors[colors.length] = black; //now at position 4

Array.isArray() can be used to test if an object is an Array


Arrays toString() and valueOf() method returns the string equivalent values of
each entry in the array, separated by commas

var colors = [red, blue, green];


alert(colors.toString()); //red,blue,green
alert(colors.valueOf()); //red,blue,green
alert(colors); //red,blue,green

That last line also returns the comma separated string listing. Alert expects a
string so the arrays toString() method is called directly

Every object in ECMAScript also has a toLocaleString() method defined. On Arrays,


this is pretty similar to the toString() implementation, except that it will list the
contents of each element by calling their toLocaleString() method instead of
toString()
The join() method of an Array can be used to specify a different separator to list
an Arrays elements, rather than a comma. This is specified by the one parameter
that join accepts. If no parameter is specified, it will just use the comma as a
seperator

var color = [red, blue, green];


alert(color.join(,)); //red,blue,green
alert(color.join(||)); //red||blue||green

If an item in the array is null or undefined, empty strings will be represented


in the output when these methods are called

You might also like