2

I am trying to understand the difference between destruct and ...Spread in the following scenario:

Example using ...Spread

function do2(a,b,c){
    alert (a+b+c);    
}

do2(...[5,3,5]);

Example using Destructing:

function do3({a , b , c}){
    alert (a+b+c);
}
do3([5,3,5]);

When do I use each way? Can anyone tell the difference between both ways and which one to use in this scenario? I am still a beginner, so any help would be good.

Jacky
  • 393
  • 1
  • 3
  • 13

2 Answers2

0

Operator Spread

Spread example:

const add = (a, b) => a + b;
let args = [3, 5];
add(...args); // same as `add(args[0], args[1])`, or `add.apply(null, args)`

Functions aren't the only place in JavaScript that makes use of comma separated lists - arrays can now be concatenated with ease:

let cde = ['c', 'd', 'e'];
let scale = ['a', 'b', ...cde, 'f', 'g'];  // ['a', 'b', 'c', 'd', 'e', 'f', 'g']

Destructuring

Destructuring is a way to quickly extract data out of an {} or [] without having to write much code.

let foo = ['one', 'two', 'three'];

let one   = foo[0];
let two   = foo[1];
let three = foo[2];
into

let foo = ['one', 'two', 'three'];
let [one, two, three] = foo;
console.log(one); // 'one'

ES6 also supports object destructuring, which might make uses more obvious:

let myModule = {
  drawSquare: function drawSquare(length) { /* implementation */ },
  drawCircle: function drawCircle(radius) { /* implementation */ },
  drawText: function drawText(text) { /* implementation */ },
};

let {drawSquare, drawText} = myModule;

drawSquare(5);
drawText('hello');
Amit kumar
  • 6,029
  • 6
  • 30
  • 40
0

The first example assigns a, b c to to elements of passed array at indexes 0, 1, 2, corresponding to the number of elements in the array

function do2(a, b, c){
    alert (a + b + c);    
}

do2(...[5, 3, 5]);

The second example expects an object as parameter to the function, {a , b , c} destructures the passed object assigning a, b, c as local variables within the function

function do3({a , b , c}){
    alert (a + b + c);
}
do3({a:5, b:3, c:5});

See also What is SpreadElement in ECMAScript documentation? Is it the same as Spread operator at MDN?

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
  • Yes, I know, so they're the same in this usage? or which one I should be using? – Jacky Dec 26 '16 at 07:22
  • You can use either approach given current `javascript` at Question. The function is expecting three parameters, three parameters are assigned to variables `a`, `b`, and `c` passing spread element or object having same keys as referenced within function body. Using spread element and array allows not explicitly having to pass object having those properties. – guest271314 Dec 26 '16 at 07:49