TypeScript: Check if a Number is Odd or Even

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

1. Introduction

Determining if a number is odd or even is a fundamental programming task that is often used in a variety of applications. TypeScript, being a superset of JavaScript, provides us with the tools necessary to accomplish this task effectively.

2. Program Overview

This program will contain a function named checkOddEven which will take a number as its parameter. It will return a string stating whether the number is 'Odd' or 'Even'.

3. Code Program

// Define the function with TypeScript type annotations
function checkOddEven(num: number): string {
    if (num % 2 === 0) {
        return 'Even';
    } else {
        return 'Odd';
    }
}

// Test the function
const numberToCheck = 8;
const result = checkOddEven(numberToCheck);
console.log(`${numberToCheck} is an ${result} number.`);

Output:

8 is an Even number.

4. Step By Step Explanation

We use the modulus operator (%) to find the remainder of the division of the number by 2. If a number is divisible by 2 with no remainder (i.e., the remainder is 0), then it's an even number. 

For our example:

8 divided by 2 = 4 with a remainder of 0.

Hence, 8 is an even number.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare