0

Started learning JS this week. Ran into trouble with the modal functions. Why is the 2nd alert function using the return value of the 1st alert function, causing the script to fail? Why not iterate the elements of the array

alert('hi')
[1,2].forEach(alert)
chanzerre
  • 2,409
  • 5
  • 20
  • 28
  • 1
    Your code is the same as `alert('hi')[1,2].forEach(alert)` which is the same as `const a = alert('hi'); const b = a[1,2]; b.forEach(alert)` which is the same as `const a = alert('hi'); const b = a[2]; b.forEach(alert)` – Quentin May 09 '22 at 16:36
  • 1
    Just don't omit semicolons unless you want to memorise the rules for how code should be handled then. – VLAZ May 09 '22 at 16:40
  • @VLAZ I was under the impression JS runtime automatically appends the semicolons during execution? – chanzerre May 09 '22 at 16:51
  • 1
    It does. And there are rules for when and how it does that. If you don't want to memorise all of them, then just add the semicolons yourself. That's what I do, personally. – VLAZ May 09 '22 at 16:52
  • @chanzerre if you leave out semicolons, JS will "guess" where you wanted them inserted. Often it will guess right but it's not foolproof. Just don't leave them out and you will never have this problem. You shouldn't rely on the language engine to fix your errors for you, and that (imo, at least - others disagree) is all ASI is. – Robin Zigmond May 09 '22 at 16:52
  • (while the actual situation is probably a little more complex, in essence the JS engine will add a semicolon for you at the end of a line *if your code wouldn't make any sense without it*. However in your case, without the semicolon your code is `alert('hi')[1,2].forEach(alert)` which while not what you meant is syntactically valid code. So no semicolons get inserted.) – Robin Zigmond May 09 '22 at 16:58
  • @Quentin What does `a[1,2]` in `const b= a[1,2]` mean? – chanzerre May 09 '22 at 17:22
  • 1
    @chanzerre — It means `const b = a[2]`. See the comma operator. – Quentin May 09 '22 at 17:33

0 Answers0