Table of Contents
JavaScript is a loosely typed language, meaning that variables can be created and changed to any type.
Because of this, JavaScript offers you two ways to compare two values to each other, strict and non-strict equality.
The way non-strict equality works is that JavaScript will attempt to convert both values to the same type before comparing them, in a process called type coercion.
Because of type coercion, every single value in JavaScript will either be truthy or falsy.
In this post, we'll dive deeper into truthy values in JavaScript and how they work.
Truthy Values
As mentioned before, a truthy value is a value that resolves to true
when type coerced.
Every single value in JavaScript is truthy except for the following values:
0
false
null
undefined
NaN
''
0n
If your value is anything other than these 7 values, it is truthy.
Checking for Truthy Values
If you're not sure if your value is truthy or not, an easy way to check if the value is truthy is to use the !!
operator.
The reason this works is that JavaScript will convert the value to a boolean when you use the !
operator, then convert it back to the correct boolean value with the second !
.
Here's how to check if a value is truthy:
JAVASCRIPTconst isTruthy = !!value;
Conclusion
In this post, we learned about what truthy values are in JavaScript and how to check if a value is truthy.
Most values are truthy, with an exception of those 7 values above.
Thanks for reading!
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js