Home > OS >  for loop outputting function not result
for loop outputting function not result

Time:12-14

Hi Im learning Js so please be kind. I have just learned about functions or methods inside of objects.

Im trying to loop through this basic object and the last key 'calcAge' is a function that should output '30' as you can see from the console.log at the bottom. But the for loop is outputting the entire function as its written. How can I get it to output 30?

let currentYear = 2021;
const myFriends = {
  firstName: 'Alan',
  lastName: 'Snape',
  job: 'teacher',
  birthYear: 1991,
  friends: ['geoff', 'dave', 'sean'],
  hasLicense: true,
  calcAge: function (birthYear) {
    myFriends.age = currentYear - this.birthYear;

    return this.age;
  },
};


for (let i in myFriends) {
  console.log(`${i} : ${myFriends[i]}`);
}

// firstName: 'Alan',
//   lastName: 'Snape',
//   job: 'teacher',
//   birthYear: 1991,
//   friends: ['geoff', 'dave', 'sean'],
//   hasLicense: true,
//   calcAge: function (birthYear) {
//     myFriends.age = currentYear - this.birthYear;

//     return this.age;
//   },
// };

console.log(myFriends.calcAge()); //30

CodePudding user response:

In order to get 30 while you are iterating your object, you should check the property value is a function or not, if it was a function you can call it to get the function result, otherwise you can log the value directly, like this:

for (let i in myFriends) {
  console.log(`${i} : ${typeof myFriends[i] == 'function' ? myFriends[i]() : myFriends[i]}`);
}

CodePudding user response:

You should fix the calcAge function into something like this:

calcAge : function () {
    this.age = currentYear - this.birthYear;

    return this.age;
}

CodePudding user response:

When you loop through an object and try to access the value of a key, you are basically pointing to the value of the key, and nothing more. You can observe that the values are correctly printed that are non-function or those that do not require any further operation on them (i.e, Arrays, string, numbers). But when the value is a function you get the function printed as it is, because it is just pointing towards the function and not invoking it. To get the result as desired, you can simply check if the value is a function or not. If it is a function, execute it, or else print as it is.

let currentYear = 2021;
const myFriends = {
  firstName: 'Alan',
  lastName: 'Snape',
  job: 'teacher',
  birthYear: 1991,
  friends: ['geoff', 'dave', 'sean'],
  hasLicense: true,
  calcAge: function (birthYear) {
    myFriends.age = currentYear - this.birthYear;

    return this.age;
  },
};


for (let i in myFriends) {
  if(typeof myFriends[i]==='function'){ //Check if the value is a function.
    console.log(`${i} : ${myFriends[i]()}`); //Execute the function.
  }
  else{
    console.log(`${i} : ${myFriends[i]}`); //Print the value directly if it is not a function.
  }
}

CodePudding user response:

Your function is missing a value called currentYear. I added a function currentYear(). Now just invoke the function like so:

myFriends.calcAge()

BTW there's no need to loop through the object, but I've altered it a bit to show the uses of Object.entries(), destructuring, and for...of loops.

const myFriends = {
  firstName: 'Alan',
  lastName: 'Snape',
  job: 'teacher',
  birthYear: 1991,
  friends: ['geoff', 'dave', 'sean'],
  hasLicense: true,
  currentYear: function() {
    let now = new Date;
    return now.getFullYear();
  },
  calcAge: function(birthYear) {
    myFriends.age = this.currentYear() - this.birthYear;
    return this.age;
  }
};

let mF = Object.entries(myFriends);

console.log(mF);

for (let [key, val] of mF) {
  console.log(`${key} : ${val}`);
}

console.log(myFriends.calcAge());

  • Related