Home > Software engineering >  This code keeps returning 'undefined' for (names[i]). what am I doing wrong?
This code keeps returning 'undefined' for (names[i]). what am I doing wrong?

Time:09-01

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]));
  }
}

})();

CodePudding user response:

You got undefined because you call:

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

But its return nothing. That's why you got undefined. You can fix it. Just call the function, not log it. Like that:

byeSpeaker.speak(names[i]))    
helloSpeaker.speak(names[i])

Hope you got it. Thank You

CodePudding user response:

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())
  • Related