Question:

Predict the output of the following JavaScript code:
var colors = ['Red', 'Blue', 'Green'];
document.write(colors.pop() + "
");
document.write(colors.push('Yellow') + "
");
document.write(colors.join('& amp;') + "
");
document.write(colors.slice(1, 3));

Show Hint

Remember: pop() returns the removed element, but push() returns the new length (a number) of the mutated array.
Updated On: Jun 29, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Execute colors.pop()

Initial array:

\[ \texttt{colors = ['Red', 'Blue', 'Green']} \]

  • The pop() method removes and returns the last element of the array.
  • The removed element is "Green".
  • document.write(colors.pop() + "<br>") prints Green.

Array after execution:

\[ \texttt{colors = ['Red', 'Blue']} \]


Step 2: Execute colors.push('Yellow')

Current array:

\[ \texttt{colors = ['Red', 'Blue']} \]

  • The push('Yellow') method appends "Yellow" to the end of the array.
  • The push() method returns the new length of the array, not the array itself.
  • The new array length is 3.
  • document.write(colors.push('Yellow') + "<br>") prints 3.

Array after execution:

\[ \texttt{colors = ['Red', 'Blue', 'Yellow']} \]


Step 3: Execute colors.join('&')

Current array:

\[ \texttt{colors = ['Red', 'Blue', 'Yellow']} \]

  • The join('&') method combines all array elements into a single string using & as the separator.
  • The resulting string is Red&Blue&Yellow.
  • The original array remains unchanged.

Output:

Red&Blue&Yellow


Step 4: Execute colors.slice(1, 3)

Current array:

\[ \texttt{colors = ['Red', 'Blue', 'Yellow']} \]

  • The slice(begin, end) method returns a new array containing elements from index 1 up to, but not including, index 3.
  • Extracted elements are:
    • Index 1 → Blue
    • Index 2 → Yellow
  • The returned array is ['Blue', 'Yellow'].
  • When passed to document.write(), JavaScript converts the array into the string Blue,Yellow.

Final Output

The complete output displayed in the browser is:

Green 3 Red&Blue&Yellow Blue,Yellow

Was this answer helpful?
0
0