nick jchn
nick jchn

Reputation: 5

I got a unexpected undefined console log output when I using Typescript

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!

Upvotes: 0

Views: 521

Answers (1)

S Overfow
S Overfow

Reputation: 161

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

Upvotes: 1

Related Questions