JavaScript Cheat Sheet
Basics Variables
Actions Description Example Snippet Actions Description Example Snippet
On page script Embed JavaScript directly within an <script>alert('Welcome to the 'use strict';
Strict mode Enforce stricter parsing and error
Bookshop!');</script>
HTML file. handling.
Include external JS file Link an external JavaScript file to an <script Values Store data in variables. let bookPrice = 19.99;
src="[Link]"></script>
HTML document.
setTimeout(() => { alert('Book Operators Perform operations on variables and let totalPrice = bookPrice + 5;
Delay Execute a function after a specified delay.
special offers!'); }, 2000); values.
Bitwise operators Perform bitwise operations. let result = 5 & 1;
Functions Define reusable blocks of code. function showGreeting() {
alert('Welcome to Book
Haven!'); }
Arithmetic Perform arithmetic operations. let discount = bookPrice * 0.1;
Edit DOM element Modify HTML elements. [Link]('title'
).innerHTML = 'Book Haven
Sale';
Output Display output via console, alert, or [Link]('Books loaded If-Else
successfully');
document.
Actions Description Example Snippet
Comments Add single-line or multi-line comments. // Single-line comment / /*
Multi-line comment */ If-Else Statement Perform conditional execution of code blocks. if (bookPrice > 20) {
[Link]('Eligible for free
shipping'); } else {
[Link]('Shipping fee
applies'); }
Loops
Switch statement Perform different actions based on different switch (day) { case 1:
conditions. [Link]('Monday Deals');
Actions Description Example Snippet break; case 2:
[Link]('Tuesday
For Loop Loop through a block of code a number for (let i = 0; i < 5; i++) { Discounts'); break; default:
[Link](i); } [Link]('Regular Prices');
of times.
}
While Loop Loop while a specified condition is true. let i = 0; while (i < 5) {
[Link](i); i++; }
Data Types
let i = 0; do { [Link](i);
Actions Description Example Snippet
Do While Loop Execute a block of code at least once,
i++; } while (i < 5);
then loop. 'use strict';
Strict mode Enforce stricter parsing and error
for (let i = 0; i < 5; i++) {
handling.
Break Exit a loop or switch statement
if (i === 3) break; let bookPrice = 19.99;
prematurely. Values Store data in variables.
[Link](i); }
Continue Skip the current iteration of a loop. for (let i = 0; i < 5; i++) {
if (i === 3) continue; Operators Perform operations on variables and let totalPrice = bookPrice + 5;
[Link](i); } values.
Strings Events
Actions Description Example Snippet Actions Description Example Snippet
Declare String Declare string variables. let bookTitle = 'JavaScript Mouse Handle mouse events. [Link]('buyBtn'
Guide'; ).addEventListener('click',
function() { alert('Book added
Escape Characters Use escape characters within let quote = 'It\'s a great to cart!'); });
book!';
strings.
Keyboard Handle keyboard events. [Link]('keydo
let len = [Link]; wn', function(event) {
Length Get the length of a string.
[Link]([Link]); });
Split Split a string into an array of let words = [Link](' ');
Frame Handle frame events. [Link]('load',
substrings. function() { alert('Page
loaded!'); });
Concat Concatenate strings. let fullTitle =
[Link](' for Form Handle form events. [Link]('orderFo
Beginners'); rm').addEventListener('submit',
function(event) {
CharAt Get a character at a specified let firstChar = [Link]();
[Link](0); alert('Order submitted!'); });
index.
Drag Handle drag events. [Link]('dragIte
m').addEventListener('dragstart'
, function() {
Math alert('Dragging!'); });
Clipboard Handle clipboard events. [Link]('copy'
Actions Description Example Snippet
, function() { alert('Text
copied!'); });
Pi Get the value of Pi using Math. let pi = [Link];
Media Handle media events. [Link]('bookTra
iler').addEventListener('play',
Round Round a number to the nearest [Link](4.6); function() { alert('Trailer
integer. playing!'); });
Animation Handle animation events. [Link]('animate
Power Calculate the power of a number. [Link](2, 3);
').addEventListener('animationst
art', function() {
Square Root Calculate the square root of a [Link](16);
alert('Animation started!'); });
number.
Miscellaneous Handle various other events. [Link]('resize'
Ceiling Round a number up to the nearest [Link](4.2); , function() { alert('Window
integer. resized!'); });
Floor Round a number down to the [Link](4.7);
nearest integer. Dates
Sine Calculate the sine of a number. [Link]([Link] / 2);
Actions Description Example Snippet
Cosine Calculate the cosine of a number. [Link]([Link]);
Get Time Get the current date and time. let now = new Date();
Minimum Find the smallest number in a set. [Link](1, 2, 3);
Maximum Find the largest number in a set. [Link](1, 2, 3);
Set Part of a Date Set specific parts of a date object. [Link](2023);
[Link](10);
[Link](15);
Arrays Numbers
Actions Description Example Snippet Actions Description Example Snippet
To String Convert array to string. let books = ['HTML', 'CSS', Pi Constant Define the value of Pi. let pi = 3.141;
'JavaScript'];
[Link]();
To Fixed Format a number to a specified [Link](0);
Join Join array elements into a string. let bookList = [Link](',
number of decimal places.
');
To Precision Format a number to a specified [Link](2);
Pop Remove the last element from an [Link]();
length.
array.
Value Of Get the primitive value of a number. [Link]();
Push Add a new element to the end of an [Link]('React');
array.
Shift Remove the first element from an [Link](); Convert to Number Convert various values to numbers. Number(true); Number(new
array. Date());
Unshift Add new elements to the beginning [Link]('[Link]'); parseInt("6 months");
Parse Int Parse a string to an integer.
of an array.
Parse Float Parse a string to a floating-point parseFloat("7.5 days");
Splice Remove or replace existing elements [Link](1, 1,
and/or add new elements in an 'TypeScript'); number.
array. Number.MAX_VALUE;
Max Value Return the maximum representable
Slice Extract a portion of an array. let newBooks = [Link](1, number.
2);
Min Value Return the minimum representable Number.MIN_VALUE;
Sort Sort the elements of an array. [Link]();
number.
Reverse Reverse the order of the elements in [Link]();
Negative Infinity Represent negative infinity. Number.NEGATIVE_INFINITY;
an array.
Positive Infinity Represent positive infinity. Number.POSITIVE_INFINITY;
Errors
Actions Description Example Snippet JSON
Throw Error Manually throw an error. throw new Error('Book not
found!'); Actions Description Example Snippet
Input Validation Check and validate user inputs. if ([Link] === '') {
Send JSON Send JSON data to a server. fetch('[Link]
alert('Input is required'); }
m/data', { method: 'POST',
body: [Link](book) });
Error Name Values Access the name properties of try { throw new TypeError('Error
occurred!'); } catch (e) { [Link]('bookData'
error objects. Store and Retrieve JSON Store and retrieve JSON data.
[Link]([Link]); } , [Link](book)); let
retrievedData =
[Link]([Link]
('bookData'));