JavaScript: Convert a boolean into an integer

From The Travis van der Font Wiki
Jump to: navigation, search

There are several ways to go about this. use the method which seems most readable.

Method 1:

+('test' === 'test') // 1
+('test' === 'demo') // 0

Method 2:

(('test' === 'test') === true ? 1 : 0) // 1
(('test' === 'demo') === true ? 1 : 0) // 0

Method 3:

(('test' === 'test') * 1) // 1
(('test' === 'demo') * 1) // 0

Method 4:

(('test' === 'test') & 1) // 1
(('test' === 'demo') & 1) // 0

Method 5:

(('test' === 'test') | 0) // 1
(('test' === 'demo') | 0) // 0

Method 6:

Number('test' === 'test') // 1
Number('test' === 'demo') // 0