-1

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")
}
Mina
  • 14,386
  • 3
  • 13
  • 26

2 Answers2

1

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;
}
jacky la mouette
  • 523
  • 4
  • 17
0

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")
}
Elna Haim
  • 545
  • 1
  • 5
  • 19
  • Note - this won't work because `querySelectorAll` doesn't have a `classList` property. It's a nodelist. – Andy Aug 17 '22 at 20:18
  • It says "Uncaught ReferenceError: option is not defined" – Nazmul Hassan Aug 17 '22 at 20:18
  • @Andy you are correct, i just wanted to answer the main question. how to pass variable. and this is a way of passing variabls. to fix the error above you need to define which node from the querySelectorAll you want. e.g `options_list.querySelectorAll(".options")[0]` – Elna Haim Aug 17 '22 at 20:23