Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a global constant from within a function in javascript

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?

like image 212
Henry Howeson Avatar asked Jan 02 '19 02:01

Henry Howeson


1 Answers

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);
like image 153
Meme Composer Avatar answered Nov 29 '22 16:11

Meme Composer