Martin Markovic Martin Markovic - 4 months ago 7
Javascript Question

JS simple function in function won't work

I wanted to make this 1 function and call it in function 2.

function d6Roll(){
var d6 = 1 + Math.floor(Math.random() * 6);
}
function attackModifier(){
d6Roll();
var aMod = d6;
document.getElementById("rezultatD6").innerHTML = aMod;
}


For some reason it works only like this:

function d6Roll(){
var d6 = 1 + Math.floor(Math.random() * 6);
document.getElementById("rezultatD6").innerHTML = d6;
}


Is it possible that function can't go inside another function?

Answer

I think you want to change the first function to this

function d6Roll(){
  return 1 + Math.floor(Math.random() * 6);
}  

so that you can call it in the second function like this

function attackModifier(){
  var aMod = d6Roll();
  document.getElementById("rezultatD6").innerHTML = aMod;
}