Home:ALL Converter>Why is it impossible to assign constant properties of JavaScript objects using the const keyword?

Why is it impossible to assign constant properties of JavaScript objects using the const keyword?

Ask Time:2012-06-01T10:51:10         Author:danronmoon

Json Formatter

First, I had asked is it possible: How to create Javascript constants as properties of objects using const keyword?

Now, I gotta ask: why? The answer to me seems to be 'just because', but it would be so useful to do something like this:

var App = {};  // want to be able to extend
const App.goldenRatio= 1.6180339887  // throws Exception

Why can constants set on an activation object work but not when set on they are set on any other?

What sort of damage can be done if this were possible?

What is the purpose of const, if not to prevent a public API from being altered?

Author:danronmoon,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/10843809/why-is-it-impossible-to-assign-constant-properties-of-javascript-objects-using-t
Phrogz :

If you want an unchangeable value in a modern browser, use defineProperty to create an unwritable (aka read-only) property:\n\nvar App = {};\nObject.defineProperty(App,'goldenRatio',{value:1.6180339887});\nconsole.log( App.goldenRatio ); // 1.6180339887\nApp.goldenRatio = 42;\nconsole.log( App.goldenRatio ); // 1.6180339887\ndelete App.goldenRatio; // false\nconsole.log( App.goldenRatio ); // 1.6180339887\n\n\nIf you don't pass writable:true in the options to defineProperty it defaults to false, and thus silently ignores any changes you attempt to the property. Further, if you don't pass configurable:true then it defaults to false and you may not delete the property.",
2012-06-01T03:30:13
bfavaretto :

Apart from the fact that const is and not supported cross-browser (it's an ES6 feature), const App.goldenRatio= 1.6180339887 doesn't work for the same reason var App.goldenRatio= 1.6180339887 doesn't: you're setting an object property, so it's a syntax error to prepend it with a var or const keyword.",
2013-02-19T18:04:38
djechlin :

Going to answer the question you meant to ask and say never use const. The interpreter doesn't do anything with it. All it does is mislead the developer into thinking s/he can assume that the value never changes, which is about as likely as if the const keyword weren't present.",
2012-06-01T03:12:20
yy