Why is this code outputting 21 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
19th Apr 2021, 11:58 AM
E∆SI🇳🇬🤖
E∆SI🇳🇬🤖 - avatar
4 Answers
+ 3
E∆SI 🇳🇬 Before your alert on line 4, you have an array of length 3 like this: var a = new Array(); a = [, 2, 1] So, alert([2] + a.length - a[1]) will convert the first part which is an array with 2 to a string "2" because of the + operator. Your array.length is 3 because you inserted two items in index positions 1 and 2, so a placeholder item exists in index position 0. Now we have "2" + 3 which becomes the string "23". You then subtract from that the item at index position 1 of your array which is 2. The final calculation is "23" - 2 which comes to "21".
19th Apr 2021, 12:19 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
20th Apr 2021, 7:40 AM
E∆SI🇳🇬🤖
E∆SI🇳🇬🤖 - avatar
+ 2
E∆SI.py 🇳🇬 Because [2] + 3 - 2 = [2] + 1 = 21
19th Apr 2021, 12:03 PM
A͢J
A͢J - avatar
0
E∆SI 🇳🇬 You're welcome.
20th Apr 2021, 8:48 AM
CamelBeatsSnake
CamelBeatsSnake - avatar