SlideShare a Scribd company logo
JavaScript Yoav Rubin,  [email_address] 24.06.10
A little bit about myself Graduated from the CS faculty in 2001 Started to work in IBM research – Haifa about a year before that In the domains of visual programming environments, end user development, cloud computing  Extensive usage of Java and JavaScript Source: If applicable, describe source origin
JavaScript The language of the web Web applications Mobile applications Dynamic language Dynamic typing Dynamic binding No compilation till execution time
How would you summarize JavaScript in one sentence: Everything is dynamic Code simplification Exactly what web apps developers need (because the web is a hostile platform, and the mobile web is even worse) JavaScript
Type system Prototypes and inheritance Functions as first class citizens Closures Dynamic binding What will  we cover
JavaScript type system
Types Number – a 64 bit (a.k.a double) No integer String immutable No char Boolean Objects Array Function Unit types null undefined NaN
Type system Strongly typed (loose definition) With clear coercion rules == , !=  a comparison without type coercion ===, !== a comparison with type coercion 4 == ‘4’; //true 4 === ‘4’ // false The type of a variable can be determined using the ‘typeof’ operator Dynamic typing The type is not declared var a = 3; // number Changing the variable’s content changes its type a = ‘s’; // string Type rules are enforced at runtime
Everything is a boolean Strongly typed, but still… Everything in JavaScript has its boolean interpretation Usually referred as ‘truthy’ and ‘falsy’ These values are interpreted as false when needed: 0, “”, null, undefined, NaN, false Everything else is true What is it good for ?
Everything is a boolean – what is it good for? Part of an ‘if’ statement All of the following statements are equivalent If(a != null) If(a) If(a !== null && a !== undefined && a !== ‘’ && a !== 0 &&  a !== NaN &&  a !== false)
Everything is boolean – what is it good for? Logical and (&&) Receives two operands If the first operand is truthy, then returns the second operand’s  value Otherwise returns the first one Sometimes called the guard operator var val; If(obj){ val = obj.methodCall(); } else{ val = obj; } var val = obj && obj.methodCall();
Everything is boolean – what is it good for? Logical or (||) Receives two operands If the first operand is falsy, then returns the second operand’s  value Otherwise returns the first one Sometimes called the default operator var val; If(possibleVal){ val = possibleVal; } else{ val = defaultVal; } var val = possibleVal ||  defaultVal;
Objects are objects An object is a collection of things (fields) Data (members) Functions (methods) A set of mappings between a name of a field (key) to the field (value), done using one of these ways: anObject.fieldName = 3; anObject[“fieldName”] = 3; (*)these lines are usually equivalent Just like a hashmap (without hash value and rehash)  The mapping can be changed in run-time It is possible to replace a method with another method Still, there is a way to extend objects based on other  objects   (note - not classes)
I’ll have what she’s having – prototypal inheritance
The prototype The prototype is an object Just like any other object Each object can act as a prototype Each object has a prototype This is a hidden link  Created when the object is created Cannot be changed The prototype itself can be changed Just like any other object
The prototype – when is it used? Inheritance - using functionality declared elsewhere On access to a field of an object  WHEN  this field is not part of that object The object’s prototype is accessed for that field And then the prototype’s prototype This goes all the way till the prototype of Object A nice metaphor for it is that an object is a transparency placed on top of its prototype
The prototype (pType) The object (theObject) theObject.age;   // 32 pType.age ++; The object (theObject) The prototype (pType) theObject.age;   // 33 delete theObject.age;   // nothing happens theObject.age;   // 33 delete pType.age;   // no more age field theObject.age;   // undefined “ Mr” title: “ barber” job: 32 age: “ Jeff” name: “ Mr” title: “ barber” job: 33 age: “ Jeff” name:
The prototype (pType) The object (theObject) theObject.age;   // 32 theObject.age ++;   //  value read from pType, added to theObject The object (theObject) The prototype (pType) theObject.age;   // 33 delete theObject.age;   //  no more age member in theObject theObject.age;   // 32 delete pType.age; theObject.age;   // undefined “ Mr” title: “ barber” job: 32 age: “ Jeff” name: “ Mr” title: “ barber” job: 32 age: “ Jeff” name: 33 age:
Polymorphism  One of the most important attributes of OO languages JavaScript’s objects are not rigid enough to provide single-morphism There are JavaScript toolkits that add this functionality to the language The most renown for it is the “Dojo Toolkit”
(From the tyranny of the compiler)
Functions
Functions are objects Have members e.g., length (the number of arguments in the function’s declaration) Have methods E.g., toString (returns a string containing the function’s signature and body) Are first class citizens Can be sent as arguments to a function Can be returned as a return value from a function Can be executed
function add(a,b){ return a+b; }; add.length; // 2 add.toString();  // “function add(a,b){return a+b;}” Functions are objects
More about functions Can be defined within another function In that case the inner function knows of all the things defined within the outer function This is called closure What is it good for?
Write a function that calculates the fibonacci value of a number
Classic solution  function fib(n){ if(n < 2)  return n; return fib(n-1) + fib(n-2)  } fib(10) results in 177 calls to the fib function
Solution with closure function fastFib(n){ var memo = [0,1]; var fib =   function(n){ var result = memo[n]; if(result === undefined){ result = fib(n-1) +fib(n-2); memo[n] = result; } return result; } return fib(n);  } fastFib(10) results in 19 calls to the fib function  This pattern is nicknamed memoization
Functions - what else is dynamic  Every time a function is executed it has a built in array-like variable called ‘arguments’ It holds the set of arguments sent in the function call arguments[i] is the i-th argument in the function call This is needed since the function’s signature is just like road signs in Rome Recommendation only It is valid to call the function with either more or less arguments then in its signature
Functions – arguments  vs  length func.length > arguments.length The last (func.length - arguments.length) have the value of undefined func.length < arguments.length The last (arguments.length - func.length) are accessible only from the arguments variable func.length == arguments.length No problem
Functions – what’s ‘this’ Every time a function is executed it has a built in variable called ‘this’ ‘this’ points out to the context in which the function would run The context is bound to the function The binding is done in run-time The binding is dependant  upon the way  the function was called There are 4 forms a function can be called
Function call forms Method form Function form Apply form Constructor form
The method form The function is a field of an object The call is written in the following way:  theObject.FuncName(); The ‘this’ variable points out to theObject
The function form The call is written in the following way:  funcName(); The ‘this’ variable points out to the global object This call form makes the usage of helper function within other function to be sometimes tricky
The apply form Each function has a function called ‘apply’ Receives two arguments An object that would act as the ‘this’ variable when the function is executed An Array that would act as the ‘arguments’ variable when the function is executed The call is written in the following way:  funcName.apply(thisPtr, [newArgs]);
The constructor form Constructors are the only element in JavaScript that starts with capital letters Though this is just a convention Used to create and initialize a specific object The ‘this’ variable points out to a newly created object If the function has a field called ‘prototype’ then this field is the prototype of the created element This call is written in the following way:   var newMyObj = new MyObject();
Constructor form – an example function AA (name, title) { this.name = name; this.title = title; } AA.prototype = {‘height’:3}; var a = new AA(“John”, “Mr”); function AA (name, title) { this = {}; this.linkToPrototype =  AA.prototype || Object.prototype; this.name = name; this.title = title; return this; } a.name; // “John” a.title;   // “Mr” a.height; // 3 The code Behind the scenes of the constructor The result
Call forms “ The binding is dependant  upon the way  the function was called”   var obj = {}; obj.f = f; obj.f(); obj.a ;   //   3 f();   // now there’s a global variable a whose value is 3 var newObj = new f(); newObj.a; // 3 var str = ‘xyz’; f.apply(str,[]); str.a; // 3 function f(){this.a = 3}; Method form Function form Constructor form Apply form
What about access rights? There are no access rights in JavaScript Everything is public, there is no such thing as ‘private’ The various function execution forms simply deflate this important concept  However, it is possible to mimic a private access right for a field in an object Done using closure
function Counter(){ var count = 0; this.getValue = function(){ return count ;}; this.increase = function(){count ++;}; this.decrease = function(){count --;}; this.setValue = function(newVal){count = newVal;}; } var c = new Counter();  c.setValue(5);  c.increase();  c.getValue();  // 6 c. count;  // undefined public public public public private
Anonymous functions Functions doesn’t have to have an identifier They can be anonymous Becomes very useful when combined with immediate execution of the function
Write a function that receives an array of objects and sets their  showIndex  method to show their index in that array
Bad solution function(objs){ for(var i=0,l=objs.length;i<l;i++)  { objs [i].showIndex =  function(){ alert(i); }   } } What will be alerted?
Good solution function(objs){ for(var i=0,l=objs.length;i<l;i++)  { objs[i].showIndex = ( function(t){  // a function that returns a function,  t here is a local variable return   function() { // this function sees the local variable ‘t’ of the red function alert(t); } } )(i);   // executing the red function } }
“Everything should be made as simple   as possible, but not simpler” Albert Einstein
What happens when things are too simple (the dark side of JavaScript)
Two scopes In JavaScript there are two scopes only The global scope The function scope No block scope
Global as the default scope The default scope for variable definition is the global scope function (){ var a = 3;  // local variable b = 4;  // global variable } Whenever a function is executed in the function form, ‘this’ points out to the global scope And the function form is the simplest one => the one most novice developers would use unwittingly  It is very simple to pollute the global scope
Semicolon insertion You don’t have to write semicolon at the end of a code line The run-time compiler does it for you This may lead to errors that are hard to find function f1 (){ return {val: 4}; }; function f1 (){ return; {val: 4}; }; var a = f1();   // undefined What the developer wrote Behind the scenes of the function The result
The ‘with’ keyword Define a scope for a block Intended to be used as a  short hand a.b.c = a.b.d +a.b.e; with(a.b){ c=d+e; }
with(obj){ a = b }  if(obj.a === undefined){ if(obj.b === undefined){ a=b ;// two global variables }  else  { a = obj.b;   // a is global, b is not }  else { if(obj.b === undefined){ obj.a=b;   // b is global , a not }  else { obj.a = obj.b;   // both not global } } The ‘with’ keyword obj.a = obj.b;   // both not global obj.a = b;   // b is global, a is not + a = obj.b;   //  a is global, b not a=b;   // two global variables - + - a\b   (exist in obj)
Bitwise operators JavaScript supports bitwise operators: & , |, ^ , >>, << , >>> But JavaScript have only 64 bit number type No integer Bitwise operators are used for faster, close to the hardware computations In JavaScript this is not the case
Numerical calculations All calculations in JavaScript are floating point calculation 10 / 3 = 3.3333333333333335 Simply put – erroneous when the decimal point is involve 0.1 + 0.2 =  0.30000000004
The utility parseInt ParseInt(stingValue, radix) Strings that start with 0x are treated as hexadecimal Strings that start with 0 are treated as octal based parseInt(“08”) and parseInt(“09”) returns undefined Used often when parsing dates
Remember this ? Imperative With prototypes (object-based, but not object-oriented) Functions are first-class entities Has lambda functions With closures Is weakly typed Has dynamic typing Has dynamic binding
Thank You

More Related Content

What's hot (20)

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
C questions
C questionsC questions
C questions
parm112
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
ramya marichamy
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
Michael Stal
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Pranali Chaudhari
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
Lovely Professional University
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
2.dynamic
2.dynamic2.dynamic
2.dynamic
bashcode
 
Applicative Functor
Applicative FunctorApplicative Functor
Applicative Functor
Philip Schwarz
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Prof .Pragati Khade
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
Robbin Zhao
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
Knoldus Inc.
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
C questions
C questionsC questions
C questions
parm112
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
ramya marichamy
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
Michael Stal
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
Dmitri Nesteruk
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
Alexis Gallagher
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
Robbin Zhao
 
DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#DISE - Windows Based Application Development in C#
DISE - Windows Based Application Development in C#
Rasan Samarasinghe
 
Shapeless- Generic programming for Scala
Shapeless- Generic programming for ScalaShapeless- Generic programming for Scala
Shapeless- Generic programming for Scala
Knoldus Inc.
 

Viewers also liked (11)

Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
JavaScript
JavaScriptJavaScript
JavaScript
Matheus Soares
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Java script ppt
Java script pptJava script ppt
Java script ppt
The Health and Social Care Information Centre
 
Javascript
JavascriptJavascript
Javascript
guest03a6e6
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
guestceb98b
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
Collaboration Technologies
 
Pragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScriptPragmatic Parallels: Java and JavaScript
Pragmatic Parallels: Java and JavaScript
davejohnson
 
The JavaScript Programming Primer
The JavaScript  Programming PrimerThe JavaScript  Programming Primer
The JavaScript Programming Primer
Mike Wilcox
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
guestceb98b
 
Ad

Similar to JavaScript - Programming Languages course (20)

Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
David Atchley
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Js in-ten-minutes
Js in-ten-minutesJs in-ten-minutes
Js in-ten-minutes
Phong Vân
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
deannalagason
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
François Sarradin
 
Javascript
JavascriptJavascript
Javascript
Aditya Gaur
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
Daniel Cousineau
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
All of javascript
All of javascriptAll of javascript
All of javascript
Togakangaroo
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
vivek p s
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Rediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison
 
Js in-ten-minutes
Js in-ten-minutesJs in-ten-minutes
Js in-ten-minutes
Phong Vân
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
Donald Sipe
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
Manish Jangir
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
Vijay Kalyan
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
Douglas Crockford Presentation Goodparts
Douglas Crockford Presentation GoodpartsDouglas Crockford Presentation Goodparts
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
Srdjan Strbanovic
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
vivek p s
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Ad

More from yoavrubin (6)

CR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologistCR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologist
yoavrubin
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
yoavrubin
 
Clojure's take on concurrency
Clojure's take on concurrencyClojure's take on concurrency
Clojure's take on concurrency
yoavrubin
 
Functional OOP, Clojure style
Functional OOP, Clojure styleFunctional OOP, Clojure style
Functional OOP, Clojure style
yoavrubin
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
yoavrubin
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web apps
yoavrubin
 
CR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologistCR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologist
yoavrubin
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
yoavrubin
 
Clojure's take on concurrency
Clojure's take on concurrencyClojure's take on concurrency
Clojure's take on concurrency
yoavrubin
 
Functional OOP, Clojure style
Functional OOP, Clojure styleFunctional OOP, Clojure style
Functional OOP, Clojure style
yoavrubin
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
yoavrubin
 
Dojo - from web page to web apps
Dojo - from web page to web appsDojo - from web page to web apps
Dojo - from web page to web apps
yoavrubin
 

JavaScript - Programming Languages course

  • 1. JavaScript Yoav Rubin, [email_address] 24.06.10
  • 2. A little bit about myself Graduated from the CS faculty in 2001 Started to work in IBM research – Haifa about a year before that In the domains of visual programming environments, end user development, cloud computing Extensive usage of Java and JavaScript Source: If applicable, describe source origin
  • 3. JavaScript The language of the web Web applications Mobile applications Dynamic language Dynamic typing Dynamic binding No compilation till execution time
  • 4. How would you summarize JavaScript in one sentence: Everything is dynamic Code simplification Exactly what web apps developers need (because the web is a hostile platform, and the mobile web is even worse) JavaScript
  • 5. Type system Prototypes and inheritance Functions as first class citizens Closures Dynamic binding What will we cover
  • 7. Types Number – a 64 bit (a.k.a double) No integer String immutable No char Boolean Objects Array Function Unit types null undefined NaN
  • 8. Type system Strongly typed (loose definition) With clear coercion rules == , != a comparison without type coercion ===, !== a comparison with type coercion 4 == ‘4’; //true 4 === ‘4’ // false The type of a variable can be determined using the ‘typeof’ operator Dynamic typing The type is not declared var a = 3; // number Changing the variable’s content changes its type a = ‘s’; // string Type rules are enforced at runtime
  • 9. Everything is a boolean Strongly typed, but still… Everything in JavaScript has its boolean interpretation Usually referred as ‘truthy’ and ‘falsy’ These values are interpreted as false when needed: 0, “”, null, undefined, NaN, false Everything else is true What is it good for ?
  • 10. Everything is a boolean – what is it good for? Part of an ‘if’ statement All of the following statements are equivalent If(a != null) If(a) If(a !== null && a !== undefined && a !== ‘’ && a !== 0 && a !== NaN && a !== false)
  • 11. Everything is boolean – what is it good for? Logical and (&&) Receives two operands If the first operand is truthy, then returns the second operand’s value Otherwise returns the first one Sometimes called the guard operator var val; If(obj){ val = obj.methodCall(); } else{ val = obj; } var val = obj && obj.methodCall();
  • 12. Everything is boolean – what is it good for? Logical or (||) Receives two operands If the first operand is falsy, then returns the second operand’s value Otherwise returns the first one Sometimes called the default operator var val; If(possibleVal){ val = possibleVal; } else{ val = defaultVal; } var val = possibleVal || defaultVal;
  • 13. Objects are objects An object is a collection of things (fields) Data (members) Functions (methods) A set of mappings between a name of a field (key) to the field (value), done using one of these ways: anObject.fieldName = 3; anObject[“fieldName”] = 3; (*)these lines are usually equivalent Just like a hashmap (without hash value and rehash) The mapping can be changed in run-time It is possible to replace a method with another method Still, there is a way to extend objects based on other objects (note - not classes)
  • 14. I’ll have what she’s having – prototypal inheritance
  • 15. The prototype The prototype is an object Just like any other object Each object can act as a prototype Each object has a prototype This is a hidden link Created when the object is created Cannot be changed The prototype itself can be changed Just like any other object
  • 16. The prototype – when is it used? Inheritance - using functionality declared elsewhere On access to a field of an object WHEN this field is not part of that object The object’s prototype is accessed for that field And then the prototype’s prototype This goes all the way till the prototype of Object A nice metaphor for it is that an object is a transparency placed on top of its prototype
  • 17. The prototype (pType) The object (theObject) theObject.age; // 32 pType.age ++; The object (theObject) The prototype (pType) theObject.age; // 33 delete theObject.age; // nothing happens theObject.age; // 33 delete pType.age; // no more age field theObject.age; // undefined “ Mr” title: “ barber” job: 32 age: “ Jeff” name: “ Mr” title: “ barber” job: 33 age: “ Jeff” name:
  • 18. The prototype (pType) The object (theObject) theObject.age; // 32 theObject.age ++; // value read from pType, added to theObject The object (theObject) The prototype (pType) theObject.age; // 33 delete theObject.age; // no more age member in theObject theObject.age; // 32 delete pType.age; theObject.age; // undefined “ Mr” title: “ barber” job: 32 age: “ Jeff” name: “ Mr” title: “ barber” job: 32 age: “ Jeff” name: 33 age:
  • 19. Polymorphism One of the most important attributes of OO languages JavaScript’s objects are not rigid enough to provide single-morphism There are JavaScript toolkits that add this functionality to the language The most renown for it is the “Dojo Toolkit”
  • 20. (From the tyranny of the compiler)
  • 22. Functions are objects Have members e.g., length (the number of arguments in the function’s declaration) Have methods E.g., toString (returns a string containing the function’s signature and body) Are first class citizens Can be sent as arguments to a function Can be returned as a return value from a function Can be executed
  • 23. function add(a,b){ return a+b; }; add.length; // 2 add.toString(); // “function add(a,b){return a+b;}” Functions are objects
  • 24. More about functions Can be defined within another function In that case the inner function knows of all the things defined within the outer function This is called closure What is it good for?
  • 25. Write a function that calculates the fibonacci value of a number
  • 26. Classic solution function fib(n){ if(n < 2) return n; return fib(n-1) + fib(n-2) } fib(10) results in 177 calls to the fib function
  • 27. Solution with closure function fastFib(n){ var memo = [0,1]; var fib = function(n){ var result = memo[n]; if(result === undefined){ result = fib(n-1) +fib(n-2); memo[n] = result; } return result; } return fib(n); } fastFib(10) results in 19 calls to the fib function This pattern is nicknamed memoization
  • 28. Functions - what else is dynamic Every time a function is executed it has a built in array-like variable called ‘arguments’ It holds the set of arguments sent in the function call arguments[i] is the i-th argument in the function call This is needed since the function’s signature is just like road signs in Rome Recommendation only It is valid to call the function with either more or less arguments then in its signature
  • 29. Functions – arguments vs length func.length > arguments.length The last (func.length - arguments.length) have the value of undefined func.length < arguments.length The last (arguments.length - func.length) are accessible only from the arguments variable func.length == arguments.length No problem
  • 30. Functions – what’s ‘this’ Every time a function is executed it has a built in variable called ‘this’ ‘this’ points out to the context in which the function would run The context is bound to the function The binding is done in run-time The binding is dependant upon the way the function was called There are 4 forms a function can be called
  • 31. Function call forms Method form Function form Apply form Constructor form
  • 32. The method form The function is a field of an object The call is written in the following way: theObject.FuncName(); The ‘this’ variable points out to theObject
  • 33. The function form The call is written in the following way: funcName(); The ‘this’ variable points out to the global object This call form makes the usage of helper function within other function to be sometimes tricky
  • 34. The apply form Each function has a function called ‘apply’ Receives two arguments An object that would act as the ‘this’ variable when the function is executed An Array that would act as the ‘arguments’ variable when the function is executed The call is written in the following way: funcName.apply(thisPtr, [newArgs]);
  • 35. The constructor form Constructors are the only element in JavaScript that starts with capital letters Though this is just a convention Used to create and initialize a specific object The ‘this’ variable points out to a newly created object If the function has a field called ‘prototype’ then this field is the prototype of the created element This call is written in the following way: var newMyObj = new MyObject();
  • 36. Constructor form – an example function AA (name, title) { this.name = name; this.title = title; } AA.prototype = {‘height’:3}; var a = new AA(“John”, “Mr”); function AA (name, title) { this = {}; this.linkToPrototype = AA.prototype || Object.prototype; this.name = name; this.title = title; return this; } a.name; // “John” a.title; // “Mr” a.height; // 3 The code Behind the scenes of the constructor The result
  • 37. Call forms “ The binding is dependant upon the way the function was called” var obj = {}; obj.f = f; obj.f(); obj.a ; // 3 f(); // now there’s a global variable a whose value is 3 var newObj = new f(); newObj.a; // 3 var str = ‘xyz’; f.apply(str,[]); str.a; // 3 function f(){this.a = 3}; Method form Function form Constructor form Apply form
  • 38. What about access rights? There are no access rights in JavaScript Everything is public, there is no such thing as ‘private’ The various function execution forms simply deflate this important concept However, it is possible to mimic a private access right for a field in an object Done using closure
  • 39. function Counter(){ var count = 0; this.getValue = function(){ return count ;}; this.increase = function(){count ++;}; this.decrease = function(){count --;}; this.setValue = function(newVal){count = newVal;}; } var c = new Counter(); c.setValue(5); c.increase(); c.getValue(); // 6 c. count; // undefined public public public public private
  • 40. Anonymous functions Functions doesn’t have to have an identifier They can be anonymous Becomes very useful when combined with immediate execution of the function
  • 41. Write a function that receives an array of objects and sets their showIndex method to show their index in that array
  • 42. Bad solution function(objs){ for(var i=0,l=objs.length;i<l;i++) { objs [i].showIndex = function(){ alert(i); } } } What will be alerted?
  • 43. Good solution function(objs){ for(var i=0,l=objs.length;i<l;i++) { objs[i].showIndex = ( function(t){ // a function that returns a function, t here is a local variable return function() { // this function sees the local variable ‘t’ of the red function alert(t); } } )(i); // executing the red function } }
  • 44. “Everything should be made as simple as possible, but not simpler” Albert Einstein
  • 45. What happens when things are too simple (the dark side of JavaScript)
  • 46. Two scopes In JavaScript there are two scopes only The global scope The function scope No block scope
  • 47. Global as the default scope The default scope for variable definition is the global scope function (){ var a = 3; // local variable b = 4; // global variable } Whenever a function is executed in the function form, ‘this’ points out to the global scope And the function form is the simplest one => the one most novice developers would use unwittingly It is very simple to pollute the global scope
  • 48. Semicolon insertion You don’t have to write semicolon at the end of a code line The run-time compiler does it for you This may lead to errors that are hard to find function f1 (){ return {val: 4}; }; function f1 (){ return; {val: 4}; }; var a = f1(); // undefined What the developer wrote Behind the scenes of the function The result
  • 49. The ‘with’ keyword Define a scope for a block Intended to be used as a short hand a.b.c = a.b.d +a.b.e; with(a.b){ c=d+e; }
  • 50. with(obj){ a = b } if(obj.a === undefined){ if(obj.b === undefined){ a=b ;// two global variables } else { a = obj.b; // a is global, b is not } else { if(obj.b === undefined){ obj.a=b; // b is global , a not } else { obj.a = obj.b; // both not global } } The ‘with’ keyword obj.a = obj.b; // both not global obj.a = b; // b is global, a is not + a = obj.b; // a is global, b not a=b; // two global variables - + - a\b (exist in obj)
  • 51. Bitwise operators JavaScript supports bitwise operators: & , |, ^ , >>, << , >>> But JavaScript have only 64 bit number type No integer Bitwise operators are used for faster, close to the hardware computations In JavaScript this is not the case
  • 52. Numerical calculations All calculations in JavaScript are floating point calculation 10 / 3 = 3.3333333333333335 Simply put – erroneous when the decimal point is involve 0.1 + 0.2 = 0.30000000004
  • 53. The utility parseInt ParseInt(stingValue, radix) Strings that start with 0x are treated as hexadecimal Strings that start with 0 are treated as octal based parseInt(“08”) and parseInt(“09”) returns undefined Used often when parsing dates
  • 54. Remember this ? Imperative With prototypes (object-based, but not object-oriented) Functions are first-class entities Has lambda functions With closures Is weakly typed Has dynamic typing Has dynamic binding