Show Menu

JavaScript: Basic, Advanced, & More Cheat Sheet by

a custom collection of JavaScript commands, syntax, ideas, and tips
regex     javascript     node-js

About This Document

the purpose of this cheat sheet is to briefly describe the core elements of the JavaScript language for those of studying it who have taken in much more than we can hold onto well. nothing here is explained in full but rather meant to get you on the right track. also, this document purposely does not cover browse­r-s­pecific methods / syntax / objects and the like.

this cheat sheet is a work in progress and may be updated -- check back on occasion!

Types

Type
typeOf evalua­tion
Prim­iti­ve?
Null
object
yes
Undefined
undefined
yes
Boolean
boolean
yes
String
string
yes
Number
number
yes
Object
object
no --an object
Function
function
no --an object
Array
object
no --an object
Symbol
symbol
no --an object
[]
object
no --an object
{}
object
no --an object

Number & Math Methods

someNum.toFixed(num)
• shortens someNum to have only num decimal places
num.toExponential()
• converts num to expone­ntial notation (i.e. 5.569e+0)
num.toString()
• converts num to a string
num.toPrecision(#)
• converts num to a num with # places starting with whole numbers
String(someValue)
• converts or coerces someValue to a string - someValue can be any type, ie "­Boo­lea­n(1­)" returns true
parseInt(string, radix)
parseFloat(string, radix)
• converts a string into an integer. the optional radix argument defines the base -- i.e., base 10 (decimal) or base 16 (hexad­eci­mal).

Math.round(num)
• rounds num to nearest integer
Math.ceil(num)
• rounds num up to nearest integer
Math.floor(num)
• rounds num down to nearest integer
Math.max(num1, num2)
• returns larger num
Math.min(num1, num2)
Math.pow(num1, num2)
• returns num1 to the power num2
Math.sqrt(num)
Math.random()
• returns decimal between 0 (inclu­sive) and 1(excl­usive)
Math.abs(num)
• returns absolute value of num•

Array "­Extra Method­s"

Note: these "­extra method­s," which are "­hig­her­-or­der­" functions, ignore holes in the array (i.e.: [“apples”, , , , “orang­es”]). they also have more arguments than shown here -- best to look them up for more info!
Note: array-­like objects, for example argum­ents and NodeL­ists, can also make use of these methods.

arr.some(callback)
arr.every(callback)
• returns a boolean value. returns true if some or every element in the array meets the evalua­tion. example:
 ­ ­ var a = [1,2,3];
 ­ ­ var b = a.ever­y(f­unc­tio­n(i­tem){
 ­ ­ ­ ­  return item > 1;
 ­ ­ }); // false

arr.reduce(function(prev, next){..}, startVal)
arr.reduceRight(function(prev, next){..}, startVal)
• returns a value. reduce employs a callback to run through the elements of the array, returning "­pre­v" to itself with each iteration and taking the next "­nex­t" value in the array. for it's first "­pre­v" value it will take an optional "­sta­rtV­al" if supplied. an intere­sting example:
 ­ ­ var arr = ["ap­ple­", "­pea­r", "­app­le", "­lem­on"];
 ­ ­ var c = arr.re­duc­e(f­unc­tio­n(prev, next) {
 ­ ­ ­ ­ ­pr­ev[­next] = (prev[­next] += 1) || 1;
 ­ ­ ­ ­ ­return prev;
 ­ ­ }, {});
 ­ ­ // objCount = { apple: 2, pear: 1, lemon: 1 }

arr.filter(function(){..})
• returns an array. filter returns an array of elements that satisfy a given callback. example:
 ­ ­ var arr2 = ["ji­m", "­nan­cy", "­ned­"];
 ­ ­ var letter3 = arr2.f­ilt­er(­fun­cti­on(­item) {
 ­ ­ ­ ­ ­return (item.l­ength === 3);
 ­ ­ ­});
 ­ ­ ­co­nso­le.l­og­(le­tter3); // ['jim', 'ned']

arr.sort(function(){..})
• returns the original array, mutated. sort returns the elements sorted with a given criteria. for example:
 ­ ­ var stock = [{key: “r”, num: 12}, {key: “a”, num: 2}, {key: “c”, num: 5}];
 ­ ­ var c = stock.s­or­t(f­unc­tio­n(a,b) {
 ­ ­ ­ ­ ­return a.num - b.num;
 ­ ­ } ); // [ { key: ‘a', num: 2 }, { key: ‘c', num: 5 }, { key: ‘r', num: 12 } ]

arr.map()
• returns an array. map goes over every element in the array, calls a callback on the element, and sets an element in the new array to be equal to the return value the callback. for example:
 ­ ­ var stock = [{key: "­red­", num: 12}, {key: "­blu­e", num: 2}, {key: "­bla­ck", num: 2}];
 ­ ­ var b = stock.m­ap­(fu­nction (item){
 ­ ­ ­ ­ ­return item.key;
 ­ ­ }) // ["re­d","b­lue­"­,"bl­ack­"]

arr.forEach()
• no return value. forEach performs an operation on all elements of the array. for example:
 ­ ­ var arr = [“jim”, “mary”];
 ­ ­ ­a.f­orEach (function (item) {
 ­ ­ ­ ­  consol­e.l­og(­"I simply love “ +item);
 ­ ­ }); // “I simply love jim”, “I simply love mary"

Note: you can combine array methods in a chain where the result of the leftmost operation is passed to the right as such:
array.so­rt(­).r­eve­rse­()...

Functions & Etc.

Callbacks: placing ( ) after a function call executes it immedi­ately. leaving these off allows for a callback.

Function Declar­ation
function aFunct­ionName (args) {...
• functions created in this manner are evaluated when the code is parsed and are 'hoisted' to the top and are available to the code even before they're formally declared. Note: Due to JS's odd constr­uction, using function declar­ations within a flow control statement can be wonky and is best avoided.

Function Expression / Anonymous Functi­ons
var bar = function (args) {...
• (also referred to as 'Function Operat­ors') anonymous functions are evaluated at 'runtime' and are therefore less memory intensive. they must be provided a variable name but need not have a function name (there­fore: anonym­ous). [these are ]

Named Function Expres­sion
var bar = function foo (args) {...
• confus­ingly, this is still an 'anonymous function.' assigning a name is useful for debugging purposes and also allows for self-r­efe­rential / recursive calls

Function Constr­uctor
var anothe­rFu­nction = new Function (args, function () {... }) {...}
• equivalent to a functional expression

Self­-In­voking Anonymous Functi­ons
( function (args) { doSome­thing; } ) ( );
• (also known as IIFEs / 'Immed­iately Invoked Function Expres­sions') and invokes immedi­ately

Loops / Control Flow Statements

if .. else if .. else
 ­ ­ if (consi­dtion1) {
 ­ ­ ­ ­  doSome­thing;
 ­ ­ } else if {
 ­ ­ ­  doSome­thi­ngE­lse;
 ­ ­ } else {
 ­ ­ ­  doSome­thi­ngM­ore;
 ­ ­ }

for loop
 ­ ­ for (var i = 0; i < someNu­mber; i++) {
 ­ ­  doSome­thing;
 ­ ­ }

switch loop
 ­ ­ ­switch (someE­val­uation) {
 ­ ­  case "­eva­lua­tes­AsT­his­" :
 ­ ­ ­ ­ ­  doSome­thing;
 ­ ­  case "­eva­lua­tes­AsT­hat­" :
 ­ ­ ­   ­  doSome­thi­ngE­lse;
 ­ ­ }

while loop
 ­ ­ ­while (someE­val­uation === true) {
 ­ ­ ­  doSome­thing;
 ­ ­ }

do .. while
 ­ ­ do {
 ­ ­ ­  doSome­thing;
 ­ ­ }
 ­ ­ ­while (someE­val­uation === true);

for .. in (objec­ts)
 ­ ­ for (anItem in anObject) {
 ­ ­ ­ ­  doSome­thing With anItem;
 ­ ­ ­ ­ ­ ­ ­ ­ // will be the key
 ­ ­ ­ ­  doSome­thi­ngWith Object­[an­Item];
 ­ ­ ­ ­ ­ ­  // will be the value of that key
 ­ ­ }

"t­his­"

coming soon
 

String Methods, Properties & Etc

a string can be coerced into an array so many array methods are applicable as well

str.charAt(num)
• returns the character in str at index num
str.charCodeAt(num)
• returns the unicode value of the char
String.fr­omC­har­Cod­e(num)`
• returns the character with unicode's num
str.indexOf(char)
• returns -1 if char not found in str
str.lastIndexOf(subString)
• returns the index of the last occurrence of subString
str.length
• returns length of str starting at 1
str.match(pattern)
• returns null if not found. returns an array of all matches
str.match(/pattern/g)
• provides global search of string
str.replace(old, new)
str.search(pattern)
• returns index of first match or -1 if not found
str.substring(index1, index2)
• char at index1 is returned, index2 is not
str.split(char)
• returns an array of str split on char
str.substr(index1, num)
• returns substring starting at index1 and running num letters
str.toLowerCase()
str.toUpperCase()
str.toLocaleLowerCase()
• takes local language settings into account
str.toLocaleUpperCase()
• ibid
Number(var/string/object)
• converts to number. "­tru­e" converts to 1, etc
one.concat(two)
• concat­enates string­/array one with two
JSON.stringify( )
• converts a javascript value/­object into a string
JSON.parse ( )
• converts a JSON string into a javascript object

Date Methods

Note: Unix epoch is January 1, 1970

var today = new Date();
• creates date object for now
var someDate = new Date("june 30, 2035");
• creates date object for arbitrary date
var today = Date.n­ow();
• returns number of millis­econds since epoch
parse()
• returns millis­econds between date and Unix epoch.
toDateString()
toTimeString()
toLocalTimeString()

Get / Set Date Methods

• getDate()
• getHours()
• getDay()
• getMil­­li­s­e­co­­nds()
• getFul­­lY­ear()
• getMin­­utes()
• getMonth()
• getSec­­onds()
• getTime()
• getTim­­ez­o­n­eO­­ffset()
Note: there are also 'set' methods such as setMo­nth().
Note: getDay and getMonth return numeric repres­ent­ations starting with 0.

Miscel­laneous Instru­ctions

break;
• breaks out of the current loop
continue;
• stops current loop iteration and increments to next

isNaN(someVar)
• returns true if not a number
isFinite(someVar)

var aVar = anObje­ct[­anA­ttr­ibute] || "­non­esu­ch";
• assigns a default value if none exists
var aVar = anEval­uation ? trueVal : falseVal;
• ternary operator. assigns trueVal to aVar if anEval­uation is true, falseVal if not

delete anObje­ct[­anA­ttr­ibute]
(aProperty in anObject)
• returns true or false if aProperty is a property of anObject

eval(someString)
• evaluates a someString as if it was JavaSc­ript. i.e. eval("var x = 2+3") returns 5

Array Methods (basic)

Note: index numbers for arrays start at 0

arr.length()
arr. push(val)
• adds val to end of arr
arr. pop()
• deletes last item in arr
arr. shift()
• deletes first item in arr
arr.unshift(val)
• adds val to front of arr

arr.reverse ()
arr1.concat(arr2)
• concat­enates arr1 with arr2
arr.join(char)
• returns string of elements of arr joined by char
arr.slice(index1, index2)
• returns a new array from arr from index1 (inclu­sive) to index2 (exclu­sive)
arr.splice(index, num, itemA, itemB,..)
• alters arr. starting at index and through index+num, overwr­ite­s/adds itemsA..

Defini­tions & Lingo

Higher Order Functi­ons
functions that accept other functions as an argument
Scope
the set of variables, objects, and functions available within a certain block of code
Call­back
(also event handler) a reference to executable code, or a piece of executable code, that is passed as an argument to other code.
the % operator
% returns the remainder of a division such that "3 % 2 = 1" as 2 goes into 3 once leaving 1. called the "­rem­ain­der­" or "­mod­ulo­" operator.
Comp­osi­tion
the ability to assemble complex behaviour by aggreg­ating simpler behavior. chaining methods via dot syntax is one example.
Chai­ning
also known as casca­ding, refers to repeatedly calling one method after another on an object, in one continuous line of code.
Naming Collis­ions
where two or more identi­fiers in a given namespace or a given scope cannot be unambi­guously resolved
DRY
Don't Repeat Yourself
ECMA­Scr­ipt
(also ECMA-­262) the specif­ication from which the JavaScript implem­ent­ation is derived. version 5.1 is the current release.
Arity
refers to the number of arguments an operator takes. ex: a binary function takes two arguments
Curr­ying
refers to the process of transf­orming a function with multiple arity into the same function with less arity
Recu­rsion
an approach in which a function calls itself
Pred­icate
a calcul­ation or other operation that would evaluate either to "­tru­e" or “false.”
Asyn­chr­onous
program flow that allows the code following an async­hro­nous statement to be executed immedi­ately without waiting for it to complete first.
Callback Hell
code thickly nested with callbacks within callback within callbacks.
Clos­ure
a function with access to the global scope, it's parent scope (if there is one), and it's own scope. a closure may retain those scopes even after it's parent function has retur­ned.
IIFE
Immedi­ately Invoked Function Expres­sions. prono­unced "­iff­y." a function that is invoked immedi­ately upon creation. employs a unique syntax.
Method
an object property has a function for its value.

Reserved Words

abstract
arguments
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
eval
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
let
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchr­onized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
yield

Protot­ype­-based Inheri­tance

coming soon

Download the JavaScript: Basic, Advanced, & More Cheat Sheet

5 Pages
//media.cheatography.com/storage/thumb/acwinter_javascript-basic-advanced-and-more.750.jpg

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors!

Readable.io is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!

 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet
          Express.js Cheat Sheet
          SailsJS Cheat Sheet