Array in Javascript reset to null after its second iteration

'''

const users = []

const addUser = ({ id, username, room }) => {
    // Clean the data
    username = username.trim().toLowerCase()
    room = room.trim().toLowerCase()

    // Validate the data
    if (!username || !room) {
        return {
            error: 'Username and room are required'
        }
    }
    // Check for existing user
    const existingUser = users.find((user) => {
        return user.username === username || user.room === room
    })

    // Validate username
    if (existingUser) {
        return {
            error: 'Username already exists!'
        }
    }

    // Store user
    const user = { id, username, room }
    users.push(user)
    return { user }
}

addUser({
    id: 03,
    username: 'rohan',
    room: 'playground'
})
console.log(users)

'''

If I execute this code in console, it will output [ { id: 3, username: 'rohan', room: 'playground' } ]

However, if I comment out the function call and print the array again, it appears to be empty.

'''

//addUser({
//    id: 03,
//    username: 'rohan',
//    room: 'playground'
//})
console.log(users)

'''

After the initial run, the object should be stored in the users array permanently. So why does the array appear empty when no value is added?

Answer №1

This unique demonstration showcases 2 distinct entities (userObjA and userObjB), along with an arrow function named addUser(...user). This function is designed to handle any number of input objects (thanks to the magical spread operator: ...), ultimately returning these objects encapsulated in an array called users.

Important: The utilization of const was deliberately avoided in this showcase -- opting for the more flexible and painless let for variable declarations and assignments.


Innovative Example

let userObjA = {
  id: 3,
  name: 'Rohan',
  room: 'Suite 42'
};

let userObjB = {
  id: 4,
  name: 'Dell',
  room: 'Single 601'
};

const addUser = (...user) => {
  let users = [];
  users.push(user);
  return users.flat();
};

console.log(addUser(userObjA, userObjB));

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

Instructions for ordering this jQuery script that executes ajax and should return a 'true' value

In my javascript for form validation, I have added a new layer that calls an external function to send an Ajax request with the form validation results. The goal is to receive an email indicating whether the user passed or failed the validation. While cal ...

Last month's display is currently unidentified

function calculateTime() { var Make_It_12_Hour = true; var currentTime = new Date(); var hour1 = currentTime.getHours() - 1; var hour2 = currentTime.getHours(); var hour3 = currentTime.getHours() + 1; var minutes = currentTime.getM ...

Unable to modify the default Nuxt favicon

Just getting started with Nuxt and attempting to update the default favicon for my project. I swapped out the favicon.png and favicon.ico files in my static directory, but unfortunately, it didn't take effect. Next, I tried replacing the favicon.png ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

Error encountered in Angular10: XHR request for POST failed due to browser blocking HTTP Request to a domain with a similar name

I am encountering an issue with my webpage that consists of a Django REST API and an Angular 10 Frontend SPA. Normally, I can successfully send GET, POST, PUT, and DELETE XHR Requests to my backend without any problems. However, there is a specific API End ...

Loading jQuery on an ajax request

The loader is working with the code now, but it is not replacing and calling the URL. The ajax url call should be placed within searchable. <button onclick="myFunction()">LOAD</button><br /><br /> <div class="spinner bar hide" ...

When a user inputs in the field, it automatically loses focus

An error is encountered in two scenarios: When the input includes an onChange event handler When the input is located within a component that is called on another page For instance: In Page1.js, we have: return <div> <Page2 /> </div ...

Retrieving JSON data from an API

As a beginner with Jquery JSON and API's, I am trying to work on hitting an API that returns city names in JSON format. I need to display these city names dynamically on my webpage in a list format. Can someone guide me through this process? If you w ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

Evaluating the Material ui Select element without relying on test identifiers

Currently, I am working with Material UI and react-testing-library to test a form. The form includes a Select component that is populated by an array of objects. import React, { useState } from 'react'; import { Select, MenuItem, FormControl, Inp ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

Issue with ng-true-value in AngularJS version 1.6.1 - not functioning as expected

Recently, I delved into AngularJS and followed an online tutorial that showcased how to utilize ng-true-value and ng-false-value. Here's the snippet: <!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis ...

Exploring the process of gathering information using Node.js' http.request

I am currently facing a challenge where I need to call a REST API URL in one method and then use the response from that call to form a subsequent query to another URL, let's say git, to fetch some information. Despite browsing through several examples ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

Disable the javascript link on small devices

I currently have a javascript link (Trustwave) on my desktop website theme that I need to deactivate when viewed on mobile devices: Located in footer.tpl: <div style="position:absolute; margin-left:100px; margin-top:50px"> <script type="text/j ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Prevent keypress from being detected while the confirm box is displayed

My website heavily relies on key events, and for certain actions, it triggers a bootbox confirm box. This confirm box appears over a transparent layer, blocking all mouse click actions unless the user interacts with the confirm box. Now, I also want to dis ...

leveraging angular service with ionic framework

(function () { 'use strict'; angular .module('app') .factory('UserService', UserService); UserService.$inject = ['$http']; function UserService($http) { var service = {}; ...

Ways to include "working hours" if statement a particular holiday dates are specified

Trying to update the code for an "if statement" to include specific dates that are official holidays when the business is not operational. The current code works if the day falls on Mon, Tue, Wed, Thu, or Fri and the time is between 09:00 and 15:00 in a 24 ...

displaying the local path when a hyperlink to a different website is clicked

fetch(www.gnewsapi.com/news/someID).then(response => newsurl.href = JSON.stringify(data.articles[0].url) fetch('https://gnews.io/api/v3/search?q=platformer&token=642h462loljk').then(function (response) { return response.json(); }).th ...