-1

Can someone please help me understand what concept from JavaScript could ensure below line of code runs? feel free to make code changes to make it execute & provide output.

    (20).add(10).multiply(2)
Sunny
  • 194
  • 3

1 Answers1

1

You can make use of prototype. Using .prototype, you are adding a property in the prototype chain to all numbers.

Any number can use it.

Number.prototype.add = function(x){
return this + x;
}
console.log((20).add(10));
Number.prototype.multiply = function(x){
return this * x;
}
console.log((20).multiply(10));

console.log((20).add(10).multiply(2));

Note: This is generally a bad practice, and should only be used for self-learning and practice.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • 1
    While this is accurate and worth knowing about, it's also worth pointing out that modifying common objects prototypes is generally considered bad practise. See: [Why is it frowned upon to modify JavaScript object's prototypes?](https://stackoverflow.com/questions/6223449/why-is-it-frowned-upon-to-modify-javascript-objects-prototypes) – DBS Sep 08 '21 at 10:58
  • Yeah. Thanks for pointing that out. I have added in the answer in BOLD – Tushar Shahi Sep 08 '21 at 11:08