Boolean Conversion in JavaScript // Boolean(value) VS !!value

preview_player
Показать описание
There are two key ways people convert truthy and falsy values to true and false in #JavaScript. This tutorial discusses the two methods. We also present which one we recommend, so that it should be your default (with reasons) 🌹

🚥 Professional Courses

#basarat

0:00 The plan
0:22 The ways
1:27 The better way
4:06 Smash that like

👇 ❤️ Subscribe for MOORE ❤️ 👇

**Feel Free To Read This Lot**

I'm Basarat, and I love helping developers. More about me:

Microsoft MVP for TypeScript
200K contributions on Stackoverflow. Top Contributor for TypeScript.
Book Author : Beginning NodeJS
Book Author : TypeScript Deep Dive
Creator of multiple hot ✨ed Github Open Source projects

Рекомендации по теме
Комментарии
Автор

Great little video. I had always wondered this, but preferred the double bangs!! 🙂

IainSimmons
Автор

In this case I'd say that it's better to use val !== null over implicit casting to boolean value because this check is the way more explicit and clearly shows your intension of this check, especially if a value might be a string of a number. Explicit is better than implicit.

As for the topic I'd say that you need to use any of this (I prefer Boolean() since it's more explicit and a minifier will replace it with !! anyway) only in case of converting a result to boolean, i.e. when the result of an expression should be a boolean, e.g. when you return something from a function or declare a variable.

timocov
Автор

Nice video. What I'd personally add is a use case that Boolean looks better in, that is in array.prototype functions such as array.prototype.filter.
values.filter(v=>!!v) vs values.filter(Boolean)

danieljanjanocha
Автор

This seems like a bug in the TypeScript interpreter. Why does TS treat them differently if they are JS runtime equivalent?

avi
Автор

I think the second use case of `!!` is redundant, as neither `!!` or `Boolean()` is required in this case. It seems that JS/TS automatically cast a value to its truthy form when used as a condition in boolean logic.

e.g. `valueFromNetwork && use(valueFromNetwork)` is valid, providing both the expected runtime result & accurate type linting.

ficoprieto
join shbcf.ru