Tips for incorporating if-else statements into your code

How can I incorporate an if statement into my code to print different statements based on different scenarios? For example, I want a statement for when the sum is less than 1, and another for when the sum is greater than 1. I attempted to use examples from W3Schools, but the if statement did not work as expected.

<!DOCTYPE html>
<!-- Network Latency Calculator -->
<html>
<head>
  <meta charset = "utf-8">
  <title>Network Latency Calculation</title>
  <script>

     var firstNumber; // user-entered value
     var secondNumber; // user-entered value
     var thirdNumber; // user-entered value
     var fourthNumber; // user-entered value
     var number1; 
     var number2; 
     var number3; 
     var number4; 
     var sum; 


     // read in values from user
     firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );
     secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );
     thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );
     fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );

     // convert input to integers
     number1 = parseInt( firstNumber ); 
     number2 = parseInt( secondNumber );
     number3 = parseInt( thirdNumber );
     number4 = parseInt( fourthNumber );

     sum = number1 + number2 + number3 + number4; 

     // display the results
     document.writeln( "<h1>The network latency is " + sum + "</h1>" );

  </script>

Answer №1

Before we move forward, I recommend checking out this resource: https://www.w3schools.com/jsref/met_doc_writeln.asp

Currently, you are writing within the head section of the HTML rather than the body.

<body>

<p>It's important to note that write() does not automatically create a new line after each statement:</p>

<pre>
<script>
var NowDate = new Date();
var number1 = NowDate.getHours(); //added current hour 0-23
var number2 = 5; // second number to add
var number3 = 0.3; // third number to add
var sum = number1+number2*number3;
if (sum > 5){
    document.write("That's a");
    document.write(" big Sum ("+sum+")");
} else if (sum === 4) {
    document.write("Sum =");
    document.write(" 4");
}else{
    document.write("Sum is ");
    document.write("small ("+sum+")");
}
</script>
</pre>


<p>On the other hand, writeln() adds a new line after each statement:</p>

<pre>
<script>
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</pre>

</body>

Answer №2

Initially, based on the brief description you provided regarding your requirements, it seems like you are looking to display a specific statement after calculating the total. This process is quite simple to achieve.

For instance:

sum = number1 + number2 + number3 + number4; // add the numbers

if(sum > 1){
    //Your code
} else {
    //Your code
}

I opted not to include an else if condition because when the sum exceeds one, it will execute the desired statement. If not, it will proceed with the alternate statement under the else clause.

If you wish to explore additional examples of using if/else statements, you can refer to this helpful StackOverflow link for detailed examples and instructions on implementation.

Answer №3

Once you have calculated the sum, you may choose to include an if-statement like the one below:

if (sum < 1) {
   document.write ("The total is less than one");
} else if (sum > 1) {
   document.write( "The total is more than one"); 
}

If you need further assistance with if-conditional statements, O'Reilly offers a variety of technical books that focus on JavaScript.

var firstNumber; // First input provided by user
 var secondNumber; // Second input provided by user
 var thirdNumber; // Third input provided by user
 var fourthNumber; // Fourth input provided by user
 var number1; // First number for addition
 var number2; // Second number for addition
 var number3; // Third number for addition
 var number4; // Fourth number for addition
 var sum; // Total of number1 + number2 + number3 + number4



 // Retrieve first number as a string from user input
 firstNumber = window.prompt( "Enter the Propagation time (in milliseconds)" );

 // Retrieve second number as a string from user input
secondNumber = window.prompt( "Enter the Transmission time (in milliseconds)" );

// Retrieve third number as a string from user input
 thirdNumber = window.prompt( "Enter the Queuing time (in milliseconds)" );

// Retrieve fourth number as a string from user input
 fourthNumber = window.prompt( "Enter the Propagation delay (in milliseconds)" );

 // Convert string inputs to integers
 number1 = parseInt( firstNumber ); 
 number2 = parseInt( secondNumber );
 number3 = parseInt( thirdNumber );
 number4 = parseInt( fourthNumber );

 sum = number1 + number2 + number3 + number4; // Perform addition

if (sum < 1) {
   document.write ("The total is less than one");
} else if (sum > 1) {
   document.write( "The total is more than one"); 
}

 // Display the result
document.writeln( "<h1>The network latency is " + sum + "</h1>" );

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

What is the best way to add a new row in Material-UI?

I have been working on a contacts application that stores all data temporarily on the client-side. I decided to use material-ui table to showcase the contacts in a visually appealing way. Upon clicking the "Add New Contact" button located at the bottom ri ...

Having difficulties transmitting numerical values through res.send() in express with node

Currently, I'm faced with a challenge in my express application on node.js as I attempt to retrieve the "imdb rating." movies.json [{ "id": "3962210", "order": [4.361276149749756, 1988], "fields": { "year": 2015, "title": "David and Goliath" ...

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

Is there a way to automatically submit an upload form once a file has been selected?

Need help with automatically submitting a file upload form when a file is selected. Is there a way to bypass the need for the user to click the Submit button? ...

What is the method to activate a select event on a particular row using Google visualizations?

Currently, there is a single table where clicking on a row should simulate the same action on another GV table. The code for the listener is as follows: $(".mytable tbody tr td").click(function() { var colIndex = $(this).parent().children().index($(th ...

Can you determine the sequence in which these code statements are placed on the call stack?

I am a beginner in the world of Javascript and currently seeking to grasp a better understanding of how the JS execution engine operates. I am aware that any asynchronous code statement is pushed onto the call stack and then promptly removed, allowing it t ...

What is the best way to fill out a mandatory text field within the text area?

I am currently facing a challenge with making the comment field mandatory in my PHP application. Despite my lack of expertise, I have been unsuccessful in finding a solution so far. Below is an example code snippet where PHP generates the comment field. Du ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Access-Control-Allow-Origin does not permit AngularJS Origin http://localhost:8080

I'm working on a web application using AngularJS. It's an admin interface that depends on a json-rpc API hosted on a different domain. When testing in my local environment, I encountered the error "Origin http://localhost:8080 is not allowed by ...

Retrieve the identifiers of various HTML elements and store them in an array

Within a div, there are multiple objects. I am trying to retrieve the IDs of all elements based on their class, knowing that the number of elements may vary. So far, my attempt has been: arr = $(".listitem #checkBox").hasClass('checkedItem').att ...

Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one ...

Is there a way to display the button solely when the cursor is hovering over the color?

When I hover over a particular color, I want the button to show up. However, instead of displaying the button only for that color, it appears for all the colors of the product. Also, the placement of the button on the left side means that if I try to hover ...

JavaScript (geolocation) error: Unhandled TypeError - Invocation not allowed

Encountering the Javascript error "Uncaught TypeError: Illegal invocation" while executing the code var nativeGeoloation = window.navigator.geolocation.getCurrentPosition; nativeGeoloation(function (){ alert("ok")}); Despite attempting to call the code w ...

Ways to send user input to a function within a React component

I am currently working on implementing a simple feature where users can search posts by their tags. To achieve this, I have created the Feed.jsx component with the following code: "use client"; import { useState, useEffect } from "react&quo ...

Trouble with the Ngx-Captcha feature

I am currently utilizing https://www.npmjs.com/package/ngx-captcha/v/11.0.0. <ngx-recaptcha2 #captchaElem [siteKey]="'6Leh1ZIjAAAAAG8g0BuncTRT-VMjh3Y7HblZ9XSZ'" (success)="handleSuccess($event)" [useGlobalDomain]="fals ...

Retrieve information from the input field and then, upon clicking the submit button, display the data in the

When a user inputs their name, email, subject, text, and telephone number, I want to send an email with that data. The email will be sent to a specific email address, such as [email protected]. This process is crucial for a hotel website, where the em ...

What is the best way for a parent process to interrupt a child_process using a command?

I'm currently in the process of working on a project that involves having the user click on an 'execute' button to trigger a child_process running in the backend to handle a time-consuming task. The code snippet for this operation is shown b ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

preventing the page from scrolling whenever I update my Angular view

Whenever I update a part of my model that is connected to my view, my page automatically scrolls. I suspect that the page scrolling is triggered by the view updates. How can I stop this from happening? For instance, here is an example involving a dropdown ...