JavaScript Cheat Sheet

Written by Coursera • Updated on

Quickly reference essential JavaScript functionalities with this comprehensive JavaScript Cheat Sheet. Streamline your coding process and efficiently implement various JS actions with clear examples

JavaScript Cheat Sheet

JavaScript is a powerful and versatile programming language crucial for creating interactive and dynamic websites. From manipulating the DOM to handling events and performing calculations, JavaScript enables developers to enhance user experiences in countless ways. This JavaScript cheat sheet quickly references essential actions, helping you streamline your coding process and efficiently implement various JS functionalities.

JavaScript Cheat Sheet

Click here to download

Basics

Action Definition Example Snippet for Book Seller’s Website
On page script Embed JavaScript directly within an HTML file <script>alert('Welcome to the Bookshop!');</script>
Include external JS file Link an external JavaScript file to an HTML document <script src="scripts.js"></script>
Delay Execute a function after a specified delay setTimeout(() => { alert('Book special offers!'); }, 2000);
Functions Define reusable blocks of code function showGreeting() { alert('Welcome to Book Haven!'); }
Edit DOM element Modify HTML elements document.getElementById('title').innerHTML = 'Book Haven Sale';
Output Display output via console, alert, or document console.log('Books loaded successfully');
Comments Add single-line or multi-line comments // Single-line comment /
/* Multi-line comment */

Loops

Action Definition Example Snippet
For Loop Loop through a block of code a number of times for (let i = 0; i < 5; i++) { console.log(i); }
While Loop Loop while a specified condition is true let i = 0; while (i < 5) { console.log(i); i++; }
Do While Loop Execute a block of code at least once, then loop let i = 0; do { console.log(i); i++; } while (i < 5);
Break Exit a loop or switch statement prematurely for (let i = 0; i < 5; i++) { if (i === 3) break; console.log(i); }
Continue Skip the current iteration of a loop for (let i = 0; i < 5; i++) { if (i === 3) continue; console.log(i); }

Variables

Action Definition Example Snippet
Strict mode Enforce stricter parsing and error handling 'use strict';
Values Store data in variables let bookPrice = 19.99;
Operators Perform operations on variables and values let totalPrice = bookPrice + 5;
Bitwise operators Perform bitwise operations let result = 5 & 1;
Arithmetic Perform arithmetic operations let discount = bookPrice * 0.1;

IF-Else

Action Definition Example Snippet
If-Else Statement Perform conditional execution of code blocks if (bookPrice > 20) { console.log('Eligible for free shipping'); }
else { console.log('Shipping fee applies'); }
Switch statement Perform different actions based on different conditions switch (day) {
case 1: console.log('Monday Deals'); break;
case 2: console.log('Tuesday Discounts'); break;
default: console.log('Regular Prices');
}

Data Types

Action Definition Example Snippet
Objects Store collections of data and functionalities let book = { title: 'JavaScript Basics', author: 'Jane Doe', price: 19.99 };
Access Object Property Access properties of objects book.title
Assign Object Property Assign new values to existing properties book.price = 21.99;

Strings

Action Definition Example Snippet
Declare String Declare string variables let bookTitle = 'JavaScript Guide';
Escape Characters Use escape characters within strings let quote = 'It\'s a great book!';
Length Get the length of a string let len = bookTitle.length;
Split Split a string into an array of substrings let words = bookTitle.split(' ');
Concat Concatenate strings let fullTitle = bookTitle.concat(' for Beginners');
CharAt Get a character at a specified index let firstChar = bookTitle.charAt(0);

Events

Action Definition Example Snippet
Mouse Handle mouse events document.getElementById('buyBtn').addEventListener('click', function() { alert('Book added to cart!'); });
Keyboard Handle keyboard events document.addEventListener('keydown', function(event) { console.log(event.key); });
Frame Handle frame events window.addEventListener('load', function() { alert('Page loaded!'); });
Form Handle form events document.getElementById('orderForm').addEventListener('submit', function(event) { event.preventDefault(); alert('Order submitted!'); });
Drag Handle drag events document.getElementById('dragItem').addEventListener('dragstart', function() { alert('Dragging!'); });
Clipboard Handle clipboard events document.addEventListener('copy', function() { alert('Text copied!'); });
Media Handle media events document.getElementById('bookTrailer').addEventListener('play', function() { alert('Trailer playing!'); });
Animation Handle animation events document.getElementById('animate').addEventListener('animationstart', function() { alert('Animation started!'); });
Miscellaneous Handle various other events window.addEventListener('resize', function() { alert('Window resized!'); });

Numbers

Action Definition Example Snippet
Pi Constant Define the value of Pi let pi = 3.141;
To Fixed Format a number to a specified number of decimal places pi.toFixed(0);
To Precision Format a number to a specified length pi.toPrecision(2);
Value Of Get the primitive value of a number pi.valueOf();
Convert to Number Convert various values to numbers Number(true); Number(new Date());
Parse Int Parse a string to an integer parseInt("6 months");
Parse Float Parse a string to a floating-point number parseFloat("7.5 days");
Max Value Return the maximum representable number Number.MAX_VALUE;
Min Value Return the minimum representable number Number.MIN_VALUE;
Negative Infinity Represent negative infinity Number.NEGATIVE_INFINITY;
Positive Infinity Represent positive infinity Number.POSITIVE_INFINITY;

Math

Action Definition Example Snippet
Pi Get the value of Pi using Math let pi = Math.PI;
Round Round a number to the nearest integer Math.round(4.6);
Power Calculate the power of a number Math.pow(2, 3);
Square Root Calculate the square root of a number Math.sqrt(16);
Ceiling Round a number up to the nearest integer Math.ceil(4.2);
Floor Round a number down to the nearest integer Math.floor(4.7);
Sine Calculate the sine of a number Math.sin(Math.PI / 2);
Cosine Calculate the cosine of a number Math.cos(Math.PI);
Minimum Find the smallest number in a set Math.min(1, 2, 3);
Maximum Find the largest number in a set Math.max(1, 2, 3);

Dates

Action Definition Example Snippet
Get Time Get the current date and time let now = new Date();
Set Part of a Date Set specific parts of a date object now.setFullYear(2023); now.setMonth(10); now.setDate(15);

Arrays

Action Definition Example Snippet
To String Convert array to string let books = ['HTML', 'CSS', 'JavaScript']; books.toString();
Join Join array elements into a string let bookList = books.join(', ');
Pop Remove the last element from an array books.pop();
Push Add a new element to the end of an array books.push('React');
Shift Remove the first element from an array books.shift();
Unshift Add new elements to the beginning of an array books.unshift('Node.js');
Splice Remove or replace existing elements and/or add new elements in an array books.splice(1, 1, 'TypeScript');
Slice Extract a portion of an array let newBooks = books.slice(1, 2);
Sort Sort the elements of an array books.sort();
Reverse Reverse the order of the elements in an array books.reverse();

Errors

Action Definition Example Snippet
Throw Error Manually throw an error throw new Error('Book not found!');
Input Validation Check and validate user inputs if (input.value === '') { alert('Input is required'); }
Error Name Values Access the name properties of error objects try { throw new TypeError('Error occurred!'); } catch (e) { console.log(e.name); }

JSON

Action Definition Example Snippet
Send JSON Send JSON data to a server fetch('https://api.bookhaven.com/data', { method: 'POST', body: JSON.stringify(book) });
Store and Retrieve JSON Store and retrieve JSON data localStorage.setItem('bookData', JSON.stringify(book));
let retrievedData = JSON.parse(localStorage.getItem('bookData'));

This cheat sheet helps you quickly reference essential JavaScript functionalities, ensuring your coding process is efficient and effective. Keep this guide on hand as you continue to explore and master JavaScript.

Further Web Development Resources:

Updated on
Written by:

Coursera

Writer

Coursera is the global online learning platform that offers anyone, anywhere access to online course...

This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.