1

So with my code, the question which I'm trying to answer in Javascript is to reset the items in an array, where it's creating a function named empty, and then reset the items inside an array. So far I have tried out pop array and it lists the whole array out, and then I have tried to write it by using array length.

Here is my code set up for this one:

function empty(){
 for(var basket = basket.length=0; basket--);
}
console.log('Reset basket:', basket);
asked Mar 18, 2021 at 19:44
2
  • um, firstly, basket would be undefined so an error would throw immediately, secondly, the syntax in that forloop makes no sense :{ Commented Mar 18, 2021 at 19:47
  • 1
    What are you trying to do to basket? Couldn't you just do basket = [] (or basket.length = 0;)? Commented Mar 18, 2021 at 19:50

1 Answer 1

5

If you need to replace just the variable basket with an empty array, simply reassign it:

basket = [];

If you need to reset the actual array referenced by the variable, and therefore reset all references to the same array, simply set .length to 0.

basket.length = 0;

Your syntax though is incorrect. As a function, it would look like:

function empty(array) {
 array.length = 0;
}
let arr1 = [1, 2, 3];
let arr2 = arr1; // both variables reference the same array
let arr3 = [...arr1]; // references a different array
empty(arr1);
console.log(arr1); // []
console.log(arr2); // []
console.log(arr3); // [1, 2, 3]

answered Mar 18, 2021 at 19:50
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.