JavaScript Essentials for React Native - #4 ES6 and Beyond

Piyush NanwaniPiyush Nanwani
2 min read

Here, we will talk about examples on de-structuring, rest/spread operators and template literals

De-structuring assignment

Array De-structuring Example

let arr = ["Art", "Vandelay"];
let [firstName, lastName] = arr;

console.log(firstName); // Art
console.log(lastName); // Vandelay
  • De-structuring applies to any iterables, not just arrays

  • More examples:

// 1. swapping 2 variables
let x = 2;
let y = 1;
[x,y] = [1,2]
console.log(x,y); // 1 2

// 2. The Rest operator ...
let [a, b, ...etc ] = ["Apple", "Banana", "Cat", "Dog"];

console.log(etc[0]);
console.log(etc[1]);

// 3. Object destructuring
let user = {
    id: 1,
    name: "Rahul",
    age: 20
};

let {id, name, age, gender = "male"} = user;

console.log(id); // 1
console.log(name); // Rahul
console.log(age); // 20
console.log(gender); // male

Rest parameter examples

// 1. merging arrays
let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9, 10];

let merged = [...arr1, ...arr2]; 
console.log(merged); // 1, 2, 3, 5, 6, 7, 8, 9, 10

Template literals example

// Simple template literal example in JavaScript
const name = "Rahul";
const greeting = `Hello, ${name}!`;

console.log(greeting);
// Output: Hello, Rahul!

Conclusion

De-structuring assignment, rest/spread operators and template literals are used so much in React projects. They help in enhancing code readability and maintaining clean, efficient code, especially in React projects.

Thanks for Reading!

Resources

2
Subscribe to my newsletter

Read articles from Piyush Nanwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Piyush Nanwani
Piyush Nanwani

Experienced full-stack developer with a passion for tackling complex challenges. Dedicated to helping you become a top 1% mobile app developer. Passionate about mentoring, teaching, and continuous learning in new technologies.