1

I just got the result "[object Object]'s score is 0" printed on the terminal. The result 27 was all fine until I separated the function into a return object.

  1. How do I get 27 if I have to return an object?
  2. How do I get "alex" printed on the console.log instead of [object Object]?

const alex = {
  first: [1, 2, 9, 8],
  second: [3],
  third: [0, 0, 0, 1, 3]
};
const gordon = {
  first: [3],
  second: [2, 2, 4, 5, 6, 6, 7, 8]
}

function createPlayer(object) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        for (const item in object[key]) {
          score += object[key][item]
        }
      }
    },
    result: function() {
      return `${object}\'s score is ${score}`
    }
  }
}
createPlayer(alex).add()
console.log(createPlayer(alex).result())
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Edith
  • 95
  • 5

2 Answers2

2

const alex = {
  first: [1, 2, 9, 8],
  second: [3],
  third: [0, 0, 0, 1, 3]
};
const gordon = {
  first: [3],
  second: [2, 2, 4, 5, 6, 6, 7, 8]
}

function createPlayer(object, name) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        for (const item in object[key]) {
          score += object[key][item]
        }
      }
      return this; // <<<<<
    },
    result: function() {
      return `${name}\'s score is ${score}`
    }
  }
}
console.log(createPlayer(alex, 'Alex').add().result())
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • This is a smart way doing it. Except, I do not understand the meaning of putting"return this" there? – Edith Sep 16 '20 at 06:37
  • 1
    so you can chain the methods ... `.add()` returning `this` means you can `.add().result()` – Jaromanda X Sep 16 '20 at 06:43
  • yes, it does more than chaining the methods. I find that without "return this", even if I .log it separately, the .result method will not show 27. It is like it has no connection with the .add method's result. it is hard to understand for beginner. Do you know what topic I should look into to understand this concept? – Edith Sep 16 '20 at 06:51
  • method chaining? I don't know, been years since I did javascript 101 – Jaromanda X Sep 16 '20 at 06:56
0

You would not show alex for an object named alex

You might mean this

const alex = {
  Name: "Alex",
  first: [1, 2, 9, 8],
  second: [3],
  third: [0, 0, 0, 1, 3]
};
const gordon = {
  Name: "Gordon",
  first: [3],
  second: [2, 2, 4, 5, 6, 6, 7, 8]
}

function createPlayer(object) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        if (key!=="Name") {
          for (const item in object[key]) {
            score += object[key][item]
          }
        }   
      }
    },
    result: function() {
      return `${object.Name}\'s score is ${score}`
    }
  }
}
const player1 = createPlayer(alex)
player1.add()
console.log(player1.result())
mplungjan
  • 169,008
  • 28
  • 173
  • 236