-3
function format(template, ...values) { return template.replace(/{(\d+)}/g, (_,i) => values[i]); } 

The above solution returns a formatted string. for example format("{0}{1}{2}{1}{0}", "k", "a", "y") returns "kayak".

I know the string replace function in JS , Here I didn't get the arrow function

10
  • The first argument is just going unused. Commented Feb 2, 2020 at 5:49
  • but how the i value is incrementing? i mean i am not able to understand how the placeholders are replaced by the values with the arrow function Commented Feb 2, 2020 at 5:51
  • The second argument is the capture group. {0} will capture 0, eg, so the second argument passed to format will be the replacement Commented Feb 2, 2020 at 5:53
  • I think this is wrongly tagged as duplicate question. Commented Feb 2, 2020 at 5:55
  • The regex matches constructs like {0}, _ will be {0} (the entire regex) and i will be 0 (the first capturing group), the arrow function returns values[0] for the first match replacing {0} with k. Commented Feb 2, 2020 at 5:57

1 Answer 1

0

_ in fat arrow function is called as throwaway variable.

The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter.

A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter". Since JavaScript doesn't do parameter-count checking the parameter could have been omitted entirely.

This symbol is often used (by convention again) in conjunction with fat-arrow functions to make them even terser and readable, like this:

const fun = _ => console.log('Hello, World!') fun() 

In this case, the function needs no params to run, so the developer has used the underscore as a convention to indicate this. The same thing could be written like this:

const fun = () => console.log('Hello, World!') fun() 

The difference is that the second version is a function with no parameters, but the first version has a parameter called _ that is ignored. These are different though and the second version is safer, if slightly more verbose (1 extra character).

Also, consider a case like

arr.forEach(function (_, i) {..}) 

Where _ indicates the first parameter is not to be used.

Sign up to request clarification or add additional context in comments.

2 Comments

i tried to remove the underscore and ran the solution i got undefined in the output,if possible please breakdown the entire solution
@BalaKrishnaKesani That is because in that case, i will be the substring that matches the entire regex, you should take a look at String.replace to see how replace with a function works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.