Advanced Javascript Part I: Gowtham K
Advanced Javascript Part I: Gowtham K
part‐I
Gowtham K
Agenda
• Defini:on
• Quick tour of Basics
• Objects
• Arrays
• Func:ons
• Closures
• Exercises
Defini:ons
• Javascript is a programming language which is
– Object Based
– Impera:ve
– Event Driven
– Func:onal
– Interpreted
– Weakly Typed
• An implementa:on of the ECMAScript language
standard
• Primarily executed in browsers, but suited for server
side execu:on as well.
• Not even remotely related to Java. The naming is a
Marke:ng gimmick by suits!
Datatypes
• Javascript allows you to work with five primi:ve
data types
– Numbers
– Strings
– Boolean
– null
– undefined
• Everything else is a composite data type called
Object
• Primi:ve types are also objects internally.
Numbers
• All Real numbers fall under numbers data type.
• No separate int, double or float data types.
• Represented as 64‐bit (double precision) floa:ng
point numbers internally
• Numbers Datatype also supports a special value –
NaN – Not a Number.
• NaN is a result of undefined or erroneous
opera:on. Eg: 10/0
• NaN is not equal to anything, including itself!
Strings
• A string is a sequence of Unicode le_ers.
• No separate char type. A character is string of
length 1.
• Strings are immutable
• String literals use either single or double quotes.
• Can be concatenated using a ‘+’ operator and
compared using ‘==’ operator.
• Important proper:es of String object – length,
charAt, subString, indexOf.
Boolean
• true and false are the only possible values.
• Result of any logical opera:ons
• Following are falsy values
– false
– null
– undefined
– “”
– 0
– NaN
Null & undefined
• Null ‐ A value that isn’t anything.
• undefined – A value whose value can’t be
determined. Not even Null.
• prin:ng a variable that was never defined in code
prints undefined
Objects
• Collec:on of key‐value pairs
• Key is any valid iden:fier. (numeric also possible)
• Value can be a number, string, boolean, null,
undefined, NaN or another object.
• One way to create object is to use object literal
var obj = {}; //empty object
var point = { //object with 2 keys
x:2,
y:2
};
The new keyword
• Second way to create objects.
• The new keyword can be used in conjunc:on
with constructor func:on to create objects of
the constructor type.
• Object is a constructor offered by Javascript
that creates a generic empty object
var obj = new Object();
• Likewise, new can be used to create specialized
objects.
var a = new Array() //empty array
var b = new Date() //Date object
Object Proper:es
• Keys are proper:es of object.
• Dot nota:on to access proper:es of object.
point.x = 1;
point.y = 2;
alert(“title: ”+book.chapter.title);
• Familiar. Easier to comprehend. Faster to
process.
Objects as Associa:ve Arrays
• Another way to access object proper:es is by
using [] operator.
point[“x”];
book[“chapter”][“title”];
• Wait. This looks like associa:ve array or Hash
table!
• Yes, indeed. Objects are associa:ve arrays in
Javascript.
• It is technically possible, but useless to
differen:ate.
Enumera:ng Proper:es
• Using array‐like nota:on to access proper:es
has its own advantages
• Proper:es can be accessed dynamically
function getProperty(key){
return obj[key];
}
• in operator can be used to enumerate
proper:es and traverse object.
for(var key in obj){
alert(“value of ”+key+” is ”+obj[key]);
}
Objects are Dynamic
• Javascript is loosely typed.
• Proper:es can be added/deleted to/from
object (thus changing its type)
• Akin to Hash Table, but hashing nature is
transparent (no hash codes, rehash method)
var circle = {
radius:2
}; //circle object with one property
function addColor(c){
circle.color = c; //now circle also has
//color
}
Arrays
• Number, string, boolean, null, undefined, NaN
and Object are the only types recognized by
Javascript
• What about arrays?
• “Everything else is an object”. Arrays are also
objects
• Recall that numeric keys are allowed in objects
Var arr = {
0:1,
1:2
};
Arrays (contd)
for(var i in arr){
console.log(arr[i]+”,”); //1,2,
}
• However, numeric keys can’t be accessed via dot
nota:on
console.log(arr.0) //Syntax Error!
Console.log(arr[0])//prints 1
The Array Class
• Arrays are so frequently used in programming.
• Language support for a variety of opera:ons
over Arrays is necessary.
• Javascript provides the support through the
Array class.
var arr = new Array(1,2,3);
• arr is an object with numeric keys and
variety of proper:es as well as methods to
support array style opera:ons
The Array Class (contd)
• C‐style array itera:on possible with length
property.
for(var i=0;i<arr.length;i++){
console.log(arr[i]);
}
• Push, pop, concat, join, slice, splice, sort
are methods available in Array class.
The Array Literal
• To further ease usage of arrays, array literal ([])
has been provided
var arr = [1,2,3]; //equivalent to new
//Array(1,2,3);
• arr has all proper:es of an object created with
Array class
• Arrays need not be homogenous.
var arr = [1,”hello world”,{x:1,y:2},null];
• Before we move on, mind the fact that arrays are
objects in Javascript
Func:ons
• Javascript implementa:on of func:ons is what
differs it from other programming languages, in a
significant way.
• Defined and invoked in conven:onal way.
function printMsg(msg){
console.log(msg);
}
printMsg(“hello world!”);
• Loosely typed – no type checking for arguments,
no return type. Should rely on documenta:on.
/* void */ function printMsg(/*String*/ msg);
Func:ons ‐ Arguments
• Pass by value or reference?
– Primi:ve types are passed by value.
– Objects are passed by reference.
• Strings?
– Strings are immutable. So the argument is moot.
• Op:onal arguments
– Check whether op:onal argument is undefined.
• Variable number of arguments – the arguments
object.
– max func:on can be wri_en for any number of args
Func:ons – first class objects
• Can be defined passed, returned and stored just
like any other value.
• The following is a perfectly valid Javascript
var point = {
x:3,
y:4,
distance:function(a,b){
return Math.sqrt(a*a + b*b);
}
};
console.log(point.distance(point.x,point.y));
/*prints 5*/
Func:ons as Methods
• Func:ons can be stored in proper:es of an object
(previous example)
• In such case, func:on is method of that object.
• The this keyword has special meaning inside a
method. It points to the object to which current
func:on belongs.
• In previous example, this.x and this.y refer to
variables x and y of the point object.
• What would this point to in a func:on defined
in global scope?
The this Keyword
var print = function(){
console.log(this.name);
};
var person = {
name:”Bob”,
printName:print
};
var dog = {
name:”Scooby”,
printName:print
};
print();
Person.printName();
Dog.printName();
The this Confusion
• Inside a method, the this keyword always
points to current object even in Java and C++.
However, unlike those languages, func:ons are
first class in Javascript. Same func:on can be a
method of two completely unrelated objects, in
which case this points to the object whose
method is currently being executed.
• A metaphor: What you mean by ‘my city’
depends on where you are staying. It may be
Bangalore or Sunnyvale.
Func:ons – Data Type
• What would be the data type of func:on?
– “Everything else is an object”. Func:ons too are objects
with special proper:es.
• Constructor of func:on objects is Function
function printMsg(msg){
console.log(msg);
}
console.log(printMsg.constructor); //prints “Function”
• What are the proper:es of func:on objects?
– call()
– apply()
– prototype (will revisit shortly)
Func:ons – call and apply Methods
• You want to execute a func:on as a method of
an object without actually making it a method.
• That means you should be able to dictate
what this points inside a func:on. Call allows
you to do that
• Call method invokes the func:on and makes
the first argument as this inside the func:on.
• Apply also similar. Takes list of arguments
instead of values.
• Makes more sense with inner func:ons.
Func:ons – Call Example
var TwoDPoint = {
x:3,
y:4
distance:function(){
return Math.sqrt(this.x*this.x + this.y*this.y);
};
};
var ThreeDPoint = {
x:6,
y:8,
z:10,
XYProjectionLength:function(){
TwoDpoint.distance.call(this);
};
};
Nested Func:ons
• Func:ons are first class => func:ons should be
able to create func:ons => Nested func:ons are
possible
function binaryAdderGenerator(x,y){
return (function(){return x+y;});
}
var add_2_3 = binaryAdderGenerator(2,3);
alert(add_2_3()); //alerts 5
Func:ons – Scope
• Func:on and only a func:on can define scope in
Javascript. Everything else is in global scope.
– No language constructs for namespaces
– No Block Scope
• Local variables take precedence over global
variables.
var x = 2;
function alertX(){
var x = 3;
alert(x); //prints 3
}
Func:ons – Call Object & Scope Chain
Like C/Java, every func:on will have an ac:va:on
record (Call object) on call stack (Scope Chain).
function f(){
var x = 2, y=3; h
function g(){ sum(13)
var y = 5;
var z = 6;
function h(){ g
var sum; y(5),z(6)
sum = x+y+z;
}
h(); f
} x(2),y(3)
g();
}
var x = 1; global
f(); x(1)
Func:ons – Lexical Scope
• Javascript func:ons are lexically scoped.
– Run in scope where they are defined Vs where they
are executed
• What would be the output?
function binaryAdderGenerator(x,y){
return (function(){return x+y;});
}
var adder_2_3 = binaryAdderGenerator(2,3);
var adder_5_6 = binaryAdderGenerator(5,6);
alert(adder_2_3());
alert(adder_5_6());
Func:ons – Closures
• Observe binaryAdderGenerator
– Variables defined in binaryAdderGenerator scope
are available even ater it exited. Func:on scope lives
on even ater func:on is dead. Ghost!
• A deliberate design decision to provide what is
called closure ‐ A First‐class func:on with free
variables that are bound in the lexical environment
• An important ingredient of func:onal
programming.
• Closures preserve a state that can be accessed
only by the inner func:on ‐ A property that gives
Javascript immense expressiveness.
Using Closures – Private Variables
• Unlike OO languages like C++/Java, JS lacks formal
support for access control.
• Closures make up for it.
function decryptGenerator(){
var key = 92p4508f49;
return (function(crypticText){
/*decrypt using key and return*/
});
}
/*key is not accessible here*/
var decrypt = decryptGenerator();
var plainText = decrypt(cipher);
Private Variables – More Prac:cal Eg
function personGenerator(name,age,SSN){
return {
getName:function(){
return name;
},
setName:function(newName){
name = newName;
}
};
}
var person = personGenerator(“Mark”,26,423958);
var name = person.getName(); /*only way to get
person’s name*/
Using Closures – Event Handlers
• Event handler is executed only when event fires.
• May have to maintain a state between execu:ons.
var toggleFont = (function(){
var fonts = [12,14],current=0;
return (function(){
current = (current+1)%2;
document.body.style.fontSize =
fonts[current]+“px”;
});
})();
document.getElementById(’fontLink').onclick =
toggleFont;
Using Closures – Asynchronous calls
• Asynchronous calls are those func:on calls which take
a callback func:on and execute it to signal finish of its
opera:on.
• Like event handlers, async callbacks make use of
Closures to keep tack of the state.
function addName(newName){
var callback = function(status){
if(status==200)
alert(newName+” added to Database”);
else
alert(“addition of ”+newName+” failed”);
}
api.makeXHR({“action”:”addName”,
”name”:newName}, callback);
}
addName(“Mark”);
Using Closures – Async in loop
• Consider the following code. What does it alert?
function delayedAlert(namesList){
for(var i=0;i<namesList.length;i++){
var name = namesList[i];
var callback = function(){
alert(name);
};
setTimeout(callback,100);
}
}
delayedAlert([“citius”,”altius”,”fortius”]);
Using Anonymous Closures
• Beware loops while crea:ng closures. Corrected ‐
function delayedAlert(namesList){
for(var i=0;i<namesList.length;i++){
var name = namesList[i];
/*Anonymous closure to hold name*/
var callback = (function(name){
function(){
alert(name);
};
})(name);
setTimeout(callback,100);
}
}
delayedAlert(["citius","altius","fortius"]);
Func:ons – Call Object Life Cycle
• If every func:on execu:on is going to leave a
closure trail, we’d eventually run out of space.
• Only those closures which are reachable from
current scope stay in memory. Rest will be garbage
collected.
• Colloquially, Not all ghosts are going to s:ck
around. Only those who are ‘in the memory’ of
living ones remain.
• Revisit scope chain
• Remember: Call objects are created in Heap
memory.
Execu:on Context Vs Scope
function personGenerator(name,age,SSN){
return {
name:name,
age:age,
SSN:SSN,
getName:function(){
return name;
},
setName:function(newName){
this.name = newName;
}
};
}
var person = personGenerator(“Mark”,26,423958);
person.setName(“Larry”);
alert(person.getName()); //alerts Mark
Execu:on Context Vs Scope(2)
• this keyword points to the execu:on context of
current program whereas closure is a concept
related to scope.
• Both are orthogonal concepts.
• Imagine execu:on context as consciousness of
your locality i.e., where you belong. eg: your city
• Closure can be imagined as your private space,
where only you have access.
• Dis:nc:on has to be minded to avoid confusion.
That’s it for now!
• Object Oriented Programming Constructs will be
dealt in next class
• References
Javascript: The definitive Guide by David Flanagan!
Javascript: The good parts by Douglas Crockford!
https://developer.mozilla.org/en/a_re-introduction_to_javascript!
https://developer.mozilla.org/en/JavaScript/Guide/Closures!
http://en.wikipedia.org/wiki/Closure_(computer_programming)!
• This slide deck can be found online at
h_p://gowthamkaki.info