'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
}
}
Solution 1:[1]
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^^
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arnav Mishra |
