Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Javascript - Class - Method Returning Undefined When Calling Constructor Property

I'm currently learning Javascript. When I run the following code, I am getting undefined. Not sure what is wrong. Everything seems to be fine. Any help will be appreciated. Thank you.

class User{
  constructor(){
    this.array = [1, 2, 3]
  }

  static getNumber(){
    return console.log(this.array)
    
  }
}


User.getNumber()

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First of all, you have to create a new instance of User with new User() or new User if you want to be able to access instance properties (such as array), because they are created with this.array = .... From the Mozilla Web Docs:

The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

Because getNumber is called on the constructor itself, it doesn't have access to any of the instance properties (the only one is this.array). When new User is called, it creates the this.array, but only for the instance, not the constructor.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!