5 JavaScript features you (probably) haven’t used

Posted by: Hamza Comments: 0

5 JavaScript features you (probably) haven’t used

  1. Optional chaining (?. operator): Optional chaining allows you to safely access deeply nested properties of an object without worrying about whether intermediate properties are null or undefined. Here’s an example:
const user = {
  name: 'Alice',
  address: {
    city: 'New York',
    zip: '10001'
  }
};

// Without optional chaining
const city = user.address && user.address.city;

// With optional chaining
const city = user.address?.city;
  1. Nullish coalescing (?? operator): Nullish coalescing allows you to provide a default value when a variable is null or undefined. Here’s an example:
const name = null ?? 'Anonymous'; // name will be 'Anonymous'

Note that this is different from the || operator, which also provides a default value for falsy values like empty strings and 0.

  1. Array destructuring: Array destructuring allows you to extract values from an array and assign them to variables in a single statement. Here’s an example:
const [a, b, c] = [1, 2, 3];
console.log(a, b, c); // outputs 1 2 3
  1. Template literals: Template literals allow you to interpolate variables into strings using backticks (`) instead of quotes. Here’s an example:
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // outputs "Hello, Alice!"

Template literals also allow you to write multiline strings without using escape characters.

  1. Object spread syntax: Object spread syntax allows you to create a new object that contains all the properties of an existing object, plus additional properties that you specify. Here’s an example:
const user = {
  name: 'Alice',
  age: 30
};

const userWithAddress = {
  ...user,
  address: {
    city: 'New York',
    zip: '10001'
  }
};

console.log(userWithAddress); // outputs { name: 'Alice', age: 30, address: { city: 'New York', zip: '10001' } }

This is a more concise way to create a new object that is based on an existing object, instead of using Object.assign().

Leave a Reply

Your email address will not be published. Required fields are marked *

Get Your Free Analyze

Improve your Website, Facebook Page and More...

Read the latest Google Search Central blog posts about performance & speed.. After Sharing URL Results will be emailed to you