w3resource

JavaScript: Compute the absolute difference between a specified number and 19

JavaScript Basic: Exercise-17 with Solution

Write a JavaScript program to compute the absolute difference between a specified number and 19. Returns triple the absolute difference if the specified number is greater than 19.

Sample Solution:

JavaScript Code:

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

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

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

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

Sample Output:

7
0
9

Live Demo:

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


Flowchart:

Flowchart: JavaScript - Compute the absolute difference between a specified number and 19

ES6 Version:

// Using ES6 arrow function syntax to define the diff_num function
const diff_num = (n) => {
  // Check if n is less than or equal to 19
  if (n <= 19) {
    // If true, return the difference between 19 and n
    return 19 - n;
  } else {
    // If false, return three times the difference between n and 19
    return (n - 19) * 3;
  }
};

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

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

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

Previous: JavaScript program to compute the sum of the two given integers.
Next: JavaScript program to check two given numbers and return true if one of the number is 50 or if their sum is 50.

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.