JavaScript - ilya-khadykin/notes-outdated GitHub Wiki

JavaScript cheatsheet

The secret to writing large apps in JavaScript is not to write large apps. Write many small apps that can talk to each other.

JavaScript vs ECMAScript

ECMAScript is the official name for JavaScript. This is due to a trademark on Java (held originally by Sun and now by Oracle)

  • JavaScript means the programming language
  • ECMAScript is the name used by the language specification. The current version of JavaScript is ECMAScript 5; ECMAScript 6 is currently being developed

The Language

Identifiers and Variable names

All Variables and function names are case sensitive

Statements vs Expressions

JavaScript has two major syntactic categories: statements and expressions:

  • Statements "do things". A program is a sequence of statements, for example var foo;
  • Expressions produce values. They are function arguments, the right side of an assignment, for example 3 * 7
// this is 'expression statement'
myFunc(7, 1);

The function call is an expression

Values

JavaScript makes a somewhat arbitary distinction between values:

  • the primitive values are booleans, numbers, strings, null and undefined
    • Booleans: true, false
    • Numbers: 1736, 1.351
    • Strings: 'abc', "abc"
    • Two "nonvalues": undefined, null
  • all other values are objects

A major difference between them is how they are compared; each object has a unique identity and is only (strictly) equal to itself:

var obj1 = {};
var obj2 = {};

obj1 === obj2 // false
obj1 === obj1 // true


var prim1 = 123;
var prim2 = 123;

prim1 === prim2 // true

Primitives are compared by value

Objects are compared by reference

undefined and null

undefined means 'no value':

  • uninitialized variables;
  • missing parameters;
  • nonexistent properties.

'null' means 'no object'; it's used as a nonvalue whenever an object is expected (parameters, last in a chain of objects, etc)

Enable Strict Mode

Strict Mode enables more warnings and makes JavaScript a cleaner language

'use strict'; // put this line at the top of the file

// or function
function functionInStrictMode() {
  'use strict';
}

callbacks

Callbacks are typically used to run a piece of code after a certain event has happened (mouse-click, data was written in db etc). Typically it's an anonymous function (function declared without a name) that's passed directly into the receiving function as a parameter.

Callbacks are asynchronous

Callback doesn't inherit the scope of the function it's passed into

A callback function inherits the scope in which it's defined

You can also use named callbacks and pass the code as a reference to avoid callback hell

// var myTimer = setTimeout(callback, delay);

var waitForIt = setTimeout(function() {
  console.log('This is callback function');
}, 2000);
// clearTimeout(waitForIt);

Closures

The closure protects the value from outside interference.

The returned method has access to the scope in which it was created

var user = {};

var setAge = function (myAge) {
  return {
    getAge: function () {
      return myAge;
    }
  };
};

user.age = setAge(30);
console.log(user.age); // Object {getAge: function}
console.log(user.age.getAge()); // 30

var usertwo = {};
usertwo.age = setAge(35);
console.log(usertwo.age.getAge()); // 35
console.log(user.age.getAge()); // 30

Syntax

Core syntax

// single-line comment

/*
    Multi-line comment
*/

// declaring a variables
var x; 
var x = 6;
var x = 1, y = 2, z = 3; // not recommended

x = 3 + y; // assignment 

foo(x, y); // function call
obj.bar(3); // calling method 'bar' of object 'obj'

// A conditional statement
if (x === 0) {
  x = 123;
}

// Defining a function
function func1(param1, param2) {
  return param1 + param2;
}

Logic Flow

Conditionals

// typical conditinal statemet
var x;
if (y >= 0) {
  x = y;
} else {
  x = -y;
}
// ^^^ the same result as above but as an expression
var x = y >= 0 ? y : -y;
// you can use expressions as a function arguments
myFinction(y >= 0 ? y : -y) {}


if (myvar === 0) {
  // then
} else if (myvar === 1) {
  // else-if
} else if (myvar === 2) {
  // else-if
} else {
  // else
}

if (x < 0) return -x;

switch (fruit) {
  case 'banana':  // === equality operator is used
    // ...
    break;
  case 'apple':
    break;
  default:  // all other cases
    // ...
}

Loops

// for loop
for (var i=0; i < arr.length; i++) {
  console.log(arr[i]);
}

// while loop
var i = 0;
while (i < arr.length) {
  console.log(arr[i]);
  i++;
}

do {
  // always execute at least once
} while (condition);

break; // leaves the loop
continue; // starts a new loop iteration

Functions

function add(param1, param2) {
  return param1 + param2;
}

add(6,1); // 7

// preferred
var add = function (param1, param2) {
  return param1 + param2;
};

// function expression
someOtherFunction(function (p1, p2) { ... });

// function declarations are hosted
function foo() {
  bar(); // Ok, bar is hoisted
  function bar() {
    // ...
  }
}
// variables are also hoisted
function foo() {
  bar(); // Ok, bar is hoisted
  var bar = function () {
    // ...
  }
}

// Special variable arguments
function f() { return arguments }
var args = f('a', 'b', 'c');
args.length; // 3
args[0] // 'a'


// COMMON PATTERN FOR ASSIGNING DEFAULT VALUES TO PARAMETS
function pair(x, y) {
  x = x || 0; // (1)
  y = y || 0;
  return [ x, y ];
}

// ENFORCING AN ARITY
function pair(x, y) {
  if (arguments.length !== 2) {
    throw new Error('Need exactly 2 arguments');
  }
  // ...
}

// CONVERTING ARGUMENTS TO AN ARRAY
// 'arguments' is not an array, you cannot remove elements, etc
function toArray(arrayLikeObject) {
  return Array.prototype.slice.call(arrayLikeObject);
}

Exception Handling

function getPerson(id) {
  if (id < 0) {
    throw new Error('ID must not be negative: '+id);
  }
  return { id: id }; // normally: retrieved from db
}

function getPersons(ids) {
  var result = [];
  ids.forEach(function (id) {
    try {
      var person = getPerson(id);
      result.push(person);
    } catch (exception) {
      console.log(exception);
    }
  });
  return result;
}
// ^^^ result
getPersons([2, -5, 137]);
// [Error: ID must not be negative: -5]
// [ { id: 2 }, { id: 137 } ]

Properties

// value.propKey

var str = 'abc';
str.length // outputs 3
'abc'.length // also outputs 3

You can also invoke methods as properties of an object: 'hello'.toUpperCase()

Creating property with dot operator

var obj = {};
obj.foo = 123;  // creating a new property
// accessing the property of an object
console.log(obj.foo); // outputs 123

Objects

// Plain object
{
  firstName: 'Jane',
  lastName: 'Doe'
}

// Array, indexing starts from 0
['apple', 'banana', 'cherry']

// Regular expression
/^a+b+$

Data types

Booleans

Operators

Produce true or false:

  • binary logical operators: && (and), || (Or)
  • Prefix logical operator: ! (Not)
  • Comparison operators: >, >=, <, <=
  • Equality operators: ===, !==, ==, !=

Boolean() converts its parameter to a boolean

Boolean(undefined) // false

Boolean(3) // true

Boolean({}) // true

Numbers

All numbers in JavaScript are floating-point: 1 === 1.0 // true

NaN and Infinity

Number('xyz') // 'xyz' can't be converted to a number
NaN

3 / 0
Infinity

Math.pow(2, 1024) // number too large
Infinity

(-)Infinity is larger(smaller) than any other number (except NaN)

Operators

  • Addition: nuber1 + number2
  • Substraction: nuber1 - number2
  • Multiplication: nuber1 * number2
  • Division: nuber1 / number2
  • Remainder: nuber1 % number2
  • Increment: ++variable, variable++
  • Decrement: --variable, variable--
  • Negate: -value
  • Convert to number: +value

Strings

"Did she say \"Hello\"?" // \ escapes characters 

var str = 'abc';
str[1] // 'b'

'abc'.length // 3

Checking for undefined or null

if (x === undefined || x === null) {
  ...
}

// undefined and null are considered false
if (!x) {
  ...
}

Be careful! false, 0, NaN and '' are also considered false

Checking data type or object type

// typeof value
typeof true // 'boolean'
typeof 'abc' // 'string'
typeof {} // 'object' empty object literal
typeof [] // 'object' empty array literal
typeof null // 'object' this is a bug

// value instanceof Constr
var b = new Bar();
b instanceof Bar // true
{} instanceof Object // true
[] instanceof Array // true
[] instanceof Object // true // Array is a subconstructor of Object

References