Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

227
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda