-3

I have searched the internet trying to find a good answer for this question. What I mainly found is suggestions to move the variable in the global scope, or using the functions as parameters for the function I want to use the variable in, but without explanation on how that works

To explain my dilema, lets say we have this piece of code:

function foo(){
 var x = 2;
}

function bar(){
 var z = 2;
}

function compare(foo,bar){
 if ( z === x ) {
  console.log("text");
}
}

This is the problem I'm facing. Is the code I've written above correct and if I call the compare() function it should console log "text" ?

As above so below
  • 619
  • 1
  • 6
  • 13
  • 4
    `x` & `z` are _local_ to the function and not accessible from outside of function. – Tushar Oct 25 '16 at 09:09
  • Well haven't you tested your actual code before asking? It won't work. – cнŝdk Oct 25 '16 at 09:12
  • I know it wont work. I just gave the code as an example about how I understand it from what I've found searching for the answer. – As above so below Oct 25 '16 at 09:14
  • In JavaScript each function has its own scope, so variables local to a function aren't accessible outside this function. In your case `x` and `y` are respectively local to `foo` and `bar` functions, so they're only accessible inside these functions scopes, and calling them in the `compare` function` will raise an Error because `x` and `y` are not defined in this function. – cнŝdk Oct 25 '16 at 09:18

1 Answers1

1

declare with globel variable it's will easy to pass Another function

var x;
var y;

function foo(){
 x = 2;
}

function bar(){
  z = 2;
}

function compare(){
 if ( z === x ) {
  console.log("text");
}
}

foo()
bar()
compare();
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • So this is the only options, declaring the variables globally ? – As above so below Oct 25 '16 at 09:24
  • Its the mostly used one and easy way.Or using with [localstorge](http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_webstorage_local) .You wish to save the data to locally and retrieve the data . – prasanth Oct 25 '16 at 10:05