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

Troubleshooting: AngularJS fails to refresh UI when using SignalR

When I attempt to incorporate this angularjs code into a signalR function, the UI does not update. Even using $scope.$apply() does not trigger a digest. This is the code snippet: var notificationHub = $.connection.progressNotificationHub; notificationHub. ...

Transform json nested data into an array using JavaScript

Can anyone assist me in converting Json data to a Javascript array that can be accessed using array[0][0]? [ { "Login": "test1", "Nom": "test1", "Prenom": "test1p", "password": "124564", "Email": "<a href="/c ...

Filter numbers within an Array using a Function Parameter

I'm currently experimenting with Arrays and the .filter() function. My goal is to filter between specified parameters in a function to achieve the desired output. However, I'm encountering an issue where my NPM test is failing. Although the outpu ...

What is the syntax for calling a constructor using "require"? Is it "require(module)(CONSTRUCTOR)"?

I am facing the following issue: I am trying to instantiate my constructor in this way: var object = require('module')([params]); The code for the module looks like this: function FunctionName(param) { // function body.. } exports = mod ...

angular model bind include move

I'm working on developing custom elements that will transform my form elements to match the styling structure of Bootstrap's forms. Essentially, <my-input ng-model="myname"> should be transformed into <div class="form-element"> ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

"Utilizing JSON data to implement custom time formatting on the y-axis with AmCharts

Looking to convert minutes to hh:mm:ss format in my JavaScript code var allDataTime = [{ date: new Date(2012, 0, 1), "col": "LONG CALL WAITING", "duration1": '720', "duration2": '57', "duration3": ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

What is the best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...

transfer the output from the second selection to the adjacent div

I am utilizing a library called select2 specifically for single choice scenarios. My goal is to transfer the selected option to a different div once it has been chosen. Here is the code I have so far: https://jsfiddle.net/hxe7wr65/ Is there a way to ach ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

jQuery for Cross-Site AJAX Communication: Enhancing Website Function

I currently have a jQuery plugin that performs numerous AJAX calls, mostly JSON data. I'm interested in finding the most efficient way to enable cross-site calls, where the URLs used in $.get and $.post are not from the same domain. While I've h ...

I am receiving an undefined value when using document.getElementsByClassName

<canvas id="can" height="500px" width="1200px"></canvas> <div class="name"> <h1>LEONARDO</h1> </div> <script> var name=['WATSON','LEONARDO',"SMITH","EMILY"] var counter=0 var dat ...

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...

The state in the React components' array functions is not current

import React, { useState } from "react"; const Person = ({ id, name, age, deleteThisPerson }) => { return ( <div className="person"> <p>{name}</p> <p>{age}</p> <button onClick ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

Tips for modifying jsFiddle code to function properly in a web browser

While similar questions have been asked before, I am still unable to find a solution to my specific issue. I have a functional code in jsFiddle that creates a table and allows you to select a row to color it red. Everything works perfectly fine in jsFiddle ...

Suggestions for managing AngularJS within ASP.NET Web Forms?

Recently, I integrated AngularJs into a website that is built with asp.net webforms. I discovered that when using ng-Submit on a button, the form also triggers a Post call. How can I prevent the form from automatically submitting so that Angular can perf ...

Wait for the scope value to become available before executing the directive or div

I have a unique directive created for SoundCloud that necessitates the SoundCloud URL. The URL is fetched from the database using the $http service, but the issue arises when the div for the directive is loaded before the URL value is defined. The code fo ...

Utilize the Spotify API to discover tracks by including the album title and artist's name in the search

Currently working on a project that involves searching for a music track on Spotify. The idea is to input the track name in the text area and generate a list of matching Track IDs along with Artist Names, Album Names, and Artwork. I have made some progress ...