Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!