Essential Javascript Cheat Sheet

, 2/10/2017

Note : All the content here comes from this awesome article : https://www.codementor.io/johnnyb/javascript-cheatsheet-fb54lz08k

This cheat sheet include a couple of browser features you can access with JavaScript on the client side and platform-agnostic features you can use either on the client or server.

Table of content

Primitives values

  • Booleans: false, true
  • Numbers: 42, 3.14, 0b11010, 0x16, NaN (check out The magic of numbers)
  • Strings: ‘Earth’, « Mars »
  • Special values: undefined, null

Variables

You can create variables using var, let, const (the last two ones are available only in ES6).

// This is how you define a variable
// `x` will be `undefined`
var x;

// Declare a constant (the convention is to use CAPS for constants)
const FOO = 42;

// Declare another two variables, using `var` and `let`
var hello = 'world';
let bar = 'baz';

Variables don’t have a type. As long as they are not constants, you can change their data:

let foo = 42;
foo = 'bar';
foo
// will return 'bar'

Let vs var

let and var are pretty similar, but unlike var, let declares a block scope local variable, optionally initializing it to a value.

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. The var keyword which defines a variable to an entire function regardless of block scope.

var a = 42;
if (true) {
  var b = 7;
  let c = 123;
}

// Obviously, we can access the `a` variable
console.log(a);
// => 42

// We can access `b` as well, even it was assigned in the
// if block (see below what happens if the expressions is
// false).
console.log(b);
// => 7

// We cannot access `c` here because it was declared using
// `let`, inside of the `if` block, therefore it's only
// accessible in the `if` block.
console.log(c);
// => Error: c is not defined

How does const work ?

const is simple: you can use it for variables which values remain the same.

const PI = 3.14;

PI = 3;
→ TypeError: Assignment to constant variable.

Note, this won’t freeze the objects:

// Create an object
const myObj = { foo: 'bar' };

// Update the `foo` field
myObj.foo = 42;

// Add a new field
myObj.hello = 'world';

myObj
→ { foo: 42, hello: 'world' }

// Tho, if you try to reset the whole thing, you can't
myObj = {};
→ TypeError: Assignment to constant variable.

Regular expressions

Regular expressions are delimited by slashes:

/^[0-9]+$/gm.test("a")
// => false

/^[0-9]+$/gm.test("42")
// => true

A regular expression has a pattern and flags. The pattern in this example is ^[0-9]+$—meaning if the input is one or more digits (from 0 to 9), we validate it—while the flags are g (global) and m (multiline).

regex101.com is a good resource for visualizing and sharing regular expressions with others.

Regular expressions can be used to match things in strings, such as numbers:

// Get all the numbers from this input (note you'll get an array of strings)
> "Alice was born in 1974, so she's 42 years old in 2016.".match(/[0-9]+/g)
[ '1974', '42', '2016' ]

// Want to get numbers? Map them using the `Number` function
> "Alice was born in 1974, so she's 42 years old in 2016.".match(/[0-9]+/g).map(Number)
[ 1974, 42, 2016 ]

// BE CAREFUL that if there's no match `match` will return `null`
> "Bob is seven years old.".match(/[0-9]+/g)
null

Also, they can be used to replace parts of the strings:

// Mask all the digits of a credit card number, but the last 4
> "1234234534564567".replace(/\d(?=\d{4})/g, "*");
'************4567'

Useful Math functions and constants

// Get the PI number
> Math.PI
3.141592653589793

// Get the E number
> Math.E
2.718281828459045

// Maximum between two numbers
> Math.max(7, 42)
42

// Minimum between numbers (arguments)
> Math.min(7, 42, 255, 264)
7

// Power
> Math.pow(2, 4)
16

// Random number between 0 (inclusive) and 1 (exclusive)
> Math.random()
0.2114640628617317

// Round
> Math.round(41.8)
42

If statements

let foo = 42;

if (foo > 40) {
    // do something
} else {
    // do something else
}

Operators

  • && logical and
  • || logical or
  • ! logical not
  • == equal to
  • === equal value and equal type
  • != not equal
  • !== not equal value or not equal type
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to
  • ? ternary operator
  • typeof Returns the type of a variable
  • instanceof Returns true if an object is an instance of an object type

Switches

let planet = 'Earth';

switch (planet) {
  case "Mercury":
  case "Venus":
    console.log("Too hot here.");

  case 'Earth' :
    console.log("Welcome home!");
    break;

  case 'Mars' :
    console.log("Welcome to the other home!");
    break;

  case "Jupiter":
  case "Saturn":
  case "Uranus":
  case "Neptune":
  case "Pluto":
    console.log("You may get gold here.");
    break;

  default:
    console.log("Seems you found another planet.");
    break;
}

Objects

Common way to declare objects is by using the curly braces:

let myObj = { world: "Earth" };

Arrays

In addition to objects, the array data is ordered by indexes. Arrays are actually objects, having the indexes (numbers from 0 to legnth – 1) as keys.

let fruits = ["apples", "pears", "oranges"];

fruits[1]
→ "pears"

Acces, add, remove and update elements

> let fruits = ["Apple"]

// Add to the end of the array
> fruits.push("Pear")
2 // < The new length of the array

 [ 'Apple', 'Pear' ]
 //         ^ This was just added

// Add to the start of the array
> fruits.unshift("Orange")
3 // < The new length of the array

 [ 'Orange', 'Apple', 'Pear' ]
 // ^ This was just added

// Access the element at index 1 (the second element)
> fruits[1]
'Apple'

// How many items do we have?
> fruits.length
3

// Turn the Apple into Lemon
> fruits[1] = "Lemon"
'Lemon'

 [ 'Orange', 'Lemon', 'Pear' ]
 //          ^ This was before an Apple

// Insert at index 1 a new element
> fruits.splice(1, 0, "Grapes")
[] // < Splice is supposed to delete things (see below)
   //   In this case we're deleting 0 elements and
   //   inserting one.

 [ 'Orange', 'Grapes', 'Lemon', 'Pear' ]
 //          ^ This was added.

// Get the Lemon's index
> fruits.indexOf("Lemon")
2

// Delete the Lemon
> fruits.splice(2, 1)
[ 'Lemon' ]

 [ 'Orange', 'Grapes', 'Pear' ]
 //                   ^ Lemon is gone

// Remove the last element
> fruits.pop()
'Pear'

 [ 'Orange', 'Grapes' ]
 //                  ^ Pear is gone

// Remove the first element
> fruits.shift()
'Orange'

   [ 'Grapes' ]
 // ^ Orange is gone

Iterating over arrays

There are few ways to loop trough an array.

// Using for-loop
var arr = [42, 7, -1]
for (var index = 0; index < arr.length; ++index) {
    var current = arr[index];
    /* Do something with `current` */
}

// Others prefer defining an additional `length` variable:
for (var index = 0, length = arr.length; index < length; ++index) {
    var current = arr[index];
    /* ... */
}

// Another way i using `forEach`:
arr.forEach((current, index, inputArray) => {
    /* Do something with `current` */
});

// Or using the for ... of:
for (let current of arr) {
    /* current will be the current element */
}

Loops

This will print all the integers from 1 to 42.

for (var i = 1; i <= 42; ++i) {
  console.log(i);
}

Using for ... in ... can be used to iterate object keys:

var name = {
  first: "Johnny",
  last: "B."
};

for (var key in name) {
  if (name.hasOwnProperty(key)) {
    console.log(key, name[key]);
    // "first", "Johnny"
    // "last", "B."
  }
}

In ES6 there is a for ... of ... as well. It's pretty neat since it iterates any iterable objects (arrays, strings etc).

let numbers = [-1, 7, 42, 64];
for (let num of numbers) {
  console.log(num);
}
// -1
// 7
// 42
// 64

While

var i = 1;
while (i <= 42) {
    console.log(i);
    ++i;
}

Do - while

var i = 0;
do {
    ++i;
    console.log(i);
} while (i < 42);

Incrementing / decrementing numbers

You can increment a variable name x using ++x or x++. Similarly, you can decrement it by --x or x--.

The difference is that ++x (--x) returns the incremented (decremented) value, while x++ (x--) returns the previous value of x.

// Let's declare x
let x = 42;

// Store in y, the result of ++x
let y = ++x;

// Let's see the result
console.log(`x is ${x} and y is ${y}`);
→ 'x is 43 and y is 43'

// Now, store in y the result of x++. Note, x is now 43.
y = x++;

// Let's see again
console.log(`x is ${x} and y is ${y}`);
→ 'x is 44 and y is 43'

// So, `y` is 43, because `x++` returned the pre-incremented value (which was 43)

Functions

There are a couple of ways to define functions in JavaScript. The common uses are:

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

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

// Using the ES6 arrow functions
let sum = (a, b) => a + b;

Then you can call the function like:

let result = sum(40, 2);
// => 42

Constructor and classes

There are a couple of ways you can obtain a class-like functionality in JavaScript.

Factory functions

Creating an object and returning it.

function Person (name) {
   var self = {};

   // Public field
   self.name = name;

   // Public method
   self.getName = function () {
     // `this` is the `self`
     return this.name;
   };

   return self;
}

var p = Person("Alice");
console.log(p.getName());
// => "Alice"

Using prototypes

By adding a method in the prototype object of a function, you're adding that method as a public method to all the instances of that class.

function Person (name) {
  this.name = name;
}

Person.prototype.getName = function () {
  // `this` is the `self`
  return this.name;
};

var p = new Person("Bob");
console.log(p.getName());
// => "Bob"

Using ES6 classes

class Person {
  constructor (name) {
    this.name = name;
  }
  getName () {
    return this.name;
  }
}

var p = new Person("Carol");
console.log(p.getName());
// => "Bob"

Inherit classes in Es6

class Musician extends Person {
   constructor (name, instrument) {
     // Call the base class
     super(name);

     this.instrument = instrument;
   }

   play () {
     console.log(`${this.getName()} is playing ${this.instrument}`);
   }
}

var me = new Musician("Johnny B.", "piano");

// Get the name of the musician, who is also a person
console.log(me.getName());
// => "Johnny B."

me.play();
// => "Johnny B. is playing piano."

Async vs sync

Sometimes you have to wait a little bit for things to be done: such as when making a cake, you have to work on it and you have to wait a while for it to be ready. Most familiar things in our lives are asynchronous.

Sync

// Synchronous sum
function sum (a, b) {
  return a + b;
}
var result = sum(40, 2);
// => 42

Async

To have an async function, you need a source of async stuff. In this example, we will use the setTimeout function. It accepts a function as first argument (which is called callback function) and a number as second argument—representing the time delay after the function is called:

function asyncSum (a, b, cb) {
  setTimeout(function () {
    cb(a + b); // -----------+ This is the place
  }, 1000);    //            | where we call then
}              //            V callback function
asyncSum(40, 2, function (result) {
  console.log(result);
  // => 42
});

Callback

Callbacks are functions which are sent as an argument to another function and are invoked when something happens.

function Cake() { /* Just a dummy class-like constructor for now */ }

// We won't make a ckae if we're busy
var busy = false;

function makeCake ( callback) {
  // If we're busy making a cake, send back an error
  if (busy) {
    return callback(new Error("Already busy with creating a cake. Please wait a bit and try again later."));
  }
  // Well, if we weren't busy before, we are now
  busy = true;

  // Wait one second
  setTimeout(function () { // <- This is a callback function too. It is called after one second.

    // After one second we call the callback function
    callback(null, new Cake());

    // After sending the cake, we're not busy anymore
    busy = false;
  }, 1000);
}

makeCake(function (err, cake) {
  if (err) { console.error(err); }
  console.log("Made a cake.");
  // => "Made a cake."
});

// This will end with an error because we're busy already
makeCake(function (err, cake) {
  if (err) { console.error(err); }
  // !=> "Already busy with creating a cake. Please wait a bit and try again later."
  console.log("Made a cake.");
});

// Wait 2 seconds
setTimeout(function () {
  // This will work again
  makeCake(function (err, cake) {
    if (err) { console.error(err); }
    console.log("Made a cake.");
    // => "Made a cake."
  });
}, 2000);

Promises

A promise can be in one of these three states:

  • pending : the operation is pending
  • fulfilled : the operation was finished
  • rejected : an error appeared, so the promise is rejected

StackOverflow Documention has a good section about promises here.

function sum (a, b) {
   return Promise(function (resolve, reject) {
     // Let's wait a second and only then send the response
     setTimeout(function () {
       if (typeof a !== "number" || typeof b !== "number") {
         return reject(new TypeError("Please provide two numbers to sum."));
       }
       resolve(a + b);
     }, 1000);
   });
}

var myPromise = sum(40, 2);

myPromsise.then(function (result) {
  // After one second we have the response here
  console.log("> Summed 40 + 2: ", result);

  // Let's pass some invalid data and return another promise
  return sum(null, "foo");
}).then(function () {
  // This won't be called because we have an error
}).catch(function (err) {
  // Instead, this `catch` handler is called: (after another second)
  console.error(err);
  // => Please provide two numbers to sum.
});


Error handling

// Callback
fetchDataFromServer(function (err, data) {
  if (err) {
    /* do something if you have an error */
  } else {
    /* Do something with `data` */
  }
});

// Promise
fetchDataFromServer().then(function (data) {
    /* Do something with `data` */
}).catch(function (err) {
    /* do something if you have an error */
});
function assert (truly) {
  if (!truly) {
    throw new Error("Not true.");
  }
}

try {
  // This will *not* throw an error
  assert(42 === 42);

  // This will throw an error, so that will go in the catch
  assert(42 === -1);

  // Everything put after the place where the error was thrown
  // is not executed
} catch (e) {
  console.error(e);
  // => Not true.
}

Strict mode

The strict mode, when turned on, shows potential errors you made:

a = 42;
// 42

"use strict";
b = 42;
// Error: `b` is not defined

Dates

Use the Date constructor to create date objects.

var now = new Date();
now.getFullYear();
// => 2016

Quick Example

Let's create a small app which checks if a number is odd or even :

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>Odd or Even?</title>
    </head>
    <body>
        <input type="number" id="inputNumber"><button id="runBtn">Odd or Even?</button>
        <p class="result">Enter a number and click the button to find out if the number is odd or even.</p>
        <script type="text/javascript">
            // Use a wrapping function to prevent global variables
            (function () {
                // Enable the strict mode (in short, it tells us some potential errors)
                "use strict";

                // You can select elements using document.querySelector
                var $result = document.querySelector(".result");

                // Another way is using getElementById(<id>)
                var $input = document.getElementById("inputNumber");
                var $btn = document.getElementById("runBtn");

                // Append a click handler on the button
                $btn.addEventListener("click", function (event) {

                    // Validate the input
                    if (!$input.value) {
                        return alert("Please provide a number.");
                    }

                    // When clicking on the button, take the value from input
                    // Also convert it into a number
                    var x = +$input.value;

                    // Create t a new variable that will contain the result
                    // ("odd" or "event")
                    var result;

                    // Check if the number is even
                    if (x % 2 === 0) {
                      result = "even";
                    } else {
                      result = "odd";
                    }

                    // Tell the user if the number is odd or even
                    $result.textContent = x.toString() + " is " + result;
                });
            })();
        </script>
    </body>
</html>