-2

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
Ying
  • 299
  • 1
  • 5
  • 20

1 Answers1

1

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}`;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Ah and may I know that in (params) => expression, does this expression always mean "return something"? If I write something like (params) => let i = 10, does it mean: (params) => { return let i = 10; } ? Thank you so much! – Ying Oct 30 '18 at 21:27
  • Yes, it always means that. Since `let` is a statement, not an expression, that won't work. – Barmar Oct 30 '18 at 21:28
  • Basically, if you can't write `(blah)` you can't write `=> blah` – Barmar Oct 30 '18 at 21:29
  • Thank you so much! So I can write (params) => i = 10 and (params) => { return i = 10; } right? and it will first assign 10 to i then return i which is 10? – Ying Oct 30 '18 at 21:51
  • Yes, you can do that. It will be assigning to a variable declared in the outer scope. – Barmar Oct 30 '18 at 21:55
  • Thank you so much! So let i has to be declared in an outer scope than this function right? – Ying Oct 30 '18 at 22:05
  • Of course. You can't put a declaration in the expression form of the arrow function. – Barmar Oct 31 '18 at 15:55