Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

name() function not returning value in javascript class

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading