Home > OS >  name() function not returning value in javascript class
name() function not returning value in javascript class

Time:08-24

I am learning about classes in JavaScript. I have created a Student class and defined object inside a constructor function.

class Student {
    constructor(firstName, lastName, age){
        this.firstName = firstName
        this.lastName = lastName
        this.age = age
    }

    name(){
        return `The student's name is ${firstName} ${lastName}`
    }
}

const student1 = new Student('John', 'Carter', '26')

I want to print the statement in cmd written inside name() function that returns a statement. But I am getting nothing when I run the code.

Output I am expecting: The student name is John Carter

CodePudding user response:

You need to use this to access class property

name function return string, so you need to console.log to see the output

class Student {
  constructor(firstName, lastName, age) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
  }

  name() {
    return `The student's name is ${this.firstName} ${this.lastName}`
  }
}

const student = new Student('John', 'Carter', 26)

console.log(student.name())

CodePudding user response:

For accessing class properties you have to use this keyword inside a function.

class Student {
    private firstName;
    private lastName;
    private age;
    constructor(firstName, lastName, age){
        this.firstName = firstName
        this.lastName = lastName
        this.age = age
    }

    name(){
        return `The student's name is ${this.firstName} ${this.lastName}`
    }
}

const student1 = new Student('John', 'Carter', '26')
console.log(student1.name())
  • Related