Beginner’s Essential Javascript Cheat Sheet


Beginner’s EssentialJavascript Cheat SheetThe language of the web.

Table of ContentsJavascript If - Else Statements7Strings7Regular Expressions9Numbers and Math10Dealing with Dates12DOM Node14Working with the - Beginner’s Javascript Cheat Sheet 1

Javascript BasicsIncluding JavaScript in an HTML Page script type "text/javascript" //JS code goes here /script Call an External JavaScript File script src "myscript.js" /script code /code Including Comments//Single line comments/* comment here */Multi-line commentsVariablesvar, const, letvarThe most common variable. Can be reassigned but only accessed within a function. Variablesdefined with var move to the top when code is executed.constCannot be reassigned and not accessible before they appear within the code.letSimilar to const, however, let variable can be reassigned but not re-declared.Data Typesvar age 23Numbersvar - Beginner’s Javascript Cheat Sheet 2

var a "init"Text (strings)var b 1 2 3Operationsvar c trueTrue or false statementsconst PI 3.14Constant numbersvar name {firstName:"John", lastName:”Doe"}ObjectsObjectsvar person y:"German"};Arraysvar fruit ["Banana", "Apple", "Pear"];Array Methodsconcat()Join several arrays into oneindexOf()Returns the first position at which a given element appears in an arrayjoin()Combine elements of an array into a single string and return the stringlastIndexOf()Gives the last position at which a given element appears in an - Beginner’s Javascript Cheat Sheet 3

pop()Removes the last element of an arraypush()Add a new element at the endreverse()Reverse the order of the elements in an arrayshift()Remove the first element of an arrayslice()Pulls a copy of a portion of an array into a new array of 4 24sort()Sorts elements alphabeticallysplice()Adds elements in a specified way and positiontoString()Converts elements to stringsunshift()Adds a new element to the beginningvalueOf()Returns the primitive value of the specified objectOperatorsBasic Operators */(.)% g operatorModulus (remainder)Increment numbersDecrement - Beginner’s Javascript Cheat Sheet 4

Comparison Operators ! ! ?Equal toEqual value and equal typeNot equalNot equal value or not equal typeGreater thanLess thanGreater than or equal toLess than or equal toTernary operatorLogical Operators&& !Logical andLogical orLogical notBitwise Operators& AND statementOR statementNOTXORLeft shiftRight shiftZero fill right shiftFunctionsfunction name(parameter1, parameter2, parameter3) {// what the function does}Outputting Dataalert()Output data in an alert box in the browser windowconfirm()Opens up a yes/no dialog and returns true/false depending on user clickconsole.log()Writes information to the browser console, good for debugging - Beginner’s Javascript Cheat Sheet 5

document.write()Write directly to the HTML documentprompt()Creates an dialogue for user inputGlobal FunctionsdecodeURI()Decodes a Uniform Resource Identifier (URI) created by encodeURI or similardecodeURIComponent()Decodes a URI componentencodeURI()Encodes a URI into UTF-8encodeURIComponent()Same but for URI componentseval()Evaluates JavaScript code represented as a stringisFinite()Determines whether a passed value is a finite numberisNaN()Determines whether a value is NaN or notNumber()Returns a number converted from its argumentparseFloat()Parses an argument and returns a floating point numberparseInt()Parses its argument and returns an - Beginner’s Javascript Cheat Sheet 6

Loopsfor (before loop; condition for loop; execute after loop) {// what to do during the loop}forThe most common way to create a loop in JavascriptwhileSets up conditions under which a loop executesdo whileSimilar to the while loop, however, it executes at least once and performs a check at the end tosee if the condition is met to execute againbreakUsed to stop and exit the cycle at certain conditionscontinueSkip parts of the cycle if certain conditions are met of 7 24If - Else Statementsif (condition) {// what to do if condition is met} else {// what to do if condition is not met}Stringsvar person "John Doe";Escape Single quoteDouble quoteBackslashBackspaceForm feedNew lineCarriage returnHorizontal - Beginner’s Javascript Cheat Sheet 7

\v— Vertical tabulatorString MethodscharAt()Returns a character at a specified position inside a stringcharCodeAt()Gives you the unicode of character at that positionconcat()Concatenates (joins) two or more strings into onefromCharCode()Returns a string created from the specified sequence of UTF-16 code unitsindexOf()Provides the position of the first occurrence of a specified text within a stringlastIndexOf()Same as indexOf() but with the last occurrence, searching backwardsmatch()Retrieves the matches of a string against a search patternreplace()Find and replace specific text in a stringsearch()Executes a search for a matching text and returns its positionslice()Extracts a section of a string and returns it as a new stringsplit()Splits a string object into an array of strings at a specified positionsubstr()Similar to slice() but extracts a substring depended on a specified number of characterssubstring()Also similar to slice() but can’t accept negative indicestoLowerCase() - Beginner’s Javascript Cheat Sheet 8

Convert strings to lowercasetoUpperCase()Convert strings to uppercasevalueOf()Returns the primitive value (that has no properties or methods) of a string objectRegular ExpressionsPattern ModifierseigmsxU———————Evaluate replacementPerform case-insensitive matchingPerform global matchingPerform multiple line matchingTreat strings as single lineAllow comments and whitespace in patternNon Greedy patternBrackets[abc][ abc][0-9][A-z](a b c)FindFindUsedFindFindany of the characters between the bracketsany character not in the bracketsto find any digit from 0 to 9any character from uppercase A to lowercase zany of the alternatives separated with ��————————————Find a single character, except newline or line terminatorWord characterNon-word characterA digitA non-digit characterWhitespace characterNon-whitespace characterFind a match at the beginning/end of a wordA match not at the beginning/end of a wordNUL characterA new line characterForm feed characterCarriage return characterTab characterVertical tab - Beginner’s Javascript Cheat Sheet 9

\xxx — The character specified by an octal number xxx\xdd — Character specified by a hexadecimal number dd\uxxxx — The Unicode character specified by a hexadecimal number xxxxQuantifiersn — Matches any string that contains at least one nn*— Any string that contains zero or more occurrences of nn?— A string that contains zero or one occurrences of nn{X} — String that contains a sequence of X n’sn{X,Y} — Strings that contains a sequence of X to Y n’sn{X,} — Matches any string that contains a sequence of at least X n’sn — Any string with n at the end of it n— String with n at the beginning of it? n — Any string that is followed by a specific string n?!n — String that is not followed by a specific string nNumbers and MathNumber PropertiesMAX VALUEThe maximum numeric value representable in JavaScriptMIN VALUESmallest positive numeric value representable in JavaScriptNaNThe “Not-a-Number” valueNEGATIVE INFINITYThe negative Infinity valuePOSITIVE INFINITYPositive Infinity valueNumber MethodstoExponential()Returns a string with a rounded number written as exponential notationtoFixed()Returns the string of a number with a specified number of - Beginner’s Javascript Cheat Sheet 10

toPrecision()String of a number written with a specified lengthtoString()Returns a number as a stringvalueOf()Returns a number as a numberMath PropertiesELN2LN10LOG2ELOG10EPISQRT1 2SQRT2Euler’s numberThe natural logarithm of 2Natural logarithm of 10Base 2 logarithm of EBase 10 logarithm of EThe number PISquare root of 1/2The square root of 2Math Methodsabs(x)Returns the absolute (positive) value of xacos(x)The arccosine of x, in radiansasin(x)Arcsine of x, in radiansatan(x)The arctangent of x as a numeric valueatan2(y,x)Arctangent of the quotient of its argumentsceil(x)Value of x rounded up to its nearest integercos(x)The cosine of x (x is in radians) - Beginner’s Javascript Cheat Sheet 11

exp(x)Value of Exfloor(x)The value of x rounded down to its nearest integerlog(x)The natural logarithm (base E) of xmax(x,y,z,.,n)Returns the number with the highest valuemin(x,y,z,.,n)Same for the number with the lowest valuepow(x,y)X to the power of yrandom()Returns a random number between 0 and 1round(x)The value of x rounded to its nearest integersin(x)The sine of x (x is in radians)sqrt(x)Square root of xtan(x)The tangent of an angleDealing with DatesSetting DatesDate()Creates a new date object with the current date and - Beginner’s Javascript Cheat Sheet 12

Date(2017, 5, 21, 3, 23, 10, 0)Create a custom date object. The numbers represent year, month, day, hour, minutes, seconds,milliseconds. You can omit anything you want except for year and month.Date("2017-06-23")Date declaration as a stringPulling Date and Time ValuesgetDate()Get the day of the month as a number (1-31)getDay()The weekday as a number (0-6)getFullYear()Year as a four digit number (yyyy)getHours()Get the hour (0-23)getMilliseconds()The millisecond (0-999)getMinutes()Get the minute (0-59)getMonth()Month as a number (0-11)getSeconds()Get the second (0-59)getTime()Get the milliseconds since January 1, 1970getUTCDate()The day (date) of the month in the specified date according to universal time (also available forday, month, fullyear, hours, minutes etc.)parseParses a string representation of a date, and returns the number of milliseconds since January1, - Beginner’s Javascript Cheat Sheet 13

Set Part of a DatesetDate()Set the day as a number (1-31)setFullYear()Sets the year (optionally month and day)setHours()Set the hour (0-23)setMilliseconds()Set milliseconds (0-999)setMinutes()Sets the minutes (0-59)setMonth()Set the month (0-11)setSeconds()Sets the seconds (0-59)setTime()Set the time (milliseconds since January 1, 1970)setUTCDate()Sets the day of the month for a specified date according to universal time (also available forday, month, fullyear, hours, minutes etc.)DOM NodeNode PropertiesattributesReturns a live collection of all attributes registered to and elementbaseURIProvides the absolute base URL of an HTML elementchildNodesGives a collection of an element’s child - Beginner’s Javascript Cheat Sheet 14

firstChildReturns the first child node of an elementlastChildThe last child node of an elementnextSiblingGives you the next node at the same node tree levelnodeNameReturns the name of a nodenodeTypeReturns the type of a nodenodeValueSets or returns the value of a nodeownerDocumentThe top-level document object for this nodeparentNodeReturns the parent node of an elementpreviousSiblingReturns the node immediately preceding the current onetextContentSets or returns the textual content of a node and its descendantsNode MethodsappendChild()Adds a new child node to an element as the last child nodecloneNode()Clones an HTML elementcompareDocumentPosition()Compares the document position of two elementsgetFeature()Returns an object which implements the APIs of a specified - Beginner’s Javascript Cheat Sheet 15

hasAttributes()Returns true if an element has any attributes, otherwise falsehasChildNodes()Returns true if an element has any child nodes, otherwise falseinsertBefore()Inserts a new child node before a specified, existing child nodeisDefaultNamespace()Returns true if a specified namespaceURI is the default, otherwise falseisEqualNode()Checks if two elements are equalisSameNode()Checks if two elements are the same nodeisSupported()Returns true if a specified feature is supported on the elementlookupNamespaceURI()Returns the namespaceURI associated with a given nodelookupPrefix()Returns a DOMString containing the prefix for a given namespaceURI, if presentnormalize()Joins adjacent text nodes and removes empty text nodes in an elementremoveChild()Removes a child node from an elementreplaceChild()Replaces a child node in an elementElement MethodsgetAttribute()Returns the specified attribute value of an element nodegetAttributeNS()Returns string value of the attribute with the specified namespace and - Beginner’s Javascript Cheat Sheet 16

getAttributeNode()Gets the specified attribute nodegetAttributeNodeNS()Returns the attribute node for the attribute with the given namespace and namegetElementsByTagName()Provides a collection of all child elements with the specified tag namegetElementsByTagNameNS()Returns a live HTMLCollection of elements with a certain tag name belonging to the givennamespacehasAttribute()Returns true if an element has any attributes, otherwise falsehasAttributeNS()Provides a true/false value indicating whether the current element in a given namespace has thespecified attributeremoveAttribute()Removes a specified attribute from an elementremoveAttributeNS()Removes the specified attribute from an element within a certain namespaceremoveAttributeNode()Takes away a specified attribute node and returns the removed nodesetAttribute()Sets or changes the specified attribute to a specified valuesetAttributeNS()Adds a new attribute or changes the value of an attribute with the given namespace and name - Beginner’s Javascript Cheat Sheet 9 \xxx — The character specified by an octal number xxx \xdd — Character specified by a hexadecimal number dd \uxxxx — The Unicode character specified by a hexadecimal number xxxx Quantifiers n — Matches any string that contains at