How to access a LOCAL variable in one function from another function

function func1() {
    var num1 = 6;
    console.log(num1);
}
 
function func2() {
    var final = num1 + 5;
    console.log(final);
}

func2(); 

Please help. I searched and read about 15-20 articles on Google but nothing helped. Thank you.

That’s because it’s not possible. You simply can’t access a variable that is not in your line of scope.

1 Like

Hey there.

It really depends on what you want to solve and how.
Variables are scoped to their function and all sub contexts.

You are missing one very important part here: functions have inputs and outputs.

For example, you can pass a number to that function

function func1(num1) {
    return num1 + 5
}

var num2 = func1(7)
console.log(num2) // 12

So you can pass values as arguments and get the value via return.

I hope this answers your question.

4 Likes

Many many Thanks Martin. Issue solved. Here is my code now.

function func1(num1) {
    return num1 + 5;
}

function func2() {
	var num2 = func1(7);
	console.log(num2);
}

func2();

Thank you :slight_smile:

1 Like

Awesome! This looks a lot better. Glad you made it :smiley:

1 Like

func2() should return the result (like func1() does), not log it. This way you are more flexible with what you can do with the result (logging/display/more calculations).

1 Like

Yup, right now I am just watching it in the console :slight_smile:

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