0

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")
}
2
  • What are one and two in the functions parameter lists? Commented Aug 17, 2022 at 20:14
  • I think it's not necessary, so i did not mention the parameters Commented Aug 17, 2022 at 20:16

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Note - this won't work because querySelectorAll doesn't have a classList property. It's a nodelist.
It says "Uncaught ReferenceError: option is not defined"
@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]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.