DEV Community

Divyajyoti Ukirde
Divyajyoti Ukirde

Posted on • Updated on

 

Easy peasy perfect square

The question is to return true if the number is perfect square otherwise false.
A perfect square is an integer that is the square of an integer.
Javascript provides numerous ways to write a code for this. I will let you know that this is what I did:

const isSquare = (n) => {
    return  (Math.sqrt(n) === Math.ceil(Math.sqrt(n)));
}
Enter fullscreen mode Exit fullscreen mode

Below is the solution that impressed me, because it is simple Math my brain couldn't get hold of first:

const isSquare = function(n){
  return Math.sqrt(n) % 1 === 0;
}
Enter fullscreen mode Exit fullscreen mode

And it is clever and also follows the best practices!

Checking the datatype would also work using isInteger. But you never know when it would get obsolete! Languages change but the Math around remains the same! Choose better!

Top comments (4)

Collapse
 
itsjzt profile image
Saurabh Sharma • Edited

I used Number.isInteger detect if the square is integer github.com/itsjzt/euler-project/bl...

Collapse
 
divyajyotiuk profile image
Divyajyoti Ukirde • Edited

That is very much correct. It shows your knowledge in the language is really good. Also, it is always better to know the underlying operations. :)

Collapse
 
itsjzt profile image
Saurabh Sharma

It shows your knowledge in the language is really good

Stack overflow

Thread Thread
 
divyajyotiuk profile image
Divyajyoti Ukirde

The solution doesn't matter, when you get it, you need to understand and ask why ;)

The JavaScript Brief

1. Top 5 MERN STACK projects to improve your practical understanding

Boost your MERN Stack development skills by undertaking interesting beginner projects. These five engaging projects cover web applications and range from social media website applications to geo-social networking maps. Hone your understanding and apply modern techniques backed up by hands-on experience.

2. How To Optimize Your React App’s Performance

Learn the best optimizing techniques to make your React applications faster and more efficient. Focusing on the identification of performance bottlenecks and common pitfalls to avoid, these optimization strategies will keep your applications running smoothly even when faced with growing complexity.

3. A story of let, const, object mutation, and a bug in my code

In the pursuit of bug-free code, explore an incident involving a mix-up between const and let, making sure your custom code works effectively with third

party documentation. Discover best practices on program flow and learn about JavaScript's unpredictable aspects to ensure your core code is robust.