0

I was trying to solve a problem where I would iterate through a dictionary, returning the corresponding values. This is my code.

var dict = {"Cost":"16","Description":"dkjfdkljskjf"};
var keys = Object.keys(dict);
console.log(keys)
for(var i = 0;i < keys.length;i++){
  console.log(dict[keys[i]]);
}

When this code ran, it returned the following: enter image description here

Even though it returns the values, it also returns an undefined. What returns the undefined?What does it mean?Why is it returning both?

Thanks in advance

Dylan Ong
  • 786
  • 2
  • 6
  • 14
  • 4
    Javascript has no dictionaries. What you have there is an object. Use `Object.keys`, `Object.values`, and `Object.entries` to iterate through an object. Your `undefined` is not coming from your code, but from your entering of the code into the console manually; `console.log` returns `undefined`, and the console automatically prints the return value of the last statement (I think). – CertainPerformance Apr 21 '18 at 19:26
  • Cause you ran the code in some kind of REPL, and as you have no `return` in there, the list of statwments youve provided does evaluate to nothing – Jonas Wilms Apr 21 '18 at 19:27
  • 1
    Because after evaluating the code in the REPL, nothing is returned from the last line... – Andrew Li Apr 21 '18 at 19:30
  • Use console.log some more to see what is going on. console.log(”key:” +keys[i] + ”, value: ” + dict[keys[i]]); – teroi Apr 21 '18 at 19:33
  • The undefined printed in green is your function’s return value. In your case you are not returning anything, so it is undefined. – teroi Apr 21 '18 at 19:36
  • By the way, for iterating over an objects keys: the [`for ... in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop. – Lucas Apr 21 '18 at 19:36
  • @Lucas No, don't do that, that requires the `hasOwnProperty` check. `Object.keys` is far superior in most cases. – CertainPerformance Apr 21 '18 at 19:58

0 Answers0