Home > front end >  using slice() to retrieve items from the end of an array in JS
using slice() to retrieve items from the end of an array in JS

Time:09-21

Disclaimer: I'm new to JS. So, all of my test are passing but one - the last one - and I can't figure out how to fix it. Why is 0 returning the last element and not an empty array? Also, on a separate note, when I tried to use a default value it returned the wrong values hence why I decided to include a conditional statement.

const takeRight = (array, n) => {
n = -n;
//setting both default and a negative value for 'n': if there is no number, then n should be -1
const condition = !n ? -1 : n;
return array.slice(condition);
};

console.log(takeRight([1, 2, 3])); // returns [3] --> expected [3] 
console.log(takeRight([1, 2, 3], 2)); //returns [2, 3] --> expected [2,3] 
console.log(takeRight([1, 2, 3], 5)); //returns [1, 2, 3] --> expected [1,2,3]
console.log(takeRight([1, 2, 3], 0)); //returns [3] --> expected []

CodePudding user response:

The problem is in calculating condition variable:

const condition = !n ? -1 : n;

expression !0 is true, so n is changed to -1 when has value 0.

If you want to check against not a numbers, use isNaN.:

const takeRight = (array, n) => {
    n = isNaN(n) ? -1 : -n;
    return array.slice(n);
};

CodePudding user response:

The problem might be your expression. Check for "Not a Number"

const condition = isNaN(n) ? -1 : n;

MDN: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/isNaN

CodePudding user response:

So, first of all, you shouldn't reassign arguments. But the actual issue here is using !n to test if it exists. It might be a neat trick here and there but is actually just confusing. Prefixing anything with a ! in JavaScript turns it into a boolean and then negates it, and the rules for this conversion are not obvious and also not the same in every language. But in JS, !0 gives you the same result as !undefined or !null, because the number 0 often symbolizes an "off-state", basically a false, but shorter. Anyways, to avoid all of that, just use default parameters and use a ternary operator in the return statement to check for the specific case of n = 0 like so:

const takeRight = (array, n = 1) => n === 0 ? [] : condition array.slice(-n);

You can of course make that a bit more verbose as well:

const takeRight = (array, n = 1) => {
    if (n === 0) {
        return [];
    }

    return condition array.slice(-n);
};

EDIT: Even !"" returns true by the way, which is not really "obvious" as well, so using ! to check if something is defined or exists, can really cause problems and unexpected outcomes. I'd advise against it unless you really really know what you are doing and why.

  • Related