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.

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.



Follow us on Facebook and Twitter for latest update.