+ 1
Why is it like this in javascript?
Why In first Code it says x is not initialized While in second code logic does not work Third can be used to avoid such mis-matched logic??? https://sololearn.com/compiler-playground/cOY0E0I6cEY7/?ref=app https://sololearn.com/compiler-playground/cn4mk4sJ972w/?ref=app https://sololearn.com/compiler-playground/cq4m2aaEFp8I/?ref=app
2 Antworten
+ 2
I assume it has to do with how Javascript inserts left-out semicolons (Automatic Semicolon Insertion).
The interpreter "guesses" where the semicolon needs to be. Perhaps for your example 1, it expects something like
let x = [1,2][0];
which might be a plausible interpretation attempt but not the one you intend it to actually have.
We would need to dig deeper into the specification of ES6...
+ 1
Agree with Lisa. I had unexpected bugs that happens when lines of code get unexpectedly concatenated. It's good practice to always end statements with semicolons in js.
the simple version should be
let x = [1, 2];
x = [x[1], x[0]];
console.log(x);