0

This is just out of curiosity, but do any of you have an idea why this code won't work?

CASE 1: If I don't put semicolon after console.log(), the code doesn't work.

console.log('foo')
[3, 2, 1].forEach( v => console.log(v) )

Output of case1:

foo
TypeError: Cannot read property '1' of undefined

CASE 2: If I don put semicolon after console.log();, the code works fine.

console.log('foo');
[3, 2, 1].forEach( v => console.log(v) )

Output of case2:

foo
3
2
1
Ashutosh
  • 662
  • 6
  • 19
  • 2
    think of your code as `console.log('foo')[3, 2, 1].forEach( v => console.log(v) )` .. since `fn(x)[1,2,3]` IS valid javascript, you can easily see the issue - my advice, ALWAYS use `;` where they should go - it makes you a more professional looking coder - and nobody is using 9600 baud dialup any more where every character saved is important – Jaromanda X May 12 '21 at 06:28
  • Thanks @JaromandaX finally I understood. – Ashutosh May 12 '21 at 06:57
  • I have one doubt also, why this [[11, 12][21,22]][3, 2, 1] is undefined? @JaromandaX – Ashutosh May 12 '21 at 06:58
  • I think because [11,12][21,22] is undefined which is inside an array and by using [3, 2, 1] you are trying to access the element of the array using index. But as you have specified multiple comma separated indexes, JS takes the last one mentioned i.e., 1 in your case and there's no element at index 1. If you had [[11, 12][21,22], 10][3, 2, 1] it would have printed 10. – Lakshya May 12 '21 at 07:07
  • I think you are correct @Lakshya – Ashutosh May 12 '21 at 07:10

0 Answers0