Why the answer is 4? Could somebody explain this example, please? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why the answer is 4? Could somebody explain this example, please?

var arr, arr1, arr2; arr1 = new Array(1, 0, 2); arr2= new Array(4, 2, 0); arr = arr2.concat(arr1); console.log(arr[arr[2]]);

27th Jan 2020, 9:44 PM
Nata Martí
Nata Martí - avatar
3 Answers
+ 2
🤔🤷‍♂️
27th Jan 2020, 9:49 PM
Artemis Ariamehr
Artemis Ariamehr - avatar
+ 1
after concatenation, arr elements are [4,2,0,1,0,2] so arr[2] equals 0 because it is the third element (indexes: 0 = 4, 1 = 2, 2 = 0,...) and arr[0] equals 4. basically arr[ arr[2]] is equivalent to arr[0] which is 4.
27th Jan 2020, 10:38 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 1
After concat (add) gets one array: arr = [4,2,0,1,0,2] then inner array points to: arr[2] = 0 (we count from 0 so we get third item, which is 0) therefore outer array: arr[0] = 4 (first item of the same array)
27th Jan 2020, 11:07 PM
JaScript
JaScript - avatar