JavaScript Global Variables Keep Getting Reset

Here's the concept behind my project: I've created a simple game that utilizes a do/while function and a switch statement to determine the player's current room. When the player is in room 1, the switch selects room1 and executes the room1() function. Within the room, the player can choose which direction to go. If they choose north or east, a door1() or door4() function will prompt them to open the door and progress to the next room, updating their room value in the process.

While everything seems to be working smoothly and the functions are functioning correctly, there is a major issue with the variables resetting whenever the player walks through a door. As a result, the player always ends up back in room 1, with their compass set to 0 and none of the doors or rooms marked as "visited."

Essentially, walking through a door should lead the player to room 2 or 4, but instead, they keep returning to room 1.

Below is the code, along with a step-by-step guide:

    var room1V = 0;
    var room2V = 0;
    var room3V = 0;
    var room4V = 0;

    var door1V = 0;
    var door2V = 0;
    var door3V = 0;
    var door4V = 0;

    var compass = 0;
    var room = 1;
    var reply = 1;
    win = 0;

    do {
        quit = 0;
        switch(room) {
            case '1':
                room1(compass,room1V);
                break;
            case '2':
                room2(compass,room2V);
                break;
            case '3':
                room3(compass,room3V);
                break;
            case '4':
                room4(compass,room4V);
                break;
        }
    } while (win != 1);

Upon initiating the program, the room1(compass,room1V) function is invoked since the default room is set to 1.

    function room1(compass,room1V) {
        // Function logic
    }   // Working

If the player selects 'north,' the compass will be updated accordingly, and door4(room,door4V) will be executed.

    function door4(room,door4V) {
        // Function logic
    }       // Working

Despite the intention for the program to recognize the player's shift to room 4, they keep returning to room 1 whenever the do/while loop restarts, and all variables appear to be reset.

Answer №1

The issue with the resetting of your variables is due to the nature of primitives being passed by value in JavaScript. Within your do-while loop, when you pass variables like room1V to functions such as room1, the changes made to these variables inside the function do not affect the original variable. The same concept applies when passing variables like compass and door4V to the door4 function. For a deeper understanding, consider exploring this chapter.

Answer №2

If you're encountering a problem known as "variable shadowing" (learn more about it here), it means there are multiple variables with the same name in a certain scope.

var apple = 0;

function basket(apple) {
  /* In this case, there are two variables both named 'apple' within the scope */
  apple = 1;
}

console.log(apple); // 0
basket();
console.log(apple); // 0

To overcome this issue, simply rename the argument in the function like so:

function basket(anotherApple) { apple = 1; }
Now, when you run the following code:

console.log(apple); // 0
basket();
console.log(apple); // 1

Answer №3

The variable 'room' is never updated to reflect the new room. It remains set in the global parameters and does not change dynamically.

To correctly update the room in the do-while loop, use the following code snippet:

// This do-while loop determines the current room:
    do {
        quit = 0;
        switch(room) {
            case '1':
                room1(compass, room1Value);
                room = 1;
                break;
            case '2':
                room2(compass, room2Value);
                room = 2;
                break;
            case '3':
                room3(compass, room3Value);
                room = 3;
                break;
            case '4':
                room4(compass, room4Value);
                room = 4;
                break;
        }
    } while (win != 1);

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

Creating a radial progress chart using Plotly JavaScript

I recently started working with the Plotly library and now I need to display a circular progress graph in Vuejs 2, like the one shown below. While Plotly is a comprehensive tool, I have not come across an example that matches this specific design using Ja ...

Is there a way to determine the precise location of the scrollbar within a div element?

Is there a way to obtain the exact position of the scrollbar (scrollY) for a specific div, rather than the entire window? I found an example that seems similar to what I need at the following link: http://plnkr.co/edit/45gKhAIt0DrozS7f0Bz2?p=preview Ho ...

Maintain MUI Autocomplete in the open state even after making a selection from the

Whenever I select certain options on my Autocomplete component, I want to keep the component open. However, each time I click on onChange, the Autocomplete closes automatically and I can't seem to find a way to prevent this. Is there a workaround? In ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

What is it about this JavaScript code that IE8 seems to have a problem with?

Encountered an error in IE8 that has been causing trouble for me SCRIPT65535: Unexpected call to method or property access. load-scripts.php, line 4 character 25690 After removing a .js file from the code, the error disappeared. By commenting out f ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

What is the correct way to send parameters in the action tag?

Can I set the res variable as the form action in HTML? <script> var name =$("#name").val(); var file =$("#file").val(); var res= localhost:8080 + "/test/reg?&name="+name+"&file=" +file ; </script> <form acti ...

Tips for programmatically focusing on a v-textarea using Vuetify and TypeScript

It feels impossible right now, I've attempted some unconventional methods like: (this.refs.vtextarea as any).textarea.focus() ((this.refs.vtextarea as Vue).$el as HTMLElement).focus() and so on... Javascript source code is quite complex for me to ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Using logical equality operators in Javascript

Imagine I have two boolean variables and I need to determine when they are both true or false, essentially requiring a logical equality operator.' Most JavaScript resources recommend using bitwise operators, with the XOR operator performing a similar ...

How can one eliminate the white space surrounding the data that Vue is binding?

Working with Vue, I've noticed a gap on the screen following the data binding. Instead of using Vanilla JavaScript's trim() function, is there a way to remove leading and trailing whitespace? Let me provide you with the code for the data binding ...

Can JavaScript bypass the need for an html page and go directly to the printing process?

Is it possible for a user to click a "print" button and have the printer start printing? Please note that there is already a server process in place (via AJAX) that can respond with success for printing or return HTML content for display, so that is not a ...

Having trouble displaying DIV Content with CSS through printing

<script type="text/javascript"> function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { var mywindow = window.open('', 'mydiv', 'height=550,width=750'); mywindow.doc ...

Continuously tapping on overlapping slides

I encountered an issue where the slide that I set the opacity to 0 on is still clickable, despite setting pointer events to none. In my slideshow, consisting of 2 slides, clicking on the first slide redirects me to the hyperlink of the second slide. Chec ...

Using AngularJS to Showcase JSON Array

I am currently working with a .json file that contains information about networks, IP addresses, and zones. I am trying to figure out how to display the "ip" array in my .html file. [ { "network":"net1", "ip":[ "19 ...

What are the steps to gather user data and generate a roster of individuals currently online?

I am currently working on a way to gather information about the users who are currently logged into my website. Here's how it works: When a user enters my website, they have the option to choose a nickname using an input box. Then, there are five diff ...

Utilizing AngularJS to include information into JSON-LD

As a newcomer to AngularJS, I find myself stuck in one of my projects. My goal is to convert the user-entered data in a form into the format: << "schema:data" >> and then push and display it within the @graph of the json-ld. Here are my HTML an ...

picking out a particular set of data from a JSON document

I have a map of Europe along with a JSON file that displays the unemployment rate for each country in the year 2011. The JSON file also includes x and y elements, allowing me to place a blue circle on top of each country on the map. My goal is to be able ...

What are the advantages of utilizing NGRX over constructor-injected services?

Have you ever wondered about the benefits of using NGRX or NGXS for an Angular application instead of constructor injected services to manage component IO? Is it simply to prevent mutation of component properties references without replacing the entire pr ...

Switch between various components using Vue

Hello, I am currently diving into the world of VueJS and eager to learn more about it. I recently created a simple tooltip that should appear when clicked and disappear when clicked again. I managed to achieve this with basic beginner-friendly code for a ...