Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Removing Items From Arrays

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,621 Points

Removing Items From Array

I wanted to delete a specific element within the array not first or last element. So I write the solution as-

var arr = [2, 3, 5, 6];
var itemIndex = arr.indexOf(3);
arr.splice( itemIndex , 1);

But when I searched to find , is it the correct one. I found this solution-

var array = [2, 5, 9];
var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

So my question is "why condition statement is used here?". What are the conditions where "indexOf() function can return negative index?" . Please explain . Thankyou.

1 Answer

Andreas Nyström
Andreas Nyström
8,879 Points

Hi.

The indexOf-function returns -1 if it doesn't find an index. So if you try to look for 33 in your code your index would be -1. The conditional is there to prevent it from splicing if you didnt find an index. If you don't have it, you will splice the LAST item in your array.

See this example:

let myArray = [3, 55, 4]

// index is now set to -1 because it didn't find the number in the array.
let index = myArray.indexOf(344);

// This will now remove 4 in the array as it is the last item of the array.
// Because it didnt find an index.
// This is not what you wanted.
myArray.splice(index, 1);

// Instead we're using a condintional statement
// Because we only want the splice to happen if an index was found
if (index > -1) {
  myArray.splice(index, 1);
}