Search code examples
node.jsreturnoperator-keywordspread

...return Math.random() meaning?


everyone.

I am confused when I see this code. What does this code mean? Why spread operator is used before return here?

I tried this code with node, and it says Unexpected token 'return'

Fyi, this code snippet is from nodejs document.

function generateRandom() {
...return Math.random()
}

Appreciate for any explanation.


Solution

  • Those dots are not actually part of the code. They are a part of the Node REPL only, an indicator to the user, after they press enter, that the statement you've typed is not complete. As the link where you found this code says:

    The Node REPL is smart enough to determine that you are not done writing your code yet, and it will go into a multi-line mode for you to type in more code.

    That is, if you start typing:

    function generateRandom() {
    

    and then press enter, you'll see the following

    function generateRandom() {
    ...
    

    with the text cursor at the end of the ..., indicating that you need to finish the statement before the REPL executes it.

    So

    function generateRandom() {
    ...return Math.random()
    }
    

    when you take out the REPL's visual indicator that you're in multi-line mode, is just

    function generateRandom() {
    return Math.random()
    }
    

    which is syntactically correct.