Javascript value as boolean

# 2 Ways to Convert Values to Boolean in JavaScript

In JavaScript, there are 6 falsy values. If you convert any of these to a boolean , it will return false .

false undefined null NaN 0 "" (empty string) 

Anything not on the falsy list, will return true 👍

More information on this, you can read my Code Notes on Falsy Values

# Examples

Applying !! on falsy values

!!false; // false !!undefined; // false !!null; // false !!NaN; // false !!0; // false !!''; // false 

Applying Boolean on falsy values

Boolean(false); // false Boolean(undefined); // false Boolean(null); // false Boolean(NaN); // false Boolean(0); // false Boolean(''); // false 

# How the !! works

The first ! coerce the value to a boolean and inverse it. In this case, !value will return false . So to reverse it back to true , we put another ! on it. Hence the double use !! .

const value = 'string'; !value; // false !!value; // true 

# Watch out for ‘false’

const value = 'false'; !!value; // true Boolean(value); // true 

Notice the «false» is between quotes ‘ . Although it says false , it’s actually a string. I know most of you won’t fall for this, but if you’re like me, you might just want to be alert for these funny mind tricks people might be playing on you 😂

Читайте также:  Python перевод типов данных

# Community Input

: I enjoy filtering falsy values from arrays like this: myArray.filter(Boolean)

: I like !+! just to be cool and throw people off 😛

# Speed Test

Here’s a test that I found:

Looks like the !! is a bit faster than Boolean

# Which one to use?

I’ve gotten a lot of comments on this post. Some people prefer the Boolean because it’s more explicit.

But, Kyle Simpson from You Don’t Know JS, mentioned that both are explicit.

// better (works explicitly): if (!!a)  > // also great (works explicitly): if (Boolean(a))  > 

I don’t think I have a great answer for you. You will know your team way better I do. I will continue to use !! in my own personal projects, cause it’s less typing and I understand this syntax. But if I was on a team, I might choose Boolean because I think most developers would understand that better. No matter which one you choose, the most important thing is to be consistent. Don’t flip-flop between the two in your code base. Pick one and stick with it 💪

Aludding to an awesome comment I got:

@patrick_developer: I say one should understand both just in case one is presented with different code bases that use each one. Knowledge is power.

In other words, one is not better than the other. This one I’d argue is more of a preference. So you can’t go wrong. But don’t deprive yourself from understanding both. Like Patrick said, «Knowledge is power» 💪

# Avoid new Boolean

Use Primitives instead of Object Types

var str = 'str'; // Avoid typeof new Boolean(str); // object // Preferred typeof Boolean(str); // boolean typeof !!str; // boolean 

CJ J.: It’s worth noting that new Boolean isn’t a boolean but rather an instance of Boolean. Primitives are cheaper and should be preferred over the object type.

CJ J.: new Boolean(str) returns an object type. Boolean(str) just returns a primitive boolean. I would suspect Boolean(str) is faster then !!str because it’s only one operation, but it’s also entirely possible that browsers implement an optimization such that when they see !! they know to directly cast the argument to a boolean primitive (instead of actually doing NOT() twice in a row).

CJ J.: Primitives are cheap because they’re immutable so you can share references and not have to hold any state on the instance. It’s just true or false . But new Boolean(str) is an object. It has it’s own unique memory address and it can hold internal state that is unique to it. This means it can’t just hold a reference to an immutable singleton instance. Every call to new Boolean(str) instantiates an entire new Boolean() object.

# Remove empty strings with Boolean Constructor

CJ J.: This is the classic example. If you get a list of string values separated by commas and you want to filter out the empty strings, you can pass the Boolean constructor function into Array.prototype.filter and it will automatically strip out the zero-length strings leaving an array of only valid strings.

var str = 'some,list,,of,values'; var arr = str.split(','); arr; // [ 'some', 'list', '', 'of', 'values' ] arr.filter(Boolean); // [ 'some', 'list', 'of', 'values' ] 

Источник

Boolean

The Boolean object represents a truth value: true or false .

Description

Boolean primitives and Boolean objects

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

Any object, including a Boolean object whose value is false , evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true :

const x = new Boolean(false); if (x)  // this code is executed > 

This behavior does not apply to Boolean primitives. For example, the condition in the following if statement evaluates to false :

const x = false; if (x)  // this code is not executed > 

Do not use the Boolean() constructor with new to convert a non-boolean value to a boolean value — use Boolean as a function or a double NOT instead:

const good = Boolean(expression); // use this const good2 = !!expression; // or this const bad = new Boolean(expression); // don't use this! 

If you specify any object, including a Boolean object whose value is false , as the initial value of a Boolean object, the new Boolean object has a value of true .

const myFalse = new Boolean(false); // initial value of false const g = Boolean(myFalse); // initial value of true const myString = new String("Hello"); // string object const s = Boolean(myString); // initial value of true 

Warning: You should rarely find yourself using Boolean as a constructor.

Boolean coercion

Many built-in operations that expect booleans first coerce their arguments to booleans. The operation can be summarized as follows:

  • Booleans are returned as-is.
  • undefined turns into false .
  • null turns into false .
  • 0 , -0 , and NaN turn into false ; other numbers turn into true .
  • 0n turns into false ; other BigInts turn into true .
  • The empty string «» turns into false ; other strings turn into true .
  • Symbols turn into true .
  • All objects become true .

Note: A legacy behavior makes document.all return false when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.

Note: Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives.

In other words, there are only a handful of values that get coerced to false — these are called falsy values. All other values are called truthy values. A value’s truthiness is important when used with logical operators, conditional statements, or any boolean context.

There are two ways to achieve the same effect in JavaScript.

  • Double NOT: !!x negates x twice, which converts x to a boolean using the same algorithm as above.
  • The Boolean() function: Boolean(x) uses the same algorithm as above to convert x .

Note that truthiness is not the same as being loosely equal to true or false .

if ([])  console.log("[] is truthy"); > if ([] == false)  console.log("[] == false"); > // [] is truthy // [] == false 
[] is truthy, but it’s also loosely equal to false . It’s truthy, because all objects are truthy. However, when comparing with false , which is a primitive, [] is also converted to a primitive, which is «» via Array.prototype.toString() . Comparing strings and booleans results in both being converted to numbers, and they both become 0 , so [] == false is true . In general, falsiness and == false differ in the following cases:

  • NaN , undefined , and null are falsy but not loosely equal to false .
  • «0» (and other string literals that are not «» but get coerced to 0) is truthy but loosely equal to false .
  • Objects are always truthy, but their primitive representation may be loosely equal to false .

Truthy values are even more unlikely to be loosely equal to true . All values are either truthy or falsy, but most values are loosely equal to neither true nor false .

Constructor

Creates a new Boolean object.

Instance properties

These properties are defined on Boolean.prototype and shared by all Boolean instances.

The constructor function that created the instance object. For Boolean instances, the initial value is the Boolean constructor.

Instance methods

Returns a string of either true or false depending upon the value of the object. Overrides the Object.prototype.toString() method.

Returns the primitive value of the Boolean object. Overrides the Object.prototype.valueOf() method.

Examples

Creating Boolean objects with an initial value of false

const bNoParam = new Boolean(); const bZero = new Boolean(0); const bNull = new Boolean(null); const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); 

Creating Boolean objects with an initial value of true

const btrue = new Boolean(true); const btrueString = new Boolean("true"); const bfalseString = new Boolean("false"); const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean(>); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 25, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Convert a Value to a Boolean in JavaScript

Natalie Pina

Natalie Pina

How to Convert a Value to a Boolean in JavaScript

A boolean is a primitive value that represents either true or false. In Boolean contexts, JavaScript utilizes type casting to convert values to true/false. There are implicit and explicit methods to convert values into their boolean counterparts.

This article provides an overview of truthy and falsy values and how to convert values into booleans in JavaScript.

JavaScript Truthy and Falsy Values Cheatsheet

Boolean(false); // false Boolean(undefined); // false Boolean(null); // false Boolean(''); // false Boolean(NaN); // false Boolean(0); // false Boolean(-0); // false Boolean(0n); // false Boolean(true); // true Boolean('hi'); // true Boolean(1); // true Boolean([]); // true Boolean([0]); // true Boolean([1]); // true Boolean(<>); // true Boolean(< a: 1 >); // true

It’s best to start by first understanding which values are interpreted as truthy or falsy by JavaScript. It’s also important to understand implicit coercion compared to explicit coercion.

Implicit coercion is initiated by the JavaScript engine and happens automatically. Explicit coercion is performed by manually converting values, and JavaScript provides built in methods to handle this.

The !! Operator

You may already be familiar with ! as the logical NOT operator. When using two in succession ( !! ), the first ! coerces the value to a boolean and inverts it. For example !true would result in false. The second ! reverses the previous inverted value, resulting in the true boolean value.

This is generally a preferred method, as it has better performance. A potential con to this method is a loss in readability, mainly if other developers are unfamiliar with how this operator works.

const value = "truthy string" !!value // true

Here is an example breaking this down into steps:

const value = "truthy string"; !value; // false !!value; // true

Below is a list of example output with the !! operator.

// Falsy Values !!'' // false !!false // false !!null // false !!undefined // false !!0 // false !!NaN // false // Truthy Values !![] // true !!"false" // true !!true // true !!1 // true !!<> // true

The Boolean() Function

Boolean() is a global function that converts the value it’s passed into a boolean.

You shouldn’t use this with the new keyword ( new Boolean ) as this creates an instance of a Boolean that has a type of object. Below is an example of the correct use of this function.

const value = "truthy string" Boolean(value) // true

TL;DR

There are two methods to cast a value to a boolean in JavaScript.

1. !!

2. Boolean()

const finalThoughts = "I really enjoyed writing this article. Thanks for reading!" !!finalThoughts // true Boolean(finalThoughts) // true 

Источник

Оцените статью