JavaScript Cheat Sheet

JavaScript programming reference guide

JavaScript Cheat Sheet

Quick reference guide for JavaScript programming. Click the copy button to copy any command.

117
Total Commands
117
Filtered Results

Variables

CommandCopyDescription
let x = 5Declare variable (block scope)
const x = 5Declare constant
var x = 5Declare variable (function scope)

Data Types

CommandCopyDescription
typeof xGet type of variable
Number(x)Convert to number
String(x)Convert to string
Boolean(x)Convert to boolean

Strings

CommandCopyDescription
s.lengthString length
s.toUpperCase()Convert to uppercase
s.toLowerCase()Convert to lowercase
s.trim()Remove whitespace
s.split(",")Split into array
s.replace("old", "new")Replace substring
s.includes("text")Check if contains text
s.startsWith("pre")Check start
s.endsWith("suf")Check end
s.slice(0, 5)Extract substring
`Hello ${name}`Template literal

Arrays

CommandCopyDescription
arr.lengthArray length
arr.push(item)Add to end
arr.pop()Remove from end
arr.shift()Remove from start
arr.unshift(item)Add to start
arr.splice(index, count)Remove/replace items
arr.slice(start, end)Extract portion
arr.concat(arr2)Combine arrays
arr.join(",")Join to string
arr.reverse()Reverse array
arr.sort()Sort array
arr.indexOf(item)Find index
arr.includes(item)Check if includes
arr.find(fn)Find first matching
arr.filter(fn)Filter array
arr.map(fn)Transform array
arr.reduce(fn, initial)Reduce to single value
arr.forEach(fn)Iterate over array
[...arr]Spread operator

Objects

CommandCopyDescription
obj.keyAccess property
obj["key"]Access with bracket notation
obj.key = valueSet property
delete obj.keyDelete property
Object.keys(obj)Get all keys
Object.values(obj)Get all values
Object.entries(obj)Get key-value pairs
{...obj}Spread object
Object.assign({}, obj)Copy object

Functions

CommandCopyDescription
function name() {}Function declaration
const name = function() {}Function expression
const name = () => {}Arrow function
function name(a = 1) {}Default parameter
function name(...args) {}Rest parameters
return valueReturn value

Conditionals

CommandCopyDescription
if (condition) {}If statement
else if (condition) {}Else if statement
else {}Else statement
condition ? true : falseTernary operator
switch (x) { case 1: break; }Switch statement

Loops

CommandCopyDescription
for (let i = 0; i < 10; i++) {}For loop
for (let item of array) {}For...of loop
for (let key in object) {}For...in loop
while (condition) {}While loop
do {} while (condition)Do...while loop
breakExit loop
continueSkip iteration

DOM Manipulation

CommandCopyDescription
document.getElementById("id")Get element by ID
document.querySelector("selector")Query selector
document.querySelectorAll("selector")Query all
element.textContentGet/set text content
element.innerHTMLGet/set HTML content
element.classList.add("class")Add CSS class
element.classList.remove("class")Remove CSS class
element.classList.toggle("class")Toggle CSS class
element.style.property = valueSet inline style
element.setAttribute("attr", "value")Set attribute
element.getAttribute("attr")Get attribute
document.createElement("div")Create element
parent.appendChild(child)Append child
parent.removeChild(child)Remove child

Events

CommandCopyDescription
element.addEventListener("click", fn)Add event listener
element.removeEventListener("click", fn)Remove event listener
event.preventDefault()Prevent default action
event.stopPropagation()Stop event bubbling

Promises

CommandCopyDescription
new Promise((resolve, reject) => {})Create promise
promise.then(fn)Handle success
promise.catch(fn)Handle error
promise.finally(fn)Always execute
Promise.all([p1, p2])Wait for all
Promise.race([p1, p2])Wait for first

Async/Await

CommandCopyDescription
async function name() {}Async function
await promiseWait for promise
try {} catch(e) {}Try-catch block

Fetch API

CommandCopyDescription
fetch(url)Make HTTP request
fetch(url, {method: "POST"})POST request
response.json()Parse JSON response
response.text()Get text response

JSON

CommandCopyDescription
JSON.stringify(obj)Convert to JSON string
JSON.parse(str)Parse JSON string

Math

CommandCopyDescription
Math.random()Random number 0-1
Math.floor(x)Round down
Math.ceil(x)Round up
Math.round(x)Round to nearest
Math.max(a, b)Maximum value
Math.min(a, b)Minimum value

Date

CommandCopyDescription
new Date()Create date object
date.getFullYear()Get year
date.getMonth()Get month (0-11)
date.getDate()Get day of month
date.getTime()Get timestamp
Date.now()Current timestamp

Console

CommandCopyDescription
console.log(x)Log to console
console.error(x)Log error
console.warn(x)Log warning
console.table(arr)Display as table

Timing

CommandCopyDescription
setTimeout(fn, ms)Execute after delay
setInterval(fn, ms)Execute repeatedly
clearTimeout(id)Cancel timeout
clearInterval(id)Cancel interval

All operations are performed locally in your browser. No data is sent to any server.

About JavaScript Cheat Sheet

This section will contain detailed, SEO-friendly content about the JavaScript Cheat Sheet.

In the future, this content will be managed through a headless CMS, allowing you to:

  • Add detailed explanations about how to use this tool
  • Include examples and use cases
  • Provide tips and best practices
  • Add FAQs and troubleshooting guides
  • Update content without touching the code

How to Use

Step-by-step instructions for using the JavaScript Cheat Sheet will appear here. This content will be fully customizable through the admin panel.

Features

Key features and benefits of this tool will be listed here. All content is editable via the CMS.