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 JavaScript Foundations Numbers Operators

Balint Nagy-Bajnoczi
Balint Nagy-Bajnoczi
1,618 Points

How do I use the "E" (e.g. 1E2) scientific notation with the variables in this challenge?

If

var a = 1; b = 2; c = 4;

Then to get to 100 I could use aEb (i.e. 1E2), but JS doesn't understand aEb (even if I use backslashes). Is there a way to make this work?

Thanks!

5 Answers

Hi Balint,

I suppose the closest thing to what you're trying to do would be to use the eval function to create a number in exponential form using variables as opposed to number literals like 1E2

eval(a + 'E' + b); This will evaluate to 100.

Generally, it's considered bad to use eval I don't know enough about it to say whether or not this would be one of the acceptable uses for it. Some people say it's evil and never to use it and others say it's ok if you understand it and know when it's appropriate.

That being said, it won't get you past the challenge because you're not allowed to use functions in the challenge. I didn't try Math.pow but I suspect that won't work either, at least in the challenge.

Thinking about it a little more you could also do this: Number(a + 'E' + b); and avoid the eval function

There you're converting the string '1E2' to a number.

But again, it won't pass the challenge.

Use the Math.pow( base, exponent ) method:

var a = 1;
var b = 2;
var c = 4;


var pow = Math.pow( b, c ); // 16

It's a little weird. With a lot of languages, you can use the ** operator. Maybe it works like that with JS too; I've never tried it.

EDIT: Ugh, silly me. Hold on while I get a better answer.

I guess the best way to do so is a little verbose. Still using Math.pow().

// aEb

var a = 1;
var b = 2;

var pow = a * Math.pow( /* base 10 */ 10, /* exponent */ b ); // 100
Balint Nagy-Bajnoczi
Balint Nagy-Bajnoczi
1,618 Points

Thanks Ryan, so then I guess you can't use the "E"...

Balint Nagy-Bajnoczi
Balint Nagy-Bajnoczi
1,618 Points

Cool, thanks Jason!

I realized the challenge wouldn't accept Math.pow after a good 15-20min looking through results to my query on google, nevertheless, I wanted to know if and how it could be done irrespective of the challenge.