Venkatraman Venkatraman - 1 year ago 101
Javascript Question

Spread Operator Issue with Float and Boolean Variable

Spread Operator
throws error for float and boolean variable. Is there any specific reason for getting error on float and boolean variable.

// Works, Array Variable
'use strict';

let aVal = [1, 2, 3];

// Works, String Variable
'use strict';

let sVal = 'String';

// throws error, Integer Variable
'use strict';

let iVal = 1234567890;

// throws error, Float Variable
'use strict';

let fVal = 99.45;

// throws error, Boolean Variable
'use strict';

let bVal = true;

Answer Source

Is there any specific reason for getting error on float and boolean variable.

Yes: Spread syntax (it isn't an operator) only works with iterable objects (objects that implement iteration). Numbers and booleans are not iterable. Things like arrays and maps and sets are iterable.

console.log(...aVal); asks the JavaScript engine to iterate through aVal and then call console.log with each iterated value as a discrete argument. That is, it asks javaScript to "spread out" that iterable.

Here's an example of spread with an iterable (in this case, an array):

function foo(a, b, c, d) {
let a = ["the", "answer", "is", 42];

Note how the entries in a are "spread out" into discrete (separate) arguments for foo.

The examples below were from earlier when your question was asking about "the rest operator" by mistake. Just for completeness:

Here's an example of rest syntax (also not an operator) in a function signature:

function foo(...args) {
  console.log(`I got ${args.length} args`);
foo('a', 'b', 'c');

...and rest syntax in a destructuring assignment:

let a = ['a', 'b', 'c', 'd', 'e'];
let [ x, y, ...z ] = a;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download