DEV Community

Cover image for (Javascript) My learning journey: Destructuring
Eric The Coder
Eric The Coder

Posted on

(Javascript) My learning journey: Destructuring

An essential point to remember a training course is to take notes and discuss the subject with others. That's why every day I will post on the concepts and notes that I learned the day before.

If you want to miss nothing click follow and you are welcome to comments and discuss with me.

Without further ado here is a summary of my notes for today.

Destructuring Arrays

// long version
const names = ['Mike', 'Paul', 'John']
const name1 = names[0]
const name2 = names[1]
const name3 = names[2]

// or same result with Destructuring Array
const [name1, name2, name3] = names

// or only get first two element
const [name1, name2] = names

// or only get first and third element
const [name1, ,name3] = names

// Destructuring from a multi returns function
const sumAndMultiplication = function(num1, num2) {
  return [num1 + num2, num1 * num2]
const [sum, multiplication] = sumAndMultiplication(10, 10)

console.log(sum, multiplication) // 20 100

// Destructuring when less value
const [number1, number2] = [1]
// number1 = 1, number2 = undefined

// Destructuring default value
const [number1 = 0, number2 = 0] = [1]
// number1 = 1, number2 = 0
Enter fullscreen mode Exit fullscreen mode

Destructuring Objects

const post = {
  id: 100,
  title: 'This is my Blog',
  description: 'This is my blog text body..',
  tags: ['web', 'dev', 'js'],

// Destructuring with same matching object property name
const {id, title} = post

// Variable name different from property name
const {number: id, main: title} = post

// Default value if property not present in object
const {id, title, user = 1} = post

// or another example
const {id, title, categorie = []} = post

// Assign existing variables
let id = 100
let title = 'My Blog title'
// use the parentheses
({id, title} = post)

// Function parameters destructuring
const createPost = function({id = 200, name, title}) {

// Pass object as parameters
const obj = {
  name: 'Mike',
  title: 'New Title'
// or direct
createPost({name: 'Mike', title: 'New title'})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)