0

So I am following a javascript course on codecademy, I decided to try things out on my own script. So the script is:

function family1 (name, age) {
    this.name = name;
    this.age = age;
}

var family = new Array();

family[0] = new family1("alice", 40);
family[1] = new family1("bob", 42);
family[2] = new family1("michelle", 8);
family[3] = new family1("timmy", 8);

printFamily1 = function(person) {
        console.log(person.name + " aged " + person.age);
}

console.log(printFamily1(family[0]))
console.log(printFamily1(family[1]))
console.log(printFamily1(family[2]))
console.log(printFamily1(family[3]))

It works, but in the console, it printed

alice aged 40
undefined
bob aged 42
undefined
michelle aged 8
undefined
timmy aged 8
undefined

It works, but I don't want the undefined part! How do I fix these!

  • `printFamily1` function returns `undefined` (since it returns nothing). If you don't want it - don't output it, but simply `printFamily1(family[0])` – zerkms Oct 13 '15 at 07:10
  • @zerkms YOU SAVED MY LIFE! TYSM! I'm such a dumbass. – Aditya Dananjaya Oct 13 '15 at 07:14
  • why you didnt just return a string and print in on the console like that: printFamily = function(person) { return person.name + " aged " + person.age; } and then just saying console.log(printFamily(person[0])): – Vasil Indzhev Oct 13 '15 at 07:16

2 Answers2

0

Update your printFamily1 function to look like this:

printFamily1 = function(person) {
        console.log(person.name + " aged " + person.age); 
        return (person.name + " aged " + person.age);
}

The issue is your trying to print what printFamily1 returns, but you don't have a return defined. So Simply add a return of what you want to be printed in your console

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
0

You have 2 options:

  1. Don't call console.log again:

    printFamily1(family[0])
    printFamily1(family[1])
    printFamily1(family[2])
    printFamily1(family[3])
    
  2. Don't call console.log inside the function

    printFamily1 = function(person) {
        return person.name + " aged " + person.age;
    }
    
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199