I would like to be able to define a constant that is in the global scope from within a function. With a normal variable this would be possible by defining it outside the function and setting its' value from within the function as shown below:
var carType;
function carType(){
carType = 'Reliant Robin';
}
However you cannot define global variables without setting a value so this would not work with a constant, is there any way around this?
The answer is "yes", but it is not a typical declaration, see the code snippet below
function carType(){
Object.defineProperty(window, 'carType', {
value: 'Reliant Robin',
configurable: false,
writable: false
});
}
carType();
carType = 'This is ignored'
console.log(carType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With