JavaScript Perfect Square Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Is a Perfect Square?

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 ideaPerfect square?
164 × 4Yes
255 × 5Yes
10between 3² and 4²No
00 × 0Yes

How to Check a Perfect Square in JavaScript

Four clear steps — then pick an integer loop or a sqrt-and-verify check.

  1. Reject negatives (this tutorial treats only n >= 0).
  2. Try candidate roots i = 0, 1, 2, … while i * i <= n.
  3. If some i * i === n, return true; if you pass n, return false.
  4. Or compute root = Math.floor(Math.sqrt(n)) and verify root * root === n.
MethodIdeaTimeBest for
Integer loopCompare i * i with nO(√n)Interviews without floating point
sqrt + verifySquare the truncated root backO(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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Definitionn = k² for some integer k ≥ 0
Zero0 is a perfect square
NegativesNot perfect squares here
Loop stopWhile i * i <= n
sqrt verifyroot * root === n after Math.floor
Classic checks16 yes; 10 no; 25 yes

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

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");
}
Try It Yourself

How It Works

  1. Negatives return false immediately.
  2. The loop condition i * i <= n stops once squares go past n.
  3. Each step checks whether i * i === n.
  4. For 16, i = 4 matches and the function returns true.
  5. 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());
Try It Yourself

How It Works

  1. Negatives are rejected the same way as Example 1.
  2. Math.sqrt(n) returns a floating-point approximation of √n.
  3. Math.floor keeps the integer part of that root.
  4. Squaring root again and comparing with === confirms an exact square.
  5. The outer loop prints every match from 1 to 50 on one line.

Example 3 — Generate Squares

Build perfect squares directly by squaring successive integers k.

JavaScript
const maxK = 7;

console.log("First squares from k = 0 to " + maxK + ":");
for (let k = 0; k <= maxK; k++) {
  const square = k * k;
  console.log(k + " * " + k + " = " + square);
}
Try It Yourself

How It Works

  1. maxK is the largest root you want to print.
  2. Each step computes square = k * k — that value is always a perfect square.
  3. No floating-point check is needed because you build the square yourself.
  4. Change maxK in the Try it Yourself editor to print a longer list.
  5. This pattern is useful when you need a sequence of squares, not a yes/no test.

Edge Cases & Pitfalls

Check these before calling the solution done.

0

Zero counts

0 = 0². Do not special-case it as false.

Negatives

Not squares here

Return false for n < 0 in this beginner definition.

Precision

Safe integers

For very large n, stay within Number.MAX_SAFE_INTEGER so i * i stays exact.

sqrt

Always verify

Never decide from the float alone — square the floored root back and use ===.

Time and Space Complexity

ProgramTimeExtra space
Integer loopO(√n)O(1)
sqrt + verify / rangeO(1) per check; O(R) for range size RO(1)
Generate squaresO(maxK)O(1)

Both checks are fine for interviews. Prefer the loop when you must avoid floating-point discussion.

Key Takeaways

  • Definition: n = k² for some integer k ≥ 0.
  • Loop: test i * i while i * i <= n.
  • sqrt: Math.floor, then verify root * root === n.
  • Test set: 0 → yes; 16 → yes; 10 → no; -4 → no.

One line: find an integer root whose square equals n — by looping or by verifying Math.sqrt.

Frequently Asked Questions

A non-negative integer that equals some integer multiplied by itself. Examples: 0, 1, 4, 9, 16, 25.
Loop with i*i until you match or pass n, or take Math.floor(Math.sqrt(n)) and verify root*root === n.
Yes. 0 = 0 × 0.
sqrt returns a floating-point number. Rounding can misclassify edge values, so always square the integer root back and compare with ===.
A loop up to √n is O(√n). The sqrt-and-verify method is O(1) for practical interview sizes (one math call plus a few ops).
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.

Next: Power of 2

Check whether a number is a power of two.

Power of 2 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.

6 people found this page helpful