Posted by: Hamza
Comments: 0
Post Date: February 21, 2023
5 JavaScript features you (probably) haven’t used
- 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;
- 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
.
- 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
- 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.
- 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