Error in math code


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-javascript/lessons/introduction-to-javascript/exercises/random?action=lesson_resume

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
I defined a variable as a random number and tried to multiply it by 100. Although the random number is getting generated and but I am not able to go through with the multiplication.

var myNum = console.log(Math.floor(Math.random()*50))
console.log(myNum*100)

#2

@mahvash the random number expression you created is going to give you a result between 0 and 50
Math.random()*50
Math.floor will round the number down, while Math.ceil will round the number up.
Math.floor(Math.random()*50)

Assuming the rest of the code is correct
Your console statement will most likely give you a number between 0-4,900

However, in your first line of code, the variable myNum has been assigned a console.log statement
var myNum = console.log(Math.floor(Math.random()*50));

AND the second line of code is assuming that the variable myNum holds a numeric value, which it does not and will result in an error
console.log(myNum*100)


#3

I was including console.log in the variable definition. That was wrong. Thanks :slight_smile:


#4

It’s always good to find the reason why we are wrong.

The log method does not have a return value, so myNum will be undefined.


In JS, operators have a return value, so = will return a value. Consequently we can make an assignment in the expression we pass to console.log(). Don’t try this in the lessons, though, or it won’t pass. The pattern is not recognized by the SCT.

console.log(myNum = Math.floor(Math.random() * 50))

is a valid statement, though not very typical. Repeat, do not try to use this in lessons. The above will store the return value of = in myVar, then will log it.

The value will remain cached in the variable for continued processing, as needed.


#5

Thanks for the explanation. That was helpful :+1:


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.