-3

I'm solving this problem on one of the coding platform and I wonder if given answer is correct. Please refer to the code below:

What is the output of the following code?

var color= ["Orange", "Blue", "Green"];

color.push("Red");

console.log(color[0]+ " " +color[color.length-1]);

I think output for this code should be Orange Green as "Red" will join the array and color.length-1 will return green as the output but the correct answer given is ** "Orange Red**". What is logic behind this?

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • 2
    You appear to know that arrays are 0-index!? Do you know what the index of the last element is? **`...length - 1`**! No idea what is unclear about this. – luk2302 Jan 10 '23 at 13:12
  • see also: https://stackoverflow.com/questions/3216013/get-the-last-item-in-an-array or https://stackoverflow.com/questions/9050345/selecting-last-element-in-javascript-array – depperm Jan 10 '23 at 13:13
  • in this example length is 4, your last element index is 3 so it makes perfect sense – Chris G Jan 10 '23 at 13:14
  • The last element is at position `length-1`. This is because the array starts at position `0` instead of `1`. The final array has `4` elements, so `color.length` is `4`. The elements are: `color[0] = 'Orange'` and `color[1] = 'Blue'` and `color[2] ='Green'` and `color[3] = 'Red'`. While the length of the array is `4` the last element is `color[3]`. The element at `color[4]` does not exist because the length of the array is only 4, not 5. – slebetman Jan 10 '23 at 13:22
  • Instead of asking at SO, [why not test](https://jsfiddle.net/mjxuhetk/) by yourself? – Teemu Jan 10 '23 at 13:23

1 Answers1

0

You're correct that the first output would be orange since the list colors has orange in the 0th index. However, once you push 'red' to the list it alters the list to look like this: ['orange', 'blue', 'green', 'red'] so now color[color.length-1] will be 'red' by pushing something to the list you add it to the end of the list, changing the size of the list.

Jerry Spice
  • 63
  • 1
  • 8