Johnny Depp
Johnny Depp

Reputation: 171

"Undefined" coming as output of an array

I am newbie to Javascript and the syntax just bugs me. The output is giving me undefined as an alert after every function declaration output.

let func=[
    {
        sayHi:function(){
            alert('hello');
        },
        saybi:function(){
            alert('Bye');
        }
    },
    {
        sayName:function(name){
            alert('Hii !! ', +name);
        },
        askName:function(){
            alert("What's your name ??");
        }
    }
];

alert(func[0].sayHi());

let name=prompt("What's your name ?","");
if(name!="")
{
    alert(func[1].sayName(name));
}
else{
    alert(func[1].askName());
}

Upvotes: 2

Views: 63

Answers (3)

niry
niry

Reputation: 3308

You don't need to wrap every function call with alert() as those functions returns undefined and confuses you. Also alert() takes one argument, so the comma (',') there isn't helping.

Try this:

let func = [
    {
      sayHi: function(){
        alert('hello');
      },
      saybi: function(){
        alert('Bye');
      },
    },{
      sayName: function(name) {
        alert('Hi !! ' + name);
      },
      askName: function() {
        alert("What's your name ??");
      },
    }];

func[0].sayHi();

let name = prompt("What's your name ?", "");
if (name != "") {
    func[1].sayName(name);
} else {
    func[1].askName();
}

Upvotes: 2

zmag
zmag

Reputation: 8241

functions in func array call alert function. But you have called alert again after invoking a function like alert(func[0].sayHi()).

You should call function like below:

let func = [{
    sayHi: function() {
      alert('hello');
    },
    saybi: function() {
      alert('Bye');
    }
  },
  {
    sayName: function(name) {
      alert('Hii !! ' + name);
    },
    askName: function() {
      alert("What's your name ??");
    }
  }
];

func[0].sayHi();

let name = prompt("What's your name ?", "");
if (name != "") {
  func[1].sayName(name);
} else {
  func[1].askName();
}

Update: I've fixed sayName function to work properly.

Upvotes: 2

Kai Lehmann
Kai Lehmann

Reputation: 508

It works perfect. sayHi() returns nothing so it returns undefined. That is it what you are alerting in the last line.

Upvotes: 0

Related Questions