Check Perfect Square in JavaScript

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A perfect square equals k * k for some whole number k. Examples: 1, 4, 9, 16, 25. This tutorial covers the loop and Math.floor(Math.sqrt(n)) approaches, a live checker, worked JavaScript examples, edge cases, and complexity.

Definition

n = k²

Some integer k squares to n.

i*i Loop

Beginner

Try candidates while i*i <= n.

Math.sqrt

Robust

Integer root, then root * root === n.

0 and 1

Both square

0*0 and 1*1 both count.

Live Preview

Try 16 / 15

See k and the verdict instantly.

Not Perfect Number

Different idea

Squares vs divisor sums.

Introduction

A perfect square is a non-negative integer that equals some integer squared. So 16 is perfect because 4 * 4 = 16, while 15 is not because no whole k works.

Interviews usually accept either a clear i * i loop or a Math.floor(Math.sqrt(n)) check. Prefer integer roots over floating sqrt so large values stay exact.

Why it matters?

It is a classic math interview warm-up that teaches exact integer reasoning without float traps.

Key Highlights

n = k²

Some integer k squares to n.

Two Methods

Loop or Math.floor(Math.sqrt(n)).

0 and 1

Both are perfect squares.

Avoid Float

Math.sqrt with floor beats raw float sqrt.

In short: find whether some integer k satisfies k * k === n.

📝 Problem & Approach

Given an integer n, decide whether it is a perfect square of a non-negative integer.

JavaScript
# 16 -> 4 * 4 = 16   perfect
# 15 -> no integer k  not perfect
# 0  -> 0 * 0 = 0    perfect
# 1  -> 1 * 1 = 1    perfect

Inputs & Outputs

ItemTypeDescription
n / numberintValue to test (non-negative for yes).
Returnbooltrue when some k has k * k === n.
Optional kintThe integer root when the answer is yes.

Minimal workflow

Pseudocode
function isPerfectSquareLoop(n) {
  if (n < 0) {
    return false;
  }
  let i = 0;
  while (i * i <= n) {
    if (i * i === n) {
      return true;
    }
    i += 1;
  }
  return false;
}

Method comparison

MethodIdeaNotes
i*i loopTry candidates until square exceeds nClearest for beginners
Math.sqrtroot = Math.floor(Math.sqrt(n)); root * root === nFast and exact for integers
float sqrtMath.round(Math.sqrt(n)) ** 2 === nRisky for large n — avoid

⚡ Quick Reference

GoalPattern
Reject negativesif (n < 0) return false
Loop checkwhile (i * i <= n)
Exact hitif (i * i === n) return true
Math.sqrt checkroot = Math.floor(Math.sqrt(n))
Verify rootreturn root * root === n
Build squaresk * k for k = 0, 1, 2, …

📋 Loop vs Math.sqrt vs Float

Same question — different reliability.

i*i loop
while i*i <= n

Interview-friendly and exact

Math.sqrt
root * root === n

Preferred production check

float sqrt
avoid for ints

Rounding can lie on big n

vs perfect number
k*k vs s(n)=n

Different “perfect” meaning

Context

When This Problem Shows Up

Reach for a square check whenever you need exact integer roots.

  1. Interview warm-ups

    Simple math with an exactness twist.

  2. Grid / geometry puzzles

    Can n form a square layout?

  3. Filtering sequences

    Keep only square values in a range.

  4. Teaching Math.sqrt

    Show why integer roots beat floats.

  5. Not for float domains

    This tutorial targets integer n.

Key benefit: one crisp boolean question that forces you to think in exact integers, not approximate roots.

🔮 Live Preview

Checks with integer logic, then reports the root and verdict.

Use whole numbers n >= 0.

Live result
Press “Run check” to see result.

Examples Gallery

Three complete JavaScript programs — loop check for 16, list squares from 1 to 50 with Math.sqrt, and generate squares by squaring. Click View Output to reveal sample console results.

📚 Getting Started

A beginner-friendly loop that never needs floating roots.

Example 1 — Integer Loop Check

Simple and beginner-friendly perfect square check.

JavaScript
function isPerfectSquare(number) {
  if (number < 0) {
    return false;
  }
  let i = 0;
  while (i * i <= number) {
    if (i * i === number) {
      return true;
    }
    i += 1;
  }
  return false;
}

const testNumber = 16;
if (isPerfectSquare(testNumber)) {
  console.log(`${testNumber} is a perfect square.`);
} else {
  console.log(`${testNumber} is not a perfect square.`);
}

How It Works

Candidates advance from 0 while i * i has not passed 16. When i reaches 4, the product matches and the function returns true.

⚡ Integer Square Root

Use Math.floor(Math.sqrt(n)) for a crisp, exact check.

Example 2 — Range Scan Using Math.sqrt

Use Math.floor(Math.sqrt(n)) and log all perfect squares from 1 to 50.

JavaScript
function isPerfectSquare(num) {
  if (num < 0) {
    return false;
  }
  const root = Math.floor(Math.sqrt(num));
  return root * root === num;
}

console.log("Perfect Squares in the Range 1 to 50:");
let line = "";
for (let i = 1; i <= 50; i++) {
  if (isPerfectSquare(i)) {
    line += i + " ";
  }
}
console.log(line.trim());

How It Works

Math.floor(Math.sqrt(num)) returns the floor of the square root. Squaring that root recovers num exactly when num is a perfect square.

Example 3 — Generate Squares by Squaring

Build squares directly instead of filtering every integer.

JavaScript
console.log("First squares from k = 0 to 7:");
for (let k = 0; k <= 7; k++) {
  const square = k * k;
  console.log(`${k} * ${k} = ${square}`);
}

How It Works

When you only need the square sequence, squaring consecutive integers is cheaper than testing every n in a range.

🧠 How the Algorithm Decides

1

Reject negatives

No non-negative integer squares to a negative.

Guard
2

Find a candidate root

Loop i while i*i <= n, or call Math.sqrt(n).

Search
3

Compare square to n

Exact match means perfect square.

Rule
=

Return the verdict

true with root k, or false.

🔎 Worked Walkthrough — 16

Trace the loop method for n = 16.

ii * ii*i <= 16?Match?
00YesNo
11YesNo
24YesNo
39YesNo
416YesYes — return true

4 * 4 equals 16 — perfect square.

Use Cases

Where perfect-square checks show up beyond the interview prompt.

1. Interview Classics

Exact integer math checks.

Example: is_square(16).

2. Range Filtering

List squares inside a band.

Example: 1..50 list.

3. Sequence Generation

Build squares with k*k.

Example: Example 3.

4. Grid Layouts

Can n tiles form a square?

Example: 25 -> 5×5.

5. Teaching Math.sqrt

Show exact integer roots.

Example: avoid float sqrt.

6. Next: Averages

Continue the interview chain.

Example: related CTA.

Pro Tip: say “I’ll check whether root*root equals n using an integer root” before coding.

Advantages

Why these approaches work well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 16 on paper and watch i grow.

  2. 2. Exact Integers

    No float rounding surprises with Math.sqrt.

  3. 3. Two Clear Styles

    Loop for clarity; Math.sqrt for speed.

  4. 4. Generates Cleanly

    k*k builds the sequence without scanning.

Pro Tip: lead with the loop in interviews, then mention Math.floor(Math.sqrt(n)) as the robust alternative.

Usage Tips

Small habits that keep square checks interview-ready.

  1. 1. Guard Negatives

    Return false immediately for n < 0.

  2. 2. Prefer Math.sqrt

    Exact integer root for production code.

  3. 3. Verify root*root

    Never trust a root without squaring back.

  4. 4. Generate When Possible

    Use k*k if you need the sequence itself.

  5. 5. Separate From Perfect Number

    Name the definition so interviewers know you know.

Pro Tip: sanity-check 0, 1, 16, and 15 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break perfect-square programs.

  1. 1. Trusting float sqrt

    Large ints can round incorrectly.

    → Use Math.floor(Math.sqrt(n)) or an integer loop.

  2. 2. Skipping root verification

    Taking floor(sqrt) without squaring back.

    → Always compare root * root to n.

  3. 3. Confusing With Perfect Number

    Different “perfect” concept entirely.

    → This page is about k * k.

  4. 4. Forgetting 0

    Starting i at 1 and rejecting zero.

    → 0 = 0 * 0 is a square.

  5. 5. Accepting Negatives

    Returning true for -16 in real-integer checks.

    → Reject n < 0 in this tutorial.

Edge Cases

Handle these before claiming the check is complete.

n = 0

Zero is square

0 = 0 * 0.

n = 1

One is square

1 = 1 * 1.

Negative

Not a real integer square

Return false for negatives in this tutorial.

Large n

Avoid float precision

Prefer Math.floor(Math.sqrt(n)) over float sqrt.

15

Classic no

Between 9 and 16 — not square.

16

Classic yes

4 * 4 = 16.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Odd gaps. Differences between consecutive squares are odd: 3, 5, 7, 9…
  • Grid picture. n tiles form a square if and only if n is a perfect square.
  • Math.sqrt identity. Perfect ⇔ Math.floor(Math.sqrt(n)) ** 2 === n for n >= 0.
  • Name clash. Perfect square ≠ perfect number.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 16

  • Trace the loop
  • Confirm 4 * 4

2. Reject 15

  • Show no matching i
  • Math.floor(Math.sqrt(15)) = 3, 9 !== 15

3. List 1..50

  • Reproduce Example 2
  • Expect seven values

4. Generate k*k

  • Print first eight squares
  • Match Example 3

Notes

  • Definition: n is square if n = k * k.
  • Methods: integer loop or Math.floor(Math.sqrt(n)).
  • Remember: 0 and 1 are perfect squares.
  • Prefer Math.floor(Math.sqrt(n)) over float sqrt. The loop approach takes O(sqrt(n)) checks. Return false immediately for negatives.

Quick Takeaway: n is a perfect square when some integer k satisfies k * k === n.

⏱️ Time and Space Complexity

ApproachTime (single n)Extra space
Loop until i*i > nO(sqrt(n))O(1)
Math.sqrt-based checkO(1) practicalO(1)
Range 1..U scanO(U) checksO(1)

For interview demos, either method is fine; mention float pitfalls when asked about reliability.

Wrap Up

🎉 Conclusion

A perfect square equals some integer squared. Use an i * i loop or Math.floor(Math.sqrt(n)), reject negatives, and remember that 0 and 1 count.

Practice the three examples above, then continue to finding the average of N numbers.

n = k² means perfect square; verify with integers, not float sqrt.

💡 Best Practices

✅ Do

  • Reject negatives early
  • Verify root * root === n
  • Prefer Math.floor(Math.sqrt(n)) for exactness
  • Treat 0 and 1 as squares
  • Generate with k*k when listing

❌ Don’t

  • Trust float sqrt alone
  • Skip squaring the root back
  • Confuse with perfect numbers
  • Forget zero as a square
  • Accept negatives as yes

Key Takeaways

Knowledge Unlocked

Five things to remember about perfect squares

Decide exact squares the interview-friendly way.

5
Core concepts
i 02

Loop

while i*i

Method
03

Math.sqrt

root*root

Robust
0 04

Edges

0, 1 yes

Guards
O 05

Cost

O(√n)

Analysis

❓ Frequently Asked Questions

A whole number is a perfect square if it equals k * k for some whole number k.
Yes. 1 = 1 * 1.
The loop is easy to understand and avoids floating-point concerns.
It means we only test candidate roots whose square has not passed n.
Yes. Use Math.floor(Math.sqrt(n)) and verify root * root === n for integer checks.
No. Perfect square is about k * k; perfect number is about divisor sums.
Yes. 0 = 0 * 0.
Large integers can round incorrectly with floating sqrt; squaring the floored root stays safer.
About O(sqrt(n)) candidate checks for a single n.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Did you Know? 🔊

A perfect square can be arranged into a square grid with equal rows and columns. The gaps between consecutive squares (1, 4, 9, 16...) are odd numbers (3, 5, 7, 9...).

Continue to Average of N Numbers

Learn how to find the average of N numbers in JavaScript.

Average tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful