Why does it happen that the below code throws the error Uncaught ReferenceError: Cannot access 'arr' before initialization
function swap(str,a,b){
let arr = str.split("")
[arr[a],arr[b]] = [arr[b],arr[a]]
return arr.join("")
}
swap("abcde",2,4) // throws error "Uncaught ReferenceError: Cannot access 'arr' before initialization"
But as soon as I insert any dummy statement between line 2 and 3, surprisingly code starts to work
function swap(str,a,b){
let arr = str.split("")
23456; // this could be anything like a variable declaration, or any valid javascript statement
[arr[a],arr[b]] = [arr[b],arr[a]]
return arr.join("")
}
swap("abcde",2,4) // returns "abedc" as expected
I am surprised to see why does this even work now ? It should have given error in both the cases, or should have worked in both cases.
I’m sure that in the 1st case, split
is not finishing it’s work till the time line 3 is executed and in 2nd case, it is getting enough time because of 1 extra statement in between.
But I would still love to get a clear explanation as to why it is behaving like this.
I’m not sure if this is same for all browsers, but I’ve tried it on Chrome and Safari on mac, and both of them gave same error.