Docsity

JavaScript Cheat Sheet for Beginners: Essential Concepts and Syntax, Cheat Sheet of Javascript programming

Partial preview of the text

Download JavaScript Cheat Sheet for Beginners: Essential Concepts and Syntax and more Cheat Sheet Javascript programming in PDF only on Docsity!

Beginner’s essential

JavaScript Cheat Sheet

The Language of the Web.

#################

TABLE OF CONTENTS

  • JavaScript Basics
  • Variables in JavaScript
  • The Next Level: Arrays
  • Operators
  • Functions
  • JavaScript Loop
  • If - Else Statements
  • Strings
  • Regular Expression Syntax
  • Numbers and Math
  • Dealing with Dates in JavaScript
  • DOM Mode
  • Working with the User Browser
  • JavaScript Events

True or fase statements — var c = true Constant numbers — const PI = 3. Objects — var name = {firstName:"John", lastName:”Doe"}

Objects

var person = { firstName:"John", lastName:"Doe", age:20, nationality:"German" };

THE NEXT LEVEL: ARRAYS

var fruit = ["Banana", "Apple", "Pear"];

Array Methods

concat() — Join several arrays into one indexOf() — Returns the primitive value of the specified object join() — Combine elements of an array into a single string and return the string lastIndexOf() — Gives the last position at which a given element appears in an array pop() — Removes the last element of an array push() — Add a new element at the end reverse() — Sort elements in descending order shift() — Remove the first element of an array slice() — Pulls a copy of a portion of an array into a new array

sort() — Sorts elements alphabetically splice() — Adds elements in a specified way and position toString() — Converts elements to strings unshift() — Adds a new element to the beginning valueOf() — Returns the first position at which a given element appears in an array

OPERATORS

Basic Operators

  • — Addition
  • — Subtraction
  • — Multiplication / — Division (...) — Grouping operator, operations within brackets are executed earlier than those outside % — Modulus (remainder ) ++ — Increment numbers -- — Decrement numbers

Comparison Operators

== — Equal to === — Equal value and equal type != — Not equal !== — Not equal value or not equal type

— Greater than < — Less than = — Greater than or equal to

document.write() — Write directly to the HTML document prompt() — Creates an dialogue for user input

Global Functions

decodeURI() — Decodes a Uniform Resource Identifier (URI) created by encodeURI or similar decodeURIComponent() — Decodes a URI component encodeURI() — Encodes a URI into UTF- encodeURIComponent() — Same but for URI components eval() — Evaluates JavaScript code represented as a string isFinite() — Determines whether a passed value is a finite number isNaN() — Determines whether a value is NaN or not Number() — Returns a number converted from its argument parseFloat() — Parses an argument and returns a floating point number parseInt() — Parses its argument and returns an integer

JAVASCRIPT LOOPS

for (before loop; condition for loop; execute after loop) { // what to do during the loop } for — The most common way to create a loop in JavaScript while — Sets up conditions under which aloop executes do while — Similar to the while loop, however, it executes at least once and performs a check at the end to see if the condition is met to execute again break — Used to stop and exit the cycle at certain conditions continue — Skip parts of the cycle if certain conditions are met

IF - ELSE STATEMENTS

if (condition) { // what to do if condition is met } else { // what to do if condition is not met }

STRINGS

var person = "John Doe";

Escape Characters

' — Single quote " — Double quote \ — Backslash \b — Backspace \f — Form feed \n — New line \r — Carriage return \t — Horizontal tabulator \v — Vertical tabulator

String Methods

charAt() — Returns a character at a specified position inside a string charCodeAt() — Gives you the unicode of character at that position concat() — Concatenates (joins) two or more strings into one

x — Allow comments and whitespace in pattern U — Ungreedy pattern

Brackets

[abc] — Find any of the characters between the brackets [^abc] — Find any character not in the brackets [0-9] — Used to find any digit from 0 to 9 [A-z] — Find any character from uppercase A to lowercase z (a|b|c) — Find any of the alternatives separated with |

Metacharacters

. — Find a single character, except newline or line terminator \w — Word character \W — Non-word character \d — A digit \D — A non-digit character \s — Whitespace character \S — Non-whitespace character \b — Find a match at the beginning/end of a word \B — A match not at the beginning/end of a word \0 — NUL character \n — A new line character \f — Form feed character \r — Carriage return character \t — Tab character \v — Vertical tab character \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 least one n n* — Any string that contains zero or more occurrences of n n? — A string that contains zero or one occurrences of n n{X} — String that contains a sequence of X n’s n{X,Y} — Strings that contains a sequence of X to Y n’s n{X,} — Matches any string that contains a sequence of at least X n’s n$ — 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 n

NUMBERS AND MATH

Number Properties

MAX_VALUE — The maximum numeric value representable in JavaScript MIN_VALUE — Smallest positive numeric value representable in JavaScript NaN — The “Not-a-Number” value NEGATIVE_INFINITY — The negative Infinity value POSITIVE_INFINITY — Positive Infinity value

Number Methods

toExponential() — Returns a string with a rounded number written as exponential notation

max(x,y,z,...,n) — Returns the number with the highest value min(x,y,z,...,n) — Same for the number with the lowest value pow(x,y) — X to the power of y random() — Returns a random number between 0 and 1 round(x) — The value of x rounded to its nearest integer sin(x) — The sine of x (x is in radians) sqrt(x) — Square root of x tan(x) — The tangent of an angle

DEALING WITH DATES IN JAVASCRIPT

Setting Dates

Date() — Creates a new date object with the current date and time 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 string

Pulling Date and Time Values

getDate() — 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, 1970

getUTCDate() — The day (date) of the month in the specified date according to universal time (also available for day, month, fullyear, hours, minutes etc.) parse — Parses a string representation of a date, and returns the number of milliseconds since January 1, 1970

Set Part of a Date

setDate() — 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 for day, month, fullyear, hours, minutes etc.)

DOM MODE

Node Properties

attributes — Returns a live collection of all attributes registered to and element baseURI — Provides the absolute base URL of an HTML element childNodes — Gives a collection of an element’s child nodes firstChild — Returns the first child node of an element lastChild — The last child node of an element nextSibling — Gives you the next node at the same node tree level nodeName — Returns the name of a node

lookupPrefix() — Returns a DOMString containing the prefix for a given namespaceURI, if present normalize() — Joins adjacent text nodes and removes empty text nodes in an element removeChild() — Removes a child node from an element replaceChild() — Replaces a child node in an element

Element Methods

getAttribute() — Returns the specified attribute value of an element node getAttributeNS() — Returns string value of the attribute with the specified namespace and name getAttributeNode() — Gets the specified attribute node getAttributeNodeNS() — Returns the attribute node for the attribute with the given namespace and name getElementsByTagName() — Provides a collection of all child elements with the specified tag name getElementsByTagNameNS() — Returns a live HTMLCollection of elements with a certain tag name belonging to the given namespace hasAttribute() — Returns true if an element has any attributes, otherwise false hasAttributeNS() — Provides a true/false value indicating whether the current element in a given namespace has the specified attribute removeAttribute() — Removes a specified attribute from an element removeAttributeNS() — Removes the specified attribute from an element within a certain namespace removeAttributeNode() — Takes away a specified attribute node and returns the removed node setAttribute() — Sets or changes the specified attribute to a specified value setAttributeNS() — Adds a new attribute or changes the value of an attribute with the given namespace and name setAttributeNode() — Sets or changes the specified attribute node

setAttributeNodeNS() — Adds a new namespaced attribute node to an element

WORKING WITH THE USER BROWSER

Window Properties

closed — Checks whether a window has been closed or not and returns true or false defaultStatus — Sets or returns the default text in the statusbar of a window document — Returns the document object for the window frames — Returns all