What does the && in between strings mean?

Asked

Viewed 1,300 times

38

I found in a minified bootstrap file, the following:

e=e&&e.replace(/.*(?=#[^\s]*$)/,"")

The operator && seems to be being applied between two strings.

What does that mean?

1 answer

32


Meaning of the && operator in Javascript

The operator && javascript is not a simple logical operator, as usual deduce by observing the use of the same operator in other languages.

In javascript, this:

valor1 && valor2

means exactly the following:

(valor1 ? valor2 : valor1)

It turns out, in the example above, the operator who comes before the ? is treated by javascript logically, that is, it tries to convert valor1 for true or false.

If true, then the second operand is evaluated and returned, if false, then the third operand is evaluated and returned. The opposite operand, which is evaluated, will not be evaluated, that is, if the second and third methods were methods, only one of them would be called:

logico ? alert("TRUE") : alert("FALSE");

Only one of the Alert will be called.

Analysis of the question expression

So let’s see what happens when we replace the original expression of question, using the alternative syntax of the ternary operator:

e = e ? e.replace(/.*(?=#[^\s]*$)/, "") : e

If e is evaluated logically as true, so the result is the replace, otherwise it is itself e. In case, how is it expected that e be it a string, we can say the only way to evaluate e as true, is when it is not null, Undefined, nor an empty string.

replace probably serves to extract the hash from a URL:

  • replace anything that is followed by: '#' + string without spaces

  • empty string

Example: "http://www.xpto.com/abc?123#hash" will make "#hash"

So, what the original programmer probably meant is:

  • if e for a string with content, take her hash-tag, otherwise leave e the way it is: empty, null or Undefined.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Browser other questions tagged

You are not signed in. Login or sign up in order to post.