Simple use of Java Script spread operator

Converting array into object

// The array
var numbers = [1,2,3];


var obj = {...numbers }

console.log(obj)
// result: {0:1, 1:2, 2:3}

 

Expanding object with new parameter

// The array
var person = {
  name: 'Jhon'
}

var obj = {...person, age: 23 }

console.log(obj)
// expected person to be: {name: 'John', age:23 }

 

Getting sum of an array

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// resunt: 6

 

Leave a Reply