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)
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)
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.