Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning an array to myBool when the value is false can be tricky.

const boolFromBody = false;
const myBool = boolFromBody || [true, false];
console.log(myBool)

I found a workaround by checking only for null values:

const boolFromBody = null;
let otherBool = boolFromBody;
if (boolFromBody === null) {
  otherBool = [true, false]
}
console.log(otherBool);

Is there a more elegant way to handle this scenario in JavaScript?

Answer №1

Understanding the Nullish coalescing operator.

In programming, the nullish coalescing operator checks if a variable is either null or undefined and assigns it to a default value if it meets that condition. It's important to note that values like 0 or false are not considered as nullish and will not trigger the default assignment.

The nullish coalescing operator ?? functions similarly to the || logical OR operator but with a key difference in how it evaluates conditions. Instead of relying on "truthy" values, it specifically targets values that are strictly equal to either null or undefined.

let x = null;

let y = x ?? "default";

console.log(y);

Let's explore an example using false:

let x = false;

let y = x ?? "default";

console.log(y);

Answer №2

If you're looking for a solution that ensures backwards compatibility without using the nullish coalescing operator, here's an alternative option. This approach, although more verbose, is supported by even IE6 and can be more convenient and accessible if you're not using Babel. Hope this helps!

const boolFromBody = null;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = undefined;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

const boolFromBody = false;
let myBool = boolFromBody == (null || undefined) && [true, false];
console.log(myBool);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js: Optimize Webpack bundle by excluding core-js

Below is the content of my vue.config.js file: module.exports = { configureWebpack: { externals: { "vue": "Vue", "core-js": "core-js", }, }, }; By using this configuration, I have successfully excluded the vue.js (Vue) library and ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

Generating random numbers within specified character limits using Javascript and Selenium

Just starting to learn javascript - I am working on creating random user IDs for my selenium test scenarios. The line of code I am using for the value is as follows: javascript{Math.floor(Math.random()*11111)} However, there is a specific field that need ...

Loading a .css file in advance using NextJS

We have integrated NextJS and Material-UI into our website, but we are facing an issue with FOUC (Flash of Unstyled Content) upon page loading. After some investigation, I discovered that the JS files are loading faster than the CSS file, causing the probl ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

The Art of Capturing Sound: Unleashing

Currently, I am attempting to capture video via html5 .getUserMedia and play it back without needing to upload it to a server. Despite following numerous tutorials, I have only been successful on Chrome by utilizing canvas to draw the webp image and then c ...

Tips for clicking a .class a random number of times:

Could someone help me figure out how to click a random number of times on the element with class name .CLASS when a key is pressed? I think I need to incorporate the Math.floor(Math.random()) function, but I'm not sure how to do it in my existing code ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

Component does not display dynamically created DOM elements

I have a function that creates dynamic DOM elements like this: const arrMarkup = []; const getMarkup = () => { if (true) { arrMarkup.push( <Accordion expanded={expanded === cust.name} onChange={handleChange(cust.name)}> ...

Maintain the expanded menu even after selecting a sub-item using jQuery

After conducting a thorough search, I was unable to find exactly what I needed. I have successfully implemented cookies on my menu so that when the page is reloaded, it remembers which menus were open. However, I noticed that clicking on a sub-item of Hy ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

Manipulating divs by positioning them at the top, left, right, bottom, and center to occupy the entire visible portion of the page

Many suggest avoiding the use of table layouts and opting for divs and CSS instead, which I am happy to embrace. Please forgive me for asking a basic question. I am looking to create a layout where the center content stretches out to cover the entire visi ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Adjusting height in Google Maps to fill the remaining space

Currently, I am developing a map application where I want the Google Maps DIV to occupy the remaining height under the header. Here is the code snippet: <!DOCTYPE html> <head> <title>Map Application</title> <style type ...

Navigating the intricacies of retrieving network errors within an AngularJS application requires a deep

I've encountered the following code snippet in abcd.js: $http({url: 'some url' , method: 'POST', data: , headers: {} }).then(function(response)) { ............. }, function error(response) { .............. }) When an error occurs ...

How can I adjust the width of a handle/thumb for NoUiSlider?

Looking to adjust the width of a NoUiSlider using CSS: .noUi-horizontal .noUi-handle { width:8px; height:25px; left: 0px; top: -8px; border: 0px solid #000000; border-radius: 0px; background: #000; cursor: default; box- ...

Refine your search with a JSON object description in expressJS and UnderscoreJS

[ { "id": 1, "description": "Empty the garbage bin", "completed": false }, { "id": 2, "description": "Dine out for dinner", "completed": false }, { "id": 3, "description": "Exercise at the fitness center", "com ...

Exploring the functionality of JSON within the jQuery each method

I'm currently struggling with my JavaScript skills and attempting to piece this project together using various tutorials. However, I can't seem to identify why it's not functioning properly. Could someone guide me on how to properly pass an ...

Unregistering an event with AngularJS

Exploring the functions of a controller named MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... ...