JavaScript has become an indispensable tool in modern web development, powering interactive and dynamic websites across the globe. Whether you're a seasoned developer or just starting your coding journey, having a comprehensive cheat sheet at your fingertips can be a game-changer. In this blog post, we've compiled an extensive JavaScript cheat sheet that covers everything from basic syntax to advanced concepts. Whether you need a quick refresher or a handy reference during your coding sessions, this guide has got you covered. We'll dive into:
1. Basic Syntax and Data Types
2. Variables and Scope
3. Operators and Control Structures
4. Functions and Arrow Functions
5. Arrays and Objects
6. ES6+ Features
7. DOM Manipulation
8. Asynchronous JavaScript (Promises, Async/Await)
9. Error Handling 10. Best Practices and Tips
Variables
let variableName = value; // Block-scoped
const constantName = value; // Block-scoped and read-only
var variableName = value; // Function-scoped
Data Types
- String:
"Hello"
- Number:
123
,3.14
- Boolean:
true
,false
- Null:
null
- Undefined:
undefined
- Object:
{ key: value }
- Array:
[1, 2, 3]
Operators
- Arithmetic:
+
,-
,*
,/
,%
- Assignment:
=
,+=
,-=
,*=
,/=
- Comparison:
==
,===
,!=
,!==
,>
,<
,>=
,<=
- Logical:
&&
,||
,!
- Ternary:
condition ? expr1 : expr2
Functions
function functionName(parameters) {
// code to be executed
}
const functionName = (parameters) => {
// code to be executed
}
Control Structures
Conditionals
if (condition) {
// code to be executed if condition is true
} else if (anotherCondition) {
// code to be executed if anotherCondition is true
} else {
// code to be executed if all conditions are false
}
Switch
switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
default:
// code to be executed if none of the cases are true
}
Loops
// For Loop
for (let i = 0; i < 10; i++) {
// code to be executed
}
// While Loop
let i = 0;
while (i < 10) {
// code to be executed
i++;
}
// Do-While Loop
let i = 0;
do {
// code to be executed
i++;
} while (i < 10);
// For-Of Loop (for Arrays)
const array = [1, 2, 3];
for (const value of array) {
// code to be executed
}
// For-In Loop (for Objects)
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
// code to be executed
}
Arrays and Objects
Array Methods
const array = [1, 2, 3, 4, 5];
array.push(6); // Add to end
array.pop(); // Remove from end
array.unshift(0); // Add to start
array.shift(); // Remove from start
array.length; // Length of array
array.map(x => x * 2); // Apply function to each element
array.filter(x => x > 2); // Filter elements
array.find(x => x > 2); // Find first matching element
array.indexOf(3); // Find index of element
array.includes(3); // Check if element is in array
array.slice(1, 3); // Get sub-array
array.splice(2, 1); // Remove/Replace elements
array.concat([6, 7]); // Concatenate arrays
array.join(', '); // Join elements into string
Object Methods
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj); // Get array of keys
Object.values(obj); // Get array of values
Object.entries(obj); // Get array of key-value pairs
Object.assign({}, obj); // Copy object
String Methods
const str = "Hello, World!";
str.length; // Length of string
str.toUpperCase(); // Convert to uppercase
str.toLowerCase(); // Convert to lowercase
str.includes("Hello"); // Check if substring exists
str.startsWith("Hello"); // Check if starts with substring
str.endsWith("World!"); // Check if ends with substring
str.indexOf("World"); // Get index of substring
str.slice(0, 5); // Get substring
str.split(", "); // Split into array
str.replace("World", "JavaScript"); // Replace substring
str.trim(); // Remove whitespace from both sides
DOM Manipulation
// Selecting elements
document.getElementById("id");
document.getElementsByClassName("class");
document.getElementsByTagName("tag");
document.querySelector("selector");
document.querySelectorAll("selector");
// Creating elements
const element = document.createElement("div");
// Modifying elements
element.innerHTML = "<p>Hello</p>";
element.textContent = "Hello";
element.setAttribute("class", "my-class");
element.classList.add("my-class");
element.classList.remove("my-class");
// Appending elements
document.body.appendChild(element);
parentElement.appendChild(childElement);
// Removing elements
element.remove();
Event Handling
element.addEventListener("click", function(event) {
// code to be executed when element is clicked
});
element.removeEventListener("click", function(event) {
// code to remove event listener
});
Promises and Async/Await
Promises
const myPromise = new Promise((resolve, reject) => {
// asynchronous operation
if (success) {
resolve(result);
} else {
reject(error);
}
});
myPromise.then(result => {
// handle result
}).catch(error => {
// handle error
});
Async/Await
async function myFunction() {
try {
const result = await myPromise;
// handle result
} catch (error) {
// handle error
}
}
Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// handle data
})
.catch(error => {
// handle error
});
// Async/Await with Fetch
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
// handle data
} catch (error) {
// handle error
}
}
Error Handling
try {
// code that may throw an error
} catch (error) {
// handle error
} finally {
// code to be executed regardless of an error
}
This cheat sheet covers the core concepts and common tasks for a junior JavaScript developer. As you gain more experience, you'll discover more advanced topics and best practices.