Tuesday, September 9, 2014

XMLHttpRequest (XHR)

XMLHttpRequest() is an object (a constructor function) that allows you to send HTTP requests from JavaScript.

AJAX stands for Asynchronous JavaScript and XML

two steps to using the XMLHttpRequest:

  • Send the request—this includes creating an XMLHttpRequest object and attaching an event listener
  • Process the response—your event listener gets notified that the response has arrived


Send the Request

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = myCallback;
xhr.open('GET', 'somefile.txt', true);
xhr.send('');

HTTP request GET, POST, HEAD
The last parameter is a boolean specifying whether the request is asynchronous (true) or not (false).

Process the Response

There is a property of the XHR object called readyState

Every time it changes, the readystatechange event fires

0—uninitialized
1—loading
2—loaded
3—interactive
4—complete (response is back)

function myCallback() {
if (xhr.readyState < 4) {
return; // not ready yet
}
if (xhr.status !== 200) {
alert('Error!'); // the HTTP status code is not OK
return;
}
// all is fine, do the work
alert(xhr.responseText);
}




Events

browser broadcasts events

Can attach a JavaScript function (called an event listener or event handler) to a specific event and the browser will execute your function as soon the event occurs

Inline HTML Attributes

<div onclick="alert('Ouch!')">click</div>

Behind the scenes a function is still created and it contains the code you specified as a value of the onclick attribute

Element Properties

Assign a function to the onclick property of a DOM node element

<div id="my-div">click</div>
<script type="text/javascript">
    var myelement = document.getElementById('my-div');
    myelement.onclick = function() {
        alert('Ouch!');
        alert('And double ouch!');
    }
</script>


Drawback that you can attach only one function to the event

DOM Event Listeners

You can have many functions listening to an event

When the event fires, all functions are executed

Example:

<p id="closer">final</p>

>>> var mypara = document.getElementById('my-div');
>>> mypara.addEventListener('click', function()
{alert('Boo!')}, false);
>>> mypara.addEventListener('click', console.log, false);

Removing Event Listeners

to remove the event listener, use removeEventListener()

If you remove a listener, you have to pass a pointer to the same function you previously attached.
So you cannot remove listeners that use anonymous functions.

>>> para.addEventListener('click', paraHandler, false);
>>> para.removeEventListener('click', paraHandler, false);


Capturing and Bubbling

third parameter in addEventListener

DOM Level 2 Events specification suggests that the events propagate in three phases

capturing
target
bubbling



Historically

  • IE implemented only bubbling
  • Netscape only capturing
  • Firefox, Opera, and Safari implemented the three phases

You can stop the propagation of the event, in your listeners, so that it stops bubbling up and never reaches the document. To do this you can call the stopPropagation() method of the event object.

You can also use event delegation.
If you have ten buttons inside a <div>, you can always attach ten event listeners, one for each button. But a smarter thing to do is to attach only one listener to the wrapping <div> and when the event happens, check which button was the target of the click.

Prevent Default Behavior

// all links
var all_links = document.getElementsByTagName('a');
for (var i = 0; i < all_links.length; i++) { // loop all links
all_links[i].addEventListener('click', // event type
function(e) { // handler
if (!confirm('Are you sure you want to follow this link?')) {
e.preventDefault();
}
}, false); // don't use capturing
}

Not all events allow you to prevent the default behavior
can check the cancellable property of the event object.

Inheritance - Prototype Chaining

Every function has a prototype property, which contains an object.
When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object
When this function is invoked using the new operator, an object is created and this object has a secret link to the prototype object


Saturday, September 6, 2014

Prototype

Prototype property of a function

Every function has a prototype property and it contains an object

>>> function foo(a, b){return a * b;}
>>> typeof foo.prototype
"object"

It's as if you added this property yourself like this:
>>> foo.prototype = {}

prototype property of a Constructor function

Let's take a look at the constructor function Gadget

function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function() {
return 'I am a ' + this.color + ' ' + this.name;
}
}

Adding methods and properties to the prototype property of the constructor function is another way to add functionality to the objects this constructor produces.

Adding properties to the prototype object

Let's add two more properties, price and rating, and a getInfo() method

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};

another way to achieve the above result is to overwrite the prototype completely, replacing it with an object of your choice

Gadget.prototype = {
price : 100,
rating : 3,
getInfo : function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
}
};

How JavaScript Engine looks for a property

>>> var newtoy = new Gadget('webcam', 'black');
>>> newtoy.price;
100

JavaScript engine will look through all of the properties of the object.
If the property is not found, it will search the prototype of the constructor function used to create this object.

Gadget.prototype = {
price : 100,
rating : 3,
getInfo : function() {
return 'Rating: ' + Gadget.prototype.rating + ', price: ' + Gadget.prototype.price;
}
};

>>> newtoy.rating
3

>>> newtoy.constructor
Gadget(name, color)

>>> newtoy.constructor.prototype.rating
3

Overwriting Prototype's Property with Own Property

The own property takes precedence over the prototype's

Enumerating Properties

var a = [ 1, 2, 3 ];
for ( var i in a) {
console.log(a[i]);
}

var o = {p1: 1, p2: 2};
for (var i in o) {
console.log(i + '=' + o[i]);
}

o/p:
p1=1
p2=2

Points to note

Not all properties show up in a for-in loop. The properties that do show up are called enumerable.
Prototypes that come through the prototype chain will also show up as long as they are enumerable.

Related object methods

propertyIsEnumerable()

  • can check which properties are enumerable
  • return false for all of the prototype's properties

hasOwnProperty()

  • can check if a property is an own property versus prototype's

isPrototypeOf()

Every object also gets the isPrototypeOf() method
This method tells you whether that specific object is used as a prototype of another object.

var monkey = {
hair : true,
feeds : 'bananas',
breathes : 'air'
};

function Human(name) {
this.name = name;
}
Human.prototype = monkey;

>>> var george = new Human('George');

"Is monkey george's prototype?"

>>> monkey.isPrototypeOf(george)
true

The Secret __proto__ Link

The prototype property will be consulted when you try to access a property that does not exist in the current object.

var monkey = {
feeds : 'bananas',
breathes : 'air'
};
function Human() {
}
Human.prototype = monkey;

var developer = new Human();
developer.feeds = 'pizza';
developer.hacks = 'JavaScript';

>>> developer.constructor = 'junk'
"junk"

>>> typeof developer.constructor.prototype
undefined

but the following still works

>>> developer.breathes
"air"

This shows that the secret link to the prototype still exists __proto__

>>> developer.__proto__
Object feeds=bananas breathes=air

because it does not exist in Internet Explorer, so your scripts won't be portable.

__proto__ is a property of the instances, whereas prototype is a property of the constructor functions

Augmenting Built-in Objects

Array, String, and even Object, and Function can be augmented through their prototypes.
Can, for example, add new methods to the Array prototype and in this way make them available to all arrays.

String.prototype.reverse = function() {
return Array.prototype.reverse.apply(this.split('')).join('');
}

>>> "Stoyan".reverse();
"nayotS"

Error

JavaScript provides the statements try, catch, and finally to help you deal with errors

Error objects are created by using one of these built-in constructors:

  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

All of these constructors inherit from the Error object.

An example of an error will be trying to call a function that doesn't exist

>>> iDontExist();

try {
iDontExist();
} catch (e) {
// do nothing
}

try {
iDontExist();
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}

You can also create error objects yourself using new Error() or any of the other error constructors

try {
var total = maybeExists();
if (total === 0) {
throw new Error('Division by zero!');
} else {
alert(50 / total);
}
} catch (e) {
alert(e.name + ': ' + e.message);
} finally {
alert('Finally!');
}

Alternatively, you don't need any constructor; you can simply throw a normal object:

throw {
name : "MyError",
message : "OMG! Something terrible has happened"
}

Math & Date

String

Number

Boolean

Function

Functions are actually objects

Defining functions

There are two ways to give names to functions

Function declaration

function myFunc1()
{
}

>>> function sum(a, b) {return a + b;};
>>> sum(1, 2)
3

Function expression

var myFunc2 = function()
              {
              }

>>> var sum = function(a, b) {return a + b;};
>>> sum(1, 2)
3

Using the function constructor

There is a built-in constructor function called Function()

>>> var sum = new Function('a', 'b', 'return a + b;');
>>> sum(1, 2)
3

Difference between function declaration and expression

a function declared as a named function expression cannot be used in code until after it is encountered and defined. On the other hand, the function defined using the function declaration method can be called whenever you want to on the page, even as an onload handler.

Drawbacks of using a Function constructor

When using the Function() constructor, you pass the parameter names first (as strings) and then the source code for the body of the function (again as a string).

This source code evaluation suffers from the same drawbacks as the eval() function, so defining functions using the Function() constructor should be avoided when possible

stay away from cases where you pass JavaScript code as a string

Return values

The return type can be a number, a string of text, or even a DOM element (object).

The default return value is undefined

Properties of the Function Objects

>>> function myfunc(a){return a;}
>>> myfunc.constructor
Function()

Functions also have a length property, which contains the number of parameters the function accepts

>>> function myfunc(a, b, c){return true;}
>>> myfunc.length
3

which doesn't exist in the ECMA standard, but is implemented across the browsers—the caller property. This returns a reference to the function that called our function.

>>> function A(){return A.caller;}
>>> function B(){return A();}
>>> B()
B()

If you call A() from the global space (outside of any function), A.caller will be null

The most important property of a function is the prototype property

Methods of the Function Objects

toString()

>>> function myfunc(a, b, c) {return a + b + c;}
>>> myfunc.toString()
"function myfunc(a, b, c) {
return a + b + c;
}"

var some_obj = {
name : 'Ninja',
say : function(who) {
return 'Haya ' + who + ', I am a ' + this.name;
}
}

>>> some_obj.say('Dude');
"Haya Dude, I am a Ninja"

call()

the first parameters to call is an object that this refers to within the function definition
so my_obj is referred to by this in function definition that say points to.

>>> my_obj = {name: 'Scripting guru'};
>>> some_obj.say.call(my_obj, 'Dude');
"Haya Dude, I am a Scripting guru"

apply()

The method apply() works the same way as call() but with the difference that all parameters you want to pass to the method of the other object are passed as an array

some_obj.someMethod.apply(my_obj, ['a', 'b', 'c']);

>>> some_obj.say.apply(my_obj, ['Dude']);
"Haya Dude, I am a Scripting guru"

The arguments Object Revisited

arguments looks like an array but is actually an array-like object

It just has the length property but it doesn't provide any of the array methods, such as sort() or slice()

The arguments object has another interesting property—the callee property. This contains a reference to the function being called

>>> function f(){return arguments.callee;}
>>> f()
f()

arguments.callee allows anonymous functions to call themselves recursively

(function(count) {
if (count < 5) {
alert(count);
arguments.callee(++count);
}
})(1)

Array

Array

>>> var a = new Array();

is same as

>>> var a = [];

>>> var a2 = new Array(5);
>>> a2;
[undefined, undefined, undefined, undefined, undefined]

>>> typeof a;
"object"

>>> a.toString();
"1,2,3,four"

>>> a.constructor
Array()

Array objects have a length property automatically defined for them, while normal objects do not

It's OK to add both numeric and non-numeric properties to both arrays and objects

>>> a[0] = 1; o[0] = 1;
>>> a.prop = 2; o.prop = 2;

The length property can also be set by you

>>> a.length = 5
5
>>> a
[1, undefined, undefined, undefined, undefined]

Interesting Array methods

In addition to the methods inherited from the parent object, array objects also have methods, such as sort(), join(), and slice(), among others

>>> var a = [3, 5, 1, 7, 'test'];
>>> a.push('new')
6
>>> a
[3, 5, 1, 7, "test", "new"]

>>> var b = a.sort();
>>> b
[1, 3, 5, 7, "test"]

>>> a.join(' is not ');
join() returns a string
"1 is not 3 is not 5 is not 7 is not test"

slice() returns a piece of the array without modifying the source array

>>> b = a.slice(1, 3);
[3, 5]

>>> b = a.slice(0, 1);
[1]

splice() modifies the source array
It removes a slice, returns it, and optionally fills the gap with new elements
>>> b = a.splice(1, 2, 100, 101, 102);
[3, 5]
>>> a
[1, 100, 101, 102, 7, "test"]
>>> a.splice(1, 3)
[100, 101, 102]
>>> a
[1, 7, "test"]

Friday, September 5, 2014

Objects

An object is very similar to an array but with the difference that you define the keys yourself.

var o = {prop: 1};
var o = {"prop": 1};
var o = {'prop': 1};

There are some cases when you have must use quotes:

  • If the property name is one of the reserved words in JavaScript
  • If it contains spaces or special characters (anything other than letters, numbers, and the underscore character)
  • If it starts with a number


If the name you have chosen for a property is not a valid name for a variable in JavaScript, then you need to in place in quotes

A property of an object can contain a function

var dog = {
name : 'Benji',
talk : function() {
alert('Woof, woof!');
}
};

JavaScript uses arrays to represent indexed arrays and objects to represent associative arrays.

Accessing Object's Properties

Using square bracket notation, for example hero['occupation']
Using the dot notation, for example hero.occupation

if the name of the property is not a valid variable name, you cannot use the dot notation.

Accessing a non-existing property returns undefined:

>>> 'Hair color is ' + hero.hair_color;

"Hair color is undefined"

Objects can contain any data, including other objects.

var book = {
name : 'Catch-22',
published : 1961,
author : {
firstname : 'Joseph',
lastname : 'Heller'
}
};

>>> book.author.firstname
>>>"Joseph"

>>> book['author']['lastname']
>>>"Heller"

>>> book['author'].lastname
>>>"Heller"

Calling an Object's Methods

var hero = {
breed : 'Turtle',
occupation : 'Ninja',
say : function() {
return 'I am ' + hero.occupation;
}
}

>>> hero.say();

>>> hero['say']();

Altering Properties/Methods

>>> var hero = {};

Adding some properties and a method

>>> hero.breed = 'turtle';
>>> hero.name = 'Leonardo';
>>> hero.sayName = function() {return hero.name;};

Using this Value

So when you say this, you are actually saying "this object" or "the current object".

var hero = {
name : 'Rafaelo',
sayName : function() {
return this.name;
}
}

>>> hero.sayName();
"Rafaelo"

Constructor Functions

There is another way to create objects: by using constructor functions

function Hero() {
this.occupation = 'Ninja';
}

>>> var hero = new Hero();
>>> hero.occupation;
"Ninja"

function Hero(name) {
this.name = name;
this.occupation = 'Ninja';
this.whoAreYou = function() {
return "I'm " + this.name + " and I'm a " + this.occupation;
}
}

>>> var h1 = new Hero('Michelangelo');
>>> var h2 = new Hero('Donatello');
>>> h1.whoAreYou();

The Global Object

The host environment provides a global object and all global variables are actually properties of the global object

the global object is called window

>>> var a = 1;

>>> window['a'] or window.a
1

The global functions you saw in Chapter 3 can also be invoked as methods of the window object.

>>> parseInt('101 dalmatians')
>>> window.parseInt('101 dalmatians')

Oddities

Declaring a constructor function and calling it without new, returns "undefined"

>>> function Hero(name) {this.name = name;}
>>> var h = Hero('Leonardo');
>>> typeof h
"undefined"
>>> typeof h.name
h has no properties

>>> name
"Leonardo"
>>> window.name
"Leonardo"

>>> var h2 = new Hero('Michelangelo');
>>> typeof h2
"object"
>>> h2.name
Michelangelo

constructor Property

When an object is created, a special property is assigned to it behind the scenes—the constructor property
It contains a reference to the constructor function used to create this object.

>>> h2.constructor
Hero(name)

>>> var h3 = new h2.constructor('Rafaello');
>>> h3.name;
Rafaello

If an object was created using the object literal notation, its constructor is the built-in Object() constructor function

>>> var o = {};
>>> o.constructor;
Object()

>>> typeof o.constructor
function

instanceof Operator

an test if an object was created with a specific constructor function

>>> function Hero(){}
>>> var h = new Hero();
>>> var o = {};
>>> h instanceof Hero;
true
>>> h instanceof Object;
false
>>> o instanceof Object;
true

Functions that Return Objects

function factory(name) {
return {
name : name
};
}

>>> var o = factory('one');
>>> o.name
"one"

>>> o.constructor
Object()

can also use constructor functions and return objects, different from this.

>>> function C2() {this.a = 1; return {b: 2};}
>>> var c2 = new C2();
>>> typeof c2.a
undefined
>>> c2.b
2

Instead of returning the object this, which contains the property a, the constructor returned another object that contains the property b.

Passing Objects

When you copy an object or pass it to a function, you only pass a reference to that object
Consequently, if you make a change to the reference, you are actually modifying the original object

>>> var original = {howmany: 1};
>>> var copy = original;
>>> copy.howmany
1
>>> copy.howmany = 100;
100
>>> original.howmany
100

The same thing applies when passing objects to functions

>>> var original = {howmany: 100};
>>> var nullify = function(o) {o.howmany = 0;}
>>> nullify(original);
>>> original.howmany
0

Comparing Objects

you'll get true only if you compare two references to the same object.

>>> var fido = {breed: 'dog'};
>>> var benji = {breed: 'dog'};

>>> benji === fido
false
>>> benji == fido
false
>>> var mydog = benji;
>>> mydog === benji
true

Built-in Objects

The built-in objects can be divided into three groups

Data wrapper objects—Object, Array, Function, Boolean, Number, and String.
Utility objects—These are Math, Date, RegExp and can come in very handy
Error objects—The generic Error object as well as other, more specific objects

Object

Object is the parent of all JavaScript objects

>>> var o = {};
>>> var o = new Object();

An empty object already contains some methods and properties.

o.constructor
o.toString()
o.valueOf()

Closures

Scope Chain

If you define a function n() nested inside f(), n() will have access to variables in its own scope, plus the scope of its "parents". This is known as scope chain, and the chain can be as long (deep) as you need it to be

var a = 1;
function f() {
var b = 1;
function n() {
var c = 3;
}
}

Lexical Scope

In JavaScript, functions have lexical scope

This means that functions create their environment (scope) when they are defined, not when they are executed

>>> function f1(){var a = 1; f2();}
>>> function f2(){return a;}
>>> f1();

a is not defined

At the time when f2() was defined (as opposed to executed), there was no a in sight.

f2(), just like f1(), only has access to its own scope and the global scope. f1() and f2() don't share their local scopes.

When a function is defined, it "remembers" its environment, its scope chain

>>> var a = 5;
>>> f1();
5

>>> delete a;
true
>>> f1();
a is not defined

>>> delete f2;
true
>>> f1()
f2 is not defined

Breaking the Chain with a Closure



If you're at point a, you're inside the global space


If you're at point b, which is inside the space of the function F, then you have access to the global space and to the F-space

If you're at point c, which is inside the function N, then you can access the global space, the F-space and the N-space


the closure—happens when somehow N breaks out of F and ends up in the global space

N will still have access to the F-space, and hence can access b.
This is interesting, because N is where a is and yet N does have access to b, but a doesn't

And how does N break the chain?

  • By making itself global (omitting var) 
  • by having F deliver (or return) it to the global space

Closure #1

function f() {
var b = "b";
return function() {
return b;
}
}

>>> b
b is not defined

>>> var n = f();
>>> n();
"b"

f is a global function. Calling f returned function with return value b to the global space. This function is assigned to variable n. So calling n now returned b.

Closure #2

var n;
function f() {
var b = "b";
n = function() {
return b;
}
}

>>> f();

>>> n();
"b"

Closure #3

function f(arg) {
var n = function() {
return arg;
};
arg++;
return n;
}

>>> var m = f(123);
>>> m();
124

Closures in a Loop

function f() {
var a = [];
var i;
for (i = 0; i < 3; i++) {
a[i] = function() {
return i;
}
}
return a;
}

>>> var a = f();

>>> a[0]()
3
>>> a[1]()
3
>>> a[2]()
3

Closures don't remember the value, they only link (reference) the i variable and will return its current value
After the loop, i's value is 3. So all the three functions point to the same value.

function f() {
var a = [];
var i;
for (i = 0; i < 3; i++) {
a[i] = (function(x) {
return function() {
return x;
}
})(i);
}
return a;
}

Alternatively,

function f() {
function makeClosure(x) {
return function() {
return x;
}
}
var a = [];
var i;
for (i = 0; i < 3; i++) {
a[i] = makeClosure(i);
}
return a;
}

Getter/Setter

var getValue, setValue;
(function() {
var secret = 0;
getValue = function() {
return secret;
};
setValue = function(v) {
secret = v;
};
})()

>>> getValue()
0
>>> setValue(123)
>>> getValue()
123

Iterator

function setup(x) {
var i = 0;
return function() {
return x[i++];
};
}

>>> var next = setup(['a', 'b', 'c']);

>>> next();
"a"
>>> next();
"b"
>>> next();
"c"

Scope of variables

Variables in JavaScript are not defined in a block scope, but in a function scope

This means that if a variable is defined inside a function, it's not visible outside of the function.

However, a variable defined inside an if or a for code block is visible outside the code block.

The term "global variables" describes variables you define outside of any function.

It is also important to note that if you don't use var to declare a variable, this variable is automatically assigned global scope

>>> function f() { local = 2; }
>>> local
ReferenceError: local is not defined
>>> f ()
>>> local
2

The function f() contains the variable local. Before calling the function, the variable doesn't exist. When you call the function for the first time, the variable local is created with a global scope.

var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();

So a local variable overwrites any global variable with the same name
The first alert will show "undefined".
At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space.

Functions

The return statement. A function always returns a value. If it doesn't return value explicitly, it implicitly returns the value undefined.

Parameters

A function may not require any parameters, but if it does and you forget to pass them, JavaScript will assign the value undefined to the ones you skipped

If you pass more parameters than the function expects, the extra parameters will be silently ignored

You can create functions that are flexible about the number of parameters they accept. This is possible thanks to the arguments array that is created automatically inside each function

expression arguments.length returns the number of parameters passed when the function was called

Pre-defined Functions

a number of functions that are built into the JavaScript engine

parseInt()

takes any type of input (most often a string) and tries to make an integer
an optional second parameter, which is the radix, telling the function what type of number to expect decimal, hexadecimal, binary. Default is decimal, hex if 0x, and Oct if 0 is the prefix of the passed in value

If it fails, it returns NaN

>>> parseInt('123')
123

>>> parseInt('abc123')
NaN

>>> parseInt('FF', 10)
NaN

>>> parseInt('FF', 16)
255

parseFloat()

>>> parseFloat('123')
123

>>> parseFloat('123e-2')
1.23

>>> parseFloat('123e2')
12300

isNaN()

check if an input value is a valid number that can safely be used in arithmetic operations

>>> isNaN(NaN)
true
>>> isNaN(123)
false

isFinite()

checks whether the input is a number that is neither Infinity nor NaN.

>>> isFinite(Infinity)
false
>>> isFinite(-Infinity)
false
>>> isFinite(12)
true

Encode/Decode URIs

In a URL (Uniform Resource Locator) or a URI (Uniform Resource Identifier), some characters have special meanings

If you want to "escape" those characters, you can use the functions

  • encodeURI()
  • encodeURIComponent().
    • assumes you're only passing a part of the URL, like a query string for example, and will encode all applicable characters

>>> var url = 'http://www.packtpub.com/scr ipt.php?q=this and that';
>>> encodeURI(url);
"http://www.packtpub.com/scr%20ipt.php?q=this%20and%20that"


The opposites of encodeURI() and encodeURIComponent() are decodeURI() and decodeURIComponent() respectively

eval()

eval() takes a string input and executes it as JavaScript code

So eval('var ii = 2;') is the same as simply var ii = 2;

The drawbacks of using eval() are

Performance—it is slower to evaluate "live" code, than to have the code directly in the script.
Security—JavaScript is powerful, which also means it can cause damage. If you don't trust the source of the input you pass to eval(), just don't use it.

alert()

it blocks the browser thread, meaning that no other code will be executed until the user closes the alert

Functions are Data

functions in JavaScript are actually data

function f()
{
    return 1;
}

var f = function(){return 1;}

>>> function f(){return 1;}
>>> typeof f

"function"

it can be copied to a different variable and even deleted

>>> var sum = function(a, b) {return a + b;}
>>> var add = sum;
>>> delete sum

Anonymous Functions

functions can be used without assigning a name

You can pass an anonymous function as a parameter to another function
You can define an anonymous function and execute it right away

Callback Functions

function invoke_and_add(a, b) {
return a() + b();
}

function one() {
return 1;
}
function two() {
return 2;

>>> invoke_and_add(one, two);

>>> invoke_and_add(function(){return 1;}, function(){return 2;})

  • They let you pass functions without the need to name them (which means there are less global variables)
  • You can delegate the responsibility of calling a function to another function
  • They can help with performance

When you pass a function A to another function B and B executes A, it's often said that A is a callback function

Self-invoking Functions

(function() {
alert('boo');
})()

(function(name) {
alert('Hello ' + name + '!');
})('dude')


One good reason for using self-invoking anonymous functions is to have some work done without creating global variables. 
A drawback, of course, is that you cannot execute the same function twice. 
This makes the anonymous self-invoking functions best suited for one-off or initialization tasks

Inner (Private) Functions

function a(param) {
function b(theinput) {
return theinput * 2;
}
;
return 'The result is ' + b(param);
};

Benefits:

You keep the global namespace clean (smaller chance of naming collisions).

Privacy—you expose only the functions you decide to the "outside world", keeping to yourself functionality that is not meant to be consumed by the rest of the application.

Functions that Return Functions

function a() {
alert('A!');
return function() {
alert('B!');
};
}

>>> var newFunc = a();
>>> newFunc();

To execute the returned function immediately 
>>> a()();

Function, Rewrite Thyself!

>>> a = a();       alerts A!
>>> a()              alerts B!

Function overwriting itself from the inside

function a() {
alert('A!');
a = function() {
alert('B!');
};
}

Example

var a = function() {
function someSetup() {
var setup = 'done';
}
function actualWork() {
alert('Worky-worky');
}
someSetup();
return actualWork;
}();

a self-invoking function—calls itself using the parentheses following its definition
The function executes for the first time, calls someSetup() and then returns a reference to the variable actualWork which is assigned to a

Sunday, August 31, 2014

Conditions and Loops

Checking if a Variable Exists

>>> if (typeof somevar !== "undefined"){result = 'yes';}

variable somevar may have been declared but not assigned a value yet and you'll still get the same result

>>> var somevar;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""

typeof will always return a string and you can compare this string with "undefined"

>>> var somevar;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""
>>> somevar = undefined;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""

Alternative if Syntax

var result = (a === 1) ? "a is one" : "a is not one";

Switch

var a = '1';
var result = '';
switch (a) {
case 1:
result = 'Number 1';
break;
case '1':
result = 'String 1';
break;
default:
result = 'I don\'t know';
break;
}
result;

Loops

In JavaScript, there are four types of loops:

while loops
do-while loops
for loops
for-in loops

var punishment = '';
for (var i = 0; i < 100; i++) {
punishment += 'I will never do this again, ';
}

var a = [ 'a', 'b', 'c', 'x', 'y', 'z'];
var result = '\n';
for (var i in a) {
result += 'index: ' + i + ', value: ' + a[i] + '\n';
}


Arrays

>>> var a = [];
>>> typeof a;
"object"

>>> var a = [1,2,3];

Adding/Updating Array Elements

>>> a[2] = 'three';
"three"
>>> a
[1, 2, "three"]

>>> var a = [1,2,3];
>>> a[6] = 'new';
"new"
>>> a
[1, 2, 3, undefined, undefined, undefined, "new"]

Deleting Elements

>>> var a = [1, 2, 3];
>>> delete a[1];
true
>>> a
[1, undefined, 3]

Arrays of arrays

>>> var a = [1, "two", false, null, undefined];
>>> a
[1, "two", false, null, undefined]
>>> a[5] = [1,2,3]
[1, 2, 3]
>>> a
[1, "two", false, null, undefined, [1, 2, 3]]

>>> var a = [[1,2,3],[4,5,6]];
>>> a
[[1, 2, 3], [4, 5, 6]]

>>> a[0]
[1, 2, 3]

>>> a[0][0]
1

>>> var s = 'one';
>>> s[0]
"o"

Primitive Data Types

Variables are Case Sensitive

Primitive Data Types

Number

  • this includes floating point numbers as well as integers
  • Infinity
  • NaN
infinity - infinity is NAN
10 * "f" is NAN
1 + 2 + NAN is NAN

String
var s1 = "one";
var s2 = "two";
var s3 = s1 + s2;
s3 is onetwo

Boolean
  • can be either true or false
If you quote true or false, they become strings
Understanding how any value converts to a boolean is important. The following values convert to false
  • The empty string ""
  • null
  • undefined
  • The number 0
  • The number NaN
  • The boolean false
Undefined
when you try to access a variable that doesn't exist, you get the special value undefined.
The same will happen when you have declared a variable, but not given it a value yet.
>>> var i = 1 + undefined; i;
NaN
>>> 1*undefined
NaN
>>> !!undefined
false
>>> "" + undefined
"undefined"

Null
It means no value, an empty value, nothing.
The difference with undefined is that if a variable has a value null, it is still defined, it only happens that its value is nothing.
null is an object

>>> var somevar = null
>>> typeof somevar
"object"

>>> var i = 1 + null; i;
1
>>> 1*null
0
>>> !!null
false
>>> "" + null
"null"

typeof Operator

To know the data type of a variable or a value, you can use the special typeof operator.
This operator returns a string that represents the data type.

Logical Operators

!, &&, ||

Order of precedence (!, &&, ||)

Oddities

if JavaScript encounters a non-boolean expression as an operand in a logical operation, the non-boolean is returned as a result.

>>> true || "something"
true
>>> true && "something"
"something"

Comparison

==
===
  • both value and type equality

!=
  • Returns true if the operands are not equal to each other (after a type conversion)

!==
  • Non-equality comparison without type conversion
>
>=
<
<=

>>> NaN == NaN
false