1

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?

Aurora0001
13.6k6 gold badges53 silver badges53 bronze badges
asked Jul 30, 2016 at 12:25
1
  • Problem solved, sorry for bothering you people with basics i obviously missed >.< Commented Jul 30, 2016 at 12:35

3 Answers 3

2

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;
}
answered Jul 30, 2016 at 12:29
Sign up to request clarification or add additional context in comments.

Comments

1

is it possible that function cant go in another function?

It is completely possible, you're just doing it incorrectly. Variables can't 'escape' their scope (in this case, the function that they're inside), so you can't access d6 from the attackModifier function. Instead, return the value, like so:

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

You can then get the value of the roll like this:

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

The MDN documentation might have some useful explanation about how function returns work.

answered Jul 30, 2016 at 12:28

Comments

1

For you get the d6 variable in the attackModifier function, you need create this variable outside of d6Roll function.

Look like:

var d6;
function d6Roll() { ... }
function attackModifier() {...}
answered Jul 30, 2016 at 12:32

3 Comments

I find others solutions better but what you wrote here will be crucial for me later, I guess I'll have to investigate private/global variables in JS for this project and further, thank you :)
While this approach will certainly work (under strict conditions) it seems like a bad idea to actively encourage a bad practice like this, no?
Yes, this is not a good practice, dependency the situation, maybe can put the code in the IIFE to make private

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.