Reputation: 788
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?
Upvotes: 6
Views: 4800
Reputation: 6814
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);
Upvotes: 10