What is the significance of the double exclamation mark operator in determining the truthiness or falsiness of an object's values?

Trying to determine the truthiness or falsiness of an object is proving to be a challenge for me. If an object contains all truthy values, I want one outcome; if it contains falsy values such as 0, an empty string, or undefined, I want a different outcome. However, my current approach always executes the first part of the if statement. Am I missing something here?

 class Truthy {
  a: string;
  b: number;
  c: object;

  constructor() {
    this.a = 'a';
    this.b = 1;
    this.c = {};
  }
}

 class Falsely {
  a: string;
  b: number;
  c: object;

  constructor() {
    this.a = '';
    this.b = 0;
    this.c = undefined;
  }
}

  const truthy = new Truthy()
  const falsely = new Falsely()

  if (!!truthy) {
    // do something 
  } else {
    // do something else 
  }

  if (!!falsely) {
    // do something 
  } else {
    // do something else 
  }

Answer №1

To determine if every property in an object is truthy, create a function that checks each property for truthiness and combines the results one by one.

  1. Include the object as a parameter (or reference 'this' if it's a class method)
  2. Retrieve all keys from the object
  3. Initialize a boolean variable
  4. Iterate through and test each property
  5. Return the final result

Since this function returns a boolean, you can use it within an if statement as needed.

function checkAllTruthyProperties(obj){
    const keys = Object.keys(obj);
    let allTruthy = true;

    for(let k=0; k<keys.length;k++){
        console.log(`Value: ${obj[keys[k]]} Boolean: ${!!obj[keys[k]]}`);
        allTruthy = allTruthy && !!obj[keys[k]];
    }

    return allTruthy;

}

let testYes = {
    a:"hello",
    b:5,
    c: true
}

let testNo = {
    a: "hello",
    b: 5,
    c: undefined
}

console.log(`Returns true: ${checkAllTruthyProperties(testYes)}`);
console.log(`Returns false: ${checkAllTruthyProperties(testNo)}`);

Answer №2

As per the recommendation of @MathHype, it is advisable to always verify your properties for best practices.

Furthermore, I have included additional conditions to ensure that an object A contains object B and you need to confirm whether object B's properties have a value or not.

You can achieve this by adding additional recursion for validation.

var checkObjectTruthiness = function (objectValue, isZeroPresent=false) {
  if (isZeroPresent && objectValue === 0) {
    return true;
  }
  if (!objectValue) {
    return false;
  }
  if (typeof objectValue === "string" || typeof objectValue === "number") {
    console.log(objectValue);
    if (isZeroPresent && objectValue === 0) {
        return true;
    }
    return !!objectValue;
  }
  else {
    if (Object.entries(objectValue).length) {
        var objectCheck = Object.entries(objectValue).map(function (x) {
            return checkObjectTruthiness(x[1], isZeroPresent);
        });
        return objectCheck.filter(function (x) { return x; }).length > 0;
    }
    else {
        return false;
    }
  }
};
console.log(checkPropertyTruthiness({a: "", b: [{b: {d: [], e: 0}, c: ""}]})) => false (isZeroPresent = false)
console.log(checkPropertyTruthiness({a: "", b: [{b: {d: [], e: 0}, c: ""}]})) => true (isZeroPresent = true)

For a demonstration, you can visit the codesandbox URL provided below: https://codesandbox.io/s/js-playground-forked-ze7xun

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

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

Customizing the "added to cart" message in Woocommerce and setting up a notification system for customers

My main focus is on customizing the Woocommerce notation system for a personalized shopping cart experience. After some research, I stumbled upon a very helpful user response which suggested modifying the message by adding the following code snippet to th ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Execute javascript code 1.6 seconds following the most recent key release

Is there a more efficient way to execute JS 1.6 after a keyup event, considering that the timer should reset if another keyup event occurs within 1.6 seconds? One possible approach could involve utilizing a flag variable like this: var waiting = false; $ ...

An easy way to pass props to a component using useNavigate in React Router

Is it possible to send props directly to a component in React? const goToProjectPage = useNavigate(); useEffect(()=>{ ..... goToProjectPage("/projectpage"); //send props here },[]); ...

How to Use Express.js to Stream Assets (JS/CSS/images) from Amazon S3

After successfully launching my Node.js blog on AppFog, I have the idea of utilizing an Amazon S3 bucket to host and stream all my assets such as javascript, stylesheets, and images. I am now wondering how I can configure Express.js to properly serve thes ...

What could be causing the continuous "Objects are not valid as a React child" error with my array of fetched data?

App.tsx import { useEffect, useState } from "react"; import "./App.css"; import UserInput from "./components/userInput"; import { ResultRow } from "./components/ResultRow"; // type TCachedValues = { // [keys: stri ...

What is the best way to incorporate a new field into an established JSON structure?

I have a JSON data set containing 10,000 unique records and I am looking to add another field with a distinct value to each record. What is the best way to achieve this? [ { _id: "5fffd08e62575323d40fca6f", wardName: "CIC", region: &quo ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Stop the execution of jQuery ready handlers

I am facing a situation where I need to prevent jQuery ready handlers from firing on the DOMContentReady event under certain conditions. These handlers are set up in different places like include files, plugins, and more. While one approach could involve s ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Exploring the use of national flag emojis in VS code

I've been attempting to use flag emojis as reactions on a Discord bot, but they just won't cooperate. Every time I try something like this > ':flag_jp:', I encounter the following error: Error: DiscordAPIError: Unknown Emoji EDIT ...

Tips for simulating a service in Angular unit tests?

My current service subscription is making a promise: getTaskData = async() { line 1 let response = this.getTaskSV.getTaskData().toPromise(); line 2 this.loading = false; } I attempted the following approach: it('should load getTaskData', ...

I'm having trouble understanding why this code is causing confusion for the user's selection during a specific part of the execution. I can't seem

In this memory game, event listeners respond to user input after a sequence of colored divs change color to appear illuminated. The expected behavior is that once the user clicks on the correct div in the right order, the sequence restarts with an additi ...

Encountered an issue when executing "npm start": The system does not recognize 'next' as a valid internal or external command

Encountering an issue when running the "npm start" command in the terminal while attempting to create a cryptocurrency tracker using React.js Displayed contents of my package.json file: { "name": "nextjs-crypto-api", "version ...

The relationship between two distinct servers: Express.js and Node.js

Working with the Express.js framework and Node.js, I am trying to make a request to an MS SQL database on the server side. My goal is to retrieve data (in JSON or array format) from the server and send it to the client side. I'm unsure about how to ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Problems arising from Jquery append functionality

When using the append method, my inner div is only attaching one WHEAT-COLORED-BOX, whereas when using appendTo, my inner div attaches all the required number of WHEAT-COLORED-BOXES. Therefore, in this case, appendTo gives the correct result while append f ...

Unspecified outcome of Ajax array as a choice in Select

I'm fairly new to working with AJAX / JSON and I'm having trouble figuring out how to parse an AJAX array response into a <select> dropdown. Despite going through several online tutorials and attempting different approaches to return the r ...