JavaScript
Cheat
Sheet
JavaScript CheatSheet for beginners!
coding_dev_
Tilak | Web Development
coding_dev_
Basics - Javascript
What is Javascript?
JavaScript is a lightweight programming language that web developers commonly use to create
more dynamic interactions when developing web pages, applications, servers, and or even
games.
Features of JavaScript
The following are more characteristics/features of JavaScript:
1. Object-Centered Script Language
2. Client edge Technology
3. Validation of User’s Input
4. Else and If Statement
5. Interpreter Centered
6. Ability to perform In Built Function
7. Case Sensitive format
8. Light Weight and delicate
9. Statements Looping
10. Handling Events
Where is JavaScript used?
JavaScript is highly used in
1. Web Applications
2. Games
3. Mobile Apps
4. Web Servers
Who developed JavaScript, and what was the first name of JavaScript?
JavaScript was developed by Brendan Eich, who was a Netscape programmer. Brendan Eich
developed this new scripting language in just ten days in the year September 1995. At the time of
its launch, JavaScript was initially called Mocha. After that, it was called Live Script and later
known as JavaScript.
1
coding_dev_
What are different Data types in Javascript?
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object
Syntax & Meaning
On Page Script
Adding internal JavaScript to HTML
External JS File
Adding external JavaScript to HTML
Functions
JavaScript Function syntax
2
1/15
coding_dev_
Conditional Statements
Conditional statements are used to perform operations based on some conditions.
If Statement
The block of code to be executed, when the condition specified is true.
If-else Statement
If the condition for the if block is false, then the else block will be executed.
Else-if Statement
A basic if-else ladder
Switch Statement
EV_
G_D
DIN
CO
3
2/15
coding_dev_
Iterative Statements (Loops)
Iterative statement facilitates programmer to execute any block of code lines repeatedly and can
be controlled as per conditions added by the programmer.
For Loop
For loop syntax in javascript
While Loop
Runs the code till the specified condition is true
EV_
G_D
DIN
CO
Do While Loop
A do while loop is executed at least once despite the condition being true or false
Strings
The string is a sequence of characters that is used for storing and managing text data.
4
3/15
charAt method coding_dev_
Returns the character from the specified index.
concat method
Joins two or more strings together.
index of method
Returns the index of the first occurrence of the specified character from the string else -1 if not
found.
match method
Searches a string for a match against a regular expression.
replace method
Searches a string for a match against a specified string or char and returns a new string by
replacing the specified values.
search method
Searches a string against a specified value.
5
4/15
coding_dev_
split method
Splits a string into an array consisting of substrings.
substring method
Returns a substring of a string containing characters from the specified indices.
Arrays
The array is a collection of data items of the same type. In simple terms, it is a variable that
contains multiple values.
variable
Containers for storing data.
concat method
Joins two or more arrays together.
EV_
G_D
DIN
CO
indexOf method
Returns the index of the specified item from the array.
join method
Converts the array elements to a string.
6
5/15
pop method coding_dev_
Deletes the last element of the array.
reverse method
This method reverses the order of the array elements.
sort method
Sorts the array elements in a specified manner.
toString method
Converts the array elements to a string.
valueOf method
returns the relevant Number Object holding the value of the argument passed
Number Methods
JS math and number objects provide several constant and methods to perform mathematical
operations.
toExponential method
Converts a number to its exponential form.
7
6/15
toPrecision method coding_dev_
Formats a number into a specified length.
toString method
Converts an object to a string
valueOf method
Returns the primitive value of a number.
Maths Methods
ceil method
Rounds a number upwards to the nearest integer, and returns the result
exp method
Returns the value of E^x.
EV_
G_D
log method
DIN
Returns the logarithmic value of x.
CO
8
7/15
pow method coding_dev_
Returns the value of x to the power y.
random method
Returns a random number between 0 and 1.
sqrt method
Returns the square root of a number x
CODING_DEV_
Dates
Date object is used to get the year, month and day. It has methods to get and set day, month,
year, hour, minute, and seconds.
Pulling Date from the Date object
Returns the date from the date object
Pulling Day from the Date object
Returns the day from the date object
Pulling Hours from the Date object
Returns the hours from the date object
9
8/15
Pulling Minutes from the Date object coding_dev_
Returns the minutes from the date object
Pulling Seconds from the Date object
Returns the seconds from the date object
Pulling Time from the Date object
Returns the time from the date object
Mouse Events
Any change in the state of an object is referred to as an Event. With the help of JS, you can
handle events, i.e., how any specific HTML tag will work when the user does something.
click
Fired when an element is clicked
oncontextmenu
Fired when an element is right-clicked
dblclick
10
9/15
Fired when an element is double-clicked coding_dev_
mouseenter
Fired when an element is entered by the mouse arrow
mouseleave
Fired when an element is exited by the mouse arrow
mousemove
Fired when the mouse is moved inside the element
Keyboard Events
keydown
Fired when the user is pressing a key on the keyboard
11
coding_dev_
keypress
Fired when the user presses the key on the keyboard
keyup
Fired when the user releases a key on the keyboard
EV_
Errors
G_D
IN
Errors are thrown by the compiler or interpreter whenever they find any fault in the code, and it
D
can be of any type like syntax error, run-time error, logical error, etc. JS provides some functions
CO
to handle the errors.
try and catch
Try the code block and execute catch when err is thrown
Window Methods
Methods that are available from the window object
alert method
12
Used to alert something on the screen coding_dev_
blur method
The blur() method removes focus from the current window.
setInterval
Keeps executing code at a certain interval
setTimeout
Executes the code after a certain interval of time
close
The Window. close() method closes the current window
confirm
The window.confirm() instructs the browser to display a dialog with an optional message, and to
wait until the user either confirms or cancels
open
13
Opens a new window coding_dev_
prompt
Prompts the user with a text and takes a value. Second parameter is the default value
scrollBy
scrollTo
Scrolls the document to the specified coordinates.
clearInterval
Clears the setInterval. var is the value returned by setInterval call
clearTimeout
Clears the setTimeout. var is the value returned by setTimeout call
stop
Stops the further resource loading
14
coding_dev_
JavaScript Objects
Object is a non-primitive data-type that allows you to store multiple collections of data.
Object creation
Syntax to declare an object is:
Accessing Object Properties
1. Using dot Notation
2. Using bracket Notation
EV_
G_D
DIN
CO
15
coding_dev_
Query/Get Elements
The browser creates a DOM (Document Object Model) whenever a web page is loaded, and with
the help of HTML DOM, one can access and modify all the elements of the HTML document.
querySelector
Selector to select first matching element
querySelectorAll
A selector to select all matching elements
getElementsByTagName
Select elements by tag name
getElementsByClassName
Select elements by class name
Get Element by Id
Select an element by its id
16
coding_dev_
Creating Elements
Create new elements in the DOM
createElement
Create a new element
createTextNode
Create a new text node
Accessing & Updating
Elements
innerHTML
Get or set the HTML Content of an element
textContent
Modify the text content of an element
17
coding_dev_
Regular Expressions
Regular expressions can be defined as search patterns that can be used to match string
character combinations. Text search and text to replace procedures can both benefit from
the search pattern.
Pattern Modifiers
e — This is used for evaluating replacement
i — This is used for performing case-insensitive matching
U — This is used for ungreedy pattern
g — This is used for performing global matching
m — This is used for performing multiple line matching
s — This is used for treating strings as a single line
x — This is used for allowing comments and whitespace in the pattern
Metacharacters
. — This is used for finding a single character, except newline or line terminator
\w — This is used for finding Word characters
\W — This is used for finding Non-word characters
\s — Used for finding Whitespace characters
\S — This is used for finding Non-whitespace characters
\b — This is used for finding matches at the beginning or at the end of a word
\B — This is used for finding matches not at the beginning or at the end of a word
\0 — This is used for finding NULL characters
\n — Used for finding a new line character
\f — This is used for finding a Form feed character
\r — This is used for finding a Carriage return character
\t — This is used for finding a Tab character
\v — Used for finding a Vertical tab character
\d — This is used for finding digits
\D — This is used for finding non-digit characters
\xxx — This is used for finding characters given by an octal number xxx
\xdd — This is used for finding characters given by a hexadecimal number dd
\uxxxx — This is used for finding the Unicode character given by a hexadecimal number XXXX
18
coding_dev_
Brackets
Group parts of a regular expression together by putting them inside round brackets or
parentheses:
[abc] — This is used for finding all the characters between the brackets
(a|b|c) — This is used for finding all of the alternatives separated with |
[^abc] — This is used for finding every character that is not in the brackets
[0-9] — This is used for finding each digit from 0 to 9
[A-z] — This is used for finding each character from uppercase A to lowercase z
Quantifiers
Quantifiers provide the minimum number of instances of a character, group, or character
class in the input required to find a match:
n+ — This is used for matching each string which is having one or more n
n* — This is used for matching any string which is having zero or more occurrences of
n? — This is used for matching strings which are having zero or one occurrence of
^n — This is used for matching strings with n in the first plac
?=n — This is used for matching all strings which are followed by a particular string
?!n — This is used for matching strings that are not followed by a particular string n
n{X} — This is used for matching strings that contain a sequence of X n’
n{X,Y} — This is used for matching a string that contains a sequence of X to Y n’
n{X,} — This is used for matching all strings which are having a sequence of X or more n’
n$ — This is used for matching all strings having n at the end.
19
coding_dev_
Advanced Javascript
JavaScript Generators
A new way to work with functions and iterators.
Using a generator,
you can stop the execution of a function from anywhere inside the function
and continue executing code from a halted position.
Closures
A closure is a function created inside another function but has access to the outer function
variables. Example,
EV_
G_D
DIN
CO
Above the displayName() inner function is returned from the outer function before being
executed.
20
coding_dev_
Spread Operator
Quickly copy all or part of an existing array or object into another array or object
Ternary Operator
Short, one-line conditional operator to replace if/else
Error Handling
Various types of errors occur when we are coding in JavaScript. There are a few options for
dealing with them:
try — We can define a code block for testing errors using the try block.
catch — We can set up a block of code to execute in the event of an error using the catch
statement.
throw — Instead of the typical JavaScript errors, we can also create custom error
messages using the throw statement.
finally — JavaScript also allows us to run our code regardless of the outcome of try and
catch.
JavaScript possesses its own inbuilt error object which has the following properties:
name — It is used for setting or returning an error name.
message — It is used for setting or returning the error message as a string.
=> There are six types of ways in which the error property can return its name. They are as
follows:
EvalError — It indicates that an error has occurred within the eval() method.
RangeError — It indicates that some number is “out of range”.
ReferenceError — It indicates that an illegal reference was occurring.
SyntaxError — It indicates that a syntax error was occurring.
TypeError — It indicates that a type error was occurring.
URIError — It indicates that an encodeURI() error was occurring.
21
coding_dev_
Promise
To create a promise object, we use the Promise() constructor.
async/await
The syntax of async function is:
The syntax to use await is:
try...catch...finally
The finally block executes both when the code runs successfully or if an error occurs.
Syntax of try...catch...finally block is:
22
coding_dev_
Recursion
Recursion is a process of calling itself. A function that calls itself is called a recursive function.
Syntax:
Anonymous Functions
It is a function that does not have any name associated with it. General Syntax:
Anonymous function with Arrow function syntax:
coding_dev_
Tilak | Web Development
23