JavaScript Cheat Sheet for 2021 (.PDF Model Included)

Under you’ll find the Javascript cheat sheet in .pdf in addition to within the textual content.

JavaScript Cheat Sheet

JavaScript Fundamentals

Let’s begin off with the fundamentals – how one can embody JavaScript in a web site.

Together with JavaScript in an HTML Web page

To incorporate JavaScript inside a web page, you want to wrap it in

With this enter, the browser can establish and execute the code correctly.

Name an Exterior JavaScript File

You may also place JavaScript in its personal file and title it inside your HTML. That means, you may maintain various kinds of code separate from each other, making for better-organized information. In case your code is in a file referred to as myscript.js, you'll name it:

Together with Feedback

Feedback are essential as a result of they assist different folks perceive what's going on in your code or remind you in the event you forgot one thing your self. Needless to say they need to be marked correctly so the browser received’t attempt to execute them.

In JavaScript you have got two completely different choices:

  • Single-line feedback — To incorporate a remark that's restricted to a single line, precede it with //
  • Multi-line feedback — In case you wish to write longer feedback between a number of strains, wrap it in /* and */ to keep away from it from being executed

Variables in JavaScript

Variables are stand-in values that you need to use to carry out operations. Try to be accustomed to them from math class.

var, const, let

You've gotten three completely different potentialities for declaring a variable in JavaScript, every with their very own specialties:

  • var — The most typical variable. It may be reassigned however solely accessed inside a operate. Variables outlined with var transfer to the highest when the code is executed.
  • const — Cannot be reassigned and never accessible earlier than they seem throughout the code.
  • let — Much like const, the let variable will be reassigned however not re-declared.

Knowledge Varieties

Variables can include various kinds of values and information varieties. You employ = to assign them:

  • Numbers — var age = 23
  • Variables — var x
  • Textual content (strings) — var a = "init"
  • Operations — var b = 1 + 2 + 3
  • True or false statements — var c = true
  • Fixed numbers — const PI = 3.14
  • Objects — var title = {firstName:"John", lastName:"Doe"}

There are extra potentialities. Observe that variables are case delicate. Meaning lastname and lastName will likely be dealt with as two completely different variables.


Objects are sure sorts of variables. They're variables that may have their very own values and strategies. The latter are actions that you may carry out on objects.

var individual = {

The Subsequent Degree: Arrays

Subsequent up in our JavaScript cheat sheet are arrays. Arrays are a part of many alternative programming languages. They're a means of organizing variables and properties into teams. Right here’s how one can create one in JavaScript:

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

Now you have got an array referred to as fruit which incorporates three gadgets that you need to use for future operations.

Array Strategies

Upon getting created arrays, there are some things you are able to do with them:

  • concat() — Be part of a number of arrays into one
  • indexOf() — Returns the primary place at which a given ingredient seems in an array
  • be a part of() — Mix components of an array right into a single string and return the string
  • lastIndexOf() — Offers the final place at which a given ingredient seems in an array
  • pop() — Removes the final ingredient of an array
  • push() — Add a brand new ingredient on the finish
  • reverse() — Type components in a descending order
  • shift() — Take away the primary ingredient of an array
  • slice() — Pulls a duplicate of a portion of an array into a brand new array
  • kind() — Kinds components alphabetically
  • splice() — Provides components in a specified means and place
  • toString() — Converts components to strings
  • unshift() —Provides a brand new ingredient to the start
  • valueOf() — Returns the primitive worth of the required object


In case you have variables, you need to use them to carry out completely different sorts of operations. To take action, you want operators.

Fundamental Operators

  • + — Addition
  • - — Subtraction
  • * — Multiplication
  • / — Division
  • (...) — Grouping operator, operations inside brackets are executed sooner than these exterior
  • % — Modulus (the rest )
  • ++ — Increment numbers
  • -- — Decrement numbers

Comparability Operators

  • == — Equal to
  • === — Equal worth and equal sort
  • != — Not equal
  • !== — Not equal worth or not equal sort
  • > — Higher than
  • < — Lower than
  • >= — Higher than or equal to
  • <= — Lower than or equal to
  • ? — Ternary operator

Logical Operators

  • && — Logical and
  • || — Logical or
  • ! — Logical not

Bitwise Operators

  • & — AND assertion
  • | — OR assertion
  • ~ — NOT
  • ^ — XOR
  • << — Left shift
  • >> — Proper shift
  • >>> — Zero fill correct shift


JavaScript features are blocks of code that carry out a sure process. A fundamental operate seems to be like this:

operate title(parameter1, parameter2, parameter3) {
    // what the operate does

As you may see, it consists of the operate key phrase plus a reputation. The operate’s parameters are within the brackets and you've got curly brackets round what the operate performs. You may create your personal, however to make your life simpler – there are additionally a variety of default features.

Outputting Knowledge

A standard utility for features is the output of information. For the output, you have got the next choices:

  • alert() — Output information in an alert field within the browser window
  • verify() — Opens up a sure/no dialog and returns true/false relying on person click on
  • console.log() — Writes info to the browser console, good for debugging functions
  • doc.write() — Write on to the HTML doc
  • immediate() — Creates a dialogue for person enter

World Features

World features are features developed into each browser able to operating JavaScript.

  • decodeURI() — Decodes a Uniform Useful resource Identifier (URI) created by encodeURI or related
  • decodeURIComponent() — Decodes a URI element
  • encodeURI() — Encodes a URI into UTF-8
  • encodeURIComponent() — Similar however for URI parts
  • eval() — Evaluates JavaScript code represented as a string
  • isFinite() — Determines whether or not a handed worth is a finite quantity
  • isNaN() — Determines whether or not a price is NaN or not
  • Quantity() —- Returns a quantity transformed from its argument
  • parseFloat() — Parses an argument and returns a floating-point quantity
  • parseInt() — Parses its argument and returns an integer

JavaScript Loops

Loops are a part of most programming languages. They permit you to execute blocks of code desired variety of occasions with completely different values:

for (earlier than loop; situation for loop; execute after loop) {
    // what to do in the course of the loop

You've gotten a number of parameters to create loops:

  • for — The most typical method to create a loop in JavaScript
  • whereas — Units up circumstances beneath which a loop executes
  • do whereas — Much like the whereas loop however it executes a minimum of as soon as and performs a verify on the finish to see if the situation is met to execute once more
  • break —Used to cease and exit the cycle at sure circumstances
  • proceed — Skip components of the cycle if sure circumstances are met

IfElse Statements

Most of these statements are simple to know. Utilizing them, you may set circumstances for when your code is executed. If sure circumstances apply, one thing is completed, if not – one thing else is executed.

if (situation) {
    // what to do if situation is met
} else {
    // what to do if situation isn't met

An identical idea to if else is the swap assertion. Nevertheless, utilizing the swap you choose one in every of a number of code blocks to execute.


Strings are what JavaScript calls to textual content that doesn't carry out a operate however can seem on the display screen.

var individual = "John Doe";

On this case, John Doe is the string.

Escape Characters

In JavaScript, strings are marked with single or double-quotes. If you wish to use citation marks in a string, you want to use particular characters:

  • ' — Single quote
  • " — Double quote

Apart from that you simply even have extra escape characters:

  • — Backslash
  • b — Backspace
  • f — Kind feed
  • n — New line
  • r — Carriage return
  • t — Horizontal tabulator
  • v — Vertical tabulator

String Strategies

There are lots of alternative ways to work with strings:

  • charAt() — Returns a personality at a specified place inside a string
  • charCodeAt() — Offers you the Unicode of a personality at that place
  • concat() — Concatenates (joins) two or extra strings into one
  • fromCharCode() — Returns a string created from the required sequence of UTF-16 code models
  • indexOf() — Supplies the place of the primary incidence of a specified textual content inside a string
  • lastIndexOf() — Similar as indexOf() however with the final incidence, looking backward
  • match() — Retrieves the matches of a string in opposition to a search sample
  • substitute() — Discover and substitute specified textual content in a string
  • search() — Executes a seek for an identical textual content and returns its place
  • slice() — Extracts a piece of a string and returns it as a brand new string
  • break up() — Splits a string object into an array of strings at a specified place
  • substr() —  Much like slice() however extracts a substring relying on a specified variety of characters
  • substring() — Additionally much like slice() however can’t settle for damaging indices
  • toLowerCase() — Convert strings to decrease case
  • toUpperCase() — Convert strings to higher case
  • valueOf() — Returns the primitive worth (that has no properties or strategies) of a string object

Common Expression Syntax

Common expressions are search patterns used to match character mixtures in strings. The search sample can be utilized for textual content search and textual content to interchange operations.

Sample Modifiers

  • e — Consider alternative
  • i — Carry out case-insensitive matching
  • g — Carry out world matching
  • m — Carry out a number of line matching
  • s — Deal with strings as a single line
  • x — Permit feedback and whitespace within the sample
  • U — Ungreedy sample


  • [abc] — Discover any of the characters between the brackets
  • [^abc] — Discover any character which isn't within the brackets
  • [0-9] — Used to seek out any digit from 0 to 9
  • [A-z] — Discover any character from uppercase A to lowercase z
  • (a|b|c) — Discover any of the alternate options separated with |


  • . — Discover a single character, besides newline or line terminator
  • w — Phrase character
  • W — Non-word character
  • d — A digit
  • D — A non-digit character
  • s — Whitespace character
  • S — Non-whitespace character
  • b — Discover a match at first/finish of a phrase
  • B — A match not at first/finish of a phrase
  • — NUL character
  • n — A brand new line character
  • f — Kind feed character
  • r — Carriage return character
  • t — Tab character
  • v — Vertical tab character
  • xxx — The character specified by an octal quantity xxx
  • xdd — Character specified by a hexadecimal quantity dd
  • uxxxx — The Unicode character specified by a hexadecimal quantity XXXX


  • n+ — Matches any string that incorporates a minimum of one n
  • n* — Any string that incorporates zero or extra occurrences of n
  • n? — A string that incorporates zero or one incidence of n
  • n{X} — String that incorporates a sequence of X n’s
  • n{X,Y} — Strings that include a sequence of X to Y n’s
  • n{X,} — Matches any string that incorporates a sequence of a minimum of X n’s
  • n$ — Any string with n on the finish of it
  • ^n — String with n at first of it
  • ?=n — Any string that's adopted by a particular string n
  • ?!n — String that isn't adopted by a particular string ni

Numbers and Math

In JavaScript, you may also work with numbers, constants and carry out mathematical features.

Quantity Properties

  • MAX_VALUE — The utmost numeric worth representable in JavaScript
  • MIN_VALUE — Smallest constructive numeric worth representable in JavaScript
  • NaN — The “Not-a-Number” worth
  • NEGATIVE_INFINITY — The damaging Infinity worth
  • POSITIVE_INFINITY — Optimistic Infinity worth

Quantity Strategies

  • toExponential() — Returns the string with a rounded quantity written as exponential notation
  • toFixed() — Returns the string of a quantity with a specified variety of decimals
  • toPrecision() — String of a quantity written with a specified size
  • toString() — Returns a quantity as a string
  • valueOf() — Returns a quantity as a quantity

Math Properties

  • E — Euler’s quantity
  • LN2 — The pure logarithm of two
  • LN10 — Pure logarithm of 10
  • LOG2E — Base 2 logarithm of E
  • LOG10E — Base 10 logarithm of E
  • PI — The quantity PI
  • SQRT1_2 — Sq. root of 1/2
  • SQRT2 — The sq. root of two

Math Strategies

  • abs(x) — Returns absolutely the (constructive) worth of x
  • acos(x) — The arccosine of x, in radians
  • asin(x) — Arcsine of x, in radians
  • atan(x) — The arctangent of x as a numeric worth
  • atan2(y,x) — Arctangent of the quotient of its arguments
  • ceil(x) — Worth of x rounded as much as its nearest integer
  • cos(x) — The cosine of x (x is in radians)
  • exp(x) — Worth of Ex
  • flooring(x) — The worth of x rounded all the way down to its nearest integer
  • log(x) — The pure logarithm (base E) of x
  • max(x,y,z,...,n) — Returns the quantity with the best worth
  • min(x,y,z,...,n) — Similar for the quantity with the bottom worth
  • pow(x,y) — X to the ability of y
  • random() — Returns a random quantity between 0 and 1
  • spherical(x) — The worth of x rounded to its nearest integer
  • sin(x) — The sine of x (x is in radians)
  • sqrt(x) — Sq. root of x
  • tan(x) — The tangent of an angle

Coping with Dates in JavaScript

You may also work with and modify dates and time with JavaScript. That is the following chapter within the JavaScript cheat sheet.

Setting Dates

  • Date() — Creates a brand new date object with the present date and time
  • Date(2017, 5, 21, 3, 23, 10, 0) — Create a customized date object. The numbers symbolize a 12 months, month, day, hour, minutes, seconds, milliseconds. You may omit something you need aside from a 12 months 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 quantity (1-31)
  • getDay() —  The weekday as a quantity (0-6)
  • getFullYear() — Yr as a four-digit quantity (yyyy)
  • getHours() — Get the hour (0-23)
  • getMilliseconds() — The millisecond (0-999)
  • getMinutes() — Get the minute (0-59)
  • getMonth() —  Month as a quantity (0-11)
  • getSeconds() — Get the second (0-59)
  • getTime() — Get the milliseconds since January 1, 1970
  • getUTCDate() — The day (date) of the month within the specified date in keeping with common time (additionally out there for day, month, full 12 months, hours, minutes and so on.)
  • parse — Parses a string illustration of a date and returns the variety of milliseconds since January 1, 1970

Set A part of a Date

  • setDate() — Set the day as a quantity (1-31)
  • setFullYear() — Units the 12 months (optionally month and day)
  • setHours() — Set the hour (0-23)
  • setMilliseconds() — Set milliseconds (0-999)
  • setMinutes() — Units the minutes (0-59)
  • setMonth() — Set the month (0-11)
  • setSeconds() — Units the seconds (0-59)
  • setTime() — Set the time (milliseconds since January 1, 1970)
  • setUTCDate() — Units the day of the month for a specified date in keeping with common time (additionally out there for day, month, full 12 months, hours, minutes and so on.)

DOM Mode

The DOM is the Doc Object Mannequin of a web page. It's the code of the construction of a webpage. JavaScript comes with lots of alternative ways to create and manipulate HTML components (referred to as nodes).

Node Properties

  • attributes — Returns a dwell assortment of all attributes registered to a component
  • baseURI — Supplies absolutely the base URL of an HTML ingredient
  • childNodes — Offers a set of a component’s little one nodes
  • firstChild — Returns the primary little one node of a component
  • lastChild — The final little one node of a component
  • nextSibling — Offers you the following node on the identical node tree stage
  • nodeName —Returns the title of a node
  • nodeType —  Returns the kind of a node
  • nodeValue — Units or returns the worth of a node
  • ownerDocument — The highest-level doc object for this node
  • parentNode — Returns the dad or mum node of a component
  • previousSibling — Returns the node instantly previous the present one
  • textContent — Units or returns the textual content material of a node and its descendants

Node Strategies

  • appendChild() — Provides a brand new little one node to a component because the final little one node
  • cloneNode() — Clones an HTML ingredient
  • compareDocumentPosition() — Compares the doc place of two components
  • getFeature() — Returns an object which implements the APIs of a specified function
  • hasAttributes() — Returns true if a component has any attributes, in any other case false
  • hasChildNodes() — Returns true if a component has any little one nodes, in any other case false
  • insertBefore() — Inserts a brand new little one node earlier than a specified, present little one node
  • isDefaultNamespace() — Returns true if a specified namespaceURI is the default, in any other case false
  • isEqualNode() — Checks if two components are equal
  • isSameNode() — Checks if two components are the identical node
  • isSupported() — Returns true if a specified function is supported on the ingredient
  • lookupNamespaceURI() — Returns the namespace URI related to a given node
  • lookupPrefix() — Returns a DOMString containing the prefix for a given namespace URI if current
  • normalize() — Joins adjoining textual content nodes and removes empty textual content nodes in a component
  • removeChild() — Removes a baby node from a component
  • replaceChild() — Replaces a baby node in a component

Component Strategies

  • getAttribute() — Returns the required attribute worth of a component node
  • getAttributeNS() — Returns string worth of the attribute with the required namespace and title
  • getAttributeNode() — Will get the required attribute node
  • getAttributeNodeNS() — Returns the attribute node for the attribute with the given namespace and title
  • getElementsByTagName() — Supplies a set of all little one components with the required tag title
  • getElementsByTagNameNS() —  Returns a dwell HTMLCollection of components with a sure tag title belonging to the given namespace
  • hasAttribute() — Returns true if a component has any attributes, in any other case false
  • hasAttributeNS() — Supplies a real/false worth indicating whether or not the present ingredient in a given namespace has the required attribute
  • removeAttribute() — Removes a specified attribute from a component
  • removeAttributeNS() — Removes the required attribute from a component inside a sure namespace
  • removeAttributeNode() — Takes away a specified attribute node and returns the eliminated node
  • setAttribute() — Units or adjustments the required attribute to a specified worth
  • setAttributeNS() —  Provides a brand new attribute or adjustments the worth of an attribute with the given namespace and title
  • setAttributeNode() — Units or adjustments the required attribute node
  • setAttributeNodeNS() — Provides a brand new namespaced attribute node to a component

Working with the Consumer Browser

Apart from HTML components, JavaScript can also be capable of take into consideration the person browser and incorporate its properties into the code.

Window Properties

  • closed — Checks whether or not a window has been closed or not and returns true or false
  • defaultStatus — Units or returns the default textual content within the standing bar of a window
  • doc — Returns the doc object for the window
  • frames — Returns all