Conditions in Java Script - Understanding the Basics

Can you identify the issue with this function and explain why it isn't functioning correctly? The goal was to create a function that performs the following tasks: 1. Define a function named "divide" that accepts one parameter, which is a number. 2. If the number is greater than 20, divide it by 4 and return the result. 3. If the number is greater than 10, divide it by 3 and return the result. 4. Otherwise, divide it by 2 and return the result.

function divide(x) {
    if (x > 20) {
        document.write(x / 4);
    }
    else if (x > 10){
        document.write(x / 3);
    } else {
        document.write(x / 2);
    }
    document.getElementById("demo").innerHTML = divide(23);
}

Answer №1

Avoid recursively calling the function divide by moving the part that invokes it outside of the method. Apart from that, you're heading in the correct direction as indicated on this resource. To execute it properly, we can include a div element with an assigned id and then run the script. For example:

function divide(x) {
  if (x > 20) {
    return x / 4;
  } else if (x > 10) {
    return x / 3;
  } else {
    return x / 2;
  }
}
document.getElementById("result").innerHTML = divide(23);
<div id='result'></div>

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

InvalidSyntaxError: Client login cannot be completed due to an unexpected end of input. Please

I encountered an issue while trying to create a bot that sends welcome messages for my friend's server. Despite numerous attempts to troubleshoot the problem within my code, I have been unable to resolve it. Any assistance in solving this error would ...

The scrolling behavior of Chrome tabs or bookmarks can impact the functionality of an Angular

I recently came across a strange problem with my angularjs page that includes a slick carrousel. In the controller, I have code that listens for the $destroy event to remove certain injected elements by slick. However, I noticed that whenever I scroll ov ...

Looking for a Plugin that Can Responsively Display Images in a Vertical Layout - Does One Exist using Jquery

Looking for a gallery slider plugin that is responsive both horizontally and vertically. Have tried Flexslider1/2, Galleria, and others but they do not adjust to vertical resizing. Changing the CSS did not help. If you resize the browser horizontally with ...

Monitor the Ajax for any updates in the database and trigger the code accordingly

My objective is to send requests to a php file with specific parameters in this format: <!DOCTYPE html> <html> <head> <script> function onsubmit() { var id = $_SESSION['user']['id']; var xmlhttp; if ...

Is it possible to alter the input value dynamically before submitting the form or refreshing the

I am looking to automatically update a hidden input value to either "0" or "1" based on whether a user fills out the phone number field. My current code is below: <script> if(document.getElementById('user-tel').value!='') { docu ...

Need help resolving an issue with an HTML header that's overlapping in JavaScript?

Hey there! I was working on implementing a dynamic header that resizes as you scroll on the page. I also decided to try out Headroom as an additional solution, and it seems to be functioning well in terms of hiding the header. You can check out my progress ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

Read through the text, determine the length of each word, and keep track of how

Objective: Create a JavaScript program that takes input from users in the form of several lines of text and generates a table displaying the count of one-letter words, two-letter words, three-letter words, etc. present in the text. Below is an example ou ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Halt execution of routes using backbone.js

Is it feasible to halt route execution within backbone.js solely using the router? I understand there is a callback function for each route where I could verify if routing is permitted, but I am unsure how to prevent execution based on a property (such as ...

Attempting to successfully upload an image and have it appear on the screen

Hey there, I'm having trouble uploading an image and displaying it on my screen. Can anyone lend a hand? I was trying to use this example as a guide: http://jsfiddle.net/kkhxsgLu/2/ Check It Out! <div class= "col-sm-6"> Upload an image: &l ...

Could you please explain the meaning of "rc" in the names of configuration files?

Many tools in the modern JavaScript ecosystem choose to name their configuration files with a suffix of rc. This naming convention can be seen in examples such as: ES Lint -> .eslintrc.json npm -> .npmrc.json yarn -> .yarnrc I am aware that the ...

Displaying the quantity of directories within a specific location

Can anyone help me troubleshoot my code? I'm trying to have a message displayed in the console when the bot is activated, showing the number of servers it is currently in. const serversFolders = readdirSync(dirServers) const serversCount = parseInt(s ...

What is the method for transforming a string containing the name of an array into a format that can be displayed in a Vue.js template?

<b-card v-for='callType in callTypes' no-body class="mb-1"> <b-table striped hover :items="{{callType.lineType}}"> </b-table> </b-card> When each callType is the name of an array. callTypes: [m ...

How can I save the output of a function in a variable within an *ngIf directive and then utilize it within the same *ngIf block?

My scenario is as follows: I have a function that returns an array I need to conditionally render a component - only if the array exists and its length is greater than zero. The returned array should be passed as an @Input() to this component. Since t ...

How can I modify the border color within a div element?

My journey into web development is just beginning, and I've grasped the basics of Java, JSP, HTML, JS, CSS, and JQ. However, I've hit a roadblock while attempting to change the border color of a div upon mouse hover. Despite my efforts, I haven&a ...

Utilizing Vue's data variables to effectively link with methods and offer seamless functionality

I am encountering difficulty retrieving values from methods and parsing them to provide. How can I address this issue? methods: { onClickCategory: (value) => { return (this.catId = value); }, }, provide() { return { categor ...

Tips for effectively utilizing Vuelidate to display errors selectively after the user has completed input:

I have implemented a form using Bootstrap-Vue with some Vuelidation code applied to it. <b-form @submit.prevent="onSubmit"> <input type="hidden" name="_token" :value="csrf" /> <transition-group name="fade"> <b-form ...

Utilize VueJS to upload and visualize a file input on your website

I am currently working with TypeScript and Haml in conjunction with vue.js. My goal is to enable users to upload and view a file seamlessly using the vue.js framework. I have successfully managed to upload an image, however, I am facing an issue where the ...

A novel RxJS5 operator, resembling `.combineLatest`, yet triggers whenever an individual observable emits

I am searching for a solution to merge multiple Observables into a flattened tuple containing scalar values. This functionality is similar to .combineLatest(), but with the added feature that it should emit a new value tuple even if one of the source obser ...