What does the && operator mean between strings?

38

I found in a minted bootstrap file, the following:

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

The && operator appears to be applied between two strings.

What does this mean?

    
asked by anonymous 14.02.2014 / 16:46

1 answer

31

Meaning of the & amp; in Javascript

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

In the javascript, this:

valor1 && valor2

means exactly the following:

(valor1 ? valor2 : valor1)

It turns out that in the example above, the operator that comes before ? is handled by the javascript in a logical way, that is, it tries to convert valor1 to 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, ie if the second and third methods were methods, only one of them would be called:

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

Only one of the alerts will be called.

Query expression analysis

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

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

If e is logically evaluated as true, then the result is the replace, otherwise it is e itself. In this case, since% is expected to be a string, we can say the only way to evaluate e as true, is when the same is not null, undefined, nor an empty string.

Replace is likely to extract the hash from a URL:

  • by empty string

Example: " link " will make "#hash"

So what the original programmer probably wanted to say is:

  • If e is a string with content, get its hash-tag, otherwise leave e the way it is: empty, null or undefined.

Reference

link

    
14.02.2014 / 16:46