Home > Enterprise >  How to use a variable within a function and use it in a secondary function? Javascript
How to use a variable within a function and use it in a secondary function? Javascript

Time:01-16

How to get a local variabel to be set into a global one and use it in a secondary function? function 1 will be called in HTML initially then function 2 will be called...

function test1(){
  var test1 = 1;
}

function test2(){
  var test2 = test1   3;
}

CodePudding user response:

In order to use the variable "test1" within the "test2" function, you can either pass it as an argument to the "test2" function, or you can make the "test1" variable a global variable by declaring it outside of the "test1" function. Here's an example of both methods:

Method 1: Pass as an argument

function test1(){
  var test1 = 1;
  test2(test1);
}

function test2(test1){
  var test2 = test1   3;
  console.log(test2);
}

Method 2: Declare as a global variable

var test1;

function test1(){
  test1 = 1;
}

function test2(){
  var test2 = test1   3;
  console.log(test2);
}

In both cases, calling the function test1() will set test1 = 1 and test2() will use that value and print 4 to the console.

  • Related