JavaScript Cheat Sheet

posted in: ones and zeros | 0

Last Updated: March 5, 2019.

At this point in my career, I’ve worked with so many different programming languages that quickly recalling the syntax of something I haven’t used in a few months is sometimes a challenge.

While solving a user’s problem is 90% critical thinking and 10% coding, not having to Google the exact syntax for something is pretty nice, too!

Here’s my cheat sheet for JavaScript; I hope to add other common languages soon.

Table of Contents

Data Types
Variable Declaration
Comments
Loops
Control Flow
Operators
Math
Function Declaration
Strings
Arrays/Lists
Objects

Resources

To Be Continued:
(ES6 maps & weakmaps)
this
Reserved Words
Dates
Regex
Language-Specific
(reduce, map, etc)
(browser/DOM)
ES6 Sugar
Best Practices
Running a File/Interactive Command Line/Console
Debugging/Tools

Data Types

JavaScript includes the following concepts:

  • Number 42
  • String "Hello"
  • Object {key: value}
  • Boolean true
  • Array [1, 2, 3]
  • null
  • undefined

Under the hood it’s a bit more confusing:

// primitive types
typeof(42);           //=> number
typeof("Hello");      //=> string
typeof(true);         //=> boolean
typeof(undefined);    //=> undefined
// complex types
typeof({key: value}); //=> object
typeof([1, 2, 3]);    //=> object
typeof(null);         //=> object
typeof(myFunction);   //=> function

Comments

// single line

/*
multi-line
*/

Loops

Vanilla for loop:

// executes once; conditional; executes every iteration
for (var i = 0; i < 10; i++) {
  // do things
}

ES6 forEach:

products.forEach(product => console.log(product.name));

Note: best practices regarding JS loops are based on continually-evolving browser implementations of ECMAScript & browser engines – as far as I can tell the ES6 version is currently preferred over for-in and for-of.

Control Flow

for (conditional) {
  // do something
} else if (conditional) {
  // do something different 
} else {
  // final option
}

Variable Declaration

var a = "a";

ES6:

let b = "b";
const c = "c";

Assignment operators:

=
+=
-=
*=
/=
%=
**=

ES6 destructuring assignment:

// objects
var {color, position} = {
   color: "blue",
   name: "timmy",
   position: "forward"
}
console.log(position + " " + color); //=> "forward blue"

// arrays
var [firstThing,,,,fifthThing] = ['one', 'two', 'three', 'four', 'five']
console.log(firstThing); //=> one
console.log(fifthThing); //=> five

Operators

Arithmetic:

+
-
*
/
**
%
++
--

Comparison:

==
===
!=
!==
>
<
>=
<=

Logical:

&&
||
!

Ternary

conditional ? a : b;

Type:

typeof
instanceof

Math

Math.random(); //=> random number between 0 (inclusive), and 1 (exclusive)
Math.max(10, 20);
Math.round(5.3);
Math.ceil(5.3);
Math.floor(5.3);
Math.sqrt(9);

Function Declaration

function myFunction() {
  // do stuff
}

ES6 arrow syntax:

var myFunction = (arg1, arg2) => {
  return arg1 + arg2;
}

// parens unnecessary for 1 argument
// `return` unnecessary if no block {}
var littleFunction = arg => arg;

ES6 default arguments:

function greet(greeting, name = "timmy") {
  console.log(greeting + ", " + name);
}
greet("hi") //=> "hi timmy"

Strings

var str = "hello world";
str.length;
str.indexOf('e');
str.slice(start, end);
str.toUpperCase();
str.toLowerCase();
str1.concat(str2);
str1.concat(str2, str3);
str.trim(); // removes whitespace
str.split(" "); //=> ["hello", "world"]
str.replace("hello", "hi");

ES6 template literals:

var equation = `${ x } + ${ y } = ${ x + y }`
//=> '1 + 2 = 3'

Arrays/Lists

Note:

  • Prefer array literal syntax to new Array();
  • Arrays are objects and may behave in unexpected ways.
var fruits = ["banana", "pear", "apple"];
fruits[1]; //=> "pear"
fruits[1] = "orange"; // fruits=["banana", "orange"]
fruits.length; //=> 3
fruits.pop(); //=> ["apple"]  (fruits=["banana", "orange"])
fruits.push("kiwi"); //=> 3 (fruits=["banana", "orange", "kiwi"])
fruits.splice(1, 2); //=> ["orange", "kiwi"] (fruits=["banana"])
var veg = ["asparagus"];
fruits.concat(veg); // => ["banana", "asparagus"]
fruits.sort(); //=> ["asparagus", "banana"]

typeof fruits; //=> object
// ES5
Array.isArray(fruits); //=> true

// ES6
fruits.forEach(myFunction);

ES6 adds array.from() to convert an array-like object (eg. NodeLists) into array.

Objects

Key/value pairs are referred to as properties.

var person = {
  firstName: "Ada",
  lastName: "Lovelace",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

person.firstName; //=> "Ada"
person["lastName"]; //=> "Lovelace"
person.fullName(); //=> "Ada Lovelace"

See also destructuring assignment.

Strings, numbers, and booleans are objects but are addressed elsewhere.

Resources

https://eslint.org/docs/rules/

Coming Soon:
(ES6 maps & weakmaps)
this
Reserved Words
Dates
Regex
Language-Specific
(reduce, map, etc)
ES6 Sugar
Best Practices
Running a File/Interactive Command Line/Console
Debugging/Tools