How does the code minifier work?

7

I'm asking this because I went to minify a JS and it gave me a code that I did not quite understand ...

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 fine, but I did not understand, it did not use if, it checked that the string "U" equals e.value and used the & amp; and removed the item with the remove. What is the meaning of that && ali?

    
asked by anonymous 24.07.2018 / 13:21

2 answers

9

This technique is called a short circuit in logical expressions.

When you have a logical expression A && B , the result will be true if, and only if, both 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 have to evaluate B , returning A ; if A is evaluated as true, the value of B will be returned, because if B is false, the result should be false and true if it should be true.

So, in the expression:

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

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

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

What is to execute remove() only when b.value is "U" .

    
24.07.2018 / 13:30
4

Your initial code is more or less minimized, so minify has not changed much (formatting and names).

Now for validation:

&& stops validation as soon as it finds something in disagreement and does not continue to check the rest.

Example:

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

In this case runtime , the a == b statement will never be executed, because as soon as the compiler sees that 1 does not equal 2, it will exit if and not even worry about what lies ahead.

Now if you do:

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

In this case, at runtime, both statements will be checked and only then will the computer decide what to do.

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

    
24.07.2018 / 13:32