0

Let suppose we he a code block below -

function football(){
let options = {}
  let [r, s, e] = ['Ronaldo', 'Messi', 'Aguero']
  if(true){
    options = {league: 'Premier League'}
    [r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']
    console.log(options, r, s, e)
  }
}
football()

Output of this code is - ['Grealish', 'De Bruyne', 'Ramos'] Ronaldo Messi Aguero

Please suggest the reason why object assignment didn't work here without ; semicolon in the options variable.

If we put a semicolon ; after like this- options = {league: 'Premier League'}; then this would give the expected output - {league: 'Premier League'} Grealish De Bruyne Ramos.

Please anyone can explain the reason?

Thanks in advance

Arun chauhan
  • 117
  • 12

1 Answers1

1

Without the semicolon these two lines

options = {league: 'Premier League'}
[r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']

are interpreted as a single expression:

options = {league: 'Premier League'}[r, s, e] = ['Grealish', 'De Bruyne', 'Ramos']

The {league: 'Premier League'}[r, s, e] part, while interesting, is irrelevant because the "return value" of an assignment expression is always the value that was assigned:

let a = [];
let b = a[0] = 'first';
console.log(a, b);
// b = 'first' because the result of a[0] = 'first' is 'first'

Hence your code is equivalent to

options = ['Grealish', 'De Bruyne', 'Ramos']
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • It might be worth noting that `{ ... } [r, s, e]` is interpreted as: `{ ... }[e]` which will end up being an attempt to lookup the key `e` from the object `{ ... }` `e` being `"Ramos"` and the object being `{league: 'Premier League'}` resulting in `undefined`, so the expression ends up being `options = undefined = `[...]`. – Andreas Louv Aug 26 '21 at 10:33
  • 1
    @andlrc: No, the assignment (`{...}[...] = ...`) takes precedence so the property `"Ramos"` will actually be created. – Felix Kling Aug 26 '21 at 20:18