JavaScript: Check two given integers, whether one is positive and another one is negative
JavaScript Basic: Exercise-20 with Solution
Write a JavaScript program to check two given integers whether one is positive and another one is negative.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named positive_negative that takes two parameters, x and y
function positive_negative(x, y) {
// Check if either x is negative and y is positive, or x is positive and y is negative
if ((x < 0 && y > 0) || (x > 0 && y < 0)) {
// If true, return true
return true;
} else {
// If false, return false
return false;
}
}
// Log the result of calling the positive_negative function with the arguments 2 and 2 to the console
console.log(positive_negative(2, 2));
// Log the result of calling the positive_negative function with the arguments -2 and 2 to the console
console.log(positive_negative(-2, 2));
// Log the result of calling the positive_negative function with the arguments 2 and -2 to the console
console.log(positive_negative(2, -2));
// Log the result of calling the positive_negative function with the arguments -2 and -2 to the console
console.log(positive_negative(-2, -2));
Output:
false true true false
Live Demo:
See the Pen JavaScript: positive negative number: basic-ex-20 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Using ES6 arrow function syntax to define the positive_negative function
const positive_negative = (x, y) => ((x < 0 && y > 0) || (x > 0 && y < 0));
// Log the result of calling the positive_negative function with the arguments 2 and 2 to the console
console.log(positive_negative(2, 2));
// Log the result of calling the positive_negative function with the arguments -2 and 2 to the console
console.log(positive_negative(-2, 2));
// Log the result of calling the positive_negative function with the arguments 2 and -2 to the console
console.log(positive_negative(2, -2));
// Log the result of calling the positive_negative function with the arguments -2 and -2 to the console
console.log(positive_negative(-2, -2));
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to check a given integer is within 20 of 100 or 400.
Next: JavaScript program to create a new string adding "Py" in front of a given string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics