I am reading book JavaScript: The Definitive Guide.
In section 3.4, it says,
In ECMAScript 3, undefined is a read/write variable, and it can be set to any value. This error is corrected in ECMAScript 5 and undefined is read-only in that version of the language.
what exactly does it mean by a read/write variable?
If something is "read/write", it means you can both read it and write to it. Contrast with a read-only variable (you can't write to it), or a write-only variable (you can't read from it; fairly unusual, but entirely possible).
In JavaScript, variables are read/write by default. In fact, until ES2015, all true variables were read/write. In ES2018, we got const
, which lets you create a "variable" that's read-only ("constant"), but it's still a "variable" (what the spec calls a binding) in all other ways.
But it was (and is) possible to create read-only global "variables" even before const
, by creating a read-only property of the global object:
// A global scope, this refers to the global object
Object.defineProperty(this, "answer", {
value: 42,
writable: false // this is the default, including it here for emphasis
});
console.log("answer = ", answer); // 42
answer = 67; // Would be an error in strict mode
console.log("answer = ", answer); // still 42
That works because properties of the global object are accessible as global variables.