6

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?

12
  • 2
    You might set a non-configurable property on the global object, but it's still a code smell. Commented Jan 2, 2019 at 2:17
  • 2
    const carType; is illegal syntax. 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 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. 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. Commented Jan 2, 2019 at 2:32

1 Answer 1

10

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.