JavaScript programming language

Thursday 18th of December 2014 09:15:50 PM


  Toggle Advanced Options



Tutorials and documentation

"this" keyword

Execution Context Syntax of function call Value of this
Global N/A global object (e.g., window)
Function Method call:
myObject.foo();
myObject
Function Baseless function call:
foo();
global object (e.g., window)
(undefined in strict mode)
Function Using call:
foo.call(context, myArg);
context
Function Using apply:
foo.apply(context, [myArgs]);
context
Function Constructor with new:
var newFoo = new Foo();
the new instance
(e.g., newFoo)
Evaluation N/A value of this in parent context

Closures

JavaScript functions "package up" both computation and (execution) environment.

JavaScript closure example

function makeAddFunction(amount) {
  return function(number) {
    return number + amount;
  };
}

var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);

That is, a function defined inside another function retains access to the environment that existed in that function at the point when it was defined (Eloquent JavaScript - Chapter 3, Functions).

That is, a function’s scope remains intact even if it is called after its parent function and scope have closed.

Here’s another example:

var foo = function() {
    var x = "Hello World!";  
    return function() {  
        alert(x);    
    }  
};

var bar = foo();

bar(); // Displays "Hello World"

The important thing to note about the above function is that the function “foo” has finished executing. The function foo finishes executing and returns an anonymous function. Despite the fact that foo is finished, the anonymous function being returned still retains access to the variable “x”.

Truthy and falsy

Truthy and falsy are what we use to determine the result of a conditional expression. They are what we use to determine its result, they are not the result.

Here is what is falsy in JavaScript:

  • false
  • null
  • undefined
  • The empty string ""
  • The number 0
  • The number NaN ("Not a Number" is a number, it is a special number)

Everything else is truthy, and that includes Infinity (which is another special number, like NaN), and all Object objects and Array objects, empty or not.

The && and || operators (and short-circuit logic)

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objects before accessing their attributes:

var name = o && o.getName();

Or for setting default values:

var name = otherName || "default";






Google