Utilize the value of one variable to determine access to another variable in Javascript

I am working with several boolean variables and I want to create a new variable that keeps track of the most recently changed boolean variable. This way, every time a new boolean variable is modified, I can toggle the previous one.

If you have any ideas or suggestions on how to accomplish this task, please share them!

Here's an example of what I'm trying to achieve, albeit with incorrect code:

isDemo1=false; isDemo2=false; isDemo3=true; isDemo4=false; isDemo5=false; 

lastChangedBooleanVariable = this.isDemo3;

handleBooleanVaiables(currentChangedBooleanVariable: string)
{
// Toggle the currentChangedBooleanVariable
this.lastChangedBooleanVariable = currentChangedBooleanVariable;
// For instance, if currentChangedBooleanVariable = isDemo4
// Toggle the value of this.isDemo4
}


Answer â„–1

If you find yourself struggling with complex code, consider revising your approach as it may not be the best solution.

One alternative is to utilize Arrays:

isExample = [true, false, true, false, true];

lastModifiedBoolean = 2;


manageBooleanValues(updatedBooleanValue: int) {
  this.lastModifiedBoolean = updatedBooleanValue;
  isExample[updatedBooleanValue - 1] = !isExample[updatedBooleanValue - 1]
}

Answer â„–2

It seems like the functionality you're aiming for can be achieved by following a similar process:

const example = 5;

Afterwards, assign any value between 1 and 5 to this variable.
Instead of using if (isExample3), consider checking with if (example == 3).
The concept of "last changed variable" is essentially just the current value stored in the example variable, which may no longer be relevant given this method.

Answer â„–3

ES6 introduces a feature in Arrays known as fill, which proves to be quite useful in this scenario. The concept is simple - you can set all values to false before enabling a new version.

let demos = new Array(5).fill(false);

function activateDemo(demo) {
  demos = new Array(5).fill(false);
  demos[demo] = true;
}

activateDemo(4);

let demos = new Array(5).fill(false);

function activateDemo(demo) {
  const humanIndex = demo > 0 ? demo - 1 : 0; // adjusting for human counting form, if desired.
  demos = new Array(5).fill(false);
  demos[humanIndex] = true;

}

activateDemo(4);
console.log("4", demos);
activateDemo(3);
console.log("3", demos);

Answer â„–4

let flags = {
"isExample1":false, "isExample2":false, "isExample3":false, "isExample4":false, "isExample5":false;
};
let currentFlag: string = "isExample3";
const extractName = (func) => (func).toString().replace(/[ |\(\)=>]/g,'');
function getVariableName(flagName:string){
    return flagName.substring(
        flagName.indexOf(".") + 1, 
        flagName.lastIndexOf(";")
    );
}
function updateFlags(targetFlag: string)
{
    console.log(flags[currentFlag]);
    flags[currentFlag] = !flags[currentFlag];
    flags[targetFlag] = !flags[targetFlag];

    currentFlag = targetFlag;
    // let's assume targetFlag = isExample4
    // toggle the value of this.isExample4 somehow
}
function displayValues(){
    console.log(flags);
}


var extractedName = getVariableName(extractName(()=>flags.isExample1));
updateFlags(extractedName);
displayValues();

extractedName = getVariableName(extractName(()=>flags.isExample4));
updateFlags(extractedName);
displayValues();

Try it out on fiddle: https://jsfiddle.net/hjv540tk/

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

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

Tips for removing alert notifications from Pusher

I have integrated PUSHER into my website for notifications. The codes are successfully added and it is working fine. However, the issue arises when the alert is triggered as I am receiving messages that are not what I expected. The message received from t ...

Heroku Internal Server Error with NextJs version 5.0.0

Below are the scripts that I am using: "scripts": { "dev": "node server.js", "build": "next build", "start": "NODE_ENV=production node server.js", "heroku-postbuild": "next build" }, This is the content of my procfile: web: npm start ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

What is the process for refreshing HTML elements that have been generated using information from a CSV document?

My elements are dynamically generated from a live CSV file that updates every 1 minute. I'm aiming to manage these elements in the following way: Remove items no longer present in the CSV file Add new items that have appeared in the CSV file Maintai ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" âš  ...

Adding items to an array retrieved from JSON

My goal is to merge 3 different Facebook feeds into a single object called "item." Each item includes the post creation time and the JSON data itself. However, I'm facing an issue where only 5 items are displayed when I check the log, even though ther ...

Transferring JSON information from Express to Backbone

I have developed a basic Backbone application and am trying to integrate JSON data from a MYSQL database using an Express server. However, when I make a GET request with Express to fetch data for Backbone, the html template in Backbone disappears, leaving ...

Typeorm stored procedure that returns a JSON response

Whenever I execute the stored procedure defined in a Microsoft SQL database using TypeORM as shown below: const result=await conn.query('exec Spname @0,@1',[inp1val,inp2val]); I receive a response from the database, but it comes with an addition ...

How to change the background color of a slider using jQuery

As a newcomer to web programming, I am currently working on incorporating a slider into my website using jQuery. My goal is to change the background color of the slider to red when the value is less than 5 and green when it exceeds 5. Can this be achieved ...

Tips for creating a seamless Bootstrap collapse effect

I have noticed a slight flicker in the content collapse when using this code. Is there a way to make it collapse more smoothly? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script ...

Leveraging the CSS-Element-Queries Library for emulating the functionality of CSS media queries

Recently, I used a nifty CSS-Element-Queries tool to perform basic element manipulations that trigger whenever the window is resized. In simple terms, my goal was to dynamically adjust an element's attribute based on the current width of the window â ...

Property computation being initiated before property initialization

I am encountering an issue in my Vue application where I am trying to filter an array received from map getters based on a type prop within a computed property. Despite verifying that both the array elements and the prop are strings, the filtering process ...

Having issues with ng-repeat not displaying any content

Let me describe the current situation I am facing: app.controller('ResourceController', function($scope, $sce){ var resourceData; $scope.data = ''; $scope.loadResources = function(){ $.get('con ...

What could be causing my component to not update after I modify the states?

When I make an ajax request and update the state with the response data, my list of items does not rerender as expected. Even though the state is updated successfully, the changes are not reflected in the UI. export class Tiles extends React.Component { ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

ASP.NET failing to execute Javascript

Can you take a look at this code and help me figure out why the alert is not working on the webpage? The console.WriteLine statement below it is running fine, but the alert isn't appearing. private void PublishLoop() { while (Running ...

Making modifications to the state within a modal dialogue box

I am developing a note-taking application where users can write a title and note, and when they click submit, the note is displayed on the page. I want to implement an editing feature where clicking on the edit button opens a modal with the user's tit ...

In TypeScript, there is a chance that the object may be undefined, so I make use of an if

I'm encountering an issue with this code snippet. I have a check in place to ensure that the value of 'startups[i].logo' is not undefined, however I am still receiving an error stating that it may be undefined. Can anyone provide insight as ...

The dropdown feature stores and displays only the initial value

After resolving my previous question (link), I am now facing a new issue where the value of the name field is only reflecting the first item in the dropdown list. Let me explain further. I have two dropdown menus, where selecting an option in one (A) dyna ...