+ 9

Why this simple function doesn't return any value?

var RollSum, RollFirst, RollSecond; function getRoll() { RollFirst = Math.floor(Math.random() * 6 + 1); RollSecond = Math.floor(Math.random() * 6 + 1); RollSum = RollFirst + RollSecond; return RollSum; } console.log(RollSum); //outputs Undefined

8th Jul 2019, 5:36 PM
cadbrooke
cadbrooke - avatar
8 Respuestas
+ 17
To get 'RollSum' value you must call getRoll function . Eg- getRoll(); console.log (RollSum) ;
8th Jul 2019, 5:40 PM
VEDANG
VEDANG - avatar
+ 15
gotta feel the vibe All the variable gets the values. Example- getRoll(); console.log(RollSum); //8 console.log(RollFirst); //3 console.log(RollSecond); // 5 Also there is not need of 'return RollSum;'
8th Jul 2019, 6:25 PM
VEDANG
VEDANG - avatar
+ 2
8th Jul 2019, 5:55 PM
Kelly (offline)
Kelly (offline) - avatar
+ 2
Use var y = getRoll() : Call the function not a internal variable 🤔 console.log(y)
9th Jul 2019, 7:22 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
VEDANG Is it possible to get all values returned?
8th Jul 2019, 5:49 PM
gotta feel the vibe
gotta feel the vibe - avatar
+ 1
Hi, Try below code. Use "return console.log" within script block, this worked fine for me with Firefox browser. For output you can check console output log by pressing key fn+F12 <!DOCTYPE html> <html> <body> <button onclick="getRoll()">Value</button> <script> var RollSum, RollFirst, RollSecond; var random1 = Math.random() function getRoll() { RollFirst = Math.floor(random1 * 6 + 1); RollSecond = Math.floor(random1 * 6 + 1); RollSum = RollFirst + RollSecond; return console.log(RollSum); } </script> </body> </html> Else try with window.alert <!DOCTYPE html> <html> <body> <button onclick=getRoll()>Check</button> <script> var RollSum, RollFirst, RollSecond; var random1 = Math.random() function getRoll() { RollFirst = Math.floor(random1 * 6 + 1); RollSecond = Math.floor(random1 * 6 + 1); RollSum = RollFirst + RollSecond; return window.alert(RollSum); } </script> </body> </html>
8th Jul 2019, 10:44 PM
Anil
+ 1
rollsum is only defined in getroll function. try console.log(getroll()); to print rollsum. even though rollsum is a global variable, it still needs to be created by calling getroll() before you can print it.
9th Jul 2019, 6:18 AM
Rick Shiffman
Rick Shiffman - avatar
+ 1
You can do get the output in two way. 1: call the getRoll() function then print RollSum variable in console. getRoll(); console.log(RollSum) Note: As you declare the variable without var/let/const keyword. The variable becomes a global variable. So, you can access the variable anywhere in your code. When you call the function it assigns a value to the variable. So, that it can print the output of your function. It is Not Recommended to declare a variable without var keyword. It can accidentally overwrite an existing global variable. 2. You can console your function to get the result. console.log(getRoll());
9th Jul 2019, 11:25 AM
Sushil Kundu
Sushil Kundu - avatar