1

I have this piece of code where I delete the first (or last) element from an array, according to a boolean variable. I do like this:

{...
console.log("length before " + waypoints.length)
waypoints = this.deleteWaypoint(waypoints)
console.log("length after " + waypoints.length)
...}

deleteWaypoint(waypoints){
if (this.first){
  this.first = false;
  return waypoints.shift() 
} else {
  this.first = true;
  return waypoints.pop() 
}
}

The first log prints that waypoints has a certain length, then I call the method to delete elements and when the second log prints is length after undefined. "First" is a global variable initialized to true. Why is that?

5
  • As soon as your array is empty, you get undefined, as described here Commented Dec 26, 2017 at 10:28
  • 2
    Array.prototype.shift: "The shift() method removes the first element from an array and returns that removed element." Commented Dec 26, 2017 at 10:28
  • Update your return statement to return waypoints in deleteWaypoint Commented Dec 26, 2017 at 10:29
  • Also consider giving us more detail. How does your array look like? mcve Commented Dec 26, 2017 at 10:30
  • @Andreas Yep, modified now in waypoints.shift(); return waypoints. Thanks. Sorry for the silly question, if you answer I'll give you upvote and correct answer Commented Dec 26, 2017 at 10:30

3 Answers 3

2

change the function as below:

var  waypoints = [1,2,3,4,5,6,7,8,9,0];

var deleteWaypoint = (waypoints)=>{
if (this.first){
  this.first = false;
  waypoints.shift();
  return waypoints
} else {
  this.first = true;
  waypoints.pop()
  return waypoints
}
}

console.log("length before " + waypoints.length)
waypoints = deleteWaypoint(waypoints)
console.log("length after " + waypoints.length)

Sign up to request clarification or add additional context in comments.

Comments

0

This works perfectly fine for me;

var deleteWaypoint = function (waypoints) {
  if (this.first) {
    this.first = false;
    waypoints.shift()
  } else {
    this.first = true;
    waypoints.pop()
  }
};

this.first = true
var waypoints = [1,2,3,4,5];
console.log("length before " + waypoints.length);
deleteWaypoint(waypoints)
console.log("length after " + waypoints.length);

Array.shift() returns the removed array, in below line copied from code posted in question,

waypoints = this.deleteWaypoint(waypoints)

the reference of array is getting re-assigned to the removed element which is not array and does not have length property and hence returning undefined

Comments

0

Yes, its correct because in return return waypoints.shift() will return single element which is deleted from array. You can do like this first, waypoints.shift() then, return waypoints

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.