inside the while loop if i don’t include the if(j>0) , it breaks on the first cycle, saying ‘cannot set properties of undefined’. But the while loop doesn’t initiate when j is below 1 anyway. which i can check with the console.log. So don’t understand why it won’t just perform the ‘swap’.
**Your code so far**
function insertionSort(arr) {
let result=[]
for(let i=0;i<arr.length;i++){
result.push(arr[i])
let element=result[i]
let j=i
while (element<result[j-1]) {
console.log('j=',j,' j-1=',j-1)
if(j>0)[ result[j-1], result[j] ] = [ result[j], result[j-1] ]
j--
}
}
return result;
}
console.log(insertionSort([5,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]))
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36
yes, i can see good practice would be to avoid result[-1] ahead of the while loop. still a weird behaviour with the logs affecting it, but i’ll put it down to that oversight and move on. thanks.