Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

226
Vistas
using slice() to retrieve items from the end of an array in JS

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 []
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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);
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda