Ways to obtain the output of an If/Else statement

It seems like I might be missing something, but I am unsure of how to extract the result from an else-if statement. Take this code snippet that I've been working on for example:

In this scenario, the output would read "It's warm!", and what I want is to write a piece of code that reacts based on this result. However, since the result isn't stored in a variable, I'm not sure how to create a response based on the logged message. For instance, if it logs "It's warm!", I would like to include additional instructions like "Turn on the AC." or "Turn on the heater" depending on the situation. How can I achieve this?

let temperature = 36
if (temperature > 24) {
console.log ("It's warm!");
} else if (temperature < 24) {
    console.log ("It's cold!");    
} else {
    console.log ("It's cool!");

Answer №1

To easily handle different temperatures, you can assign it to a variable:

let currentTemp = 36;
const isChilly = currentTemp < 24;
const isCozy = currentTemp > 24;
if (isCozy) {
    console.log("Feeling warm!");
} else if (isChilly) {
    console.log("Feeling cold!");
} else {
    console.log("Just right temperature!");
}

if (isCozy) {
    console.log("Time to cool down!");
}

Answer №2

To include your code within the expression block delimited by {} after the if condition, you can follow this example:

For instance:

let temperature = 36;
if (temperature > 24) {
  console.log("It's warm!");
  console.log("Turn on the AC.");
  // Feel free to add more code within this condition
  // or even call another function
} else if (temperature < 24) {
  console.log("It's cold!");
} else {
  console.log("It's cool!");
}

Answer №3

Not entirely sure of your inquiry, but if you're looking to display the temperature:

let temp = 36
if (temp > 24) {
console.log ("Feels warm!", temp, "degrees");
} else if (temp < 24) {
    console.log ("Chilly weather!", temp, "degrees");    
} else {
    console.log ("Cool and pleasant!", temp, "degrees);

Answer №4

Store the outcome in a variable.

let temp = 36;
let outcome = '';
if (temp > 24) {
  outcome = "It's warm!";
} else if (temp < 24) {
  outcome = "It's cold!";
} else {
  outcome = "It's cool!";
}

console.log(outcome);

Answer №5

Within a function, you can assign a variable to represent the temperature and then output the corresponding result based on that temperature. The switch statement is used here to compare the inputted temperature against different conditions and adjust the result string accordingly. Switch statements serve as an alternative to nested or complicated if-else statements.

function setTemperature(temp){
 let result = "It's ";
  switch (true) {
    case temp > 24:
    result += "warm!";
    break;
    
    case temp > 12:
    result += "cool!";
    break;
    
    default:
    result += "cold!";
  }
  return result;
}

    
console.log( setTemperature(36)); // outputs "It's warm!"
console.log( setTemperature(16)); // It's cool!
console.log( setTemperature(6)); //It's cold!

Answer №6

If you want to determine the weather temperature, you can create a function as shown below:

let temp = 36;
function checkTemp(temperature){ 
    if (temperature > 24) {
        return "It's warm!";
    } else if (temperature < 24) {
        return "It's cold!";    
    } else {
        return "It's cool!";
    }
}

var result = checkTemp(temp); 

console.log(result); 

if(result === "It's warm!"){
    // perform actions for warm temperature
} else if (result === "It's cold!"){
    // perform actions for cold temperature
} else {
    // perform actions for cool temperature
}

You could also directly execute actions within the function or initial if statement.

I hope this explanation was useful!

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

Is add1 missing from the DOM? Learn how to include it

Having an issue with Java-Script and an HTML form. The scenario is that there's a main form with an "Add" button, which when clicked should display a second form. Next to the second form is another button labeled "Add1," which ideally should trigger ...

File is indicating a status of 200 ok, however it is not being displayed on the screen (node.js, expressjs)

I'm trying to display a video file in the browser and access it like an API on my front end. My goal is to have my front end call the video using a simple <video> tag. <video> <source ="video/randomfile.mov" type="video/mov"> < ...

Injecting a controller into an AngularJS module within an anonymous function

As a newcomer to the world of javascript and just beginning to work with angular.js, I have a question. I'm wondering if there is a method for injecting a controller into a module that is declared within an anonymous function. This is how my code cu ...

Creating dynamic SQL queries for bulk inserting data into Postgres using Vercel

Can anyone help me with creating an SQL bulk insert query using the sql helper from @vercel/postgres? I have a array of objects with different property types (number, string, date) and need to dynamically build the query. Simply creating a string and passi ...

AngularFire: Retrieve the $value

Having an issue logging the service.title to the console as it keeps returning as a strange object. .factory('service', function($firebase, FBURL, $routeParams) { var ref = new Firebase(FBURL + "services/" + $routeParams.serviceId); var titl ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

using vuejs to pass a function as a prop

As I work on creating a foundational "TableComponent," incorporating selectable rows and more, I am faced with the requirement for this TableComponent to accept a prop named "buttons." These buttons are expected to be in the form of an array of objects ...

Libraries that provide webkit support for all browsers

Looking for a library that supports CSS webkit across various browsers, including older ones like ie6. Preferably written in JavaScript. Any recommendations? ...

Is there a way to categorize data and sort it by using an action and reducer in redux?

I have developed a filtering system that allows users to filter data by different categories such as restaurants, bars, cafes, etc. Users can select whether a specific category should be displayed or not, and this information is then sent to the action and ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

What methods can we employ to prevent the GraphQL query from being triggered with every keystroke when using React?

Recently, I received a new task that requires me to implement input value debouncing to prevent backend requests on every keystroke. Additionally, I need to establish an internal useState for CollectionsAutocomplete, which is connected to the generalQuery ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

Expanding a non-bootstrap navigation bar upon clicking the menu

I'm having some difficulty getting my navigation menu to show up when I click the navigation menu icon. HTML nav role="navigation" class="navbar"> <div class="nav-header"> <a href="#"><span style="font-family: 'Cab ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

Utilizing Jade to access and iterate through arrays nested in JSON data

Take a look at this JSON data: { "Meals": { "title": "All the meals", "lunch": ["Turkey Sandwich", "Chicken Quesadilla", "Hamburger and Fries"] } } I want to pass the array from this JSON into a jade view so that I can iterate over each item in ...

Is there a way to transfer ngClass logic from the template to the TypeScript file in Angular?

I am implementing dropdown filters for user selection in my Angular application. The logic for adding classes with ngClass is present in the template: <div [ngClass]="i > 2 && 'array-design'"> How can I transfer this ...

A guide on expanding MaterialUI Accordion in React by clicking on a different component

I am trying to implement a feature where clicking on a marker on a map will expand the corresponding accordion item. Both markers and accordion items have matching key values as seen in the screenshot below. https://i.sstatic.net/PAxOO.png The code I cur ...