0

Why doesn't this give me the object I expected .. which is {1:2} Instead the console gives {a:2}

function createObject (a, b) {
    const myObject = {a:b}
    console.log(myObject);
}

createObject(1, 2);

1 Answers1

2

Without brackets, the property name of a literal object is not evaluated as an expression:

function createObject (a, b) {
    const myObject = {[a]: b}
    console.log(myObject);
}

createObject(1, 2);
Guerric P
  • 30,447
  • 6
  • 48
  • 86