Skip to content

JavaScript Features Recap

Felix Mokross edited this page Jan 9, 2024 · 2 revisions

Why recap of these JavaScript features?

There exist some features in JavaScript, which we will use a lot when writing and reading React code, and it is possible that these features are fully known to you. So here is a quick recap so we're sure that everyone can understand the code discussed in this course.

Object Destructuring

Destructure a javascript object into objects/primitives representing the fields of the object

const joe = { name: 'Joe', age: 20, home: 'Schlieren', size: 170 };
console.log(joe.name, joe.age);

const { name, age } = joe;
console.log(name, age); // "Joe", 20

Array Destructuring

Similarly, arrays can be destructed:

const fruits = ["banana", "apple", "orange"];
  
const [firstFruit, secondFruit] = fruits;

console.log(firstFruit); // "banana"
console.log(secondFruit); // "apple"

Using destructuring in function parameters

function person({ name, age }) {
    
}

person(joe);

using it with typescript

function person({ name, age }: Person) {
    
}

person(joe);

Spread syntax

Spreading the not selected fields of the object during destructuring in a new js object:

const joe = { name: 'Joe', age: 20, home: 'Schlieren', size: 170 }
const { name, ...rest } = joe
// name = 'Joe'
// rest = { age: 20, home: 'Schlieren', size: 170 }
const jack = { name: 'Jack', ...rest }
// jack = { name: 'Jack', age: 20, home: 'Schlieren', size: 170 }

Spread syntax with arrays

const fruits = ["banana", "apple", "pear"];
  
const [firstFruit, ...localFruits] = fruits;

console.log(firstFruit); // "banana"
console.log(localFruits); // ["apple","pear"]

const moreLocalFruits = [...localFruits, "apricot"]
console.log(moreLocalFruits); // ["apple","pear","apricot"]