0% found this document useful (0 votes)
9 views

JavaScript - Basic, Advanced, & More Cheat Sheet by Acwinter

Uploaded by

07Omkar Darade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JavaScript - Basic, Advanced, & More Cheat Sheet by Acwinter

Uploaded by

07Omkar Darade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

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.c​eil​(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.f​loo​r(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 browse​r-s​pecific methods /  Math.m​ax(​num1, num2)
syntax / objects and the like. • returns larger num
 this cheat sheet is a work in progress and may be updated --  Math.m​in(​num1, num2)
check back on occasion!  Math.p​ow(​num1, num2)
• returns num1 to the power num2
 Types  Math.s​qrt​(num)
Type typeOf evaluation Primitive?  Math.r​andom()
Null object yes • returns decimal between 0 (inclu​sive) and 1(excl​usive)
 Math.a​bs(num)
Undefined undefined yes
• returns absolute value of num•
Boolean boolean yes
String string yes  Array "​Extra Method​s"
Number number yes
 Note: these "​extra method​s," which are "​hig​her​-or​der​" functions,
Object object no -- an object ignore holes in the array (i.e.: [“apples”, , , , “orang​es”]). 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.so​me(​cal​lback)
{} object no -- an object  arr.ev​ery​(ca​llback)
• returns a boolean value. returns true if some or every element in the
 Number & Math Methods array meets the evalua​tion. example:
 someNu​m.t​oFi​xed​(num) ​ ​ var a = [1,2,3];
• shortens someNum to have only num decimal places ​ ​ var b = a.ever​y(f​unc​tio​n(i​tem){
 num.to​Exp​one​ntial() ​​​​ return item > 1;
• converts num to expone​ntial notation (i.e. 5.569e+0) ​ ​ }); // false
 num.to​Str​ing()  arr.re​duc​e(f​unc​tio​n(prev, next){..}, startVa
• converts num to a string l)
 num.to​Pre​cis​ion(#)  arr.re​duc​eRi​ght​(fu​nct​ion​(prev, next){..},
• converts num to a num with # places starting with whole numbers startVal)
 String​(so​meV​alue) • 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 "​pre​v" to itself with each iteration and
type, ie "​Boo​lea​n(1​)" returns true taking the next "​nex​t" value in the array. for it's first "​pre​v" value it will
 parseI​nt(​string, radix) take an optional "​sta​rtV​al" if supplied. an intere​sting example:
 parseF​loa​t(s​tring, radix) ​ ​ var arr = ["ap​ple​", "​pea​r", "​app​le", "​lem​‐
• converts a string into an integer. the optional radix argument on"];
defines the base -- i.e., base 10 (decimal) or base 16 (hexad​eci​mal). ​ ​ var c = arr.re​duc​e(f​unc​tio​n(prev, next) {
 Math.r​oun​d(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 Method​s" (cont)  Functions & Etc.

​ ​ }, {});  Callbacks: placing ( ) after a function call executes it immedi​ately. leaving the
​ ​ // objCount = { apple: 2, pear: 1, lemon: 1 } for a callback.
 arr.fi​lte​r(f​unc​tio​n()​{..}) Function Declar​ation
 function
• returns an array. filter returns an array of elements that satisfy a given callback. example: aFunct​ionName (args) {...
​ ​ var arr2 = ["ji​m", "​nan​cy", "​ned​"]; • functions created in this manner are evaluated when the code is parsed and a
​ ​ var letter3 = arr2.f​ilt​er(​fun​cti​on(​item) { the top and are available to the code even before they're formally declared. Not
​ ​ ​ ​ return (item.l​ength === 3); odd constr​uction, using function declar​ations within a flow control statement can

​ ​ }); and is best avoided.


Function Expression / Anonymous Functions
​ ​ consol​e.l​og(​let​ter3); // ['jim', 'ned']
 var bar = function (args) {...
 arr.so​rt(​fun​cti​on(​){..})
• (also referred to as 'Function Operat​ors') 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 (there​fore: anonym​ous). [these are ]
​ ​ var c = stock.s​or​t(f​unc​tio​n(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 } ]
• confus​ingly, this is still an 'anonymous function.' assigning a name is useful fo
 arr.map()
purposes and also allows for self-r​efe​rential / recursive calls
• returns an array. map goes over every element in the array, calls a callback on the element, and sets an element
Function Constr​uctor
in the new array to be equal to the return value the callback. for example:
 var anothe​rFu​nction = new Function (args, function ()
​ ​ var stock = [{key: "​red​", num: 12}, {key: "​blu​e", num: 2}, {key: "​bla​ck", nu
..}
m: 2}];
• equivalent to a functional expression
​ ​ var b = stock.m​ap​(fu​nction (item){
Self-I​nvoking Anonymous Functions
​ ​ ​ ​ return item.key;
 ( function (args) { doSome​thing; } ) ( );
​ ​ }) // ["re​d","b​lue​"​,"bl​ack​"]
• (also known as IIFEs / 'Immed​iately Invoked Function Expres​sions') and invok
 arr.fo​rEach() 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
​ ​ ​ ​ consol​e.l​og(​"I simply love “ +item);
​ ​ if (consi​dtion1) {
​ ​ }); // “I simply love jim”, “I simply love mary"
​​​​ doSome​thing;
 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:
​​​ doSome​thi​ngElse;
array.s​or​t().re​ver​se()...
​ ​ } else {
​​​ doSome​thi​ngMore;
​​}
for loop
​ ​ for (var i = 0; i < someNu​mber; i++) {
​​ doSome​thing;
​​}
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 (someE​val​uation) { • returns the index of the last occurrence of subString


​​ case "​eva​lua​tes​AsT​his​" :  str.length
​​​​​ doSome​thing; • returns length of str starting at 1
​​ case "​eva​lua​tes​AsT​hat​" :  str.ma​tch​(pa​ttern)
​​​ ​ doSome​thi​ngElse; • returns null if not found. returns an array of all matches
​​}  str.ma​tch​(/p​att​ern/g)
while loop • provides global search of string
​ ​ while (someE​val​uation === true) {  str.re​pla​ce(old, new)
​​​ doSome​thing;  str.se​arc​h(p​attern)
​​} • returns index of first match or -1 if not found
do .. while  str.su​bst​rin​g(i​ndex1, index2)
​ ​ do { • char at index1 is returned, index2 is not
​​​ doSome​thing;  str.sp​lit​(char)

​​} • returns an array of str split on char

​ ​ while (someE​val​uation === true);  str.su​bst​r(i​ndex1, num)

for .. in (objects) • returns substring starting at index1 and running num letters

​ ​ for (anItem in anObject) {  str.to​Low​erC​ase()

​​​​ doSome​thing With anItem;  str.to​Upp​erC​ase()

​ ​ ​ ​ ​ ​ ​ ​ // will be the key  str.to​Loc​ale​Low​erC​ase()

​​​​ doSome​thi​ngWith Object​[an​Item]; • takes local language settings into account


 str.to​Loc​ale​Upp​erC​ase()
​ ​ ​ ​ ​ ​ // will be the value of that key
• ibid
​​}
 Number​(va​r/s​tri​ng/​object)
• converts to number. "​tru​e" converts to 1, etc
 "t​his​"
 one.co​nca​t(two)
coming soon
• concat​enates string​/array one with two
 JSON.s​tri​ngify( )
 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.ch​arA​t(num)  Date Methods


• returns the character in str at index num
 Note: Unix epoch is January 1, 1970
 str.ch​arC​ode​At(num)
 var today = new Date();
• returns the unicode value of the char
• creates date object for now
String.fr​omC​har​Cod​e(num)`
 var someDate = new Date("june 30, 2035");
• returns the character with unicode's num
• creates date object for arbitrary date
 str.in​dex​Of(​char)
 var today = Date.n​ow();
• returns -1 if char not found in str
 str.la​stI​nde​xOf​(su​bSt​ring)

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 millis​econds since epoch  Note: index numbers for arrays start at 0
 parse()  arr.le​ngth()
• returns millis​econds between date and Unix epoch.  arr. push(val)
 toDate​Str​ing() • adds val to end of arr
 toTime​Str​ing()  arr. pop()
 toLoca​lTi​meS​tring() • deletes last item in arr
 arr. shift()
 Get / Set Date Methods • deletes first item in arr
 arr.un​shi​ft(val)
• getDate() • getHours()
• adds val to front of arr
• getDay() • getMil​​li​s​e​co​​nds()
 arr.re​verse ()
• getFul​​lY​ear() • getMin​​utes()
 arr1.c​onc​at(​arr2)
• getMonth() • getSec​​onds() • concat​enates arr1 with arr2
• getTime() • getTim​​ez​o​n​eO​​ffset()  arr.jo​in(​char)
• returns string of elements of arr joined by char
 Note: there are also 'set' methods such as setMonth() .
 arr.sl​ice​(in​dex1, index2)
 Note: getDay and getMonth return numeric repres​ent​ations
starting with 0. • returns a new array from arr from index1 (inclu​sive) to index2
(exclu​sive)

 Miscel​laneous Instru​ctions  arr.sp​lic​e(i​ndex, num, itemA, itemB,..)


• alters arr. starting at index and through index+num, overwr​ite​s/adds
 break;
itemsA..
• breaks out of the current loop
 continue;
 Defini​tions & Lingo
• stops current loop iteration and increments to next
Higher Order Functions
 isNaN(​som​eVar)
• returns true if not a number functions that accept other functions as an argument
 isFini​te(​som​eVar) Scope
 var aVar = anObje​ct[​anA​ttr​ibute] || "​non​esu
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 = anEval​uation ? trueVal : falseVal;
• ternary operator. assigns trueVal to aVar if anEval​uation 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 anObje​ct[​anA​ttr​ibute] 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 "​rem​ain​der​" or "​mod​ulo​"
 eval(s​ome​String) operator.
• evaluates a someString as if it was JavaSc​ript. i.e. eval("var x =
Compos​ition
2+3") returns 5
the ability to assemble complex behaviour by aggreg​ating 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/

 Defini​tions & Lingo (cont)  Defini​tions & 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 identi​fiers in a given namespace or a given abstract arguments boolean break
scope cannot be unambi​guously 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 specif​ication from which the JavaScript extends false final finally
implem​ent​ation 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 transf​orming a function with multiple arity return short static super
into the same function with less arity
switch synchr​onized this throw
Recursion throws transient true try
an approach in which a function calls itself typeof var void volatile
Predicate while with yield
a calcul​ation or other operation that would evaluate either to "​tru​‐
e" or “false.”  Protot​ype​-based Inheri​tance

Asynch​ronous coming soon

program flow that allows the code following an asynch​ronous


statement to be executed immedi​ately 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
Immedi​ately Invoked Function Expres​sions. pronounced "​iff​y." a
function that is invoked immedi​ately 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

You might also like