JavaScript Basics
Quick reference for JavaScript syntax, methods, and common patterns.
🔍
Variables & Data Types
Declaration
Variable declaration methods
let variable = "value"; const constant = "immutable"; var oldWay = "avoid";
Data Types
JavaScript data types and type checking
typeof "string" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (bug!)
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"Functions
Function Declarations
Different ways to declare functions
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Arrow function
const greetArrow = (name) => `Hello, ${name}!`;
// Function expression
const greetExpr = function(name) {
return `Hello, ${name}!`;
};Arrays
Common Methods
Essential array methods
const arr = [1, 2, 3, 4, 5]; // Map arr.map(x => x * 2); // [2, 4, 6, 8, 10] // Filter arr.filter(x => x > 2); // [3, 4, 5] // Reduce arr.reduce((sum, x) => sum + x, 0); // 15 // Find arr.find(x => x > 3); // 4 // Includes arr.includes(3); // true
Objects
Object Methods
Working with objects
const obj = { name: "John", age: 30 };
// Object.keys()
Object.keys(obj); // ["name", "age"]
// Object.values()
Object.values(obj); // ["John", 30]
// Object.entries()
Object.entries(obj); // [["name", "John"], ["age", 30]]
// Destructuring
const { name, age } = obj; // name = "John", age = 30Async JavaScript
Promises & Async/Await
Asynchronous programming patterns
// Promise
new Promise((resolve, reject) => {
// async operation
resolve("success");
});
// Async/Await
async function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}Modern JavaScript Features
ES6+ Features
Modern JavaScript syntax
// Template literals
const message = `Hello ${name}!`;
// Spread operator
const newArr = [...arr, 6, 7];
const newObj = { ...obj, city: "NYC" };
// Rest parameters
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
// Optional chaining
const value = obj?.prop?.subProp;
// Nullish coalescing
const result = value ?? "default";