JavaScript Cheatsheet
Language: Javascript | Reference Guide
# 1. Basics (ES6+)
// 1. Variable Declaration
const constantVar = "Cannot be reassigned";
let blockScopedVar = "Can be reassigned";
var functionScopedVar = "Legacy, avoid if possible"; // Avoid
// 2. Data Types
const aString = `Hello with template literal ${blockScopedVar}`; // String
const aNumber = 42; // Number
const aBoolean = true; // Boolean
const aNull = null; // Null
const anUndefined = undefined; // Undefined
const aSymbol = Symbol("unique"); // Symbol
const aBigInt = 9007199254740991n; // BigInt
// 3. Operators
console.log(2 + 2); // Addition
console.log("hello" + " world"); // String concatenation
console.log(aNumber === 42); // Strict equality (no type coercion)
console.log(aNumber !== "42"); // Strict inequality
console.log(true && false); // Logical AND
console.log(true || false); // Logical OR
# 2. Data Structures
// Arrays
const fruits = ["apple", "banana", "cherry"];
fruits.push("orange");
console.log(`First fruit: ${fruits[0]}`);
fruits.forEach(fruit => console.log(fruit));
// Array methods: map, filter, reduce
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
// Objects
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() { return `${this.firstName} ${this.lastName}`; }
};
console.log(person.firstName); // Dot notation
console.log(person["age"]); // Bracket notation
// Sets (unique values)
const mySet = new Set([1, 1, 2, 3]); // {1, 2, 3}
mySet.add(4);
// Maps (key-value pairs, any type can be a key)
const myMap = new Map();
myMap.set("name", "Alice");
console.log(myMap.get("name"));
# 3. Control Flow
const value = 10;
if (value > 5) {
console.log("Greater than 5");
} else {
console.log("Not greater than 5");
}
// For...of loop (for iterable objects like arrays)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// For...in loop (for object properties)
const user = { name: "Bob", role: "Admin" };
for (const key in user) {
console.log(`${key}: ${user[key]}`);
}
# 4. Functions (ES6+)
// Arrow Function
const add = (a, b) => a + b;
// Function with default parameters
const greet = (name = "Guest") => `Hello, ${name}!`;
console.log(greet()); // "Hello, Guest!"
console.log(greet("Alice")); // "Hello, Alice!"
// Rest and Spread operators
const sumNumbers = (...numbers) => numbers.reduce((acc, n) => acc + n, 0);
console.log(sumNumbers(1, 2, 3)); // 6
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // Spread operator
console.log(arr2); // [1, 2, 3, 4]
# 5. Classes (OOP)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// Inheritance
class Dog extends Animal {
constructor(name, breed) {
super(name); // Call parent constructor
this.breed = breed;
}
speak() {
console.log(`${this.name} barks.`);
}
}
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.speak(); // "Buddy barks."
# 6. Asynchronous JavaScript
// Promises
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved!");
}, 1000);
});
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
// Async/Await (syntactic sugar for Promises)
const fetchData = async () => {
try {
// Assuming fetch is in a browser/Node environment
// const response = await fetch('https://api.example.com/data');
// const data = await response.json();
const data = await myPromise; // Using the promise from above
console.log("Async/Await:", data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
# 7. ES Modules
// --- In file: math.js ---
// export const PI = 3.14;
// export default function add(a, b) {
// return a + b;
// }
// --- In file: main.js ---
// import add, { PI } from './math.js';
// console.log(PI);
// console.log(add(5, 2));
console.log("ES Modules use 'import' and 'export' keywords.");
console.log("This example is commented out as it requires separate files.");
# 8. Packaging with NPM
# 1. Initialize a new project (creates package.json)
npm init -y
# 2. Install a package (e.g., lodash)
npm install lodash
# 3. Install a development dependency (e.g., jest)
npm install --save-dev jest
# package.json will now list lodash as a dependency
# and jest as a devDependency.
# 4. Run scripts defined in package.json
# "scripts": { "test": "jest" }
npm test
Find more developer cheatsheets, guides, and resources at:
10xdev.blog/cheatsheets
master*
0
0
UTF-8
LF
Javascript