codebwoy
codebwoy

Reputation: 145

Not Understanding a Portion of a Particular Method to Solve Repeat String JavaScript

while trying to solve a "repeat a string exercise", I did some research and came across the following link: https://www.w3resource.com/javascript-exercises/javascript-string-exercise-21.php In that link, the code below is presented as a method for repeating a string. However, I have a question about a line of code within that method.

function repeat_string(string, count) 
  {
    if ((string == null) || (count < 0) || (count === Infinity) || (count == null))
      {
        return('Error in string or count.');
      }
        count = count | 0; // Floor count.
    return new Array(count + 1).join(string);
  }

console.log(repeat_string('a', 4.6));
console.log(repeat_string('a'));
console.log(repeat_string('a', -2));
console.log(repeat_string('a', Infinity));

In the above code, I do not understand what this line of code is saying:

count = count | 0; // Floor count.

does count = count | 0; // Floor count. mean count is equal to zero after the floor count?

Thanks for your help!

Upvotes: 0

Views: 41

Answers (2)

Jelmer Jellema
Jelmer Jellema

Reputation: 1116

count | 0 is a bitwise or. As a side effect, it will make count an integer. So it's sort of equivalent to Math.floor(count).

Note As @amy points out in a comment below, this construct rounds towards 0. That is: it just removes everything after the decimal point.

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191976

The | symbol is bitwise or operation. Using | 0 with a positive integer rounds the number down to nearest integer, for example 5.6 | 0 -> 5.

Note: | 0 rounds the number towards 0, so it's equal to Math#ceil when the number is negative, for example -5.6 | 0 -> -5.

Example:

var a = 5.6;

console.log(Math.floor(a) === (a | 0));

Upvotes: 2

Related Questions