I know there are a ton of EloqJS questions on here, but I haven't seen this one asked and it is throwing me for a loop. I'm curious how the key squirrel in the object entry (squirrel: squirrel) is not replaced by the argument passed by 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 for it to entry to be {events: [], true: true}, but that is not what this is returning. What am I obviously missing here? Original code at http://eloquentjavascript.net/04_data.html#arguments_object
Because object keys are literals: they don't change at runtime or act as variables to be replaced with a value.
If you look at the object initialiser section of the spec (11.1.5), it specifies that an object literal consists of a property name/value list, with property name defined to be one of:
IdentifierName
StringLiteral
NumericLiteral
The rules for IdentifierName are defined in section 7.6 to include most unicode characters, but not reserved words or whitespace.
Any IdentifierName can be wrapped in quotes to become a valid StringLiteral, although the inverse is not always true (StringLiterals containing punctuation or whitespace need the quotes to be valid). You can define the object just as well with:
{'events': [], 'squirrel': squirrel}
As of ES6, there is now a notation to specify that a key should be the value of a variable rather than an identifier or literal of its own. This is defined in section 12.2.6 as a ComputedPropertyName, using the [expr] syntax. For the object to have a true: true property, you could use the ES6 code:
{'events': [], [squirrel]: squirrel}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With