Date & Math
In real-world applications, time and calculations are everywhere. We track dates, calculate prices, generate random values, and round numbers for display.
JavaScript provides built-in tools like the Date object and the Math object to handle these tasks easily.
Working with Dates
The Date object is used to work with dates and times.
It can represent the current date or a specific date.
Creating a Date
You can create a date using the new Date() constructor.
let today = new Date();
This stores the current date and time.
Getting Date Information
JavaScript provides methods to extract parts of a date.
let now = new Date();
now.getFullYear();
now.getMonth();
now.getDate();
These methods help display readable dates to users.
Real-World Date Example
Imagine showing today’s date on a dashboard:
let date = new Date();
let message =
date.getDate() + "/" +
(date.getMonth() + 1) + "/" +
date.getFullYear();
console.log(message);
Dates are widely used in logs, reports, and scheduling systems.
The Math Object
The Math object provides useful mathematical functions.
You do not need to create it — it is available by default.
Common Math Methods
Math.round(4.6);
Math.floor(4.9);
Math.ceil(4.1);
Math.random();
These methods are commonly used in pricing, scoring, and random selection.
Real-World Math Example
Imagine generating a random discount:
let discount =
Math.floor(Math.random() * 10) + 1;
console.log("Discount:", discount + "%");
This logic is often used in promotions and games.
Common Beginner Mistakes
- Forgetting that months start from 0
- Using
Math.random()without a range - Manually calculating values instead of using Math methods
Built-in methods reduce errors and improve clarity.
Thumb Rules
- Use
Datefor all date and time operations - Remember that months are zero-based
- Use
Mathmethods instead of manual calculations - Keep date formatting user-friendly
More on Date & Math Later
This lesson covered basic usage of Date and Math objects.
More advanced handling is covered later.
- Timers and scheduling are explained in Lesson 24 (Timers)
- Advanced calculations appear in real-world projects later
What Comes Next?
Now that you can work with dates and calculations, it’s time to handle errors safely.
In the next lesson, we will learn about error handling.