Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Removing Elements: pop()

The opposite of push() is the method pop(): it removes the last element of an array. You don't write anything in the parentheses, because it always removes the last element. But you do have to write the parentheses.

Besides changing the array, pop() gives the removed element back to you, so that you can keep working with it. We say that the method returns the element, and the element is its return value. You can store the returned value in a variable:

const colors = ["blue", "green", "pink"];
const lastColor = colors.pop();
console.log(lastColor);
console.log(colors);

This prints:

pink
["blue", "green"]

The call colors.pop() removed the element "pink" from the array and returned it, so it was stored in the variable lastColor. If you don't need the removed element, simply write colors.pop(); on a line of its own.

Don't forget the parentheses. Without them, the method isn't called: const lastColor = colors.pop; removes nothing and stores the method itself in lastColor. When you print it, you see [Function: pop] instead of an element.

Instructions

  1. 1

    Ava's project is finished, and she is leaving the team. Remove the last element of coworkers with pop() and store it in a constant leavingCoworker.

  2. 2

    Print leavingCoworker.

  3. 3

    Print coworkers to check that Ava is no longer in the array.

Back

7/11

  1. 1. Introduction to Arrays
  2. 2. Creating Arrays
  3. 3. Accessing Array Elements
  4. 4. Changing Array Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: push()
  7. 7. Removing Elements: pop()
  8. 8. Searching an Array
  9. 9. Nested Arrays
  10. 10. Characters of a Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.