Variables, Scope and Memory

I covered variables in the last section and will now cover primitive and reference values in variables, I will look at execution context and explain garbage collection.

Primitive and Reference Values

Variabes can contain types tupes of data

Primitive values are accessed by value because you are manipulating the actual value stored in the variable. Reference values are objects stored in memory, the variable is a reference (pointer) to the object in memory, so they are accessed by reference

Reference values you can add, change or delete properties (dynamically), you cannot do this with Primitive values.

When you copy a Primitive value you copy the value, there is no reference to the original Primitive value, with a Reference value you copy the pointer referencing the object, the both point to the same object in memory so both variables can change the same object.

When using function Primitives are passed by copy and Reference are passed by Reference

function Primitive and Reference value passing example
let obj1 = new Object();
obj1.name = "Paul";                     // with Reference values to can add properties

primVar1 = "Valle";

console.log("Before function: " + obj1.name + " " + primVar1);          // Paul Valle
test(obj1, primVar1);

function test(obj1, primVar1) {
    console.log("Before change: " + obj1.name + " " + primVar1);        // Paul Valle
    obj1.name = "Will";
    primVar1 = "Hay";
    console.log("After change: " + obj1.name + " " + primVar1);         // Will Hay
}

console.log("After function: " + obj1.name + " " + primVar1);           // Will Valle


output
--------------------------------------
Before function: Paul Valle
Before change: Paul Valle
After change: Will Hay
After function: Will Valle

You can use the typeof operator to determine the type of of a variable and instanceof to determine if a object is of a reference type

typeof
let s = "Nicholas";
let b = true;
let i = 22;
let u;
let n = null;
let o = new Object();

console.log(typeof s);                 // string
console.log(typeof i);                 // number
console.log(typeof b);                 // boolean
console.log(typeof u);                 // undefined
console.log(typeof n);                 // object
console.log(typeof o);                 // object
instanceof
console.log(person instanceof Object); // is the variable person an Object?
console.log(colors instanceof Array); // is the variable colors an Array?
console.log(pattern instanceof RegExp); // is the variable pattern a RegExp?

Execution Context and Scope

Execution context is simply refered to as context, it defines the context a variable or function has access to, as well as how it should behave. The global execution context is the outer most, in a web browser the global context is the window object. Declarations using let and const at the top level are not defined in the global context but they resolve identically on the scope chain. When execution context has executed all of its code is destroyed taking all the variables and functions with it, the global context is only destroyed when the application exits.

In the below image when the code enters into each function it gets its own execution context, this context is pushed onto the stack, if a function calls another function it to gets its own execution context and again it gets pushhed onto the stack , when the function has finished the execution context gets destroyed. Each execution context has a scope chain of variable objects is created. The purpose of the chain is to provide ordered access to all variables and functions the execution context has access to. The Global execution context is always the last in the chain. Identifiers are resolved by navigating the scope chain in search of the identifier name. The search always begins at the front of the chain and proceeds to the back until the identifier is found.


Global and local variables
let name = "Paul";                  // Global name

function first() {
    let a = "Hello ";
    second();
    
    // name is searched through the whole execution chain stack
    // it will use the Global name variable "Paul"
    let x = a + name;
    
    displayName(x)
}

function second() {
    let name = "Lorraine"           // only used by this function only
    let b = "Hi ";
    third();
    let y = b + name;               // will use local name variable "Lorraine"
    displayName(y)
}

function third() {
    let c = "Hey ";

    // name is searched through the whole execution chain stack,
    // it will search for global name not the local one in function second()
    
    let z = c + name;                // will use the Global name variable "Paul"

    displayName(z)
}

function displayName(name) {
    console.log(name);
}

first();

There are two instances where variables are added to the front of the execution stack, the catch block in a try-catch statement and using the with statement.

Garbage Collection

I am not going to go into garbage collection with get detail but if you have used Java then the principles are the same, the garbage collector will run periodically (you can ask the grabage collector to run but this will probably be ingored) for objects that are no longer needed, the objects are know to be dereferenced no longer used by the application, the objects will be removed from memory and thus freeing up memory resources. As garbage collection is an expensive operation it will run periodically unless memory is on short supply, when using the Java Virtual Machine there are a number of options to increase garbage collectors performance but this is out of the scope of this basic tutorial. For a basic application the standard options are a good place to start, if your application is memory hungry then it would be wise to see what options the garbage collector has to increase performance. To stop memory leaks (objects using memory that are no longer needed) it is best to null the variable that points to the object (object will no longer have any pointers attached and thus its deferenced) which incidates that it is available for garbage collection.

I have a more information on garbage collection in my Java section.