Reading through some code, I came across the use of !0
and !1
. I realize that these are shorter ways of writing true
and false
.
!0 === true
!1 === false
This of course save a few bytes, but is there some other reason to use it?
Is there a name for this way of writing it?
An alternative and more common approach is to use the less than or equals to sign. To check if a number is not greater than 0 , check if the number is less than or equal to 0 , e.g. num <= 0 . If the condition returns true , the number is not greater than 0 . Copied!
The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.
init is just shorthand for initiate. Typically it is used to create a "new Object()". Like the init() function in jQuery returns a new jQuery object.
Most JavaScript minification tools, like UglifyJS, generate that code because it's shorter and semantically equivalent. For example, given:
var x = true;
if (x) {
alert(x);
}
UglifyJS will generate var x=!0;x&&alert(x)
.
Usually, you don't need to write code using that style; let the minifiers do their work :-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With