Coding Explanation: variable set with bitwise OR character in JavaScript

285 views Asked by At

I ran across some JS today that I didn't understand, and googling bitwise operations isn't really helping me out. Can someone explain the below?

     function createExcerpt(string, maxLength) {
          // Set a default value of maxLength of 110
          maxLength = maxLength | 110;
          ...

Although I read that the pipe character is a bitwise OR, I'm at a loss as to what is happening in the above. If I should post more of the function for context, just let me know.

2

There are 2 answers

0
paxdiablo On BEST ANSWER

Given the presence of that comment in the preceding line, this looks to be a simple typo.

Setting of defaults would generally be done with the logical or operator, ||, so it's almost certainly meant to be:

maxLength = maxLength || 110;

However, this is actually a bad idea since, if maxLength has been set to a falsey value (like zero), it will be replaced with the default. That may be what you want but it's by no means clear.

I would probably opt for the slightly more verbose but definitely clearer:

if (maxLength === undefined) { maxLength = 110; }

It still fits on one line and the intent is very specific.

And a better way, assuming you have ES6 available to you, would be to use default arguments baked directly into the function call:

function createExcerpt(string, maxLength = 110) {
    ...
}
0
Paul On

This is definitely a mistake. Logical OR (||) is used as a null coalescing operator. Bitwise ORing will not have the effect indicated in the comment. You can test it yourself by running it through some tests.

110 | 110 = 110
120 | 110 = 126
90 | 110 = 126
null | 110 = 110
50 | 110 = 126
200 | 110 = 238

You can see from just a few examples that the result will be pretty counter-intuitive to someone passing a "maxlength" argument.