SlideShare a Scribd company logo
1 of 89
Download to read offline
Gran Sasso Science Institute
Ivano Malavolta
JavaScript for real men
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
JavaScript
JavaScript is THE scripting language

Born in 1995, it is now of the most famous programming
languages

Heavily used by all major players in web and mobile development

….and remember this…




JavaScript HAS NOTHING TO DO WITH Java!!
Essentials
JavaScript is programming code that can be inserted into
HTML pages
à can react to events in the DOM
à can modify the DOM
Interpreted language
à see the eval() function
The HTML5 standard is adding new APIs to JavaScript


 
Can you list some of them?
Essentials
We can use the <script> tag to insert Javascript code into our
web app


<!DOCTYPE html>
<html>

<body>

<script src="myScript.js"></script>

</body>
</html>



If you want to execute code when you need it, you have to
create a function
The code in myScript is
executed immediately 
We will use a module loader
to load JS
Expressions
An expression is any valid unit of code that resolves to a value

Four types of expressions:
•  arithmetic: evaluates to a number
•  string: evaluates to a sequence of chars
•  logical: evaluates to true or false
•  object: evaluates to an object





Yes, JavaScript is object-
oriented
Statements
A JS program is composed of a set of statements, which can be:

•  Conditional
–  if
–  switch
•  Loop
–  for
–  while, do-while
–  break, continue
–  for..in, forEach
•  Exception handling
–  throw
–  try, catch
–  finally
I assume you all
know these
Operators on expressions
Operators perform some action on expressions and may
produce other expressions as output

Five main types of operators:
•  assignment
–  x = x + y; x*= 3; x %= y, x = x & y
•  comparison (always return a logical value)
–  x == 3; x != 5; x === y; 5 > 3
•  arithmetic (always return a numerical value)
•  logical 
–  && (AND), || (OR), ! (NOT)
•  String
–  + (string concatenation)
Let’s discuss && and ||
Special operators (1)

JavaScript provides the following special operators:

•  Conditional operator
	
  condition	
  ?	
  val1	
  :	
  val2	
  
•  Comma operator
–  evaluates both of its operands and returns the value of the second
operand
•  delete
–  deletes an object, a property or an array element




 
delete	
  window.obj	
  
•  in
–  checks if a property exists in an object
	
  var	
  mycar	
  =	
  {make:"Opel",	
  model:"Tigra",	
  year:1999};	
  
	
  "make"	
  in	
  mycar;	
  	
  //	
  returns	
  true	
  
Special operators (2)
•  instanceof
–  similar to the instanceOf method in Java


 
myObj instanceof Object; //returns true
•  new
–  creates an instance of an object

 
var myself = new Person("Ivano Malavolta");
•  this
–  refers to the current object
this.name;
this[‘name’];
•  typeof
–  returns the type of an expression




 
 
typeof myself.name; // returns string
Variables (1)
Variables are declared by using the keyword var

var magicNumber = 42;
var user = App.getCurrentUser();
var loggedUser = (user.isLogged()) ? user.name : undefined

If a variable has no value yet it evaluates to undefined 
If a variable has not been defined an exception will be threw: 

Uncaught ReferenceError: c is not defined

Global variable: when it is declared OUTSIDE any function
à available to any other code within the app

Local variable: when it is declared INSIDE a function
Variables (2)

The scope of Javascript statements is based on functions (not blocks) 




If you declare a variable without the var keyword, you are creating a
global variable (!)

In the browser global variables can be accessed by window.varName	
  




this works
Constants and Literals
•  Array
–  var bands = ["NIN", "Kraftwerk", "Rammstein"];
•  Boolean
–  var logged= true; // false
•  Integer and Floating point
–  var age = 12;
–  var PI = 3.14;
•  String
–  var hello = ‘hello’;
•  Objects
–  var band = {name: "NIN", founder: {name: "Trent", surname: "Reznor"}};
–  band.name; // NIN
–  band.founder["surname"]; // Reznor
Function declarations

A function declaration is composed of:
•  name
•  parameters
•  body
Primitive parameters are passed by value
Objects are passed by reference

A function is actually an expression:


This is an example of anonymous function
Function Calls

Functions can be called by referring to their name and passing its
parameters


A function can produce a result by means of the return statement

Since function declarations are expressions, a function can be declared
and executed all at once
Functional Programming

Functions can be passed as arguments to other functions, or can be
produced as output of another function









function	
  map(f,a)	
  {	
  
	
  	
  var	
  result	
  =	
  [],	
  i;	
  
	
  	
  for(i=0;	
  i	
  !=a.length;	
  i++)	
  {	
  
	
  	
  	
  	
  result[i]	
  =	
  f(a[i]);	
  
	
  	
  }	
  
	
  	
  return	
  result;	
  
}	
  
	
  
map(function(x)	
  {	
  
	
  return	
  x*x*x;	
  
},	
  [0,1,2,5,10]);	
  
result?
Closures

A closure is a special kind of object consisting of:

•  A function
•  The function’s environment
–  any local variables that were in-scope at the time that the closure was
created







http://goo.gl/Ya0be
Closures with the same function def
http://goo.gl/Ya0be
Closures with the same environment
http://goo.gl/Ya0be
wow... makeCounter looks like a class... 
What do you think about changeBy?
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
JavaScript event loop
Confusion about JavaScript’s asynchronous event model is quite common 

Confusion leads to bugs, bugs lead to anger, and Yoda taught us the rest.... 
http://goo.gl/g3xvY
First exploration
Let’s see this piece of code
http://goo.gl/g3xvY
for	
  (var	
  i	
  =	
  1;	
  i	
  <=	
  3;	
  i++)	
  {	
  	
  
	
  	
  setTimeout(function(){	
  	
  
	
  	
  	
  	
  console.log(i);	
  	
  
	
  	
  },	
  0);	
  
};	
  
Later we will see why 
the result is like this
What if a rare event happened
between these two lines of code?
Second exploration
Let’s see this piece of code
http://goo.gl/g3xvY
var	
  start	
  =	
  new	
  Date;	
  	
  
setTimeout(function(){	
  
	
  	
  	
  	
  var	
  end	
  =	
  new	
  Date;	
  
	
  	
  	
  	
  console.log('Time	
  elapsed:',	
  end	
  -­‐	
  start,	
  'ms');	
  	
  
	
  	
  },	
  500);	
  
while	
  (new	
  Date	
  -­‐	
  start	
  <	
  1000)	
  {};	
  
Hint
The setTimeout callback can’t fire until the
while loop has finished running.
JavaScript concurrency model
JavaScript has a concurrency model based on an event loop

Intuitively, you can consider as if your code is running from a loop like
this:
runYourScript();	
  
while	
  (atLeastOneEventIsQueued)	
  {	
  	
  
	
  	
  fireNextQueuedEvent();	
  	
  
};	
  	
  
The two previous examples make sense now?
JavaScript concurrency model
The JavaScript concurrency model is composed of three main entities

http://goo.gl/0zgXC
Stack
Function calls form a stack of frames


Each time a function f is called, 
1.  a frame f is created with its arguments and local variables
2.  the frame f is pushed on top of the stack
3.  all the instructions of the function f	
  are executed
4.  when the function f returns, its frame is popped out
The JavaScript engine executes all the frames until the stack is empty

http://goo.gl/0zgXC
Heap



The heap stores all the objects created during the execution of
JavaScript functions

The heap is just a name to denote a large mostly unstructured region of
memory


http://goo.gl/0zgXC
Queue
The queue contains a list of messages to be processed

Each message has an associated function callback	
  
	
  
When the stack is empty:
1.  the first message of the queue is taken out
2.  its function callback is processed
–  basically, a new stack frame is created for callback and it is processed
The message processing ends when the stack becomes empty

http://goo.gl/0zgXC
Important remarks about the queue
Each message is processed completely before any other message is
considered

à when a function is running, it cannot be interrupted in any way
à it will always run until full completion
à it can modify data without race conditions
However, if a function takes too long, then it “stops” the app
Solutions:
•  make message processing short
•  split one message into several messages
•  use web workers for multi-threading

http://goo.gl/0zgXC
Adding messages to the queue
In web browsers, a message is added when:
•  an event occurs
•  there is an event listener attached to the event
If an event occurs (eg a touch event), and there is no listener 
à the event is lost
Examples of async functions generating messages in the queue:
•  DOM interaction (touch, swipe, click…)
•  timing functions (setTimeout, setInterval)
•  I/O functions (read files, etc.)
•  Ajax requests
http://goo.gl/0zgXC
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
Ajax
Ajax lets us fire requests from the browser to the server without
page reload

à  you can update a part of the page while the user continues on
working
Basically, you can use Ajax requests to:
•  load remote HTML
•  get JSON data
Load JSON data
JSON is a lightweight alternative to XML, where data is
structured as plain JavaScript objects
Load JSON Data
The Ajax() call
All of jQuery’s Ajax functions are simply wrappers around the
$.ajax() method

$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
error: callbackError
});
This is equivalent to 
$.getJSON(url, callback);
Callback Functions
A callback is a function that 
1.  is passed as an argument to another function 
2.  is executed after its parent function has completed
–  when an effect has been completed
–  when an AJAX call has returned some data
$.get('myhtmlpage.html', myCallBack);
function myCallBack(data) {
// do something with data
}
myCallBack is invoked when the '$.get' is done getting the page
A note on nested callbacks
Nested callbacks tempt us to add more features by adding more
code, rather than implementing those features in manageable,
reusable pieces
Avoid more than two levels of function nesting 
Store async results outside of the function making the async call
so that the callback doesn’t have to be nested 


passwordHash has a
broader scope here
Promises
A promise is an object that represents a task with:
1.  two possible outcomes (success or failure) 
2.  callbacks that fire when one outcome or the other has occurred 
//	
  with	
  callbacks	
  
$.get('/mydata',	
  {	
  	
  
	
  success:	
  onSuccess,	
  
	
  failure:	
  onFailure,	
  	
  
	
  always:	
  onAlways	
  	
  
});	
  	
  
//	
  with	
  promises	
  
var	
  promise	
  =	
  $.get('/mydata');	
  
promise.done(onSuccess);	
  
promise.fail(onFailure);	
  
promise.always(onAlways);	
  	
  
	
  
Where is the difference?
Why promises?

If your Ajax request has multiple effects (animation, other Ajax
requests, updating the DOM, etc.), you do not have to mix them with
the part of your app making the request


You can attach multiple callbacks to the same request

For example, you may have a single callback for showing a spinner shared across your app


You can derive new promises from existing ones 

Encapsulation
Stacking
Promise derivation
Promise derivation
JQuery’s when method allows you to combine multiple promises

when acts as a logical AND for promise resolution and generates a
new promise that:
•  is resolved as soon as all of the given Promises are resolved
•  or it is rejected as soon as any one of the given Promises is rejected






var	
  serverData	
  =	
  {};	
  
var	
  getting1	
  =	
  $.get('/1')	
  
.done(function(result)	
  {serverData['1']	
  =	
  result;});	
  	
  
var	
  getting2	
  =	
  $.get('/2')	
  
.done(function(result)	
  {serverData['2']	
  =	
  result;});	
  	
  
$.when(getting1,	
  getting2)	
  
.done(function()	
  {	
  	
  
	
  //	
  the	
  GET	
  information	
  is	
  now	
  in	
  serverData...	
  	
  
});	
  	
  
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
The DOM
DOM = Document Object Model

Every web page have a hierarchical structure in which every
element is contained into another: its parent.

Text elements are particular since they never have children
The DOM
In Javascript the document global variable stores a reference to
the object corresponding to the <html> tag

Every node of the DOM can be navigated:
document.body.parentNode
document.body.childNodes 
document.body.firstChild
document.body.lastChild 
document.body.nextSibling
document.body.previousSibling
Accessing the DOM
nodeName to get the name of the tag of a node:
document.body.firstChild.nodeName;!
!
nodeValue to get the text of a text node:
document.body.firstChild.firstChild.nodeValue;!
!
innerHTML to get/set the content of a node:
document.body.firstChild.innerHTML = "<div>Hello</div>";!
!
getElementById to get a node by its ID:
document.getElementById("title");!
!
getElementsByTagName to get a node by its type:
document.getElementsByTagName("DIV");!
!
getElementsbyClassName to get a node by its class:
document.getElementsByClassName("listElement");!
!
Modifying the DOM
createElement to create a new node:
var myDiv = document.createElement("A");!
!
createTextNode to create a new text node:
document.createTextNode("Hello!");!
!
appendChild to put new nodes into the DOM:
document.body.appendChild(myDiv);!
!
setAttribute to set an attribute of a node:
document.setAttribute("href", "http://www.google.it");!
Events
Every time the user interacts with the DOM, a set of events is
triggered in our JS application

We can listen to these events by means of registered
eventHandlers

An eventHandler is a function automatically called by the browser,
where data about the triggered event is available as a parameter

Event handlers can be unregistered
Example
document.getElementbyId("myDiv").addEventListener(!
"touchend", manageTouch, false);!
!
!
!
!
!
function manageTouch(event) {!
!console.log("touched " + event.target);!
}!
name of the
event
callback
function
handle the event in the
capture phase
data about the event
Event Bubbling & capturing
When an event is triggered in the DOM, 
it can be:

•  captured by all the elements
containing the target element 
à event capturing
•  captured first by the target 
and then BUBBLE up through all 
the HTML elements containing 
the target à event bubbling
Event default behaviour
Each element in the DOM has a default behaviour

ex. if you tap on an <a> element, it will make the browser to point to
another location 

event.preventDefault();
Cancels the event if it is cancelable, without stopping further
propagation of the event

Usually, this is the last instruction of an event handler
Touch events
Touch events are triggered when the user touches the display

The event can describe one or more points of contact

Touches are represented by the Touch object
each touch is described by a position, size and shape, amount of
pressure, and target element. 

Lists of touches are represented by TouchList objects
Touch events
Main attributes of a touch event:

•  TouchEvent.touches
–  a TouchList of Touches
•  TouchEvent.type
–  the type of touch
•  TouchEvent.target
–  the element in the DOM 
•  TouchEvent.changedTouches
–  a TouchList of all the Touches changed between this event and the
previous one
touchstart
touchend
touchmove
touchenter
touchcancel
The Touch and TouchList objects
relative to the
viewport
relative to the
whole display
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
JavaScript objects

An object in JS can be seen as a map of key/value pairs

•  key: a JavaScript string
•  value: any JavaScript value

Everything in JavaScript is an object, and basically all its operations
involve hash table lookups (which are very fast in our browsers!)
Object creation

In JavaScript an object can be created in two ways:


new-value creation 


 


 

object literal syntax



var	
  obj	
  =	
  new	
  Object();	
  
obj.name	
  =	
  "Ivano";	
  
...	
  
var	
  obj	
  =	
  {	
  
	
  	
  	
  	
  name:	
  "Ivano",	
  
	
  	
  	
  	
  surname:	
  "Malavolta",	
  
	
  	
  	
  	
  details:	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  sex:	
  "male",	
  
	
  	
  	
  	
  	
  	
  	
  	
  address:	
  ”via..."	
  
	
  	
  	
  	
  }	
  
}	
  
These are semantically
equivalent
Object properties

In JavaScript an object property can be created in two ways:


dot notation 




 


 

 
array-like notation



obj.name	
  =	
  “Ivano”;	
  
var	
  name	
  =	
  obj.name;	
  
obj["name"]	
  =	
  ”Ivano";	
  
var	
  name	
  =	
  obj["name"];	
  
These are semantically equivalent too
In the array-like notation, the property is a string 
à it can be computed dynamically
Object Orientation (1): the model

JavaScript object model is prototype-based, rather than class-based

No notion of class, everything is an object

An object can be seen as a «template» for other objects, in this case it is
the prototype of the other objects
à it defines an initial set of properties
The inheriting objects can specify their own properties
Object Orientation (2): class definitions

In Java I can specify a Class. It can have special methods, Constructors,
which I execute in order to create instances of my class.

In JavaScript I directly define Constructor functions that I call to create
my object by means of the new keyword.
The new and this keywords
new is strongly related to 'this'. 

It creates a brand new empty object, and then calls the function
specified, with 'this' set to that new object. 

The function specified with 'this' does not return a value but
merely modifies the this object. It's new that returns the this
object to the calling site. 

Functions that are designed to be called by 'new' are called
constructor functions. Common practise is to capitalise these
functions as a reminder to call them with new.
http://goo.gl/jBTMWX
Object Orientation (3): inheritance

In Java I can define a hierarchy of classes by defining subclasses via the
extends keyword

In JavaScript I can define a constructor function X, then I can say that X
acts as the prototype of constructor function Y 

à X is a supertype of Y
Object Orientation (4): methods

In Java I can specify define methods within my class and call them by
referring to specific instances.

In JavaScript I can define properties which can be functions, then I can
call them directly on the object being used
OO Summary
!
JavaScript object model is prototype-based, rather than class-based
see here: 
http://jsfiddle.net/6kdBa/10/
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
Web Workers
Javascript is a single-threaded language
à If a tasks take a lot of time, users have to wait


Web Workers provide background processing capabilities to web
applications


They typically run on separate threads 

à apps can take advantage of multicore CPUs
Web Workers
Web Workers can be used to:
•  prefetch data from the Web
•  perform other ahead-of-time operations to provide a much
more lively UI.


Web Workers are precious on mobile applications because they
usually need to load data over a potentially slow network
Web Workers
Any JS file can be launched as a worker


Example of Web Worker declaration:


var worker = new Worker(“worker.js”);
In order to be independent from other workers, each worker
script cannot access:

–  the DOM
–  the global window object 
•  (each web worker has its own self global object)
Web Workers concurrency model
A web worker has its own 
•  stack,
•  heap
•  message queue
Two distinct runtimes can only communicate through sending
messages via the postMessage method

This method adds a message to the other runtime if the latter
listens to message events.
Web Workers
The main JS script can communicate with workers via
postMessage() calls:


$(‘#button’).click(function(event) {
$(‘#output’).html(“starting”);
worker.postMessage(“start”);
});
worker.onmessage = function(event) {
$(‘#output’).html(event.data);
}
Web Workers
The web worker script can post back messages to the main script:


onmessage = function(event) {
if(event.data === “start”) {
var result;
// do something with result
postMessage(result);
}
}
Roadmap
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction 
JavaScript object orientation
Web Workers
Useful Microframeworks
Zepto
The only relevant downside of jQuery is about 
PERFORMANCE

However,
1.  it is not very noticeable in current class-A mobile devices 
2.  You can use mobile-suited alternatives to jQuery:
Zepto
 The goal is to have a ~5-10k modular library that executes fast,
with a familiar API (jQuery)

It can be seen as a 
mini-jQuery
without support for 
older browsers
Zepto Modules
Zepto Usage
Simply replace the reference to jQuery with the one to Zepto
Underscore.js
A utility library for JavaScript that provides support for the usual
functional suspects (each, map, reduce, filter...) 

It provides low-level utilities in the following categories:

•  Collections
•  Arrays
•  Objects
•  Functions
•  Utilities
http://documentcloud.github.com/underscore/
iceCream
Minimal grid system for your layouts, pure CSS3 only

https://github.com/html5-ninja/icecream
iceCream
Ratchet
It provides the basic building blocks for realizing well-known
mobile design patterns


Examples:

•  Nav bars
•  Title bars
•  Lists
•  Toggles
•  Cards
•  Popovers
•  Sliders
•  …
http://goratchet.com
Ratchet examples
Ratchet examples
Ratchet examples
Spin JS
It allows you to dynamically create a spinning loading indicator









Pure CSS à resolution-independent

http://fgnass.github.io/spin.js/
Spin JS
Frameworks
jQueryMobile, jQuery, Backbone, etc. are beautiful tools…

However they may impact the performance of your app

à  Use a framework only when it is necessary
–  Don’t use jQuery only because of the $(selector) syntax! 

Solution
•  build your own micro-framework
•  cut out Cordova plugins you do not use
•  use micro-frameworks (http://microjs.com)
A final note
JavaScript allows you to do the same thing in many ways

In order to make your code readable (and thus maintainable), you
have to:

•  follow as mush as possible known design patterns
–  singleton, factory, etc.

•  follow conventions
–  https://github.com/rwaldron/idiomatic.js/
References
https://developer.mozilla.org/en-US/docs/JavaScript
http://www.w3schools.com
http://www.microjs.com
https://github.com/iivanoo/cordovaboilerplate
+ 39 380 70 21 600
Contact
Ivano Malavolta | 
Gran Sasso Science Institute
iivanoo
ivano.malavolta@univaq.it
www.ivanomalavolta.com

More Related Content

What's hot

From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution ContextJuan Medina
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Libraryasync_io
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaKnoldus Inc.
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresHDR1001
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScriptCodemotion
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Devang Garach
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftColin Eberhardt
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherColin Eberhardt
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive CocoaSmartLogic
 

What's hot (20)

Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Javascript Promises/Q Library
Javascript Promises/Q LibraryJavascript Promises/Q Library
Javascript Promises/Q Library
 
Angular2
Angular2Angular2
Angular2
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
JavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closuresJavaScript global object, execution contexts & closures
JavaScript global object, execution contexts & closures
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
ReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better TogetherReactiveCocoa and Swift, Better Together
ReactiveCocoa and Swift, Better Together
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 

Similar to JavaScript for real men

Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptxStefan Oprea
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipseanshunjain
 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almostQuinton Sheppard
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32Bilal Ahmed
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
javascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptjavascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptLalith86
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functionsSwapnil Yadav
 

Similar to JavaScript for real men (20)

JavaScript
JavaScriptJavaScript
JavaScript
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
oojs
oojsoojs
oojs
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
javascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptjavascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.ppt
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
JS basics
JS basicsJS basics
JS basics
 
Event Programming JavaScript
Event Programming JavaScriptEvent Programming JavaScript
Event Programming JavaScript
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 

More from Ivano Malavolta

Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Ivano Malavolta
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)Ivano Malavolta
 
Software sustainability and Green IT
Software sustainability and Green ITSoftware sustainability and Green IT
Software sustainability and Green ITIvano Malavolta
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Ivano Malavolta
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]Ivano Malavolta
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Ivano Malavolta
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Ivano Malavolta
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Ivano Malavolta
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Ivano Malavolta
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Ivano Malavolta
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Ivano Malavolta
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Ivano Malavolta
 
Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Ivano Malavolta
 
[2017/2018] Agile development
[2017/2018] Agile development[2017/2018] Agile development
[2017/2018] Agile developmentIvano Malavolta
 
Reconstructing microservice-based architectures
Reconstructing microservice-based architecturesReconstructing microservice-based architectures
Reconstructing microservice-based architecturesIvano Malavolta
 
[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design LanguageIvano Malavolta
 
[2017/2018] Architectural languages
[2017/2018] Architectural languages[2017/2018] Architectural languages
[2017/2018] Architectural languagesIvano Malavolta
 
[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software ArchitectureIvano Malavolta
 
[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineeringIvano Malavolta
 

More from Ivano Malavolta (20)

Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
Conducting Experiments on the Software Architecture of Robotic Systems (QRARS...
 
The H2020 experience
The H2020 experienceThe H2020 experience
The H2020 experience
 
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)The Green Lab - Research cocktail  @Vrije Universiteit Amsterdam (October 2020)
The Green Lab - Research cocktail @Vrije Universiteit Amsterdam (October 2020)
 
Software sustainability and Green IT
Software sustainability and Green ITSoftware sustainability and Green IT
Software sustainability and Green IT
 
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...Navigation-aware and Personalized Prefetching of Network Requests in Android ...
Navigation-aware and Personalized Prefetching of Network Requests in Android ...
 
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]How Maintainability Issues of Android Apps Evolve [ICSME 2018]
How Maintainability Issues of Android Apps Evolve [ICSME 2018]
 
Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...Collaborative Model-Driven Software Engineering: a Classification Framework a...
Collaborative Model-Driven Software Engineering: a Classification Framework a...
 
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
Experimenting on Mobile Apps Quality - a tale about Energy, Performance, and ...
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
 
Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...Modeling behaviour via UML state machines [Software Design] [Computer Science...
Modeling behaviour via UML state machines [Software Design] [Computer Science...
 
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...Object-oriented design patterns in UML [Software Design] [Computer Science] [...
Object-oriented design patterns in UML [Software Design] [Computer Science] [...
 
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
Structure modeling with UML [Software Design] [Computer Science] [Vrije Unive...
 
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
Requirements engineering with UML [Software Design] [Computer Science] [Vrije...
 
Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...Modeling and abstraction, software development process [Software Design] [Com...
Modeling and abstraction, software development process [Software Design] [Com...
 
[2017/2018] Agile development
[2017/2018] Agile development[2017/2018] Agile development
[2017/2018] Agile development
 
Reconstructing microservice-based architectures
Reconstructing microservice-based architecturesReconstructing microservice-based architectures
Reconstructing microservice-based architectures
 
[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language[2017/2018] AADL - Architecture Analysis and Design Language
[2017/2018] AADL - Architecture Analysis and Design Language
 
[2017/2018] Architectural languages
[2017/2018] Architectural languages[2017/2018] Architectural languages
[2017/2018] Architectural languages
 
[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture[2017/2018] Introduction to Software Architecture
[2017/2018] Introduction to Software Architecture
 
[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering[2017/2018] RESEARCH in software engineering
[2017/2018] RESEARCH in software engineering
 

Recently uploaded

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

JavaScript for real men

  • 1. Gran Sasso Science Institute Ivano Malavolta JavaScript for real men
  • 2. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 3. JavaScript JavaScript is THE scripting language Born in 1995, it is now of the most famous programming languages Heavily used by all major players in web and mobile development ….and remember this… JavaScript HAS NOTHING TO DO WITH Java!!
  • 4. Essentials JavaScript is programming code that can be inserted into HTML pages à can react to events in the DOM à can modify the DOM Interpreted language à see the eval() function The HTML5 standard is adding new APIs to JavaScript Can you list some of them?
  • 5. Essentials We can use the <script> tag to insert Javascript code into our web app <!DOCTYPE html> <html> <body> <script src="myScript.js"></script> </body> </html> If you want to execute code when you need it, you have to create a function The code in myScript is executed immediately We will use a module loader to load JS
  • 6. Expressions An expression is any valid unit of code that resolves to a value Four types of expressions: •  arithmetic: evaluates to a number •  string: evaluates to a sequence of chars •  logical: evaluates to true or false •  object: evaluates to an object Yes, JavaScript is object- oriented
  • 7. Statements A JS program is composed of a set of statements, which can be: •  Conditional –  if –  switch •  Loop –  for –  while, do-while –  break, continue –  for..in, forEach •  Exception handling –  throw –  try, catch –  finally I assume you all know these
  • 8. Operators on expressions Operators perform some action on expressions and may produce other expressions as output Five main types of operators: •  assignment –  x = x + y; x*= 3; x %= y, x = x & y •  comparison (always return a logical value) –  x == 3; x != 5; x === y; 5 > 3 •  arithmetic (always return a numerical value) •  logical –  && (AND), || (OR), ! (NOT) •  String –  + (string concatenation) Let’s discuss && and ||
  • 9. Special operators (1) JavaScript provides the following special operators: •  Conditional operator  condition  ?  val1  :  val2   •  Comma operator –  evaluates both of its operands and returns the value of the second operand •  delete –  deletes an object, a property or an array element delete  window.obj   •  in –  checks if a property exists in an object  var  mycar  =  {make:"Opel",  model:"Tigra",  year:1999};    "make"  in  mycar;    //  returns  true  
  • 10. Special operators (2) •  instanceof –  similar to the instanceOf method in Java myObj instanceof Object; //returns true •  new –  creates an instance of an object var myself = new Person("Ivano Malavolta"); •  this –  refers to the current object this.name; this[‘name’]; •  typeof –  returns the type of an expression typeof myself.name; // returns string
  • 11. Variables (1) Variables are declared by using the keyword var var magicNumber = 42; var user = App.getCurrentUser(); var loggedUser = (user.isLogged()) ? user.name : undefined If a variable has no value yet it evaluates to undefined If a variable has not been defined an exception will be threw: Uncaught ReferenceError: c is not defined Global variable: when it is declared OUTSIDE any function à available to any other code within the app Local variable: when it is declared INSIDE a function
  • 12. Variables (2) The scope of Javascript statements is based on functions (not blocks) If you declare a variable without the var keyword, you are creating a global variable (!) In the browser global variables can be accessed by window.varName   this works
  • 13.
  • 14. Constants and Literals •  Array –  var bands = ["NIN", "Kraftwerk", "Rammstein"]; •  Boolean –  var logged= true; // false •  Integer and Floating point –  var age = 12; –  var PI = 3.14; •  String –  var hello = ‘hello’; •  Objects –  var band = {name: "NIN", founder: {name: "Trent", surname: "Reznor"}}; –  band.name; // NIN –  band.founder["surname"]; // Reznor
  • 15. Function declarations A function declaration is composed of: •  name •  parameters •  body Primitive parameters are passed by value Objects are passed by reference A function is actually an expression: This is an example of anonymous function
  • 16. Function Calls Functions can be called by referring to their name and passing its parameters A function can produce a result by means of the return statement Since function declarations are expressions, a function can be declared and executed all at once
  • 17. Functional Programming Functions can be passed as arguments to other functions, or can be produced as output of another function function  map(f,a)  {      var  result  =  [],  i;      for(i=0;  i  !=a.length;  i++)  {          result[i]  =  f(a[i]);      }      return  result;   }     map(function(x)  {    return  x*x*x;   },  [0,1,2,5,10]);   result?
  • 18. Closures A closure is a special kind of object consisting of: •  A function •  The function’s environment –  any local variables that were in-scope at the time that the closure was created http://goo.gl/Ya0be
  • 19. Closures with the same function def http://goo.gl/Ya0be
  • 20. Closures with the same environment http://goo.gl/Ya0be wow... makeCounter looks like a class... What do you think about changeBy?
  • 21. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 22. JavaScript event loop Confusion about JavaScript’s asynchronous event model is quite common Confusion leads to bugs, bugs lead to anger, and Yoda taught us the rest.... http://goo.gl/g3xvY
  • 23. First exploration Let’s see this piece of code http://goo.gl/g3xvY for  (var  i  =  1;  i  <=  3;  i++)  {        setTimeout(function(){            console.log(i);        },  0);   };   Later we will see why the result is like this What if a rare event happened between these two lines of code?
  • 24. Second exploration Let’s see this piece of code http://goo.gl/g3xvY var  start  =  new  Date;     setTimeout(function(){          var  end  =  new  Date;          console.log('Time  elapsed:',  end  -­‐  start,  'ms');        },  500);   while  (new  Date  -­‐  start  <  1000)  {};   Hint The setTimeout callback can’t fire until the while loop has finished running.
  • 25. JavaScript concurrency model JavaScript has a concurrency model based on an event loop Intuitively, you can consider as if your code is running from a loop like this: runYourScript();   while  (atLeastOneEventIsQueued)  {        fireNextQueuedEvent();     };     The two previous examples make sense now?
  • 26. JavaScript concurrency model The JavaScript concurrency model is composed of three main entities http://goo.gl/0zgXC
  • 27. Stack Function calls form a stack of frames Each time a function f is called, 1.  a frame f is created with its arguments and local variables 2.  the frame f is pushed on top of the stack 3.  all the instructions of the function f  are executed 4.  when the function f returns, its frame is popped out The JavaScript engine executes all the frames until the stack is empty http://goo.gl/0zgXC
  • 28. Heap The heap stores all the objects created during the execution of JavaScript functions The heap is just a name to denote a large mostly unstructured region of memory http://goo.gl/0zgXC
  • 29. Queue The queue contains a list of messages to be processed Each message has an associated function callback     When the stack is empty: 1.  the first message of the queue is taken out 2.  its function callback is processed –  basically, a new stack frame is created for callback and it is processed The message processing ends when the stack becomes empty http://goo.gl/0zgXC
  • 30. Important remarks about the queue Each message is processed completely before any other message is considered à when a function is running, it cannot be interrupted in any way à it will always run until full completion à it can modify data without race conditions However, if a function takes too long, then it “stops” the app Solutions: •  make message processing short •  split one message into several messages •  use web workers for multi-threading http://goo.gl/0zgXC
  • 31. Adding messages to the queue In web browsers, a message is added when: •  an event occurs •  there is an event listener attached to the event If an event occurs (eg a touch event), and there is no listener à the event is lost Examples of async functions generating messages in the queue: •  DOM interaction (touch, swipe, click…) •  timing functions (setTimeout, setInterval) •  I/O functions (read files, etc.) •  Ajax requests http://goo.gl/0zgXC
  • 32. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 33. Ajax Ajax lets us fire requests from the browser to the server without page reload à  you can update a part of the page while the user continues on working Basically, you can use Ajax requests to: •  load remote HTML •  get JSON data
  • 34. Load JSON data JSON is a lightweight alternative to XML, where data is structured as plain JavaScript objects
  • 36. The Ajax() call All of jQuery’s Ajax functions are simply wrappers around the $.ajax() method $.ajax({ url: url, dataType: 'json', data: data, success: callback, error: callbackError }); This is equivalent to $.getJSON(url, callback);
  • 37. Callback Functions A callback is a function that 1.  is passed as an argument to another function 2.  is executed after its parent function has completed –  when an effect has been completed –  when an AJAX call has returned some data $.get('myhtmlpage.html', myCallBack); function myCallBack(data) { // do something with data } myCallBack is invoked when the '$.get' is done getting the page
  • 38. A note on nested callbacks Nested callbacks tempt us to add more features by adding more code, rather than implementing those features in manageable, reusable pieces
  • 39. Avoid more than two levels of function nesting Store async results outside of the function making the async call so that the callback doesn’t have to be nested passwordHash has a broader scope here
  • 40. Promises A promise is an object that represents a task with: 1.  two possible outcomes (success or failure) 2.  callbacks that fire when one outcome or the other has occurred //  with  callbacks   $.get('/mydata',  {      success:  onSuccess,    failure:  onFailure,      always:  onAlways     });     //  with  promises   var  promise  =  $.get('/mydata');   promise.done(onSuccess);   promise.fail(onFailure);   promise.always(onAlways);       Where is the difference?
  • 41. Why promises? If your Ajax request has multiple effects (animation, other Ajax requests, updating the DOM, etc.), you do not have to mix them with the part of your app making the request You can attach multiple callbacks to the same request For example, you may have a single callback for showing a spinner shared across your app You can derive new promises from existing ones Encapsulation Stacking Promise derivation
  • 42. Promise derivation JQuery’s when method allows you to combine multiple promises when acts as a logical AND for promise resolution and generates a new promise that: •  is resolved as soon as all of the given Promises are resolved •  or it is rejected as soon as any one of the given Promises is rejected var  serverData  =  {};   var  getting1  =  $.get('/1')   .done(function(result)  {serverData['1']  =  result;});     var  getting2  =  $.get('/2')   .done(function(result)  {serverData['2']  =  result;});     $.when(getting1,  getting2)   .done(function()  {      //  the  GET  information  is  now  in  serverData...     });    
  • 43. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 44. The DOM DOM = Document Object Model Every web page have a hierarchical structure in which every element is contained into another: its parent. Text elements are particular since they never have children
  • 45. The DOM In Javascript the document global variable stores a reference to the object corresponding to the <html> tag Every node of the DOM can be navigated: document.body.parentNode document.body.childNodes document.body.firstChild document.body.lastChild document.body.nextSibling document.body.previousSibling
  • 46. Accessing the DOM nodeName to get the name of the tag of a node: document.body.firstChild.nodeName;! ! nodeValue to get the text of a text node: document.body.firstChild.firstChild.nodeValue;! ! innerHTML to get/set the content of a node: document.body.firstChild.innerHTML = "<div>Hello</div>";! ! getElementById to get a node by its ID: document.getElementById("title");! ! getElementsByTagName to get a node by its type: document.getElementsByTagName("DIV");! ! getElementsbyClassName to get a node by its class: document.getElementsByClassName("listElement");! !
  • 47. Modifying the DOM createElement to create a new node: var myDiv = document.createElement("A");! ! createTextNode to create a new text node: document.createTextNode("Hello!");! ! appendChild to put new nodes into the DOM: document.body.appendChild(myDiv);! ! setAttribute to set an attribute of a node: document.setAttribute("href", "http://www.google.it");!
  • 48. Events Every time the user interacts with the DOM, a set of events is triggered in our JS application We can listen to these events by means of registered eventHandlers An eventHandler is a function automatically called by the browser, where data about the triggered event is available as a parameter Event handlers can be unregistered
  • 49. Example document.getElementbyId("myDiv").addEventListener(! "touchend", manageTouch, false);! ! ! ! ! ! function manageTouch(event) {! !console.log("touched " + event.target);! }! name of the event callback function handle the event in the capture phase data about the event
  • 50. Event Bubbling & capturing When an event is triggered in the DOM, it can be: •  captured by all the elements containing the target element à event capturing •  captured first by the target and then BUBBLE up through all the HTML elements containing the target à event bubbling
  • 51. Event default behaviour Each element in the DOM has a default behaviour ex. if you tap on an <a> element, it will make the browser to point to another location event.preventDefault(); Cancels the event if it is cancelable, without stopping further propagation of the event Usually, this is the last instruction of an event handler
  • 52. Touch events Touch events are triggered when the user touches the display The event can describe one or more points of contact Touches are represented by the Touch object each touch is described by a position, size and shape, amount of pressure, and target element. Lists of touches are represented by TouchList objects
  • 53. Touch events Main attributes of a touch event: •  TouchEvent.touches –  a TouchList of Touches •  TouchEvent.type –  the type of touch •  TouchEvent.target –  the element in the DOM •  TouchEvent.changedTouches –  a TouchList of all the Touches changed between this event and the previous one touchstart touchend touchmove touchenter touchcancel
  • 54. The Touch and TouchList objects relative to the viewport relative to the whole display
  • 55. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 56. JavaScript objects An object in JS can be seen as a map of key/value pairs •  key: a JavaScript string •  value: any JavaScript value Everything in JavaScript is an object, and basically all its operations involve hash table lookups (which are very fast in our browsers!)
  • 57. Object creation In JavaScript an object can be created in two ways: new-value creation object literal syntax var  obj  =  new  Object();   obj.name  =  "Ivano";   ...   var  obj  =  {          name:  "Ivano",          surname:  "Malavolta",          details:  {                  sex:  "male",                  address:  ”via..."          }   }   These are semantically equivalent
  • 58. Object properties In JavaScript an object property can be created in two ways: dot notation array-like notation obj.name  =  “Ivano”;   var  name  =  obj.name;   obj["name"]  =  ”Ivano";   var  name  =  obj["name"];   These are semantically equivalent too In the array-like notation, the property is a string à it can be computed dynamically
  • 59. Object Orientation (1): the model JavaScript object model is prototype-based, rather than class-based No notion of class, everything is an object An object can be seen as a «template» for other objects, in this case it is the prototype of the other objects à it defines an initial set of properties The inheriting objects can specify their own properties
  • 60. Object Orientation (2): class definitions In Java I can specify a Class. It can have special methods, Constructors, which I execute in order to create instances of my class. In JavaScript I directly define Constructor functions that I call to create my object by means of the new keyword.
  • 61. The new and this keywords new is strongly related to 'this'. It creates a brand new empty object, and then calls the function specified, with 'this' set to that new object. The function specified with 'this' does not return a value but merely modifies the this object. It's new that returns the this object to the calling site. Functions that are designed to be called by 'new' are called constructor functions. Common practise is to capitalise these functions as a reminder to call them with new. http://goo.gl/jBTMWX
  • 62. Object Orientation (3): inheritance In Java I can define a hierarchy of classes by defining subclasses via the extends keyword In JavaScript I can define a constructor function X, then I can say that X acts as the prototype of constructor function Y à X is a supertype of Y
  • 63. Object Orientation (4): methods In Java I can specify define methods within my class and call them by referring to specific instances. In JavaScript I can define properties which can be functions, then I can call them directly on the object being used
  • 64. OO Summary ! JavaScript object model is prototype-based, rather than class-based see here: http://jsfiddle.net/6kdBa/10/
  • 65. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 66. Web Workers Javascript is a single-threaded language à If a tasks take a lot of time, users have to wait Web Workers provide background processing capabilities to web applications They typically run on separate threads à apps can take advantage of multicore CPUs
  • 67. Web Workers Web Workers can be used to: •  prefetch data from the Web •  perform other ahead-of-time operations to provide a much more lively UI. Web Workers are precious on mobile applications because they usually need to load data over a potentially slow network
  • 68. Web Workers Any JS file can be launched as a worker Example of Web Worker declaration: var worker = new Worker(“worker.js”); In order to be independent from other workers, each worker script cannot access: –  the DOM –  the global window object •  (each web worker has its own self global object)
  • 69. Web Workers concurrency model A web worker has its own •  stack, •  heap •  message queue Two distinct runtimes can only communicate through sending messages via the postMessage method This method adds a message to the other runtime if the latter listens to message events.
  • 70. Web Workers The main JS script can communicate with workers via postMessage() calls: $(‘#button’).click(function(event) { $(‘#output’).html(“starting”); worker.postMessage(“start”); }); worker.onmessage = function(event) { $(‘#output’).html(event.data); }
  • 71. Web Workers The web worker script can post back messages to the main script: onmessage = function(event) { if(event.data === “start”) { var result; // do something with result postMessage(result); } }
  • 72. Roadmap JavaScript basics JavaScript event loop Ajax and promises DOM interaction JavaScript object orientation Web Workers Useful Microframeworks
  • 73. Zepto The only relevant downside of jQuery is about PERFORMANCE However, 1.  it is not very noticeable in current class-A mobile devices 2.  You can use mobile-suited alternatives to jQuery:
  • 74. Zepto  The goal is to have a ~5-10k modular library that executes fast, with a familiar API (jQuery) It can be seen as a mini-jQuery without support for older browsers
  • 76. Zepto Usage Simply replace the reference to jQuery with the one to Zepto
  • 77. Underscore.js A utility library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) It provides low-level utilities in the following categories: •  Collections •  Arrays •  Objects •  Functions •  Utilities http://documentcloud.github.com/underscore/
  • 78. iceCream Minimal grid system for your layouts, pure CSS3 only https://github.com/html5-ninja/icecream
  • 80. Ratchet It provides the basic building blocks for realizing well-known mobile design patterns Examples: •  Nav bars •  Title bars •  Lists •  Toggles •  Cards •  Popovers •  Sliders •  … http://goratchet.com
  • 84. Spin JS It allows you to dynamically create a spinning loading indicator Pure CSS à resolution-independent http://fgnass.github.io/spin.js/
  • 86. Frameworks jQueryMobile, jQuery, Backbone, etc. are beautiful tools… However they may impact the performance of your app à  Use a framework only when it is necessary –  Don’t use jQuery only because of the $(selector) syntax! Solution •  build your own micro-framework •  cut out Cordova plugins you do not use •  use micro-frameworks (http://microjs.com)
  • 87. A final note JavaScript allows you to do the same thing in many ways In order to make your code readable (and thus maintainable), you have to: •  follow as mush as possible known design patterns –  singleton, factory, etc. •  follow conventions –  https://github.com/rwaldron/idiomatic.js/
  • 89. + 39 380 70 21 600 Contact Ivano Malavolta | Gran Sasso Science Institute iivanoo ivano.malavolta@univaq.it www.ivanomalavolta.com