Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is !0 and !1 something more than a shorthand for true/false? [duplicate]

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?

like image 810
Christofer Eliasson Avatar asked Sep 01 '12 21:09

Christofer Eliasson


People also ask

How do you check if a value is greater than 0 in JavaScript?

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!

What is use of in JS?

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.

What is init in JavaScript?

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.


1 Answers

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 :-).

like image 131
João Silva Avatar answered Oct 14 '22 07:10

João Silva