0

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!

codebwoy
  • 145
  • 3
  • 20
  • This is a [bitwise or](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#.7c_%28Bitwise_OR%29). You can find a more detailed explanation of this here: [What does the “|” (single pipe) do in JavaScript?](https://stackoverflow.com/questions/6194950/what-does-the-single-pipe-do-in-javascript) – Gianluca Cesari Dec 12 '17 at 19:53

2 Answers2

2

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));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    It doesn't always round down. It rounds toward zero. Try `-5.5 | 0`, which gives `-5`. –  Dec 12 '17 at 19:51
1

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.

Jelmer Jellema
  • 1,072
  • 10
  • 16