1

Here upperLeft and lowerRight are not in quotes but why it does not raise any error ?

example:-
Object literals can be nested. For example:

var rectangle = { upperLeft:  { x: 2, y: 2 },
                  lowerRight: { x: 4, y: 5 } }; 

this is about object initializer in javascript.

Shri Mali
  • 69
  • 5
  • 1
    It looks like you are quoting from something; a book or online article. If this is the case, please use blockquote formatting (icon looks like double quote marks `"`) rather than code formatting. And please cite the source. – Heretic Monkey Mar 25 '20 at 18:13
  • See http://www.ecma-international.org/ecma-262/6.0/#sec-object-type – jarmod Mar 25 '20 at 18:20
  • Why do you expect it to raise an error? – Bergi Mar 25 '20 at 19:01

1 Answers1

0

Object can have keys only as string or symbol, anything else then these will be converted to string internally.

Object internally converts its keys to string, so 1 and "1" both are same. So here upperLeft and lowerLeft doesn't throw any error here because it treats them as string only

let obj = {
  1: '1',
  hey: 'hey'
}

console.log(obj["1"])
console.log(obj[1])
console.log(obj[1] === obj['1'])

The expression in object initialiser are evaluated during initialisation so you can use any expression to have a dynamic key or value.

let key = 'key'
let newKeyValue = "Some value"

const obj = {
  [key] : 'some value',
  [1 + 2] : 'some more value',
  newKey: newKeyValue
}

console.log(obj)

Legal identifiers means anything which follows the following rules

  • Identifier should have only alphabets, numbers, $ and _
  • First character should not be number

But in object keys you can use any legal string it will work where as while defining variable you can't use reserved words and illegal identifiers

const obj = {
  "1abc" : 'some value'
}

console.log(obj['1abc'])

const do = "no you can't"

Note:- To access invalid identifier you need to use [] bracket notation

Code Maniac
  • 37,143
  • 5
  • 39
  • 60