Interesting Error Based On Automatic Semicolon Insertion Js Rules. Explanation Required
Today I wrote code for some programming contest. When I run it I was surprised because of error. Cannot read property 'forEach' of undefined in a place where looks like 'error free
Solution 1:
1,2,3 === 3
so
[1,2,3] -> [3]i.e. is property named 3
therefore
sum = 0[3] is undefined -
since the Number(0) has no property called 3
to illustrate further
var sum = 0
[1,2,3,'constructor']
console.log(sum);
now the code is equivalent to
var sum = 0['constructor']
or
var sum = 0..constructor
which, as you see in the console is the Number
object constructor
Solution 2:
The problem is that when you don't put a semi-colon it doesn't automatically put ;
instead
- it tries to get the property
3
of a number. - Here
[1,2,3]
doesnot work as array but as Bracket Notation. - Due to Comma Operator the last operand
3
. - So the
0[3]
isundefined
.undefined.forEach(){...}
will obviously throw error.
let sum = 0
[1,2,3]
console.log(sum)
Post a Comment for "Interesting Error Based On Automatic Semicolon Insertion Js Rules. Explanation Required"