'why can't I override Math.PI but can override Math.floor in JavaScript?

I tried assigning Math.PI to 1000000, but when trying to use the value, I still got the default non-overridden value, while I was able to override Math.floor with function(){console.log('floor')} and calling it called the overridden function. I was wondering why that is and how I'd be able to override Math.PI. I tried this on both node v14 and Chrome v83.



Solution 1:[1]

You can check Math.PI descriptor using Object.getOwnPropertyDescriptor(), and you'll see that this property in not writable. That is why when you try to reassign its value, it is not being updated

console.log(Object.getOwnPropertyDescriptor(Math, 'PI'))

Solution 2:[2]

You can't overwrite Math.PI as suggested in the below image from this link

enter image description here

Solution 3:[3]

It can not be override because Math.PI is created using:

Object.defineProperty(obj, 'key', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: 'static'
}); 

writable inside descriptor is set to be as false.

eg -

Object.defineProperty(company, name,{value: "Sapient", writable: false, })

now if you try to change as company.name ="Mindtree" it will get ignored but if you make writeable as true then it will get reflected.

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 Tatiana Fomina
Solution 2 Akhil
Solution 3 juagicre