How to use If-else Statements In Javascript
In this approach, we will check the value of both X and Y coordinates using the if-else statement in JavaScript. The conditional statement will check whether the value is positive or negative and return their quadrant based on them.
Example: The below code will explain the use of the if-else statement to check the quadrant of the given coordinate.
function getQuadrants(x, y) {
if (x > 0 && y > 0) {
return `The point (${x}, ${y}) lies in Quadrant I`;
} else if (x < 0 && y > 0) {
return `The point (${x}, ${y}) lies in Quadrant II`;
} else if (x < 0 && y < 0) {
return `The point (${x}, ${y}) lies in Quadrant III`;
} else if (x > 0 && y < 0) {
return `The point (${x}, ${y}) lies in Quadrant IV`;
} else if (x === 0 && y !== 0) {
return `The point (${x}, ${y}) lies on the y-axis`;
} else if (x !== 0 && y === 0) {
return `The point (${x}, ${y}) lies on the x-axis`;
} else {
return `The point (${x}, ${y}) lies at the origin (0, 0)`;;
}
}
console.log(getQuadrants(5, 8));
console.log(getQuadrants(-2, 7));
console.log(getQuadrants(-7, -9));
console.log(getQuadrants(3, -6));
Output
The point (5, 8) lies in Quadrant I The point (-2, 7) lies in Quadrant II The point (-7, -9) lies in Quadrant III The point (3, -6) lies in Quadrant IV
Time Complexity : O(1)
Space Complexity : O(1)
JavaScript Program to Return Quadrants in which a given Coordinate Lies
There are four quadrants in cartesian coordinate system. The names of the quadrants are: Quadrant I, Quadrant II, Quadrant III, and Quadrant IV.
The below approaches can be used to find the quadrant of the given coordinate:
Table of Content
- Using If-else Statements
- Using the ternary operator