Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

What is the best way to square a number in JavaScript?

Let's say I want to find 4 squared, i.e. 4^2 or 4 to the power of 2.

Right now I have this:

var x = 5;

var x_squared = Math.pow(x,2);

Is this the best way? Is there a better way? I know in some languages you can do x**, or x^2.

1 Answer

The way you are doing it is perfect. There is an experimental feature in ES7 that will allow you to do a**b but that won't be out for some time so I'd stick to MATH.pow() until them.