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

Acwinter Javascript Basic Advanced and More

This document provides a summary of core JavaScript concepts including data types, number and math methods, array methods, and functions. It covers type evaluation, primitive types, number formatting and conversion methods, array filtering, sorting, mapping and reducing, function declarations, expressions, and constructors. The purpose is to briefly describe key elements of JavaScript as a study aid for those learning the language.

Uploaded by

Muthurathinam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Acwinter Javascript Basic Advanced and More

This document provides a summary of core JavaScript concepts including data types, number and math methods, array methods, and functions. It covers type evaluation, primitive types, number formatting and conversion methods, array filtering, sorting, mapping and reducing, function declarations, expressions, and constructors. The purpose is to briefly describe key elements of JavaScript as a study aid for those learning the language.

Uploaded by

Muthurathinam
Copyright
© © All Rights Reserved
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 elements of Math.ceil(num)
the JavaScript language for those of studying it who have taken in much rounds num up to nearest integer
more than we can hold onto well. nothing here is explained in full but rather Math.floor(num)
meant to get you on the right track. also, this document purposely does
rounds num down to nearest integer
not cover browser-specific methods / syntax / objects and the like.
Math.max(num1, num2)
this cheat sheet is a work in progress and may be updated -- check
returns larger num
back on occasion!
Math.min(num1, num2)
Math.pow(num1, num2)
Types
returns num1 to the power num2
Type typeOf evaluation Primitive? Math.sqrt(num)

Null object yes Math.random()


returns decimal between 0 (inclusive) and 1(exclusive)
Undefined undefined yes
Math.abs(num)
Boolean boolean yes
returns absolute value of num
String string yes

Number number yes Array "Extra Methods"


Object object no --an object
Note: these "extra methods," which are "higher-order" functions, ignore
Function function no --an object holes in the array (i.e.: [apples, , , , oranges]). they also have more

Array object no --an object arguments than shown here -- best to look them up for more info!
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 ifsome or every element in the
Number & Math Methods array meets the evaluation. example:
var a = [1,2,3];
someNum.toFixed(num)
var b = a.every(function(item){
shortens someNum to have only num decimal places
num.toExponential() return item > 1;

converts num to exponential notation (i.e. 5.569e+0) }); // false

num.toString() arr.reduce(function(prev, next){..}, startVal)

converts num to a string arr.reduceRight(function(prev, next){..}, startVal)


num.toPrecision(#) returns a value. reduce employs a callback to run through the elements
converts num to a num with # places starting with whole numbers of the array, returning "prev" to itself with each iteration and taking the
String(someValue) next "next" value in the array. for it's first "prev" value it will take an

converts or coerces someValue to a string - someValue can be any type, optional "startVal" if supplied. an interesting example:

ie "Boolean(1)" returns true var arr = ["apple", "pear", "apple", "lemon"];

parseInt(string, radix) var c = arr.reduce(function(prev, next) {

parseFloat(string, radix) prev[next] = (prev[next] += 1) || 1;

converts a string into an integer. the optional radix argument defines the return prev;
base -- i.e., base 10 (decimal) or base 16 (hexadecimal).
Math.round(num)
rounds num to nearest integer

By AC Winter (acwinter) Published 6th May, 2015. Sponsored by CrosswordCheats.com


cheatography.com/acwinter/ Last updated 13th May, 2015. Learn to solve cryptic crosswords!
Page 1 of 5. http://crosswordcheats.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.


// objCount = { apple: 2, pear: 1, lemon: 1 } leaving these off allows for a callback.

arr.filter(function(){..}) Function Declaration

returns an array. filter returns an array of elements that satisfy a given function aFunctionName (args) {...

callback. example: functions created in this manner are evaluated when the code is parsed
var arr2 = ["jim", "nancy", "ned"]; and are 'hoisted' to the top and are available to the code even before

var letter3 = arr2.filter(function(item) { they're formally declared. Note: Due to JS's odd construction, using
function declarations within a flow control statement can be wonky and is
return (item.length === 3);
best avoided.
}
);
Function Expression / Anonymous Functions
c
onsole.log(letter3); // ['jim', 'ned']
var bar = function (args) {...
arr.sort(function(){..})
(also referred to as 'Function Operators') anonymous functions are
returns the original array, mutated. sort returns the elements sorted with evaluated at 'runtime' and are therefore less memory intensive. they must
a given criteria. for example: be provided a variable name but need not have a function name
var stock = [{key: r, num: 12}, {key: a, num: (therefore: anonymous). [these are ]
2}, {key: c, num: 5}]; Named Function Expression
var c = stock.sort(function(a,b) { var bar = function foo (args) {...

return a.num - b.num; confusingly, this is still an 'anonymous function.' assigning a name is

} ); // [ { key: a', num: 2 }, { key: c', num: 5 useful for debugging purposes and also allows for self-referential /
recursive calls
}, { key: r', num: 12 } ]
Function Constructor
arr.map()
var anotherFunction = new Function (args, function
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: equivalent to a functional expression

var stock = [{key: "red", num: 12}, {key: "blue", Self-Invoking Anonymous Functions
( function (args) { doSomething; } ) ( );
num: 2}, {key: "black", num: 2}];
(also known as IIFEs / 'Immediately Invoked Function Expressions') and
var b = stock.map(function (item){
invokes immediately
return item.key;
}) // ["red","blue","black"]
Loops / Control Flow Statements
arr.forEach()
if .. else if .. else
no return value. forEach performs an operation on all elements of the
array. for example: if (considtion1) {

var arr = [jim, mary]; doSomething;


a
.forEach (function (item) { } else if {

console.log("I simply love +item); doSomethingElse;

}); // I simply love jim, I simply love mary" } else {


Note: you can combine array methods in achain where the result of the doSomethingMore;
leftmost operation is passed to the right as such: }
array.sort().reverse()... for loop
for (var i = 0; i < someNumber; i++) {
doSomething;
}
switch loop

By AC Winter (acwinter) Published 6th May, 2015. Sponsored by CrosswordCheats.com


cheatography.com/acwinter/ Last updated 13th May, 2015. Learn to solve cryptic crosswords!
Page 2 of 5. http://crosswordcheats.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)
}
provides global search of string
while loop
str.replace(old, new)
w
hile (someEvaluation === true) {
str.search(pattern)
doSomething;
returns index of first match or -1 if not found
}
str.substring(index1, index2)
do .. while
char at index1 is returned, index2 is not
do {
str.split(char)
doSomething;
returns an array of str split on char
} str.substr(index1, num)
w
hile (someEvaluation === true); returns substring starting at index1 and running num letters
for .. in (objects) str.toLowerCase()
for (anItem in anObject) { str.toUpperCase()
doSomething With anItem; str.toLocaleLowerCase()
// will be the key takes local language settings into account
doSomethingWith Object[anItem]; 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)
concatenates string/array one with two
coming soon JSON.stringify( )
converts a javascript value/object into a string
String Methods, Properties & Etc JSON.parse ( )

a string can be coerced into an array so many array methods are converts a JSON string into a javascript object
applicable as well
Date Methods
str.charAt(num)
Note: Unix epoch is January 1, 1970
returns the character in str at index num
var today = new Date();
str.charCodeAt(num)
creates date object for now
returns the unicode value of the char
var someDate = new Date("june 30, 2035");
String.fromCharCode(num)`
creates date object for arbitrary date
returns the character with unicode's num
var today = Date.now();
str.indexOf(char)
returns -1 if char not found in str
str.lastIndexOf(subString)

By AC Winter (acwinter) Published 6th May, 2015. Sponsored by CrosswordCheats.com


cheatography.com/acwinter/ Last updated 13th May, 2015. Learn to solve cryptic crosswords!
Page 3 of 5. http://crosswordcheats.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


arr.join(char)
getTime() getTimezoneOffset()
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
returns a new array from arr from index1 (inclusive) to index2
with 0.
(exclusive)
arr.splice(index, num, itemA, itemB,..)
Miscellaneous Instructions
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)
functions that accept other functions as an argument
returns true if not a number
isFinite(someVar) Scope

var aVar = anObject[anAttribute] || "nonesuch"; the set of variables, objects, and functions available within a certain
assigns a default value if none exists block of code
var aVar = anEvaluation ? trueVal : falseVal;
Callback
ternary operator. assigns trueVal to aVar if anEvaluation is true, falseVal
(also event handler) a reference to executable code, or a piece of
if not
executable code, that is passed as an argument to other code.
delete anObject[anAttribute]
(aProperty in anObject) the % operator

returns true or false if aProperty is a property of anObject % returns the remainder of a division such that "3 % 2 = 1" as 2 goes
eval(someString) into 3 once leaving 1. called the "remainder" or "modulo" operator.
evaluates a someString as if it was JavaScript. i.e. eval("var x = 2+3")
Composition
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 CrosswordCheats.com


cheatography.com/acwinter/ Last updated 13th May, 2015. Learn to solve cryptic crosswords!
Page 4 of 5. http://crosswordcheats.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 scope abstract arguments boolean break
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 into return short static super
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 "true" or


Prototype-based Inheritance
false.

Asynchronous coming soon

program flow that allows the code following anasynchronous


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 CrosswordCheats.com


cheatography.com/acwinter/ Last updated 13th May, 2015. Learn to solve cryptic crosswords!
Page 5 of 5. http://crosswordcheats.com

You might also like