Code Snippets library
Code snippets library is a collection of short, ready-to-use code snippets with practical examples that you can quickly copy and use in your projects. It helps save time and solve common problems without digging through documentation.
Guard Clauses – A Cleaner Alternative to Nested Conditionals
// (Nested Ifs)
function processStringNested(value) {
if (typeof value === 'string') {
if (value.length > 3) {
return value.toUpperCase();
}
}
return null;
}
// Guard Clauses
function processStringGuard(value) {
if (typeof value !== 'string') {
return null;
}
if (value.length <= 3) {
return null;
}
return value.toUpperCase();
}
Object Destructuring in JavaScript
// 1. Basic object destructuring
const user = { name: "Alice", age: 25 };
const { name, age } = user; // name = "Alice", age = 25
// 2. Rename variables (alias)
const { name: userName } = user; // userName = "Alice"
// 3. Default values
const { city = "Warszawa" } = user; // city = "Warszawa" (if user.city is undefined)
// 4. Nested objects
const person = { info: { country: "Poland" } };
const { info: { country } } = person; // country = "Poland"
// 5. Rest operator – collect remaining keys
const employee = { id: 1, name: "Alice", role: "Admin" };
const { name: empName, ...rest } = employee; // empName = "Alice", rest = { id: 1, role: "Admin" }
// 6. Destructuring in function parameters – BEST for clean functions
function greet({ name = "John", age = 18 }) {
console.log(`Hi ${name}, age: ${age}`);
}
greet(user); // "Hi Alice, age: 25"
// 7. Dynamic (computed) keys
const key = "age";
const { [key]: userAge } = user; // userAge = 25
5 Ways to Set Default Value
// 1. Logical OR (||) - falsy values become default
// falsy values: 0, "", false, NaN, null, undefined
let name = inputName || "John";
// 2. Nullish coalescing (??)
// Only null and undefined are replaced
let name = inputName ?? "John";
// 3. Ternary operator
let name = typeof inputAge !== "undefined" ? name : "John";
// 4. Function parameters with defaults (ES6+) - BEST for functions
function createUser(name = "John", age = 18, isActive = true) {
return { name, age, isActive };
}
// 5. Destructuring with defaults – GREAT for objects
const config = { firstName: "Alice" };
const {
firstName = "John",
lastName = "Doe",
nickname = "N/A"
} = config;
const names = { firstName, lastName, nickname };
console.log(names)
// Output: { firstName: "Alice", lastName: "Doe", nickname: "N/A" }
3 ways to save data in the browser
// 1. LOCALSTORAGE
// Save a string
localStorage.setItem("name", "John");
// Save an array
const fruits = ["apple", "banana", "pear"];
localStorage.setItem("fruits", JSON.stringify(fruits));
// Save an object
const user = { name: "Alice", age: 25 };
localStorage.setItem("user", JSON.stringify(user));
// 2. SESSIONSTORAGE
// Save an object
sessionStorage.setItem("settings", JSON.stringify({ theme: "dark", fontSize: 14 }));
// 3. COOKIES
// Save a string (valid for 7 days)
document.cookie = "token=abc123; max-age=" + 7*24*60*60;
// Save an array
const colors = ["red", "green", "blue"];
document.cookie = `colors=${JSON.stringify(colors)}; max-age=${7*24*60*60}`;
// Save an object
const product = { id: 101, name: "Laptop", price: 2500 };
document.cookie = `product=${JSON.stringify(product)}; max-age=${7*24*60*60}`;