Reputation: 7
I cannot understand this code what is the meaning of values[0]
and values[1]
var a = 5;
var b = 10;
function foo(strings, ...values) {
let a = values[0];
let b = values[1];
return `Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
}
console.log(foo`Num1 ${a + 10}
Num2 ${b * 2}
Num3 ${b / a}`);
Upvotes: -1
Views: 369
Reputation: 137
The three dots (...) is called the spread syntax. It's a neater way (especially arrays) to pass arguments to a function.
In your caseL
console.log(foo`Num1 ${a + 10}
Num2 ${b * 2}
Num3 ${b / a}`);
You're calling the foo
function here with 3 values 15, 10 and 2 which is passed to the function as [15, 10, 2]
, so values[0]
would be 15 and values[1]
would be 10 and values[3]
would be 2.
Upvotes: 1
Reputation: 25145
This an example of tagged templates. You can use a function to parse a template.
var a = 5;
var b = 10;
function foo(strings, ...values) {
let a = values[0];
let b = values[1];
console.log(a , b);
}
foo`x dwqdwq ${a} qwdqwdy ${b}`;
// prints 5, 10
function foo2(strings, a, b, c) {
console.log(a , b, c);
}
foo2`x dwqdwq ${1} qwdqwdy ${2} mmdwldw ${3}`;
// prints 1, 2, 3
strings
will be an array of the string parts in the template.
Upvotes: 0
Reputation: 1074345
A tag function is called with an array of the strings in the template as its first argument, and then discrete arguments with the value of each placeholder. The rest parameter (...values
) gathers up all values passed from the second (in your case) argument onward into an array. So values[0]
is the value of the first placeholder in the call to foo
, and values[1]
is the value of the second placeholder.
There's no good reason for using ...values
in foo
just to then get a
and b
from values
, it would be simpler and perhaps clearer to just declare a
and b
as named parameters:
function foo(strings, a, b) {
return `Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
}
var a = 5;
var b = 10;
function foo(strings, a, b) {
return `Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
}
console.log(foo`Num1 ${a + 10}
Num2 ${b * 2}
Num3 ${b / a}`);
Upvotes: 2
Reputation: 279
The spread operator (...) used like that will take a bunch of arguments and convert them into an array.
if I said:
function foo(...args) {
//do something
}
and then called it by saying:
foo(1, 2, 3, 4, 5)
args (inside the actual function) would be equal to [1, 2, 3, 4, 5]. In your example, values is an array, and it's obtaining the first value (values[0]) and the second value (values[1]) from that array.
Upvotes: 2