简体   繁体   中英

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

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")
}

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;
}

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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM