0

I am doing exercises about typescript and I got something very confusing just now, could anyone tell me the detail about these code ?

class Person{
    fullname:string;
    constructor(paramName:string){
        this.fullname = paramName;
    }
    eat(){
        console.log(`${this.fullname} is eating`);
    }
}

class Programmer extends Person{
    preferLanguage:string;
    constructor(name:string,language:string){
        super(name);
        this.preferLanguage = language
    }
    say(){
        console.log(`${this.fullname} says that ${this.preferLanguage} is the best programming language in the world`);
    }
}

let person1 = new Programmer("Amy","PHP");
console.log(person1.fullname);
console.log(person1.eat());
console.log(person1.preferLanguage);
console.log(person1.say());

and the console result like this:

[LOG]: "zhangsan" 
[LOG]: "zhangsan is eating" 
[LOG]: undefined 
[LOG]: "PHP" 
[LOG]: "zhangsan says that PHP is the best programming language in the world" 
[LOG]: undefined 

anyone knows where these undefined come from? Thanks in advance!

1 Answer 1

1

It logs what function eat() returns - nothing, a.k.a. undefined (since you do not return anything). Functions in Javascript always returns something and console logs that.

If you instead return something:

eat(){
    console.log(`${this.fullname} is eating`);
    return null;
}

It will print null instead of undefined

Sign up to request clarification or add additional context in comments.

2 Comments

oh...................thanks, and sorry for my careless
No need to sorry. Thats the way to go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.