JavaScript

Essential JavaScript syntax, methods, and best practices for modern web development.

languages
javascriptes6webfrontend

Variables

// ES6+ variable declarations
const immutable = 'cannot change';
let mutable = 'can change';
var oldWay = 'avoid using'; // function scoped

// Destructuring
const { name, age } = person;
const [first, second, ...rest] = array;

// Spread operator
const newArray = [...oldArray, newItem];
const newObject = { ...oldObject, newProp: value };

Functions

// Arrow functions
const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
const complex = (a, b) => {
  const result = a + b;
  return result;
};

// Default parameters
const greet = (name = 'World') => `Hello, ${name}!`;

// Rest parameters
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);

Arrays

// Array methods
array.map(x => x * 2);           // Transform elements
array.filter(x => x > 5);        // Filter elements
array.reduce((acc, x) => acc + x, 0); // Reduce to single value
array.find(x => x.id === 1);     // Find first match
array.some(x => x > 5);          // Check if any match
array.every(x => x > 5);         // Check if all match
array.includes(value);           // Check if contains
array.indexOf(value);            // Get index of value
array.flat();                    // Flatten nested arrays
array.flatMap(x => [x, x * 2]);  // Map and flatten

Objects

// Object methods
Object.keys(obj);                // Get keys as array
Object.values(obj);              // Get values as array
Object.entries(obj);             // Get [key, value] pairs
Object.assign({}, obj1, obj2);   // Merge objects
Object.freeze(obj);              // Make immutable

// Optional chaining
const name = user?.profile?.name;

// Nullish coalescing
const value = input ?? 'default';

Promises & Async/Await

// Promise
const promise = new Promise((resolve, reject) => {
  if (success) resolve(data);
  else reject(error);
});

promise
  .then(data => console.log(data))
  .catch(error => console.error(error))
  .finally(() => console.log('Done'));

// Async/Await
async function fetchData() {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error(error);
  }
}

// Promise.all - parallel execution
const [users, posts] = await Promise.all([
  fetchUsers(),
  fetchPosts()
]);

Classes

class Person {
  #privateField = 'private';  // Private field
  
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // Method
  greet() {
    return `Hello, I'm ${this.name}`;
  }
  
  // Getter
  get info() {
    return `${this.name}, ${this.age}`;
  }
  
  // Setter
  set info(value) {
    [this.name, this.age] = value.split(', ');
  }
  
  // Static method
  static create(name) {
    return new Person(name, 0);
  }
}

// Inheritance
class Developer extends Person {
  constructor(name, age, language) {
    super(name, age);
    this.language = language;
  }
}

Modules

// Named exports
export const name = 'value';
export function helper() {}
export class MyClass {}

// Default export
export default function main() {}

// Imports
import defaultExport from './module';
import { named1, named2 } from './module';
import { named as alias } from './module';
import * as module from './module';

Useful Snippets

// Remove duplicates from array
const unique = [...new Set(array)];

// Deep clone object
const clone = JSON.parse(JSON.stringify(obj));
// Or using structuredClone (modern)
const clone = structuredClone(obj);

// Generate random number in range
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// Debounce function
const debounce = (fn, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
};

// Sleep/delay
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));