What is the meaning of an Underscore in javascript function parameter?

后端 未结 2 1543
情书的邮戳
情书的邮戳 2020-12-05 00:07

I was going through the code of one of the chart library written in javascript, wherein I\'ve seen passing underscore(_) as a function parameter. What does that mean?

<
2条回答
  •  眼角桃花
    2020-12-05 00:37

    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.

    The use of underscores like this can get very confusing when using the popular lodash or underscore libraries.

提交回复
热议问题