Skip to content
Advertisement

This code keeps returning ‘undefined’ for (names[i]). what am I doing wrong?

This code keeps returning ‘undefined’ for (names[i]). When I console.log() it loops through the array and prints Hello (names[i]) or Good Bye (names[i])what am I doing wrong?

    (function (window) {
       var helloSpeaker = {};
       helloSpeaker.name = " ";
       var speak = "Hello";
       helloSpeaker.speak = function () {
          console.log(speak + helloSpeaker.name);
  }

  window.helloSpeaker = helloSpeaker;

})(window);

(function (window) {
    var byeSpeaker = {};
    byeSpeaker.name = " "
    var speak = "Good Bye"
    byeSpeaker.speak = function () {

     console.log(speak + byeSpeaker.name);
  }

  window.byeSpeaker = byeSpeaker;

})(window);


(function () {

    var names = ["Yaakov", "John", "Jen", "Jason", "Paul", "Frank", "Larry", "Paula", "Laura", "Jim"];

   for (var i = 0; i < names.length; i++) {
   var firstLetter = names[i].charAt(0).toLowerCase();
   if (firstLetter === 'j') {

    console.log(byeSpeaker.speak(names[i]));
  } else {
    console.log(helloSpeaker.speak(names[i]));
  }
}

})();

Advertisement

Answer

Your issue is that you’re passing the name in as an argument to the speak function, however, in your definition of speak it doesn’t take an argument at all.

You can fix it by defining it like this:

helloSpeaker.speak = function (name) {
  console.log(speak + name);
}
byeSpeaker.speak = function (name) {
   console.log(speak + name);
}

Also, here I cleaned up the logic for you.

(function () {
  class Speaker {
    constructor(greeting) {
      this.greeting = greeting;
    }
    speak(name) {
      return `${this.greeting}, ${name}`;
    }
  }

  const helloSpeaker = new Speaker('Hello');
  const byeSpeaker = new Speaker('Bye');

  const names = [
    'Yaakov',
    'John',
    'Jen',
    'Jason',
    'Paul',
    'Frank',
    'Larry',
    'Paula',
    'Laura',
    'Jim',
  ];

  names.forEach((name) => {
    const firstLetter = name.charAt(0).toLowerCase();
    const result = firstLetter === 'j' ? byeSpeaker.speak(name) : helloSpeaker.speak(name);
    console.log({result});
  });
})();

Your other issue is that your speak function wasn’t returning anything, it was returning undefined implicitly.

example:

function noReturn() {
  console.log('inside noReturn')
  // no return statement, so implicitly it's as though you wrote:
  // return undefined;
}

console.log('noReturn result:', noReturn())
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement