We can use JavaScript to create a function that will divide two numbers easily. We simply need to use the division operator / in our function. Here is the simple function to divide two numbers.

function divideTwoNumbers(number1,number2){
  return number1/number2;
};

And that’s it.

Our simple function called divideTwoNumbers takes two parameters, the two numbers you want to divide. The function just divides the first number by the second and then returns the result.

Let’s see some examples of this function in use and the output it produces.

function divideTwoNumbers(number1,number2){
  return number1/number2;
};

console.log(divideTwoNumbers(2,3));
console.log(divideTwoNumbers(-2,3));
console.log(divideTwoNumbers(3,2));
console.log(divideTwoNumbers(1092,6732));
console.log(divideTwoNumbers(0,10000));
console.log(divideTwoNumbers(10002,0));

#Output
0.6666666666666666
-0.6666666666666666
1.5
0.1622103386809269
0
Infinity

Creating a JavaScript Function to Divide Two Numbers Using User Input

Below is an example of how we can create a function that will divide two numbers, and then execute the function when a user clicks on a button we create. We will call the JavaScript function we create using an onclick event that we will attach to the HTML button.

Enter two numbers below. Click Submit to have the divided value of the numbers displayed:

Below we will write our function. Because the button has the event onclick="divideNumbers()", the divideNumbers() function, which we will create below, will run when the button is clicked. The function will divide the two numbers that the user enters together and display the result. If something other than a number is entered, NaN will be returned.

We will retrieve the numbers the user has entered using the value property.

function divideNumbers() {
  var num1 = document.getElementById("userVal1").value;
  var num2 = document.getElementById("userVal2").value;
  var total = Number(num1) / Number(num2);
  document.getElementById("results").textContent = total;    
};

The final code and output for this example is below:

Code Output:

Enter two numbers below. Click Submit to have the divided value of the numbers displayed:



Full Code:

Enter two numbers below. Click Submit to have the divided value of the numbers displayed:

Hopefully this article has been useful in helping you learn how to create a JavaScript function to divide two numbers.

Categorized in:

JavaScript,

Last Update: March 11, 2024