anatta
anatta

Reputation: 107

having trouble with JavaScript spread syntax

I just read the MDN page for the ES6 spread syntax, and most of the examples on the page worked, but the last one did not:

var obj = {"key1":"value1"};
function myFunction(x) {
    console.log(x); // undefined
}
myFunction(...obj);
var args = [...obj];
console.log(args, args.length) //[] 0

I tried it in both Chrome and Firefox, and I'm running the latest browser versions, so the page says that the code ought to work.

Can anyone tell me what the problem is?

Upvotes: 0

Views: 104

Answers (1)

Saad
Saad

Reputation: 53939

The issue is most likely that using the spread syntax with objects isn't currently supported with browsers. Doing something like this:

let inventory = {
  apples: 3,
  oranges: 4
}

let updatedInventory = {
  ...inventory,
  grapes: 4
}

console.log(updatedInventory)

should print out this:

{"apples":3,"oranges":4,"grapes":4}

but as you can see, the browsers are throwing an error. If I recall correctly, object-spread was an ES7 proposal while array spreading was an ES6 one which is probably why object-spreading hasn't been fully implemented yet.

To try out the latest ES6/ES7 stuff that hasn't been implemented yet, you can use the online REPL provided by Babel. It's cool because you can see the equivalent ES5 code output on the right side.

If you put the above code example in the repl, you'll see the correct console output (on the bottom right).

Upvotes: 4

Related Questions