Home > Mobile >  Why in console age is coming as undefined
Why in console age is coming as undefined

Time:08-14

let object = {
    name : `Rahim`,
    age : 10,
    place : `Delhi`,
    
    details : function(){
             return `The fruit name is ${name}. Color is ${age}`;

    }
}

console.log(object.details());

CodePudding user response:

The name and age variables that you are calling are not any variables and also they are the elements of the same object. So, you will be needing to use this.name or this.age. this basically says the function to get the name and age element from the same object, where the function is located. So you will be needing to update your code like this:

let object = {
    name : `Rahim`,
    age : 10,
    place : `Delhi`,
    
    details : function(){
             return `The fruit name is ${this.name}. Color is ${this.age}`;

    }
}

console.log(object.details());

CodePudding user response:

you need to define the name and age first

let age = 10;
let name = 'Rahim';
let object = {
    name : name,
    age : age,
    place : `Delhi`,
    
    details : function(){
             return `The fruit name is ${name}. Color is ${age}`;

    }
}

console.log(object.details());

or using this

let object = {
    name : `Rahim`,
    age : 10,
    place : `Delhi`,
    
    details : function(){
             return `The fruit name is ${this.name}. Color is ${this.age}`;

    }
}

console.log(object.details());

enter image description here

  • Related