Search code examples
javascriptarguments

Why should this code be expecting a comma?


I am watching this course focused on programming for beginners. So, the instructor wrote the following code:

let numberOfLines = 1;

console.log(`Line #`, numberOfLines);

My question is, why do I get an error if I do not put the comma (,) before "numberOfLines"? If I don't write it, it sends me a message about expecting it to be added.

I tried writing the code without a comma, just for curiosity, which resulted in an error. Please, can anyone explain why it happens?


Solution

  • console.log(`Line #`, numberOfLines);
    

    This code calls the log function on the console object. It provides two arguments to that function. "Line #" is the first argument, and numberOfLines is the second argument.

    And a , is how you separate arguments in a function invocation. You need a comma between all function arguments so that javascript knows where one argument ends, and the next one begins.

    It just part of the grammar of the language. You get an error without the comma because the language specification says that one is required. It's as simple as that.