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?
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?
Share Improve this question edited Jan 2, 2019 at 2:31 Henry Howeson asked Jan 2, 2019 at 2:16 Henry HowesonHenry Howeson 7888 silver badges21 bronze badges 12- 2 You might set a non-configurable property on the global object, but it's still a code smell. – CertainPerformance Commented Jan 2, 2019 at 2:17
-
2
const carType;
is illegal syntax. – Patrick Roberts Commented Jan 2, 2019 at 2:19 - @PatrickRoberts I know, "However you cannot define global variables without setting a value so the program will fail on the first line". I'm asking if there is any way around this – Henry Howeson Commented Jan 2, 2019 at 2:21
- 2 If you declare a variable before defining it, by definition it is not a constant, so your request makes no sense. – Patrick Roberts Commented Jan 2, 2019 at 2:25
-
2
The short answer is no - you can't create a global const, let, or class identifier in global scope using declarations within a function or by using
eval
. I looked into the eval case for this answer regarding scope. – traktor Commented Jan 2, 2019 at 2:32
1 Answer
Reset to default 10The 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);