0

Trying ES6 and came across this example:

var bob = {
      _name: "Bob",
      _friends: ["Pete", "Joe", "Larry"],
      printFriends() {
        this._friends.forEach(f =>
          console.log(this._name + " knows " + f));
      }
    }

Console logging bob.printFriends() gives undefined.

2
  • 1
    are you sure you're transpiling the code correctly? It's working for me esnextb.in/?gist=87892ce1aac47ec0ff90540d0c546345 Commented May 3, 2016 at 23:57
  • Well, printFriends does return undefined, so the result seems to be correct? Commented May 4, 2016 at 0:50

2 Answers 2

1

Your code

var bob = {
  _name: "Bob",
  _friends: ["Pete", "Joe", "Larry"],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f));
  }
}
bob.printFriends();

Output

"Bob knows Pete"
"Bob knows Joe"
"Bob knows Larry"
=> undefined

The reason you are seeing an undefined return value is because printFriends doesn't have a return statement.

Sign up to request clarification or add additional context in comments.

1 Comment

0

It's working for me. Please see this fiddle and check the console. It's possible that you don't have the transpiler properly configured.

https://jsfiddle.net/e7rb9e4o/

bob.printFriends();

Output:

Bob knows Pete
Bob knows Joe
Bob knows Larry

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.