Ways to retrieve an object initialized within a function

I'm sorry if my title is a bit confusing. I'm currently working on creating an object that contains key-value pairs of other objects. Below is the code snippet I'm testing in the Chrome console.

When I try to create the object using the CharactersFn() function directly with

Characters = CharactersFn("male");
or
var Characters = CharactersFn("male");
, it works fine. However, when I attempt to do it through my whatAreYou() function, I don't get the desired results. Can anyone assist me with the correct approach to achieve this?

Disclaimer: I'm still in the learning phase and trying my best to understand the right way to accomplish tasks.

var Characters,
    valueArr = [],      
    nameArr = [],           
    matchArr = [];

var CharactersFn = function (ans) {     //Are you male or female?   
    "use strict";
    if (ans === "male") {
        Characters = {
            47: aloy,
            snake: snake,
            drake: drake,
            cloud: cloud
        };
    }

    if (ans === "female") {
        Characters = {
            aloy: aloy,
            bayonetta: bayonetta,
            elizabeth: elizabeth,
            ellie: ellie
        };
    }
    return Characters;
};

function whatAreYou() {
    "use strict";
    var gender = prompt("0 or 1");

    if (gender === 0) {
        Characters = CharactersFn("female");
    }
    if (gender === 1) {
        Characters = CharactersFn("male");
    }
        return Characters;
}

Answer №1

var gender = prompt("Choose 0 or 1");
if (gender === 0) {
if (gender === 1) {

The prompt function will always return a string, not a number. Therefore, your if statements will never match the input.

Make sure to compare the input to "0" and "1" as strings, not 0 and 1 as numbers.

Answer №2

When you invoke CharactersFn, you are setting the global Characters object to the returned object. Additionally, you are returning the global Characters object from CharactersFn. In the whatAreYou function, you are assigning the global Characters object to the result of CharactersFn, which in turn returns the global Characters object. There were instances where you were referencing undefined variables in object creation, so I have replaced them with string values. Also, you were using strict equality comparison (===) between string and integer values. It would work with loose equality (==), but for strict equality, the values must be identical.

Below is an updated version where the global Characters object is set to the return value of CharactersFn, which now returns the objects themselves.

var Characters = {},
    valueArr = [],      
    nameArr = [],           
    matchArr = [];

var CharactersFn = function(ans) {   
    if (ans === "male") {
        return  {
            47: "aloy",
            snake: "snake",
            drake: "drake",
            cloud: "cloud"
        };
    }

    if (ans === "female") {
        return {
            aloy: "aloy",
            bayonetta: "bayonetta",
            elizabeth: "elizabeth",
            ellie: "ellie"
        };
    }
    return Characters;
};

function whatAreYou() {
    var gender = prompt("0 or 1");

    if (gender === "0") {
        Characters = CharactersFn("female");
    }
    if (gender === "1") {
        Characters = CharactersFn("male");
    }
        return Characters;
}

console.log(Characters);
whatAreYou();
console.log(Characters);

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

When running the `npm run dev` command, Tailwind does not seem to function

I have been given a task to create forms using tailwindcss, but when I try to run `npm run build`, it doesn't work. Can anyone assist me with this? npm ERR! code ELIFECYCLE npm ERR! errno 9 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf ...

Converting a text file to JSON format using Adobe Acrobat: A tutorial on proper referencing

I am facing an issue with converting a string from a file attached to my PDF (JSONTEST.txt) into JSON format so that I can reference it using obj[key]. Despite trying to use eval(), I encounter the following error every time: SyntaxError: missing ; before ...

Trouble arises with the chrome extension code for retrieving tweets from Twitter

I'm currently working on developing a Chrome extension that will display tweets featuring the hashtag perkytweets within the extension's popup. However, I'm facing an issue where nothing is being displayed. Let's take a look at the cod ...

JavaScript: Collecting data into an array of objects

Is there a more efficient way to fetch a specific object from an array of objects without using a for loop? Here is an example of the array of objects: 0: {code: "YJYDWO1", route_id: 1} 1: {code: "YJYDWO2", route_id: 2} 2: {code: "YJYDWO3", route_id: 3} 3 ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

React hooks causing the for loop to only work on the second iteration

I am working on a project where I need to implement tags, similar to what you see on this website. Before adding a tag, I want to ensure that it hasn't already been selected by the user. I have set up a for loop to compare the new tag with the existin ...

Angular setPristine function is not functioning properly

I am looking to achieve a simple task - cleaning the $scope.user fields without encountering errors. if ($scope.contactForm.$valid) { $scope.user = {}; $scope.contactForm.$setPristine(); } However, I'm still experiencing v ...

Is there a way to find the TextArea element on Facebook's home page using a Selenium locator? Could it possibly be using jQuery

Sign in using any of our Facebook login details. Upon successful login, you will be directed to the page below. Query: Can you spot the "What's on your mind" or "continue to post" text box? I need to find the text box, input text, and then click on ...

Issues with CORS on PUT and POST requests in AngularJS and Node.js are preventing successful communication between the two

I'm encountering a CORS issue with my application. My tech stack consists of Node.js using Express 4 and AngularJS Despite attempting various solutions, I continue to receive the following error for all POST/PUT requests: No 'Access-Control-Al ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

Node.js can be used to easily set the values of HTML elements

After successfully setting up a node.js connection to my mysql database and being able to retrieve and input data using connection.query(), I now want to display the database information on my HTML elements. Is there an equivalent of getElementById for t ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

The HTML table inexplicably displays a random comma out of nowhere

When working on my HTML table, I noticed that it was rendering a comma unexpectedly. I am using Nodemailer and SMTP Google server, and I suspect the issue lies within the HTML code. However, I am struggling to identify the exact problem. https://i.stack.i ...

Exploring the features of NodeJS, diving into the world of mapping,

Currently, I am working in a Node.js environment and dealing with an array of IDs. My goal is to filter these IDs based on the response of another API call. Essentially, I need to check if each ID meets certain criteria specified by this external API. Whi ...

In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text fil ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

Semantic UI form validation is initiated by clicking any button

Within my Semantic UI form (<div class="ui form">), it seems that every button is triggering the form validation, even if it's not a submit button. I have two different types of buttons below: <button class="ui blue right labeled icon prima ...

Guide to implementing hapi-auth-jwt2 authorization on a specific route within hapi.js?

I am facing an issue with using an access token in hapi.js. I am struggling to comprehend how to utilize this token for authentication purposes. Currently, I am referring to the article on dwyl/hapi-auth-jwt2. My database setup involves mongodb. However, I ...