JavaScript Cheat Sheet & Command Reference
A beginner-friendly JavaScript cheat sheet. Copy-paste examples, common mistakes, syntax guides, and interview questions for modern developers.
Variables
Variables are containers for storing data. Modern JavaScript uses `let` (for values that change) and `const` (for values that never change).
Syntax
let variableName = value;
const constantName = value;Example
let score = 0;
score = 10; // Allowed
const username = "Admin";
// username = "User"; // TypeError!Common Mistake
Using the old `var` keyword. `var` does not respect block scope and can cause confusing bugs.
Best Practice
Always default to `const`. Only change it to `let` if you are absolutely sure the value needs to be reassigned later.
Interview Tip
Be prepared to explain 'hoisting'. `let` and `const` are hoisted to the top of their block, but they are not initialized, meaning accessing them early throws a ReferenceError.
Data Types
JavaScript variables can hold different types of data: Strings (text), Numbers, Booleans (true/false), Arrays (lists), Objects (collections of properties), and Undefined/Null.
Syntax
const str = "Text";
const num = 42;
const bool = true;
const arr = [1, 2, 3];
const obj = { key: "value" };Example
const user = {
name: "Alice",
age: 28,
isActive: true,
hobbies: ["reading", "coding"]
};Common Mistake
Confusing `null` and `undefined`. `undefined` means a variable has been declared but has no value yet. `null` is an assigned value that means 'nothing'.
Best Practice
Use `typeof` to check the data type of a variable before performing operations on it.
Interview Tip
Remember that `typeof null` returns 'object'. This is a famous, long-standing bug in JavaScript!
Operators
Operators perform actions on variables and values. You have arithmetic (+, -, *, /), assignment (=), and comparison (==, ===, >, <).
Syntax
// Arithmetic
let sum = 10 + 5;
// Comparison
let isGreater = 10 > 5;Example
let age = 20;
let isAdult = age >= 18; // true
// Ternary Operator (Shortcut for if/else)
let status = age >= 18 ? "Adult" : "Minor";Common Mistake
Using `==` (loose equality) instead of `===` (strict equality). `==` converts types before comparing (e.g., '5' == 5 is true).
Best Practice
Always use `===` and `!==`. It prevents unexpected bugs by checking both the value and the data type.
Interview Tip
Know the difference between `==` and `===`. Also understand 'truthy' and 'falsy' values (like `0`, `""`, `null`, `undefined`, `NaN`, `false`).
Functions
Functions are reusable blocks of code. You can define a function once, pass different data (arguments) into it, and get a result back.
Syntax
// Standard Function
function name(params) {
return result;
}
// Arrow Function (Modern)
const name = (params) => result;Example
// A function to calculate tax
const calculateTax = (price, taxRate) => {
return price + (price * taxRate);
};
let total = calculateTax(100, 0.2); // 120Common Mistake
Forgetting to include the `return` statement. If a function doesn't return anything, it outputs `undefined` by default.
Best Practice
Keep functions small. A single function should do one specific job.
Interview Tip
Understand how `this` behaves differently in an arrow function compared to a standard function declaration.
Arrays
Arrays are special variables that can hold more than one value at a time in a specific order (indexed starting at 0).
Syntax
const list = [item1, item2, item3];
list.push(newItem); // Adds to end
list.pop(); // Removes from endExample
const fruits = ["Apple", "Banana"];
fruits.push("Cherry");
// Using map to transform arrays
const uppercaseFruits = fruits.map(f => f.toUpperCase());Common Mistake
Trying to access the first item using `list[1]`. Arrays are zero-indexed, so the first item is `list[0]`.
Best Practice
Use array methods like `.map()`, `.filter()`, and `.reduce()` instead of writing manual `for` loops. It makes code cleaner.
Interview Tip
Be prepared to whiteboard common array manipulations. Memorize `.map()` and `.filter()`!
Objects
Objects are collections of related data stored in 'key-value' pairs. Think of an object like a dictionary.
Syntax
const obj = {
key: "value",
method: function() {}
};Example
const car = {
make: "Toyota",
model: "Camry",
startEngine: function() {
console.log("Vroom!");
}
};
console.log(car.make); // Toyota
car.startEngine(); // Vroom!Common Mistake
Forgetting commas between properties in an object definition.
Best Practice
Use object destructuring to pull specific values out of an object easily: `const { make, model } = car;`
Interview Tip
Understand how to clone an object. Using `const newObj = oldObj` only copies the reference, not the actual data. Use the spread operator: `const newObj = { ...oldObj }`.
Promises & Async/Await
JavaScript is single-threaded. Promises handle tasks that take time (like downloading data) so the browser doesn't freeze. `async/await` is modern syntax that makes Promises easier to read.
Syntax
async function doTask() {
const result = await somePromise();
return result;
}Example
async function getUserData() {
try {
const response = await fetch("https://api.example.com/user");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Failed to load data", error);
}
}Common Mistake
Forgetting the `await` keyword. If you forget it, your variable will hold a 'Pending Promise' object instead of the actual data.
Best Practice
Always wrap `await` calls inside a `try/catch` block to handle network failures securely.
Interview Tip
Explain the Event Loop. Know the difference between the Microtask Queue (Promises) and Macrotask Queue (setTimeout).
Frequently Asked Questions
Is JavaScript the same as Java?
No. They are completely different languages. JavaScript was named similarly in the 1990s as a marketing trick because Java was popular.
What is ES6?
ES6 (ECMAScript 2015) was a massive update to JavaScript that introduced let, const, arrow functions, and promises. It represents the start of 'Modern' JavaScript.
Can I use JavaScript outside the browser?
Yes! Using Node.js, you can run JavaScript on a server, allowing you to build full-stack applications with just one language.