0

JS newbie here and having an issue with passing parameters. I'm writing a function inside of an object and can't figure out why JS won't pass in my parameter in the function. see example below

var students = ["Joseph", "Susan", "William", "Elizabeth"]

var scores = [ [80, 70, 70, 100],
           [85, 80, 90, 90],
           [75, 70, 80, 75],
           [100, 90, 95, 85] ]

var gradebook = {
"Joseph": {
    testScores: scores[0]
},
"Susan": {
    testScores: scores[1]
},
"William": {
    testScores: scores[2]
},
"Elizabeth": {
    testScores: scores[3]
},


addScore: function(student, score){
    console.log(student) //=> output as expected
    console.log(score) //=> output as expected
    console.log(gradebook.Joseph.testScores) //=> this works as expected and shows Joseph's scores
    console.log(gradebook.student.testScores) //=> gives TypeError: Cannot read property 'testScores' of undefined
}
};

gradebook.addScore("Joseph", 30);

I put the console log statements to debug and figure out whats going on. I have no idea why this works when I hardcode in the students name, but doesn't work when I pass in the student's name as a parameter from running the function outside of the gradebook object. Any help would be appreciated!

user2864740
  • 60,010
  • 15
  • 145
  • 220
xeroshogun
  • 1,062
  • 1
  • 18
  • 31
  • 2
    There is no `gradebook.student` (this looks for the property *named* "student" and *has nothing to do with a variable of the same name*), thus the expression evaluates to undefined – user2864740 Sep 07 '14 at 06:19
  • so how do I make it use the variable that I want to pass in? – xeroshogun Sep 07 '14 at 06:21
  • Also http://stackoverflow.com/questions/1184123/is-it-possible-to-add-dynamically-named-properties-to-javascript-object?rq=1, http://stackoverflow.com/questions/22747423/how-do-i-dynamically-denote-my-object-property-names?lq=1 – user2864740 Sep 07 '14 at 06:22
  • while the solution may be the same for both questions, I don't think its a duplicate question. There is nothing in that question regarding parameters in a function. People new to JS wouldn't know to look for dynamically access objects if they were having the problem that I was having. – xeroshogun Sep 07 '14 at 06:27
  • Parameters are equivalent to local variables (that are automatically bound to the values supplied in arguments). There is nothing new here with respect to "why it doesn't work" or the solutions available. If people find this question then they can follow it to the questions it *should* be closed for. That is, changing "where y is the name of a" .. "variable" to "parameter" makes *no* difference. The linked answers (all of which are suitable duplicates) explain the problem and an appropriate solution for it. – user2864740 Sep 07 '14 at 06:28

1 Answers1

1

Use [] instead of dot. gradebook[student].testScores should give you desired result.

Abhi
  • 724
  • 1
  • 6
  • 15