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

97
Vistas
Please explain logic of the javascript function code line

can you explain how works letters[pass[i]] = (letters[pass[i]] || 0) + 1?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This line adds letters from pass to the letters object as keys and it's number of occurs in the value.

So, for example, for pass = "aabbc" you'll have letters equal to

{
  "a":2,
  "b":2,
  "c":1
}

The operator on the right ((letters[pass[i]] || 0) + 1) can be splitted to two: letters[pass[i]] || 0 checks if letters has key of value pass[i], if so the expression will have it's value, if not then we will get value after || - in this case 0. To value of this expression we add always 1.

Also, we could convert this one line to something like this:

if(letters[pass[i]]) {
  letters[pass[i]]++;
} else {
  letters[pass[i]] = 1;
}

About the || operator in value assignment you can read more for example here

about 4 years ago · Juan Pablo Isaza Denunciar

0

Let's start from the inside out, like JavaScript does. :-)

(letters[pass[i]] || 0) + 1

That:

  • Starts with pass[i] which gets the letter for index i from pass (which appears to be a string)
  • Then tries to get the value for a property with that name from letters (letters[pass[i]]). It will either get a number that it's put there before or, if there is no property for that letter (yet), it'll get the value undefined.
  • It uses that value (a number or undefined) with (the value) || 0. The || operator works fairly specially in JavaScript: It evaluates its left-hand operand and, if that value is truthy, takes that value as its result; otherwise, it evaluates its right-hand operand and takes that value as its result. undefined is a falsy value, so undefined || 0 is 0. This is to handle the first time a letter is seen.
  • It adds 1 to the result it got from ||.

Basically, that's adding one to the value of the property for the letter on letters, allowing for never having seen that letter before via ||.

Then it stores the result back to the property.

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