2

I have following code

const integerDivide = (a, b) => {
  return [Math.floor(a / b), a % b]
}


let sec = 555003,
  min, hr, day;

[min, sec] = integerDivide(sec, 60)
console.log(`sec: ${sec}`)
console.log(`min: ${min}`)
[hr, min] = integerDivide(min, 60)
console.log(`hr: ${hr}`)

This code is giving following error

Uncaught TypeError: Cannot set property '9250' of undefined

I don't understand why this code don't work. Any explanation or correction will be appreciated. Below is the code pen link https://codepen.io/devbkhadka/pen/ExyyEWE?editors=1111

A_A
  • 1,832
  • 2
  • 11
  • 17
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33

1 Answers1

5

You need some semicolons to prevent using the brackets as property accessor, because the ASI (Automatic Semicolon Insertation) does not work here.

If you write this in a line, you see it directly:

console.log(`min: ${min}`)[hr, min] = integerDivide(min, 60)

The linebreak does not separate the statements, followed by brackets. To overcome this, you need to add the semicolon for separating the statements.

More to read here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

const integerDivide = (a , b) => {
    return [Math.floor(a/b), a%b]
 }

let sec = 555003, min, hr, day;

[min, sec] = integerDivide(sec, 60)
console.log (`sec: ${sec}`)
console.log (`min: ${min}`); // <-- here at least
[hr, min] = integerDivide(min, 60)
console.log (`hr: ${hr}`)
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • ya, it worked, but I didn't get what you mean by "prevent using the brackets as property accessor." can you please elaborate – Dev Khadka Oct 19 '20 at 12:10
  • 1
    @DevKhadka The auto semicolon insertion doesn’t work well with a line starting with a square bracket. It removes the new line and sees `console.log(blah)[hr, min]` – evolutionxbox Oct 19 '20 at 12:21