Best practice for transferring JavaScript variables

I'm struggling to grasp how JavaScript handles variable passing. The code snippet below is being executed in an Express controller:

const {
      sessionID,
      defenderID,
      challengerID
    } = req.body;

    console.log('sessionID', sessionID);
    console.log('defenderID', defenderID);
    console.log('challengeID', challengerID);
    const newGame = await Game.start({
      session: sessionID,
      defender: defenderID,
      challenger: challengerID
    });

This code snippet references the following function definition:

gameSchema.statics.start = async (session, defender, challenger) => {
  const date = new Date();
  console.log('attempting to start a game');
  console.log('session', session);
  console.log('defender', defender);
  console.log('challenge', challenger);
  const newGame = new Game({
    defender: defender,
    challenger: challenger,
    startTime: date
  });
  newGame.session.push(session);
  return await newGame.save().then((game) => game);
}

The current output shows:

defenderID johndoe
challengeID somechallenge
attempting to start a game
session {
  session: '620c29582ac275bd67cd3cca',
  defender: 'johndoe',
  challenger: 'somechallenge'
}
defender undefined
challenge undefined

I am puzzled by this discrepancy since I have another piece of code that performs similar actions without any issues.

Answer №1

The issue arises when passing down an object as a single argument to the Game.start method while expecting 3 arguments in the function declaration for session, defender, and challenger. This results in the object being displayed in the console log for session.

To rectify this, individual arguments should be passed when calling the method like so-

  const {
    sessionID,
    defenderID,
    challengerID
  } = req.body;

 console.log('sessionID', sessionID);
 console.log('defenderID', defenderID);
 console.log('challengeID', challengerID);
 
 const newGame = await Game.start(sessionID, defenderID, challengerID);
 

Alternatively, you can modify the function declaration to accept a single object argument and then destructure the properties as follows:

gameSchema.statics.start = async ({
 session, 
 defender, 
 challenger
}) => {
  const date = new Date();
  console.log('attempting to start a game');
  console.log('session', session);
  console.log('defender', defender);
  console.log('challenge', challenger);
  const newGame = new Game({
    defender: defender,
    challenger: challenger,
    startTime: date
  });
  newGame.session.push(session);
  return await newGame.save();
}

Subsequently, the method can be called as previously done:

const newGame = await Game.start({
  session: sessionID,
  defender: defenderID,
  challenger: challengerID
});

Furthermore, there is no need to utilize .then after .save() since the async await pattern is already in place, resulting in the saved game document being returned with await newGame.save().

return await newGame.save();

Answer №2

The entire object is passed as the first argument, labeled as 'session':

{
      session: sessionID,
      defender: defenderID,
      challenger: challengerID
}

You have the option to modify the call to:

const freshStart = await Game.begin(sessionID, defenderID, challengerID);

Alternatively, you can redefine the method as:

async (obj) => {
...
const freshStart = new Game({
    defender: obj.defender,
    challenger: challenger,
    startTime: date
  });
...

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

The WebSocket function is returning undefined even though it successfully fetches the user; however, the user is

I've been experimenting with a websocket to retrieve user information. When I establish the connection and send messages to receive the data, it returns undefined when I try to use that information elsewhere. However, if I run console.log within the ...

There was an issue with loading the THREE js obj file

I am facing an issue while trying to import a .obj file into my project using Threejs. The error message I am encountering is: Uncaught TypeError: geometry.computeCentroids is not a function at THREE.OBJLoader.parse (OBJLoader.js:304) at XMLHttpRequest.&l ...

Transfer an URL parameter from the URL to the server using PHP or JavaScript

My goal here is to pass the URL as a parameter named "web_url". The code snippet above shows an AJAX request being sent to a PHP server on the backend. On the PHP side, I'm attempting to capture this parameter using: $web_url = $_GET["web_url"]; H ...

Using JavaScript to add a class when hovering over an element

I am trying to customize the ul inside one of my li elements in the nav by adding a class when hovered. However, I am encountering an issue where the menu disappears when I try to click on it after hovering over it. I want to achieve this functionality usi ...

Mastering React state involves the skill of interpreting the updated state after making changes

I have a good grasp of JavaScript but I'm currently learning React. I decided to build a tic-tac-toe game and faced an issue with updating the game state properly. Specifically, I want the message to update immediately when there is a winner, the &apo ...

Determine if the specific subroute has a child using vue-router

After checking similar questions on stackoverflow without success, I am seeking a solution. I am attempting to determine if a subroute is a child of a specific route in order to display a container. Unfortunately, the following code snippet does not work: ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

Is there a way to figure out the number of days from the current date using jQuery UI datepicker?

Hello there, I'm currently facing an issue with calculating the number of days from the present to a chosen date after utilizing a jQuery datepicker. It seems that the date formatting is getting altered upon selection, causing discrepancies in the ca ...

Eliminate repeated elements within a JSON dataset to create a consolidated array

Looking to extract unique data from the JSON object below in order to create a result json with a list of questions and their corresponding choices. Any assistance would be greatly appreciated. Thanks in advance..!! var data = [ { "category": "s ...

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

Advantages of using jQuery's .each() function instead of conventional "for" loops

I recently had a colleague recommend using jQuery's .each() function instead of a standard javascript for loop for traversing through DOM elements on my webpage. While I am familiar with jQuery, I've always wondered why developers prefer using .e ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

What is the best way to determine if a property exclusively belongs to the child class or its subclass in Javascript?

I am currently working on a project in Javascript where I need to retrieve properties that are only present in a subclass (child class) and not in the parent class. Despite using .hasOwnProperty(), I have run into an issue where it also returns true for th ...

The Ajax form is failing to send data to PHP

Thanks to Stackoverflow, I've been diving into website design. I recently put together some code for handling data sent from an HTML form using Ajax. The code does a good job of error checking, but it seems to be missing the step of actually sending t ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

Is there a way in NodeJS to preview the contents of a file in a browser before initiating the download process?

Is there a way to preview a file in the browser before downloading it in NodeJS? This would allow users to make sure they are choosing the correct file to download. Currently, I have this code for downloading a file: app.get("/download/file", (req, res) = ...

What could be the reason why the toggle active function is not functioning as expected in this code

I need some guidance on how to properly share code on stackoverflow. For the complete code, you can view it on Codepen: Codepen const hamburger = document.querySelector(".hamburger"); const navMenu = document.querySelector(" ...

What is the most effective way to save and access British pound symbols?

Every so often, I face this issue where I end up resorting to a messy workaround. There must be a correct way to handle it though, as it's common to work with UK pound symbols. The dilemma is this: when the user inputs a UK pound symbol (£) into a t ...

Unable to transfer file using ajax (displaying print_r($_FILES); Array ( ) )

I have encountered an issue with sending a file using XHR compared to a common form confirmation. Here is the HTML code: <form action="ajax/upload.php" method="post" name="form1" enctype="multipart/form-data" id="id1"> <input type="file" name=" ...