Search code examples
javascriptecmascript-6arrow-functions

About semicolon in ES6 when using return


I'm new to JS. If I add a semicolon like this ${this.name} is friends with ${el}; I'll get an error "Uncaught SyntaxError: missing ) after argument list". May I know why? Since in ES5, I can use semicolon like return this.name + ' is friends with ' +el; Thank you so much!

function Person(name) {
    this.name = name;
}

ES6
Person.prototype.myFriends5 = function(friends) {
var arr = friends.map((el) =>
     `${this.name} is friends with ${el}`
);
console.log(arr);
}
var friends = ['Bob', 'Jane', 'Mark'];
new Person('John').myFriends5(friends);

Solution

  • Arrow functions can be written in two ways:

    (params) => expression
    

    or

    (params) => {
        body
    }
    

    where body is just like the body of a traditional function (a sequence of statements).

    When you use the first format, you can't have a ; because that's not valid in an expression, it's used to terminate statements in a function body. It's the same reason you can't write:

    console.log(a;)
    

    The first form is shorthand for:

    (params) => {
        return expression;
    }
    

    A rule of thumb for what is a valid expression is that it's the same thing that can go inside parentheses. So if you can write something like:

    a = (something)
    

    then you can write:

    (params) => something
    

    Since you can't write:

    a = (`${this.name} is friends with ${el}`;)
    

    you can't write:

    (params) => `${this.name} is friends with ${el}`;