Program does not display the expected alert message when using if/else statement

I'm grappling with creating a basic program that accomplishes the following:

Develop a function declaration named changePowerTotal which accepts:

  • The total current power generated (a numeric value)
  • A generator ID (a number)
  • The new status of a generator ("on" or "off")
  • The amount of power produced by that generator (a number)

Your function must:

  • Return the updated total generated power
  • Alert the technician using specific formats based on whether the generator is switched on or off.

For turning on, provide an alert as follows:

"Generator #2 is now on, adding 62 MW, for a total of 62 MW!"

And for switching off:

"Generator #2 is now off, removing 62 MW, for a total of 0 MW!"

Here is my current solution:

var generatorId = 2;
var status = "off";
var totalCurrentPower = 62;
var powerProduced = 62;

function changePowerTotal(totalCurrentPower, generatorId, status, powerProduced){
    if(status === "off"){
        var offPowerTotal = totalCurrentPower - powerProduced;
        alert('Generator #' + generatorId + ' is now ' + status + ', removing ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');
        return offPowerTotal;
    }
    else {
        var onPowerTotal = totalCurrentPower + powerProduced;
        alert('Generator #' + generatorId + ' is now ' + status + ', adding ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');
        return onPowerTotal;
    }
}

The issue I'm facing is that the alert isn't triggering, and to make matters worse, as a beginner, there are no errors displaying in the JavaScript console. What could be wrong?

However, when I simplify it by assigning all variables globally and then run an alert, everything works fine (see below). This makes me suspect that the problem lies within the if/else condition in my function.

var generatorId = 2; var status = "off"; var totalCurrentPower = 62; var powerProduced = 62; newPowerTotal = 0;

alert('Generator #' + generatorId + ' is now ' + status + ', removing ' + powerProduced + 'mw, for a total of ' + newPowerTotal + 'MW!');

Any guidance would be highly appreciated. I've also attempted removing the returns and leaving only the alerts, but that didn't resolve the issue.

Answer №1

Aside from the aforementioned issues, it appears that perhaps the culprit lies in failing to invoke the function. The following line must be included:

adjustTotalPower()

The absence of this call may result in malfunction or error. Furthermore, ensure that all variables are properly initialized and remember that "=" signifies assignment—when checking a variable, use "==" or "===" instead.

Answer №2

My thoughts align with the points made earlier, and for a tangible demonstration, you can visit this Plunker example. I trust this resource will be valuable.

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 would you recommend setting localStorage in an Angular application?

In my EmployeesComponent, I have a list of employees with buttons for "Education Overview" and "Salary Overview" for each record. Clicking on an overview button takes me to the OverviewComponent, which then loads either the salary or education component. B ...

Chrome browser is experiencing an issue with the Modal RadWindow not closing properly

In my main "Report" page, there are actions available to the user that open a modal RadWindow. The user can then take actions within the modal window, click Save, and the modal window should close while the main grid refreshes. While this functionality wo ...

The Material UI Icon is missing from the location '@mui/icons-material/Send.js'

I am currently utilizing the Material UI library and attempting to import SendIcon through this import statement: import { SendIcon } from "@mui/icons-material/Send.js"; Due to including "type" : "module" in my package.json f ...

Dealing with performance issues in VueJS and Vuetify's data-table component, especially when trying to implement

In my VueJS and Vuetify project, I encountered an issue. I am trying to create a table with expandable rows for displaying orders and their associated products. The table needs to show at least 100 rows of orders on one page. To achieve this, I utilized th ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

AngularJS radio buttons are interactive HTML elements that allow users

I've been looking for a solution to bind my radio inputs to a model in a simple and clean way, but I haven't found one that works for me yet. In my HTML, I have: <input ng-model="searchByRma" type="radio" name="search-type"> <input ng-m ...

Obtain a specific portion of text from a string that resembles a URL

$("#index-link")[0].search = "?isNameChecked=False&isDateChecked=False&isStatusChecked=True" Is there a way to use jQuery to identify whether isStatusChecked is set to true or false in the given string? ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

Submit form in a new tab and refresh the current page

It seems like my mind is hitting a roadblock, I'm having trouble finding a better solution for this particular issue: I need to send a form via POST method (with data handling on the server) and have it open in a new tab with a custom URL containing ...

Is there a way to combine properties from two different objects?

I am working with several JavaScript objects: { x: 5, y: 10, z: 3 } and { x: 7, y: 2, z: 9 } My task is to add these two objects together based on their keys. The resulting object should look like this: { x: 12, y: 12, z: 12 } Do you ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

Performance problem with 'Point-along-path' d3 visualization

I recently explored a d3 visualization where a point moves along a path, following the code example provided at https://bl.ocks.org/mbostock/1705868. During this movement, I observed that the CPU usage ranges from 7 to 11%. In my current project, there ar ...

The escape character appears to be misunderstood, causing an error due to an invalid escape sequence

When using the following syntax: executeJSCommand("location.href='StatusDetails.php?CHLD=1\&JNum=1024&JTitle=';"); An error occurs displaying: Invalid Escape Sequence ...

Utilizing AJAX to fetch and retrieve a JSON array

Check out the javascript code below: var formSerializedData = $('form#registration-form').serialize(); $.post( '<?php echo $this->url('/register', 'do_register')?>', function(response) { alert(response); } ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function: export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) { // Beginning point: // [key1,key2,key3], // [value1,value2,value3] // // End point: { // key1: val ...

Add a message displaying the error in the input field using jQuery Validation

Is there a way to append the jQuery Validation error messages to the input field or get help with positioning them properly? The random popping up of error messages is causing chaos in the form layout. I prefer to have the error messages displayed undern ...

Struggling to detect a click event within a VueJS application when using a bootstrap button-group

I am currently working on a VueJS project that includes a bootstrap button group... <div class="btn-group btn-group-xs pull-right" data-toggle="buttons"> <label class="btn btn-primary label-primary"> <input type="radio" name="options" i ...