javascript

examples

examples.js
// ============================================
// 17.1 Destructuring - Examples
// ============================================

// --------------------------------------------
// 1. Array Destructuring Basics
// --------------------------------------------

const colors = ['red', 'green', 'blue', 'yellow'];

// Basic destructuring
const [first, second, third] = colors;
console.log(first); // 'red'
console.log(second); // 'green'
console.log(third); // 'blue'

// Skipping elements
const [primary, , tertiary] = colors;
console.log(primary); // 'red'
console.log(tertiary); // 'blue'

// Rest pattern - collect remaining
const [head, ...tail] = colors;
console.log(head); // 'red'
console.log(tail); // ['green', 'blue', 'yellow']

// --------------------------------------------
// 2. Array Destructuring with Defaults
// --------------------------------------------

const partial = ['a', 'b'];

const [x, y, z = 'default'] = partial;
console.log(x); // 'a'
console.log(y); // 'b'
console.log(z); // 'default'

// Undefined triggers default, null doesn't
const [val1 = 10, val2 = 20] = [undefined, null];
console.log(val1); // 10 (default used)
console.log(val2); // null (not default)

// --------------------------------------------
// 3. Swapping Variables
// --------------------------------------------

let a = 1;
let b = 2;

console.log('Before:', a, b); // 1, 2

[a, b] = [b, a];

console.log('After:', a, b); // 2, 1

// Three-way swap
let p = 1,
  q = 2,
  r = 3;
[p, q, r] = [r, p, q];
console.log(p, q, r); // 3, 1, 2

// --------------------------------------------
// 4. Object Destructuring Basics
// --------------------------------------------

const person = {
  name: 'Alice',
  age: 30,
  city: 'New York',
  country: 'USA',
};

// Basic destructuring
const { name, age } = person;
console.log(name); // 'Alice'
console.log(age); // 30

// Order doesn't matter for objects
const { city, name: personName } = person;
console.log(city); // 'New York'
console.log(personName); // 'Alice'

// --------------------------------------------
// 5. Object Destructuring with Renaming
// --------------------------------------------

const user = {
  id: 1,
  username: 'alice123',
  email: 'alice@example.com',
};

// Rename during destructuring
const { username: userName, email: userEmail } = user;

console.log(userName); // 'alice123'
console.log(userEmail); // 'alice@example.com'

// Rename with default
const { role: userRole = 'user' } = user;
console.log(userRole); // 'user' (default)

// --------------------------------------------
// 6. Object Destructuring with Defaults
// --------------------------------------------

const config = {
  host: 'localhost',
  port: 3000,
};

const { host, port, protocol = 'http', timeout = 5000 } = config;

console.log(host); // 'localhost'
console.log(port); // 3000
console.log(protocol); // 'http' (default)
console.log(timeout); // 5000 (default)

// --------------------------------------------
// 7. Nested Destructuring
// --------------------------------------------

const company = {
  name: 'TechCorp',
  address: {
    street: '123 Main St',
    city: 'San Francisco',
    coordinates: {
      lat: 37.7749,
      lng: -122.4194,
    },
  },
  employees: ['Alice', 'Bob', 'Charlie'],
};

// Nested object destructuring
const {
  name: companyName,
  address: {
    city: companyCity,
    coordinates: { lat, lng },
  },
} = company;

console.log(companyName); // 'TechCorp'
console.log(companyCity); // 'San Francisco'
console.log(lat, lng); // 37.7749, -122.4194

// Mixed nested destructuring
const {
  address: { street },
  employees: [firstEmployee, secondEmployee],
} = company;

console.log(street); // '123 Main St'
console.log(firstEmployee); // 'Alice'
console.log(secondEmployee); // 'Bob'

// --------------------------------------------
// 8. Function Parameter Destructuring
// --------------------------------------------

// Object parameter destructuring
function greet({ name, greeting = 'Hello' }) {
  return `${greeting}, ${name}!`;
}

console.log(greet({ name: 'Alice' }));
// 'Hello, Alice!'

console.log(greet({ name: 'Bob', greeting: 'Hi' }));
// 'Hi, Bob!'

// Array parameter destructuring
function getFullName([first, last]) {
  return `${first} ${last}`;
}

console.log(getFullName(['John', 'Doe']));
// 'John Doe'

// With defaults for entire parameter
function createUser({ name = 'Anonymous', role = 'user', active = true } = {}) {
  return { name, role, active };
}

console.log(createUser());
// { name: 'Anonymous', role: 'user', active: true }

console.log(createUser({ name: 'Alice', role: 'admin' }));
// { name: 'Alice', role: 'admin', active: true }

// --------------------------------------------
// 9. Rest in Object Destructuring
// --------------------------------------------

const fullUser = {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  age: 30,
  city: 'NYC',
};

// Extract some, collect rest
const { id, ...userDetails } = fullUser;

console.log(id);
// 1

console.log(userDetails);
// { name: 'Alice', email: 'alice@example.com', age: 30, city: 'NYC' }

// --------------------------------------------
// 10. Destructuring in Loops
// --------------------------------------------

const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 },
];

// Destructure in for...of
for (const { name, age } of users) {
  console.log(`${name} is ${age} years old`);
}

// With array entries
const items = ['apple', 'banana', 'cherry'];
for (const [index, item] of items.entries()) {
  console.log(`${index}: ${item}`);
}

// Destructure in map
const names = users.map(({ name }) => name);
console.log(names); // ['Alice', 'Bob', 'Charlie']

// --------------------------------------------
// 11. Computed Property Names
// --------------------------------------------

const key = 'dynamicKey';
const obj = {
  dynamicKey: 'value',
  anotherKey: 'another value',
};

// Destructure with computed property
const { [key]: dynamicValue } = obj;
console.log(dynamicValue); // 'value'

// --------------------------------------------
// 12. Practical Examples
// --------------------------------------------

// API Response handling
const apiResponse = {
  status: 200,
  data: {
    user: {
      id: 1,
      name: 'Alice',
    },
    posts: [{ title: 'Post 1' }, { title: 'Post 2' }],
  },
  error: null,
};

const {
  status,
  data: {
    user: { name: authorName },
    posts: [firstPost],
  },
} = apiResponse;

console.log(status); // 200
console.log(authorName); // 'Alice'
console.log(firstPost); // { title: 'Post 1' }

// Multiple return values
function getMinMax(arr) {
  return {
    min: Math.min(...arr),
    max: Math.max(...arr),
  };
}

const { min, max } = getMinMax([3, 1, 4, 1, 5, 9]);
console.log(min, max); // 1, 9

// Named parameters pattern
function createRect({ x = 0, y = 0, width = 100, height = 100 } = {}) {
  return { x, y, width, height };
}

console.log(createRect({ width: 200, height: 150 }));
// { x: 0, y: 0, width: 200, height: 150 }

// --------------------------------------------
// 13. Destructuring Gotchas
// --------------------------------------------

// Destructuring already declared variables (needs parentheses)
let existingVar;
({ existingVar } = { existingVar: 'value' });
console.log(existingVar); // 'value'

// Destructuring null/undefined throws error
// const { prop } = null;  // TypeError!

// Safe destructuring with fallback
const maybeNull = null;
const { prop = 'default' } = maybeNull || {};
console.log(prop); // 'default'
Examples - JavaScript Tutorial | DeepML