JavaScript provides several shortened notations to make your code more concise and efficient. Here are some examples:
1. Property Shorthand:
When assigning an object property, you can use the same variable name as the property key. This eliminates the need for explicit property assignment.
Example:
const person = { name, age };
Instead of:
const person = { name: name, age: age };
2. Array Shorthand:
When creating an array with a single element, you can use the comma-separated syntax.
Example:
const fruits = ['apple', 'banana', 'orange'];
Instead of:
const fruits = new Array('apple', 'banana', 'orange');
3. Object Destructuring:
When assigning object properties to variables, you can use destructuring to extract the values.
Example:
const { x, y } = { x: 1, y: 2 };
Instead of:
const obj = { x: 1, y: 2 };
const x = obj.x;
const y = obj.y;
4. Optional Chaining:
When accessing nested object properties, you can use optional chaining (?.) to avoid null or undefined errors.
Example:
const obj = { x: { y: 1 } };
console.log(obj?.x?.y); // 1
Instead of:
const obj = { x: { y: 1 } };
if (obj && obj.x && obj.x.y) {
console.log(obj.x.y); // 1
}
5. Spread Operator:
When merging objects or arrays, you can use the spread operator (...) to concatenate or extend existing values.
Example:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 2, c: 3, d: 4 }