Can someone please clarify why the countOnlineUsers variable does not retain its value in memory when console logging?

I'm attempting to iterate through a bi-dimensional object to count the number of users whose online status is set to true. However, when I try to log the countOnlineUsers variable using console.log(), the count doesn't persist and appears to reset each time the loop encounters a "new" user with an "online" property.

    let users = {
      Alan: {
        age: 27,
        online: false
      },
      Jeff: {
        age: 32,
        online: true
      },
      Sarah: {
        age: 48,
        online: false
      },
      Ryan: {
        age: 19,
        online: true
      },
      George: {
        age: 32,
        online: true
      }
    };
    
    function countOnline(obj) {
    
      for(let user in users) {

    if (!users.hasOwnProperty(user)) continue; // Initial check

      let obj = users[user];     
      for(let prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue; // Secondary check

          let countOnlineUsers = 0;
          if(obj[prop] === true) {            
            countOnlineUsers++;
          }
          console.log(prop + " = " + obj[prop]);
          console.log(countOnlineUsers);        
      }        
  

    }

    }
    
    console.log(countOnline(users));

Answer №1

On each loop iteration, you are consistently assigning the value of 0:

for(let user in users) {
    //...
    let countOnlineUsers = 0;
    //...
}

As you only change the value once within that iteration, it will always be either 0 or 1. To resolve this, initialize the value before the loop:

let countOnlineUsers = 0;
for(let user in users) {
    //...
}

This way, every loop iteration will adjust the same value (if the condition is met), instead of creating a new one each time.

(Please note there are nested loops, thus I made an educated guess on which one needed to increment the value.)

Your modified original code:

let users = {
      Alan: {
        age: 27,
        online: false
      },
      Jeff: {
        age: 32,
        online: true
      },
      Sarah: {
        age: 48,
        online: false
      },
      Ryan: {
        age: 19,
        online: true
      },
      George: {
        age: 32,
        online: true
      }
    };
    
    function countOnline(obj) {
    
      let countOnlineUsers = 0;
      for(let user in users) {

    if (!users.hasOwnProperty(user)) continue; //Initial check

      let obj = users[user];     
      for(let prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue; //Secondary check

          if(obj[prop] === true) {            
            countOnlineUsers++;
          }
          console.log(prop + " = " + obj[prop]);
          console.log(countOnlineUsers);        
      }        
  

    }

    }
    
    console.log(countOnline(users));

Answer №2

The reason for this issue is that the variable countOnlineUsers is defined inside the loop. It should be declared outside of it and then updated within the loop.

let users = {
      Alan: {
        age: 27,
        online: false
      },
      Jeff: {
        age: 32,
        online: true
      },
      Sarah: {
        age: 48,
        online: false
      },
      Ryan: {
        age: 19,
        online: true
      },
      George: {
        age: 32,
        online: true
      }
    };
    
    function countOnline(obj) {
      let countOnlineUsers = 0;
      for(let user in users) {

    if (!users.hasOwnProperty(user)) continue; //First check

      let obj = users[user];     
      
      for(let prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue; //Second check

          
          if(obj[prop] === true) {            
            countOnlineUsers++;
          }
          console.log(prop + " = " + obj[prop]);
          console.log(countOnlineUsers);        
      }        
  

    }

    }
    
    console.log(countOnline(users));

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

Issue with displaying message (Snackbar) in React using Material UI

After creating a custom Alert component, I noticed that adding Snackbar causes it not to display. The only part I changed is: AlertPopup: const AlertPopup = () => { const { text, type } = useAlert(); if (text && type) { return ( ...

The renderer cannot process multiple calls simultaneously

Over the past couple of months, I've delved into the world of three.js and JavaScript, focusing on shaders and even exploring procedural planet generation. The challenge of working with non-euclidean geometries like spherical shapes intrigues me, espe ...

There was a problem accessing the website

Recently, I tried to access a web page from the server using command prompt by following a tutorial on YouTube. However, I encountered an error message while trying to open the page. The specific error is displayed below. Can someone please guide me on res ...

In NodeJS, inserting array objects into GraphQL is prohibited

Encountering an issue while trying to insert array objects. Below is the code snippet: GraphQL Schema type Member { _id: ID! member_id: Int! first_name: String! last_name: String username: String date: String } input MemberInput { member_i ...

Something seems off with the way WebGL is rendering shapes

I am encountering an issue with my code that is supposed to display parsed radar data on a Mapbox GL JS map using WebGL. While I have successfully managed to render the general radar shape on the map, the rendering is incorrect. Instead of drawing rectangl ...

Mastering the art of utilizing drag and drop features for both columns and rows in a React Table within ReactJS

I have managed to create a React Table with columns and rows, but now I'm looking to incorporate drag and drop functionality for both. Does anyone know how I can achieve this? Feel free to check out my CodeSandbox Sample here - https://codesandbox.io ...

Creating a nested structure for dynamic data in Angular

I'm facing an issue while attempting to create a flexible structure dynamically. I possess the following string. "Client->Plant->Route->Turn" I have an array of devices with values for each field in the string along with extra information, ...

Angular FirebaseError Permissions Not Found or Inadequate

I'm encountering an issue with permissions while trying to enable users to read and write their own data using Firestore. Despite having set up the rules in my Firestore database, I keep receiving an insufficient permissions error. The rules I have i ...

Move my site content to the appropriate location

I am working on a single-paged website built with Jquery and HTML. The main content is housed within a div called #site-content, which has a width of 4400px. Each "page" is positioned within this div, with the first page starting at left: 0px, the second a ...

Tips for executing multiple asynchronous calls simultaneously within a nested map function

I am facing a scenario where I have an object with nested arrays of objects which in turn contain another set of nested arrays. To validate these structures, I have an asynchronous function that needs to be executed concurrently while awaiting the results ...

Issues with AJAX causing MYSQL to get NULL data inserted

My HTML code collects latitude and longitude coordinates and sends them to a PHP script using AJAX. However, the issue is that the AJAX request inserts NULL values into the database table. It seems to be inserting "0.000000" for both Latitude and Longitude ...

I'm encountering a CastError while attempting to delete data in mongodb using Id

Encountered an issue while attempting to delete a MongoDB entry using the 'findByIdAndRemove' function in Mongoose. Specifically, it is throwing a 'Cast to ObjectId failed for value error'. Delete Service routes.delete('/:id' ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js t ...

Fuzzy Background to Enhance Your Bootstrap 5 Offcanvas Navigation Menu

Currently utilizing Bootstrap v5.2, I am endeavoring to replicate the image displayed in the link below: Blurry Sidebar Backdrop As per the MDN Documentation, backdrop-filter is intended for blurring the background of an element. .offcanvas-backdrop { ...

Can you provide instructions on how to utilize JavaScript in order to write to a separate webpage?

I need help with a JavaScript function that is supposed to take user input from one web page and write it to another existing web page within the same domain. The function iterates through a for loop correctly and builds the necessary information, but it ...

Employing buttons and state to eliminate an item from a roster

My list is generated using the following code: return (this.state.limit).fill().map((_,index) => { return ( <div key={`${index}`}> Item </div> ) ) I'm wondering how I can implement a button that allows me to remove a specific ...

Bringing in a standard library to a Vue single-page application

Struggling to grasp what should be a straightforward task, I'm open to the idea that my current approach may not be the best way forward. Currently, we are updating our processes and refining some of the functions within a .js file that houses numerou ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Choose between using Paypal or Google Checkout for your shopping cart - unfortunately, both options cannot be used

My dilemma is that I currently have a functional shopping cart that is only coded for either Paypal or Google Checkout, not both. Here is a demo of the shopping cart set up for Paypal checkout: The javascript code used in the demo can be found here: Loo ...

Storing image using mongoose

Among the numerous existing discussions on this subject, I have yet to find a solution that works for me. I am using angular.js along with the code example from to extract images from the client successfully. Now, moving on to the node/mongodb aspect, he ...