Home > Mobile >  Can I pass variable from one function to another in javascript?
Can I pass variable from one function to another in javascript?

Time:08-18

I am learning Javascript. I want to pass variable from one function to another. I am trying to catch option in funTwo but I do not want to declare the variable as global or use var.

function funOne(one) {
   let tags = '<div class= "options">'   arr[1]   '</div>';
   const option = options_list.querySelectorAll(".options")
}

function funTwo(two) {
   option.classList.add("correct")
}

CodePudding user response:

In javascript, variables declared with const or let are scoped: this means they exist and are accessible only in the current scope.

When you declare a variable inside a function, it is inside the function scope and inaccessible from anything that is not in that scope, including other functions. If you want to use this variable, you need to pass it either as parameter or returning it from a function call.

function b(value) {
    console.log(value);
}

function a() {
    const foo = 1;
    b(foo);
}

or

function b() {
    let value = a();
    console.log(value);
}

function a() {
    return 1;
}

CodePudding user response:

Yes, you can return option from funOne and get it in funTwo.

  function funOne(one){
  let tags = '<div class = "options">'   arr[1]   '</div>'
  const option = options_list.querySelectorAll(".options")
  return option
 }

 function funTwo(two){
  const option = funOne() // the function will return option.
  option.classList.add("correct")
}
  • Related