+ 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
8 Respuestas
+ 17
To get 'RollSum' value you must call getRoll function .
Eg-
getRoll();
console.log (RollSum) ;
+ 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;'
+ 2
gotta feel the vibe return 1;
+ 2
Use var y = getRoll() : Call the function not a internal variable 🤔 console.log(y)
+ 1
VEDANG Is it possible to get all values returned?
+ 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>
+ 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.
+ 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());