In this short, I show you the quickest way to generate a 4-digit OTP using just JavaScript – no libraries, no dependencies.
🚀 Generate 4-Digit OTPs Instantly with JavaScript (No Libraries!)
Stop searching! Learn the quickest way to create secure 4-digit OTPs using just plain JavaScript. This super lightweight trick is perfect for:
⚡ OTP generation
🔑 Temporary passwords
🧪 Testing scenarios
We break down the code step-by-step: Math.random(), * 9000, + 1000, and Math.floor(). Master this essential JavaScript trick for interviews and clean code!
Here's the code:
const otp = Math.floor(1000 + Math.random() * 9000);
console.log(otp);
Let’s break it down:
🔹 Math.random() generates a number between 0 and 1.
🔹 Multiplying it by 9000 gives a number between 0 and 8999.
🔹 Adding 1000 shifts the range to 1000–9999 — exactly 4 digits!
🔹 Math.floor() removes the decimal part to give you a whole number.
✅ This is a perfect trick for generating OTPs, temporary passwords, or testing scenarios — and it's super lightweight and efficient.
If you're preparing for JavaScript interviews or just want to learn how to write clean and practical code, this trick is a must-know!
#javascript #jsinterview #webdevelopment #codingtips #frontendinterview #techshorts #jsconcepts #es6 #developerlife #programming #learnjavascript #jstips #shorts #ytshorts #jsquestions #jsinterviewprep #javascriptshorts #techinterview #codeinterview #softwareengineering #advancedjavascript #devshorts #frontenddeveloper #webdevshorts #jsexplained #jsfundamentals #jstypes #otp #javascriptotp #mathrandom #randomnumber #cleanjavascript #quickjs #javascripttricks #jsutility #codinginterviewprep