JavaScript: Basic, Advanced, & More Cheat Sheet
by AC Winter (acwinter) via cheatography.com/21349/cs/4084/
About This Document Number & Math Methods (cont)
the purpose of this cheat sheet is to briefly describe the core Math.ceil(num)
elements of the JavaScript language for those of studying it who • rounds num up to nearest integer
have taken in much more than we can hold onto well. nothing here is Math.floor(num)
explained in full but rather meant to get you on the right track. also, • rounds num down to nearest integer
this document purposely does not cover browser-specific methods / Math.max(num1, num2)
syntax / objects and the like. • returns larger num
this cheat sheet is a work in progress and may be updated -- Math.min(num1, num2)
check back on occasion! Math.pow(num1, num2)
• returns num1 to the power num2
Types Math.sqrt(num)
Type typeOf evaluation Primitive? Math.random()
Null object yes • returns decimal between 0 (inclusive) and 1(exclusive)
Math.abs(num)
Undefined undefined yes
• returns absolute value of num•
Boolean boolean yes
String string yes Array "Extra Methods"
Number number yes
Note: these "extra methods," which are "higher-order" functions,
Object object no -- an object ignore holes in the array (i.e.: [“apples”, , , , “oranges”]). they also
Function function no -- an object have more arguments than shown here -- best to look them up for
more info!
Array object no -- an object
Note: array-like objects, for example arguments and NodeLists,
Symbol symbol no -- an object
can also make use of these methods.
[] object no -- an object arr.some(callback)
{} object no -- an object arr.every(callback)
• returns a boolean value. returns true if some or every element in the
Number & Math Methods array meets the evaluation. example:
someNum.toFixed(num) var a = [1,2,3];
• shortens someNum to have only num decimal places var b = a.every(function(item){
num.toExponential() return item > 1;
• converts num to exponential notation (i.e. 5.569e+0) }); // false
num.toString() arr.reduce(function(prev, next){..}, startVa
• converts num to a string l)
num.toPrecision(#) arr.reduceRight(function(prev, next){..},
• converts num to a num with # places starting with whole numbers startVal)
String(someValue) • returns a value. reduce employs a callback to run through the
• converts or coerces someValue to a string - someValue can be any elements of the array, returning "prev" to itself with each iteration and
type, ie "Boolean(1)" returns true taking the next "next" value in the array. for it's first "prev" value it will
parseInt(string, radix) take an optional "startVal" if supplied. an interesting example:
parseFloat(string, radix) var arr = ["apple", "pear", "apple", "lem‐
• converts a string into an integer. the optional radix argument on"];
defines the base -- i.e., base 10 (decimal) or base 16 (hexadecimal). var c = arr.reduce(function(prev, next) {
Math.round(num) prev[next] = (prev[next] += 1) || 1;
• rounds num to nearest integer return prev;
By AC Winter (acwinter) Published 6th May, 2015. Sponsored by ApolloPad.com
cheatography.com/acwinter/ Last updated 9th May, 2016. Everyone has a novel in them. Finish
Page 1 of 5. Yours!
https://apollopad.com
JavaScript: Basic, Advanced, & More Cheat Sheet
by AC Winter (acwinter) via cheatography.com/21349/cs/4084/
Array "Extra Methods" (cont) Functions & Etc.
}, {}); Callbacks: placing ( ) after a function call executes it immediately. leaving the
// objCount = { apple: 2, pear: 1, lemon: 1 } for a callback.
arr.filter(function(){..}) Function Declaration
function
• returns an array. filter returns an array of elements that satisfy a given callback. example: aFunctionName (args) {...
var arr2 = ["jim", "nancy", "ned"]; • functions created in this manner are evaluated when the code is parsed and a
var letter3 = arr2.filter(function(item) { the top and are available to the code even before they're formally declared. Not
return (item.length === 3); odd construction, using function declarations within a flow control statement can
}); and is best avoided.
Function Expression / Anonymous Functions
console.log(letter3); // ['jim', 'ned']
var bar = function (args) {...
arr.sort(function(){..})
• (also referred to as 'Function Operators') anonymous functions are evaluated
• returns the original array, mutated. sort returns the elements sorted with a given criteria. for example:
and are therefore less memory intensive. they must be provided a variable nam
var stock = [{key: “r”, num: 12}, {key: “a”, num: 2}, {key: “c”, num: 5}];
have a function name (therefore: anonymous). [these are ]
var c = stock.sort(function(a,b) {
Named Function Expression
return a.num - b.num;
var bar = function foo (args) {...
} ); // [ { key: ‘a', num: 2 }, { key: ‘c', num: 5 }, { key: ‘r', num: 12 } ]
• confusingly, this is still an 'anonymous function.' assigning a name is useful fo
arr.map()
purposes and also allows for self-referential / recursive calls
• returns an array. map goes over every element in the array, calls a callback on the element, and sets an element
Function Constructor
in the new array to be equal to the return value the callback. for example:
var anotherFunction = new Function (args, function ()
var stock = [{key: "red", num: 12}, {key: "blue", num: 2}, {key: "black", nu
..}
m: 2}];
• equivalent to a functional expression
var b = stock.map(function (item){
Self-Invoking Anonymous Functions
return item.key;
( function (args) { doSomething; } ) ( );
}) // ["red","blue","black"]
• (also known as IIFEs / 'Immediately Invoked Function Expressions') and invok
arr.forEach() ately
• no return value. forEach performs an operation on all elements of the array. for example:
var arr = [“jim”, “mary”]; Loops / Control Flow Statements
a.forEach (function (item) {
if .. else if .. else
console.log("I simply love “ +item);
if (considtion1) {
}); // “I simply love jim”, “I simply love mary"
doSomething;
Note: you can combine array methods in a chain where the result of the leftmost operation is passed to the right
} else if {
as such:
doSomethingElse;
array.sort().reverse()...
} else {
doSomethingMore;
}
for loop
for (var i = 0; i < someNumber; i++) {
doSomething;
}
switch loop
By AC Winter (acwinter) Published 6th May, 2015. Sponsored by ApolloPad.com
cheatography.com/acwinter/ Last updated 9th May, 2016. Everyone has a novel in them. Finish
Page 2 of 5. Yours!
https://apollopad.com
JavaScript: Basic, Advanced, & More Cheat Sheet
by AC Winter (acwinter) via cheatography.com/21349/cs/4084/
Loops / Control Flow Statements (cont) String Methods, Properties & Etc (cont)
switch (someEvaluation) { • returns the index of the last occurrence of subString
case "evaluatesAsThis" : str.length
doSomething; • returns length of str starting at 1
case "evaluatesAsThat" : str.match(pattern)
doSomethingElse; • returns null if not found. returns an array of all matches
} str.match(/pattern/g)
while loop • provides global search of string
while (someEvaluation === true) { str.replace(old, new)
doSomething; str.search(pattern)
} • returns index of first match or -1 if not found
do .. while str.substring(index1, index2)
do { • char at index1 is returned, index2 is not
doSomething; str.split(char)
} • returns an array of str split on char
while (someEvaluation === true); str.substr(index1, num)
for .. in (objects) • returns substring starting at index1 and running num letters
for (anItem in anObject) { str.toLowerCase()
doSomething With anItem; str.toUpperCase()
// will be the key str.toLocaleLowerCase()
doSomethingWith Object[anItem]; • takes local language settings into account
str.toLocaleUpperCase()
// will be the value of that key
• ibid
}
Number(var/string/object)
• converts to number. "true" converts to 1, etc
"this"
one.concat(two)
coming soon
• concatenates string/array one with two
JSON.stringify( )
String Methods, Properties & Etc
• converts a javascript value/object into a string
a string can be coerced into an array so many array methods are JSON.parse ( )
applicable as well • converts a JSON string into a javascript object
str.charAt(num) Date Methods
• returns the character in str at index num
Note: Unix epoch is January 1, 1970
str.charCodeAt(num)
var today = new Date();
• returns the unicode value of the char
• creates date object for now
String.fromCharCode(num)`
var someDate = new Date("june 30, 2035");
• returns the character with unicode's num
• creates date object for arbitrary date
str.indexOf(char)
var today = Date.now();
• returns -1 if char not found in str
str.lastIndexOf(subString)
By AC Winter (acwinter) Published 6th May, 2015. Sponsored by ApolloPad.com
cheatography.com/acwinter/ Last updated 9th May, 2016. Everyone has a novel in them. Finish
Page 3 of 5. Yours!
https://apollopad.com
JavaScript: Basic, Advanced, & More Cheat Sheet
by AC Winter (acwinter) via cheatography.com/21349/cs/4084/
Date Methods (cont) Array Methods (basic)
• returns number of milliseconds since epoch Note: index numbers for arrays start at 0
parse() arr.length()
• returns milliseconds between date and Unix epoch. arr. push(val)
toDateString() • adds val to end of arr
toTimeString() arr. pop()
toLocalTimeString() • deletes last item in arr
arr. shift()
Get / Set Date Methods • deletes first item in arr
arr.unshift(val)
• getDate() • getHours()
• adds val to front of arr
• getDay() • getMilliseconds()
arr.reverse ()
• getFullYear() • getMinutes()
arr1.concat(arr2)
• getMonth() • getSeconds() • concatenates arr1 with arr2
• getTime() • getTimezoneOffset() arr.join(char)
• returns string of elements of arr joined by char
Note: there are also 'set' methods such as setMonth() .
arr.slice(index1, index2)
Note: getDay and getMonth return numeric representations
starting with 0. • returns a new array from arr from index1 (inclusive) to index2
(exclusive)
Miscellaneous Instructions arr.splice(index, num, itemA, itemB,..)
• alters arr. starting at index and through index+num, overwrites/adds
break;
itemsA..
• breaks out of the current loop
continue;
Definitions & Lingo
• stops current loop iteration and increments to next
Higher Order Functions
isNaN(someVar)
• returns true if not a number functions that accept other functions as an argument
isFinite(someVar) Scope
var aVar = anObject[anAttribute] || "nonesu
the set of variables, objects, and functions available within a
ch"; certain block of code
• assigns a default value if none exists
Callback
var aVar = anEvaluation ? trueVal : falseVal;
• ternary operator. assigns trueVal to aVar if anEvaluation is true, (also event handler ) a reference to executable code, or a piece of
falseVal if not executable code, that is passed as an argument to other code.
delete anObject[anAttribute] the % operator
(aProperty in anObject) % returns the remainder of a division such that "3 % 2 = 1" as 2
• returns true or false if aProperty is a property of anObject goes into 3 once leaving 1. called the "remainder" or "modulo"
eval(someString) operator.
• evaluates a someString as if it was JavaScript. i.e. eval("var x =
Composition
2+3") returns 5
the ability to assemble complex behaviour by aggregating simpler
behavior. chaining methods via dot syntax is one example.
By AC Winter (acwinter) Published 6th May, 2015. Sponsored by ApolloPad.com
cheatography.com/acwinter/ Last updated 9th May, 2016. Everyone has a novel in them. Finish
Page 4 of 5. Yours!
https://apollopad.com
JavaScript: Basic, Advanced, & More Cheat Sheet
by AC Winter (acwinter) via cheatography.com/21349/cs/4084/
Definitions & Lingo (cont) Definitions & Lingo (cont)
Chaining Method
also known as cascading, refers to repeatedly calling one method an object property has a function for its value.
after another on an object, in one continuous line of code.
Naming Collisions Reserved Words
where two or more identifiers in a given namespace or a given abstract arguments boolean break
scope cannot be unambiguously resolved byte case catch char
DRY class const continue debugger
Don't Repeat Yourself default delete do double
ECMAScript else enum eval export
(also ECMA-262) the specification from which the JavaScript extends false final finally
implementation is derived. version 5.1 is the current release. float for function goto
Arity if implements import in
refers to the number of arguments an operator takes. ex: a binary instanceof int interface let
function takes two arguments long native new null
Currying package private protected public
refers to the process of transforming a function with multiple arity return short static super
into the same function with less arity
switch synchronized this throw
Recursion throws transient true try
an approach in which a function calls itself typeof var void volatile
Predicate while with yield
a calculation or other operation that would evaluate either to "tru‐
e" or “false.” Prototype-based Inheritance
Asynchronous coming soon
program flow that allows the code following an asynchronous
statement to be executed immediately without waiting for it to
complete first.
Callback Hell
code thickly nested with callbacks within callback within callbacks.
Closure
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 returned.
IIFE
Immediately Invoked Function Expressions. pronounced "iffy." a
function that is invoked immediately upon creation. employs a
unique syntax.
By AC Winter (acwinter) Published 6th May, 2015. Sponsored by ApolloPad.com
cheatography.com/acwinter/ Last updated 9th May, 2016. Everyone has a novel in them. Finish
Page 5 of 5. Yours!
https://apollopad.com