w3resource

JavaScript: Get the difference between a given number

JavaScript Basic: Exercise-15 with Solution

Write a JavaScript program to get the difference between a given number and 13, if the number is broader than 13 return double the absolute difference.

This JavaScript program calculates the difference between a given number and 13. If the number is less than or equal to 13, it returns the absolute difference. However, if the number is greater than 13, it returns double the absolute difference. It demonstrates conditional statements to determine the appropriate action based on the value of the given number.

Sample Solution:

JavaScript Code:

// Define a function named difference that takes a parameter n
function difference(n) {
    // Check if n is less than or equal to 13
    if (n <= 13) {
        // If true, return the difference between 13 and n
        return 13 - n;
    } else {
        // If false, return the double of the difference between n and 13
        return (n - 13) * 2;
    }
}

// Log the result of calling the difference function with the argument 32 to the console
console.log(difference(32));

// Log the result of calling the difference function with the argument 11 to the console
console.log(difference(11)); 

Output:

38
2

Live Demo:

See the Pen JavaScript: Number difference - basic-ex-15 by w3resource (@w3resource) on CodePen.


ES6 Version:

 // Difference function using arrow function
const difference = (n) => {
  return n <= 13 ? 13 - n : (n - 13) * 2;
};

// Example usage
console.log(difference(32));
console.log(difference(11));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript exercise to get the extension of a filename.
Next: JavaScript program to compute the sum of the two given integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-basic-exercise-15.php