Eloquent Javascript - Chapter 4 in the Arguments Object
I know there are a ton of EloqJS questions here, but I haven't seen this and it throws me for a loop. I'm curious how the key protein in the object (protein: protein) notation is not replaced by the argument passed to the function in this code:
function addEntry(squirrel) {
var entry = {events: [], squirrel: squirrel};
for (var i = 1; i < arguments.length; i++)
entry.events.push(arguments[i]);
journal.push(entry);
}
addEntry(true, "work", "touched tree", "pizza",
"running", "television");
I would expect it to be {events: [], true: true}, but that's not what is returned. What am I obviously missing here? Source Code http://eloquentjavascript.net/04_data.html#arguments_object
source to share
Because object keys are literals: they do not change at runtime or act like variables that need to be replaced with a value.
If you look at the object initializer section of the spec (11.1.5) , it indicates that the object literal consists of a property name / value, with the property name defined as one of:
IdentifierName
StringLiteral
NumericLiteral
The rules for are IdentifierName
defined in section 7.6 to include most Unicode characters, but not reserved words or spaces.
Anyone IdentifierName
can be quoted to be valid StringLiteral
, although the inverse is not always true ( StringLiteral
containing punctuation marks or spaces, the quotes must be valid). You can also define an object like this:
{'events': [], 'squirrel': squirrel}
Starting in ES6, there is now a directive to specify that the key must be a variable value, not an identifier or literal. It is defined in section 12.2.6 as ComputedPropertyName
using the syntax [expr]
. To make an object have a property true: true
, you could use ES6 code:
{'events': [], [squirrel]: squirrel}
source to share