Home > Software engineering >  Why I am getting age[i] as undefined?
Why I am getting age[i] as undefined?

Time:05-01

Here I am going to describe my problem that why I am getting age[i]=a as undefined when I am going to console it

enter image description here

const birthYear = [1996, 1997, 1998, 1999]

function calc(Year) {
  age = 2022 - Year;
  return age

}
var age = []
age[0] = 123;
console.log(age[0])

for (i = 0; i <= birthYear.length - 1; i  ) {
  var a = calc(birthYear[i])

  /* if you want to return the value of any function you have to  address 
     it the help of any agruement otherwise it will show you a function body
   */
  age[i] = a
  // console.log
  console.log(age[i])
}

// console.log(age[])

CodePudding user response:

The problem is that you return "age" with calc and also called your array "age". Hence the array gets replaced everytime and you're getting "undefined".

Try this :

const birthYear=[1996,1997,1998,1999]

function calc(Year) {
    age=2022-Year;
    return age
}

var ageArr = [];

for(var i = 0 ; i < birthYear.length ; i  ){
    ageArr[i] = calc(birthYear[i])
    console.log(ageArr[i]);
}

CodePudding user response:

why I am getting age[i] as undefined?

you have used var keyword to declare age array,now the age become global variable,so when you make a call to calC function it converts array to number age=2022-Year; after executing this statement . thats the reason age[i] is undefined . now whats the correct way to do this,just declare ageCount inside calc function and return it,like this

 const birthYear=[1996,1997,1998,1999]
 function calc(Year) 
 {
   //instead of using 2022, you fetch current year from date object
   let ageCount=2022-Year;
   return ageCateCount
}
var age=[]
age[0]=123;
console.log(age[0])

for(i=0;i<=birthYear.length-1;i  ){
   age[i]=calc(birthYear[i]);
// console.log

         console.log(age[i])
}

const birthYear = [1996, 1997, 1998, 1999]

function calc(Year) {
  let ageCount = new Date().getFullYear() - Year;
  return ageCount

}
var age = []
age[0] = 123;
console.log(age[0])

for (i = 0; i <= birthYear.length - 1; i  ) {
  var a = calc(birthYear[i])

  /* if you want to return the value of any function you have to  address 
     it the help of any agruement otherwise it will show you a function body
   */
  age[i] = a
  // console.log
  console.log(age[i])
}

hope this will help!

  • Related