Skip to content
the poor coder

js check which number is larger

Poor Man
Published
Reading time
1 min read
On this page

JS Check Which Number is Larger#

There are multiple ways to check which number is larger in JavaScript. Let me share with you some of the common methods.

Using Conditional Statements#

You can use conditional statements, such as if-else or ternary operators, to compare two numbers and determine which one is larger.

Text

let num1 = 10;
let num2 = 20;

if (num1 > num2) {
  console.log("num1 is larger");
} else {
  console.log("num2 is larger");
}

// Output: num2 is larger

// Using ternary operator
let result = (num1 > num2) ? "num1 is larger" : "num2 is larger";
console.log(result);

// Output: num2 is larger

Using Math.max()#

The Math.max() method can be used to find the largest number in a list of numbers. You can pass two or more numbers as arguments to this method and it will return the largest one.

Text

let num1 = 10;
let num2 = 20;

let largestNum = Math.max(num1, num2);
console.log(largestNum);

// Output: 20

If you have an array of numbers, you can use the spread operator (...) to pass the array elements as arguments to the Math.max() method.

Text

let numbers = [10, 20, 30, 40, 50];

let largestNum = Math.max(...numbers);
console.log(largestNum);

// Output: 50

Conclusion#

These are some of the common ways to check which number is larger in JavaScript. Choose the method that suits your needs and coding style.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC