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

174
Views
Conditional element in class constructor in JavaScript

I know that in javascript we can add an conditional parameter for object like this:

const a = {
   ...(someCondition && {b: 5})
}

Is there a possibility to do something like that in classes and to hide width depends if it is passed or not as above?:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width; // this should be conditional
  }
}

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

0

You don't need to use anything complex to achieve this. An if statement would suffice for a situation like this.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    if (width) this.width = width; // this should be conditional
    console.log(this)
  }
}
new Rectangle(1)

This would work completely fine in javascript^^

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!