A non-negative integer is a perfect square when it equals some integer k multiplied by itself: n = k × k.
Remember
n is a perfect square ↔ ∃ integer k ≥ 0 such that k² = n
Examples:
0 = 0²
1 = 1²
9 = 3²
16 = 4²
10 → no integer square root
n
√n idea
Perfect square?
16
4 × 4
Yes
25
5 × 5
Yes
10
between 3² and 4²
No
0
0 × 0
Yes
Approach
How to Check a Perfect Square in JavaScript
Four clear steps — then pick an integer loop or a sqrt-and-verify check.
Reject negatives (this tutorial treats only n >= 0).
Try candidate roots i = 0, 1, 2, … while i * i <= n.
If some i * i === n, return true; if you pass n, return false.
Or compute root = Math.floor(Math.sqrt(n)) and verify root * root === n.
Method
Idea
Time
Best for
Integer loop
Compare i * i with n
O(√n)
Interviews without floating point
sqrt + verify
Square the truncated root back
O(1)
Short production-style checks
Pseudocode
Pseudocode
function IsPerfectSquare(n):
if n < 0: return false
i = 0
while i * i <= n:
if i * i == n:
return true
i = i + 1
return false
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Definition
n = k² for some integer k ≥ 0
Zero
0 is a perfect square
Negatives
Not perfect squares here
Loop stop
While i * i <= n
sqrt verify
root * root === n after Math.floor
Classic checks
16 yes; 10 no; 25 yes
Try it
Live Preview
Enter an integer to see the nearest integer root and the perfect-square check.
Whole numbers only. Negatives are not perfect squares here. Tap a chip or type a value.
Result
n = 16
root = 4
4 × 4 = 16
16 is a perfect square
Code
JavaScript Programs
Start with the integer loop so you never rely on floating point. Use sqrt-and-verify for a short check, then generate squares by squaring k. Each example has a Try it Yourself editor.
Example 1 — Integer Loop
Increase i while i * i <= n and look for an exact match.
JavaScript
function isPerfectSquare(n) {
if (n < 0) {
return false;
}
for (let i = 0; i * i <= n; i++) {
if (i * i === n) {
return true;
}
}
return false;
}
const number = 16;
if (isPerfectSquare(number)) {
console.log(number + " is a perfect square");
} else {
console.log(number + " is not a perfect square");
}
The loop condition i * i <= n stops once squares go past n.
Each step checks whether i * i === n.
For 16, i = 4 matches and the function returns true.
If no match appears before the loop ends, the answer is false.
Example 2 — Perfect Squares from 1 to 50
Use Math.floor(Math.sqrt(n)), verify by squaring, and list every match.
JavaScript
function isPerfectSquare(n) {
if (n < 0) {
return false;
}
const root = Math.floor(Math.sqrt(n));
return root * root === n;
}
console.log("Perfect squares from 1 to 50:");
let line = "";
for (let i = 1; i <= 50; i++) {
if (isPerfectSquare(i)) {
line += i + " ";
}
}
console.log(line.trim());