How does the mini-code finder work?

Asked

Viewed 99 times

6

I am asking this because I was minificar a JS and he gave me a code that I did not understand very well...

My original code:

$('input').each(function(a,b){if(b.value == "U"){$('.variacao-sku').remove()}});

What he gave me:

$("input").each(function(a,e){"U"==e.value&&$(".variacao-sku").remove()});

The code worked until, but did not understand, he did not use if, checked if the string "U" is equal to e.value and used the operator && and removed the item with remove. What’s the meaning of that && there?

2 answers

11


This technique is called short-circuiting in logical expressions.

When you have a logical expression A && B, the result will be true if, and only if, both operands are true, or false otherwise. Thus, the interpreter will first evaluate the value of A, if it is considered a false value, it will not need to evaluate B, returning A; if A is evaluated as true, will be returned the value of B, for if B is false, the result should be false and if true should be true.

Therefore, in the expression:

"U" == e.value && $(".variacao-sku").remove()

The interpreter will first evaluate "U" == e.value, if true, will evaluate (execute) $(".variacao-sku").remove(), producing the same result as the original code:

if (b.value == "U") {
    $('.variacao-sku').remove()
}

Which is to execute the remove() only when b.value for "U".

  • 1

    Wow, that’s very, very interesting. Thank you for that. (no irony)

2

Your initial code is already more or less minimized, so the Minify did not change much (formatting and names).

Now for the validation:

The && discontinues the validation as soon as they find something at odds and does not continue to check the rest.

Example:

Se (1 == 2 && a == b) {}

In that case, at runtime, the instruction a == b will never run, because as soon as the compiler sees that 1 is not equal to 2, it will leave the if and will not even worry about what it has ahead.

Now if you do:

Se (1 == 2 & a == b) {}

In this case, at runtime, the two instructions will be checked and only then the computer will decide what should be done.

It is even recommended to use always && (or ||) to avoid unnecessary processing.

Browser other questions tagged

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