javascript 238 lines · 1 tab

ES6+ features: destructuring, spread operator, and template literals

Alex Chang Feb 2026
1 tab
// Array destructuring
const numbers = [1, 2, 3, 4, 5];
const [first, second] = numbers;
console.log(first, second); // 1 2

// Skip elements
const [a, , c] = numbers;
console.log(a, c); // 1 3

// Rest operator in destructuring
const [head, ...tail] = numbers;
console.log(head);  // 1
console.log(tail);  // [2, 3, 4, 5]

// Default values
const [x, y, z = 0] = [1, 2];
console.log(z); // 0

// Swapping variables
let p = 1, q = 2;
[p, q] = [q, p];
console.log(p, q); // 2 1

// Object destructuring
const user = {
  name: 'Alice',
  age: 30,
  email: 'alice@example.com',
  address: {
    city: 'New York',
    country: 'USA'
  }
};

const { name, age } = user;
console.log(name, age); // Alice 30

// Rename variables
const { name: userName, age: userAge } = user;
console.log(userName, userAge); // Alice 30

// Default values
const { role = 'user' } = user;
console.log(role); // 'user'

// Nested destructuring
const { address: { city, country } } = user;
console.log(city, country); // New York USA

// Rest in objects
const { name: n, ...rest } = user;
console.log(rest); // { age: 30, email: '...', address: {...} }

// Function parameter destructuring
function greet({ name, age }) {
  console.log(`Hello ${name}, you are ${age} years old`);
}
greet(user);

// Array parameter destructuring
function sum([a, b]) {
  return a + b;
}
console.log(sum([5, 3])); // 8

// Spread operator - Arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// Merge arrays
const merged = [...arr1, ...arr2];
console.log(merged); // [1, 2, 3, 4, 5, 6]

// Copy array
const copy = [...arr1];

// Add elements
const extended = [...arr1, 4, 5];
console.log(extended); // [1, 2, 3, 4, 5]

// Math functions
const nums = [5, 2, 9, 1, 7];
console.log(Math.max(...nums)); // 9
console.log(Math.min(...nums)); // 1

// Spread operator - Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };

// Merge objects
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }

// Override properties
const updated = { ...obj1, b: 99 };
console.log(updated); // { a: 1, b: 99 }

// Clone object (shallow)
const clone = { ...user };

// Add properties
const enhanced = { ...user, role: 'admin', verified: true };

// Rest parameters in functions
function multiply(multiplier, ...numbers) {
  return numbers.map(n => n * multiplier);
}
console.log(multiply(2, 1, 2, 3, 4)); // [2, 4, 6, 8]

// Template literals
const firstName = 'John';
const lastName = 'Doe';

// String interpolation
const fullName = `${firstName} ${lastName}`;
console.log(fullName); // John Doe

// Expressions in templates
const a1 = 5, b1 = 10;
console.log(`Sum: ${a1 + b1}`); // Sum: 15

// Multi-line strings
const message = `
  This is a multi-line string.
  It preserves line breaks.
  No need for \\n!
`;

// Nested templates
const items = ['apple', 'banana'];
const list = `
  <ul>
    ${items.map(item => `<li>${item}</li>`).join('')}
  </ul>
`;

// Tagged template literals
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return `${result}${str}<strong>${values[i] || ''}</strong>`;
  }, '');
}

const product = 'laptop';
const price = 999;
const ad = highlight`Buy a ${product} for only $${price}!`;
console.log(ad);
// "Buy a <strong>laptop</strong> for only $<strong>999</strong>!"

// Default parameters
function greetUser(name = 'Guest', greeting = 'Hello') {
  return `${greeting}, ${name}!`;
}

console.log(greetUser()); // Hello, Guest!
console.log(greetUser('Alice')); // Hello, Alice!
console.log(greetUser('Bob', 'Hi')); // Hi, Bob!

// Arrow functions
const add = (a, b) => a + b;
const square = x => x * x;
const log = () => console.log('Hello');

// Arrow function with object return
const makePerson = (name, age) => ({ name, age });
console.log(makePerson('Alice', 30)); // { name: 'Alice', age: 30 }

// Short property names
const name2 = 'Alice';
const age2 = 30;
const person = { name2, age2 };
console.log(person); // { name2: 'Alice', age2: 30 }

// Computed property names
const key = 'dynamicKey';
const obj = {
  [key]: 'value',
  [`${key}2`]: 'value2'
};
console.log(obj); // { dynamicKey: 'value', dynamicKey2: 'value2' }

// Method shorthand
const calculator = {
  add(a, b) { return a + b; },
  subtract(a, b) { return a - b; }
};

// Combining features
function processUsers({ users, filter = () => true, limit = 10 }) {
  return users
    .filter(filter)
    .slice(0, limit)
    .map(({ name, age, ...rest }) => ({
      displayName: `${name} (Age: ${age})`,
      ...rest
    }));
}

const result = processUsers({
  users: [
    { name: 'Alice', age: 25, role: 'admin' },
    { name: 'Bob', age: 30, role: 'user' }
  ],
  filter: u => u.age > 20,
  limit: 5
});

// Practical examples
function updateConfig(existingConfig, updates) {
  return {
    ...existingConfig,
    ...updates,
    updated: new Date()
  };
}

function mergeArrays(...arrays) {
  return [...new Set(arrays.flat())];
}

console.log(mergeArrays([1, 2], [2, 3], [3, 4]));
// [1, 2, 3, 4]

// Optional chaining (ES2020)
const userData = {
  user: {
    profile: {
      name: 'Alice'
    }
  }
};

console.log(userData?.user?.profile?.name); // Alice
console.log(userData?.user?.settings?.theme); // undefined

// Nullish coalescing (ES2020)
const value = null ?? 'default'; // 'default'
const zero = 0 ?? 'default'; // 0 (different from ||)
1 file · javascript Explain with highlit

ES6 destructuring extracts values from arrays and objects with concise syntax. I use const [a, b] = array for array destructuring and const {name, age} = obj for objects. The spread operator ... expands iterables in arrays, objects, and function arguments. Using [...arr1, ...arr2] merges arrays without mutation. Object spread {...obj1, ...obj2} creates shallow copies and merges properties. Template literals with backticks enable string interpolation using \${expression}. Multi-line strings work naturally in template literals. Tagged template literals process strings with custom functions. The rest parameter ...rest collects remaining arguments into array. Default parameters provide fallback values. These features make JavaScript more expressive and concise.


Related snips

javascript
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
  const success = true;

  setTimeout(() => {
    if (success) {

Promises and async/await patterns for asynchronous JavaScript

javascript promises async-await
by Alex Chang 1 tab
javascript
import { Controller } from "@hotwired/stimulus"
import Mousetrap from "mousetrap"

export default class extends Controller {
  connect() {
    // Global shortcuts

Keyboard shortcuts with Stimulus and Mousetrap

stimulus javascript ux
by Jordan Lee 2 tabs
javascript
// Get canvas and context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 1. Basic shapes
// Rectangle (filled)

Canvas API for graphics and animations

canvas javascript graphics
by Alex Chang 1 tab
javascript
// Basic event listener
const button = document.getElementById('myButton');

button.addEventListener('click', function(event) {
  console.log('Button clicked!');
  console.log('Event type:', event.type);

Event handling and event delegation patterns in JavaScript

javascript events event-delegation
by Alex Chang 1 tab
javascript
// Basic GET request
fetch('https://api.example.com/users')
  .then(response => {
    console.log('Status:', response.status);
    console.log('OK:', response.ok);
    return response.json();

Fetch API for HTTP requests and AJAX communication

javascript fetch api
by Alex Chang 1 tab
erb
<turbo-stream action="set_title">
  <template><%= "Inbox (#{@unread_count})" %></template>
</turbo-stream>

Turbo Streams: update document title with a custom action

rails hotwire turbo
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

ES6+ features: destructuring, spread operator, and template literals — share card
Link copied