Skip to content

Instantly share code, notes, and snippets.

@blainekasten
Last active January 3, 2016 06:19
Show Gist options
  • Save blainekasten/8422131 to your computer and use it in GitHub Desktop.
Save blainekasten/8422131 to your computer and use it in GitHub Desktop.
Javascript Constants
// Ever need to create constants in javascript?
// Option 1:
// Browser Support: ie9+ ff4+ chrome6+ opera12+ safari 5.1+
// You must wrap your constants variables in an object:
var constants =
{
CONSTANT1: 'constant value',
CONSTANT2: 2
};
// Freeze the object. This makes it immutable, giving it the appearance of constants.
Object.freeze(constants);
// Now, changing a variable will silently fail.
constants.CONSTANT1 = true;
console.log(constants.CONSTANT1); // prints 'constant value'
constants.CONSTANT2 = '2';
console.log(typeof constants.CONSTANT2); // prints 'number'
// option 2:
// Object.defineProperty
// Browser Support: ie9+(8 with issues) ff4+ chrome5+ opera11.6+ safari 5.1+
Object.defineProperty(this, 'varName', {
enumerable: true,
configurable: true
writable: false,
value: 2 // The value the constant should be set to.
});
console.log(varName); // prints 2
varName = 3
console.log(varName); // prints 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment