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.
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: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:
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: