20
Javascript - Variables, Scope, and Memory @farhan_faruque

Javascript - variables, scope, and memory

Embed Size (px)

Citation preview

Page 1: Javascript - variables, scope, and memory

Javascript - Variables, Scope, and Memory

@farhan_faruque

Page 2: Javascript - variables, scope, and memory

PRIMITIVE AND REFERENCE VALUES

Variables may contain two different types of data:● Primitive values are simple atomic pieces of data● Reference values are objects that may be made up of multiple

values

Reference values are objects stored in memory.

Page 3: Javascript - variables, scope, and memory

Dynamic PropertiesWhen we work with reference values, we can add, change, or delete properties and methods at any time.

var person = new Object();person.name = “Farhan”;alert(person.name); //”Farhan”

var name = “Farhan”;name.age = 27;alert(name.age); //undefinedOnly reference values can have properties defined dynamically for later use.

Page 4: Javascript - variables, scope, and memory

Copying Values(primitive type)var num1 = 5;

var num2 = num1;

Variable object before copy Variable object after copy

num1 5(Number type)

num2 5(Number type)

num1 5(Number type)

Page 5: Javascript - variables, scope, and memory

Copying Values(Reference type)var obj1 = new Object(); variable object before copy var obj2 = obj1;obj1.name = “Farhan”;

variable object after copy

object object

object object

object

obj1 Object type

obj2 Object type

obj1 Object type

Page 6: Javascript - variables, scope, and memory

Argument PassingAll function arguments in ECMAScript are passed by value.If the value is primitive, then it acts just like a primitive variablecopy, and if the value is a reference, it acts just like a reference variable copy.

function setName(obj) { obj.name = “Farhan”;}var person = new Object();setName(person);alert(person.name); //”Farhan”

Page 7: Javascript - variables, scope, and memory

Determining TypeThe typeof operator, is the best way to determine if a variable is a primitive type. var s = “Farhan”; alert(typeof s) //string

The instanceof operator returns true if the variable is an instance of the given reference type.alert(person instanceof Object); //is the variable person an Object?

Page 8: Javascript - variables, scope, and memory

EXECUTION CONTEXT AND SCOPE

Each execution context has an associated variable object upon which all of its defined 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.Each function call has its own execution context.Whenever code execution flows into a function

- the function’s context is pushed onto a context stack- after the function has finished executing,the stack is popped- returning control to the previously executing context.

Page 9: Javascript - variables, scope, and memory

ScopeWhen 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.var color = “blue”;function changeColor(){

if (color === “blue”){color = “red”;

} else {color = “blue”;

}}changeColor();changeColor() has a scope chain with two objects in it: its own variable object (upon which the arguments object is defined) and the global context’s variable object

Page 10: Javascript - variables, scope, and memory

Scope Chain AugmentationThere are only two primary types of execution contexts, global and function.Certain statements cause a temporary addition to the front of the scope chain that is later removed after code execution.➢ The catch block in a try-catch statement➢ A with statement

Page 11: Javascript - variables, scope, and memory

No Block-Level Scopesif (true) {var color = “blue”;}alert(color);//”blue

In languages such as C, C++, and Java, that variable would be destroyed after the if statement is executed.In JavaScript, however, the variable declaration adds a variable into the current execution context .

Page 12: Javascript - variables, scope, and memory

Variable DeclarationWhen 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; in a with statement, the most immediate is the function context.function add(num1, num2) {

var sum = num1 + num2;return sum;

}var result = add(10, 20); //30alert(sum); //causes an error since sum is not a valid variable

Page 13: Javascript - variables, scope, and memory

Identifier LookupWhen an identifier is referenced for either reading or writing within a particular context,

- a search must take place to determine what identifier it represents- the search starts at the front of the scope chain- If it finds that identifier name in the local context,then the search

stops and the variable is set- if the search doesn’t find the variable name, it continues along the

scope chain- This process continues until the search reaches the global context’s

variable object.

Page 14: Javascript - variables, scope, and memory

GARBAGE COLLECTIONJavaScript frees developers from worrying about memory management by automatically allocating what is needed and reclaiming memory that is no longer being used.

The basic idea is simple: figure out which variables aren’t going to be used and free the memory associated with them. This process is periodic, with the garbage collector running at specified intervals.

Page 15: Javascript - variables, scope, and memory

Mark-and-SweepA Mark-and-Sweep garbage collector has two phases:Mark: starting from roots, mark all reachable objects by using a depth-first-search pointer traversalSweep: scan the heap from the beginning to the end and reclaim the unmarked objects (and unmark the marked objects).

Internet Explorer, Firefox, Opera, Chrome, and Safari all use mark-and-sweep garbage collection.

Page 16: Javascript - variables, scope, and memory

Reference CountingThe idea is that every value keeps track of how many references are made to it.

- When a variable is declared and a reference value is assigned, the reference count is one

- If another variable is then assigned to the same value, the reference count is incremented

- if a variable with a reference to that value is overwritten with another value, then the reference count is decremented

- When the reference count of a value reaches zero, there is no way to reach that value and it is safe to reclaim the associated memory.

Page 17: Javascript - variables, scope, and memory

circular reference A circular reference occurs when object A has a pointer to object Band object B has a reference to object A.function problem(){

var objectA = new Object();var objectB = new Object();objectA.someOtherObject = objectB;objectB.anotherObject = objectA;

}

Objects in the Browser Object Model (BOM) and Document Object Model (DOM) are implemented as COM (Component Object Model) objects in C++, and COM objects use reference counting for garbage collection.

Page 18: Javascript - variables, scope, and memory

PerformanceIt’s possible, though not recommended, to trigger the garbage-collection process in some browsers. In Internet Explorer, the window.CollectGarbage() method causes garbage collection to occur immediately. In Opera 7 and higher, calling window.opera.collect() initiates the garbage-collection process.

Page 19: Javascript - variables, scope, and memory

Managing MemoryThe best way to optimize memory usage is to ensure that keeping around only data that is necessary for the execution of code. When data is no longer necessary, it’s best to set the value to null, freeing up the reference — this is called dereferencing the value.This advice applies mostly to global values

and properties of global objects.

Page 20: Javascript - variables, scope, and memory

Reference