0

What is happening in the code on line 10 ({[last]: newObj}) in the following snippet: How is JS able to use the value of parameter last instead of using last as the property name?

let first = 'first';
let last = 'last';

function foo(first, last) {
  let newObj = {
    name: 'newObj'
  };
  let obj = {};

  Object.assign(obj, {[last]: newObj});

  return obj;
}

console.log(foo('bye', 'hey'));  // { hey: { name: 'newObj' } }

Thanks.

noSelf_
  • 29
  • 5
  • 1
    It's a computed property name. Originally, javascript objects (the thing that inspired JSON) could only accept literals as keys. With computed property (the key in square bracket) it treats the key as a variable and uses the value of the variable to set the key. For example `let a = 'hello'; b = {[a]: 'world'}` generates an object `{"hello":"world"}` – slebetman Dec 06 '22 at 15:29
  • 1
    Because you wrapped `last` in `[ ]`. If you remove that, it won't evaluate the last's value. – vighnesh153 Dec 06 '22 at 15:29
  • 1
    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer -- scroll down to the "syntax" section – slebetman Dec 06 '22 at 15:31
  • @slebetman oh I see. I know about computed member access notation but this was very unfamiliar. Relearnt something in a different way today haha Thanks all! – noSelf_ Dec 06 '22 at 15:38

0 Answers0