Isaac Ameyaw - Freelance Web Developer & Digital Marketer Logo

JavaScript cheat sheet for beginners 2023

Share :

JavaScript cheat sheet for beginners 2023

Learn JavaScript the right way with this beginner’s cheat sheet

1. JavaScript Fundamentals

Here are the basics on how to add JavaScript to your website.

  • In HTML code, JavaScript is written as follows:

Adding JavaScript code to an HTML page requires it to be enclosed within the <script> tag as shown below:

<script type = "text/javascript">
//JavaScript coding can be done inside this tag

Using this input, the browser can correctly identify and execute the code.

  • Including external JavaScript files in an HTML file:

It is also possible to create a separate JavaScript file and include it within our HTML file.

Keeping different types of code separate will result in better-organized files, and different kinds of codes can be kept isolated from one another.

We can, for example, include our JavaScript code in our HTML file in the following manner if our JavaScript code is in the file script.js:

<script src="script.js"></script>
  • Including Comments:

Leaving comments in your code helps other people understand what you’re doing or reminds you if you’ve forgotten something.
Note: To prevent the browser from trying to execute them, they must be properly marked.

In JavaScript you have two different options:

Single-line comments— Whenever you want to include a comment that is limited to a single line, precede it with //
Multi-line comments — If you want to include a long comment between several lines, wrap it in /* and */ to avoid it being executed

2. JavaScript Variables

JavaScript variables are simply storage locations named by their names.

Thus, we can use them in our JavaScript codes as stand-in values through which we can perform various operations.

There are three ways to use variables in JavaScript:
var — The most common variable. It can be reassigned but only accessed within a function. with var move to the top when the code is executed.

var x = 140; //  variable x can be reassigned a new value and also redeclared

const — Cannot be reassigned and are not accessible until they appear in a program.

const x = 5; // variable x cannot be reassigned a new value or redeclared

let— Like const, the let variable can be reassigned but not re-declared.

let x = 202; // variable x cannot be redeclared but can be reassigned a new value

3. JavaScript Data Types

Variables in JavaScript can store a variety of values and data. You use the equals to “=” operator to assign values to JavaScript variables. JavaScript has the following data types:

  • Numbers: These can either be real numbers or integers.
var id = 50
  • Variables: Unlike a fixed value, a variable data type does not have a fixed value.
var x
  • Text (strings): Strings are the most basic types of JavaScript data.
var demoString = "Hello! World"
  • Operations: JavaScript variables can be assigned operations.
var mul = 10*9
  • Boolean Values: True or false are the only two types of Boolean values.
var booleanValue = true
  • Constant numbers: These data types have a constant value.const
l = 8.8
  • JavaScript objects: These are containers for properties that have names. JavaScript objects have methods and members.
var name = {name:"Jon Snow", id:"AS123"}


4. JavaScript Operators

Having variables allows you to perform various types of operations on them. Operators allow you to do this.

There are 4 types of Operators

  • Fundamental Operators:
Operator Description
+ Addition
* Multiplication
/ Division
(…) Grouping operator, operations within brackets are executed earlier than those outside
% Modulus (remainder )
++ Increment numbers
Decrement numbers
  • Bitwise Operators:
Operator Description
& AND statement
<< Left shift
>> Right shift
>>> Zero fill right shift
  • Comparison Operators:
Operator Description
== 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
<= Less than or equal to
? Ternary operator
  • Logical Operators:
Operator Description
&& Logical and
! Logical not

5. JavaScript Functions

The JavaScript function is a block of code that performs a particular task. They look like this:

function nameOfTheFunction(parameterOne, parameterTwo, parameterThree, parameterFour,....,parameterN) {
   // Job or Task of the function 
  • Function for outputting data Functions are commonly used to output data. There are several options for the output:
Function Description
alert() Output data in an alert box in the browser window
confirm() Opens up a yes/no dialog and returns true/false
console.log() Writes information to the browser console, good for debugging purposes
document.write() Write directly to the HTML document
prompt() Creates a dialogue for user input
  • Global Functions Global functions are functions built into every browser capable of running JavaScript.
Function Description
decodeURI() Decodes a Uniform Resource Identifier (URI) created by encodeURI or similar
decodeURIComponent() Decodes a URI component
encodeURI() Encodes a URI into UTF-8
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

6. JavaScript Arrays

An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];
  • Array Methods:

Which can be used to perform various types of operations.

Methods Description
pop() This method is used for removing the last element of an array.
push() This method is used for adding a new element at the very end of an array.
concat() This method is used for joining various arrays into a single array.
reverse() This method is used for reversing the order of the elements in an array.
shift() This method is used for removing the first element of an array.
slice() This method is used for pulling a copy of a part of an array into a new array.
splice() This method is used for adding elements in a particular way and position.
toString() This method is used for converting the array elements into strings.
unshift() This method is used for adding new elements at the beginning of the array.
valueOf() This method is used for returning the primitive value of the given object.
indexOf() This method is used for returning the first index at which a given element is found in an array.
lastIndexOf() This method is used for returning the final index at which a given element appears in an array.
join() This method is used for combining elements of an array into one single string and then returning it.
sort() This method is used for sorting the array elements based on some condition.

An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];

7. JavaScript Loops

Almost all programming languages include loops. It allows you to run blocks of code indefinitely with different values:

  • for loop: JavaScript’s most common method for creating loops.
for (initialization of the loop variable; condition checking for the loop; updation after the loop) {
   // code to be executed in loop
  • while loop: Determines when a loop should run. // Initialization of the loop variable is done before the while loop begins
while(condition checking for the loop){
// 1. code to be executed in loop
// 2. updation of the loop variable
  • do-while loop: Similar to the while loop, it runs at least once and checks whether there is a condition to run it again at the end. // Initialization of the loop variable is done before the do-while loop begins
// 1. code to be executed in loop
// 2. updation of the loop variable
}while(condition checking for the loop);

When it comes to loops, there are two important statements:

Continue statement: If certain conditions are met, skip sections of the loop.
break statement: Exit the cycle when a specified condition is met.

8. JavaScript If-Else

If-else is used in JavaScript to execute a block of codes conditionally. These are used to set conditions for your code block to run. There are situations where certain blocks of code are executed, and there are situations where they are not.

if (condition)
   // Executes this block if
   // condition is true
   // Executes this block if
   // condition is false

9. JavaScript Strings

In JavaScript, strings are used to represent text that does not perform a function but can be displayed.

var Name = "John Cena";

In this case, John Cena is the string.

The following are all the escape sequences in JavaScript, as well as methods that JavaScript provides for strings:

  • Escape Characters Using single or double quotes, strings are marked in JavaScript. Special characters are needed for quotation marks in a string:
Character Description
\’ Single quotes
\” Double quotes
\t Horizontal tab
\v Vertical tab
\ Backslash
\b Backspace
\f Form feed
\n Newline
\r Carriage return
  • String methods: Strings can be worked with in many different ways:
Method Description
charAt() Returns a character at a specified position inside a string
charCodeAt() Gives you the Unicode of a character at that position
concat() Concatenates (joins) two or more strings into one
fromCharCode() Returns a string created from the specified sequence of UTF-16 code units
indexOf() Provides the position of the first occurrence of a specified text within a string
lastIndexOf() Same as indexOf() but with the last occurrence, searching backward
match() Retrieves the matches of a string against a search pattern
replace() Find and replace specified text in a string
search() Executes a search for a matching text and returns its position
slice() Extracts a section of a string and returns it as a new string
split() Splits a string object into an array of strings at a specified position
substr() Similar to slice() but extracts a substring depending on a specified number of characters
substring() Also similar to slice() but can’t accept negative indices
toLowerCase() Convert strings to lower case
toUpperCase() Convert strings to upper case
valueOf() Returns the primitive value (that has no properties or methods) of a string object

10. JavaScript Regular Expression

Strings can be matched by regular expressions, which are search patterns. They can be used for text search and text replacement.

  • Pattern Modifiers
Pattern Description
e Evaluate replacement
i Perform case-insensitive matching
g Perform global matching
m Perform multiple line matching
s Treat strings as a single line
x Allow comments and whitespace in the pattern
U Ungreedy pattern
  • Brackets
Operator Description
[abc] Find any of the characters between the brackets
[^abc] Find any character which is 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
  • Metacharacters
Operator Description
. Find a single character, except newline or line terminator
\w 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
Operator Description
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 occurrence of n
n{X} String that contains a sequence of X n’s
n{X,Y} Strings that contain 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 ni

11. Data Transformation

‘Data transformation’ is the conversion of one format to another. Using higher-order JavaScript functions, you can transform data by taking two or more functions as inputs and returning a function as a consequence. Map(), filter(), and reduce() are all higher-order functions that take a function as input.

  • Map() By calling a specific function on each element of a parent array, JavaScript’s map() method creates an array. Iterating over an array and calling functions on every element is accomplished using
map(), a non-mutating method.
var arr = [10,20,30];
var triple  = => x * 3);
triple; // [30,60,90]
  • filter() With arr.filter(), a new array is generated that consists only of those elements in a given array that meet a given set of conditions and criteria.
var arr = [13,40,47];
var odd = arr.filter(x => x % 2);
odd; // [13,47]
  • Reduce() When used in JavaScript, the arr.reduce() method reduces a given array to a single value by running a function provided for each value (from left-to-right), and storing the output in an accumulator.
var arr = [10,20,30];
var counter = 0;
let answer = arr.reduce((accumulator, value) => value + accumulator, counter);
console.log(answer) // answer = 10 + 20 + 30 = 60

12. Dealing with Dates in JavaScript

Dealing with Dates in JavaScript
You can also work with and modify dates and time with JavaScript. This is the next chapter in the JavaScript cheat sheet.

  • Setting Dates
Methods Description
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.
Date(“2017-06-23”) Date declaration as a string
  • Pulling Date and Time Values
Properties Description
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, full year, 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
Properties Description
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, full year, hours, minutes etc.)

13. Document Object Model (DOM) in JavaScript

A website’s code is organized into Document Object Models (DOMs). JavaScript allows you to build and alter HTML elements (called nodes) in many different ways.

  • Node Properties
Properties Description
attributes Returns a live collection of all attributes registered to an 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
nodeType Returns the type of a node
nodeValue Sets or returns the value of a node
ownerDocument The top-level document object for this node
parentNode Returns the parent node of an element
previousSibling Returns the node immediately preceding the current one
textContent Sets or returns the textual content of a node and its descendants
  • Node Methods
Methods Description
appendChild() Adds a new child node to an element as the last child node
cloneNode() Clones an HTML element
compareDocumentPosition() Compares the document position of two elements
getFeature() Returns an object which implements the APIs of a specified feature
hasAttributes() Returns true if an element has any attributes, otherwise false
hasChildNodes() Returns true if an element has any child nodes, otherwise false
insertBefore() Inserts a new child node before a specified, existing child node
isDefaultNamespace() Returns true if a specified namespaceURI is the default, otherwise false
isEqualNode() Checks if two elements are equal
isSameNode() Checks if two elements are the same node
isSupported() Returns true if a specified feature is supported on the element
lookupNamespaceURI() Returns the namespace URI associated with a given node
lookupPrefix() Returns a DOMString containing the prefix for a given namespace URI 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
Methods Description
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

14. JavaScript Numbers & Math

Mathematical functions and constants can also be performed in JavaScript.

  • Number Properties
Properties Description
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
Methods Description
toExponential() Returns the string with a rounded number written as exponential notation
toFixed() Returns the string of a number with a specified number of decimals
toPrecision() String of a number written with a specified length
toString() Returns a number as a string
valueOf() Returns a number as a number
  • Math Properties
Properties Description
E Euler’s number
LN2 The natural logarithm of 2
LN10 Natural logarithm of 10
LOG2E Base 2 logarithm of E
LOG10E Base 10 logarithm of E
PI The number PI
SQRT1_2 Square root of 1/2
SQRT2 The square root of 2
  • Math Methods
Method Description
abs(x) Returns the absolute (positive) value 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 value
atan2(y,x) Arctangent of the quotient of its arguments
ceil(x) Value of x rounded up to its nearest integer
cos(x) The cosine of x (x is in radians)
exp(x) Value of Ex
floor(x) The value of x rounded down to its nearest integer
log(x) The natural logarithm (base E) of x
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

15. JavaScript Events

Events are things that can happen to HTML elements and are performed by the user. The programming language can listen for these events and trigger actions in the code. No JavaScript cheat sheet would be complete without them.

  • Mouse
Properties Description
onclick The event occurs when the user clicks on an element
oncontextmenu User right-clicks on an element to open a context menu
ondblclick The user double-clicks on an element
onmousedown User presses a mouse button over an element
onmouseenter The pointer moves onto an element
onmouseleave Pointer moves out of an element
onmousemove The pointer is moving while it is over an element
onmouseover When the pointer is moved onto an element or one of its children
onmouseout User moves the mouse pointer out of an element or one of its children
onmouseup The user releases a mouse button while over an element
  • Keyboard
Properties Description
onkeydown When the user is pressing a key down
onkeypress The moment the user starts pressing a key
onkeyup The user releases a key
  • Frame
Properties Description
onabort The loading of a media is aborted
onbeforeunload Event occurs before the document is about to be unloaded
onerror An error occurs while loading an external file
onhashchange There have been changes to the anchor part of a URL
onload When an object has loaded
onpagehide The user navigates away from a webpage
onpageshow When the user navigates to a webpage
onresize The document view is resized
onscroll An element’s scrollbar is being scrolled
onunload Event occurs when a page has unloaded
  • Form
Properties Description
onblur When an element loses focus
onchange The content of a form element changes (for , and )
onfocus An element gets focus
onfocusin When an element is about to get focus
onfocusout The element is about to lose focus
oninput User input on an element
oninvalid An element is invalid
onreset A form is reset
onsearch The user writes something in a search field (for )
onselect The user selects some text (for and )
onsubmit A form is submitted
  • Drag
Properties Description
ondrag An element is dragged
ondragend The user has finished dragging the element
ondragenter The dragged element enters a drop target
ondragleave A dragged element leaves the drop target
ondragover The dragged element is on top of the drop target
ondragstart User starts to drag an element
ondrop Dragged element is dropped on the drop target
  • Clipboard
Properties Description
oncopy User copies the content of an element
oncut The user cuts an element’s content
onpaste A user pastes the content in an element
  • Media
Properties Description
onabort Media loading is aborted
oncanplay The browser can start playing media (e.g. a file has buffered enough)
oncanplaythrough The browser can play through media without stopping
ondurationchange The duration of the media changes
onended The media has reached its end
onerror Happens when an error occurs while loading an external file
onloadeddata Media data is loaded
onloadedmetadata Metadata (like dimensions and duration) are loaded
onloadstart The browser starts looking for specified media
onpause Media is paused either by the user or automatically
onplay The media has been started or is no longer paused
onplaying Media is playing after having been paused or stopped for buffering
onprogress The browser is in the process of downloading the media
onratechange The playing speed of the media changes
onseeked User is finished moving/skipping to a new position in the media
onseeking The user starts moving/skipping
onstalled The browser is trying to load the media but it is not available
onsuspend The browser is intentionally not loading media
ontimeupdate The playing position has changed (e.g. because of fast forward)
onvolumechange Media volume has changed (including mute)
onwaiting Media paused but expected to resume (for example, buffering)
  • Animation
Properties Description
animationend A CSS animation is complete
animationiteration CSS animation is repeated
animationstart CSS animation has started
  • Other
Properties Description
transitionend Fired when a CSS transition has completed
onmessage A message is received through the event source
onoffline The browser starts to work offline
ononline The browser starts to work online
onpopstate When the window’s history changes
onshow A element is shown as a context menu
onstorage A Web Storage area is updated
ontoggle The user opens or closes the element
onwheel Mouse wheel rolls up or down over an element
ontouchcancel Screen-touch is interrupted
ontouchend User’s finger is removed from a touch-screen
ontouchmove A finger is dragged across the screen
ontouchstart A finger is placed on the touch-screen

16. JavaScript Errors

When working with JavaScript, different errors can occur. There are several ways of handling them:

Properties Description
try Lets you define a block of code to test for errors
catch Set up a block of code to execute in case of an error
throw Create custom error messages instead of the standard JavaScript errors
finally Lets you execute code, after try and catch, regardless of the result
  • Error Name Values

JavaScript also has a built-in error object. It has two properties:

Properties Description
name Sets or returns the error name
message Sets or returns an error message in a string from

The error property can return six different values as its name:

Methods Description
EvalError An error has occurred in the eval() function
RangeError A number is “out of range”
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An encodeURI() error has occurred

17. JavaScript Working With Browser

Besides HTML elements, JavaScript is also able to take into account the user browser and incorporate its properties into the code.

  • Window Properties
Methods Description
closed Checks whether a window has been closed or not and returns true or false
defaultStatus Sets or returns the default text in the status bar of a window
document Returns the document object for the window
frames Returns all elements in the current window
history Provides the History object for the window
innerHeight The inner height of a window’s content area
innerWidth The inner width of the content area
length Find out the number of elements in the window
location Returns the location object for the window
name Sets or returns the name of a window
navigator Returns the Navigator object for the window
opener Returns a reference to the window that created the window
outerHeight The outer height of a window, including toolbars/scrollbars
outerWidth The outer width of a window, including toolbars/scrollbars
pageXOffset Number of pixels the current document has been scrolled horizontally
pageYOffset Number of pixels the document has been scrolled vertically
parent The parent window of the current window
screen Returns the Screen object for the window
screenLeft The horizontal coordinate of the window (relative to the screen)
screenTop The vertical coordinate of the window
screenX Same as screenLeft but needed for some browsers
screenY Same as screenTop but needed for some browsers
self Returns the current window
status Sets or returns the text in the status bar of a window
top Returns the topmost browser window
  • Window Methods
Methods Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialogue box with a message and an OK and Cancel button
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to a specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialogue box that prompts the visitor for input
resizeBy() Resizes the window by the specified number of pixels
resizeTo() Resizes the window to a specified width and height
scrollBy() Scrolls the document by a specified number of pixels
scrollTo() Scrolls the document to specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals
setTimeout() Calls a function or evaluates an expression after a specified interval
stop() Stops the window from loading
  • Screen Properties
Properties Description
availHeight Returns the height of the screen (excluding the Windows Taskbar)
availWidth Returns the width of the screen (excluding the Windows Taskbar)
colorDepth Returns the bit depth of the color palette for displaying images
height The total height of the screen
pixelDepth The color resolution of the screen in bits per pixel
width The total width of the screen

Credits: Prajwal k

Looking for a programmer for your project? I will be happy to assist you. Contact me now!

Leave a Message