-1

I have the following function

var VisibilityNewDevice = 1
function visibilityNewDevice() {
    if (VisibilityNewDevice === 1) {
         toggleVisibility('buttonPressesTable'),
         toggleVisibility('IconMinimize'),
         toggleVisibility('IconSync'); 
         var VisibilityNewDevice = 0;
    }
}

Which if I call visibilityNewDevice() I get undefined returned and doesn't run the code. However if I run the like this

if (VisibilityNewDevice === 1) {
    toggleVisibility('buttonPressesTable'),
    toggleVisibility('IconMinimize'), 
    toggleVisibility('IconSync'); 
    var VisibilityNewDevice = 0;
}

It works fine. I'm confused why the function doesn't work, but when I run the if statement it works fine.

2

5 Answers 5

2

Your function tries to define the variable again.

Your

var VisibilityNewDevice = 0;

at the end of the function should be

VisibilityNewDevice = 0;

Sign up to request clarification or add additional context in comments.

Comments

1

The answer is to simply remove the var inside the function

You write

var VisibilityNewDevice = 1
function visibilityNewDevice() {
  // expecting: 1 === 1
  if (VisibilityNewDevice === 1) {
     ...
     var VisibilityNewDevice = 0;
  }
}

Javascript compiles

var VisibilityNewDevice = 1
function visibilityNewDevice() {
    var VisibilityNewDevice = undefined;

    // undefined === 1
    if (VisibilityNewDevice === 1) {
     ... 
     VisibilityNewDevice = 0;
   }
}

Notice your var is hoisted at the top, that goes for any var you create inside the function. That hoisted var will overwrite any global var with the same name when the program enters the function.

See also: JavaScript Hoisting Explained

Finally when your create private var its not a bad idea to hoist it your self so you can follow your code better

function () {
    var a, b, c, d;
}

Comments

1

its not working because youre calling var VisibilityNewDevice = 0;. specifically the var. that means the VisibilityNewDevice in your if statement is not referencing your outer variable, its referencing the inner one, which is undefined at the time of execution.

removing the var in the if statement should get this working

Comments

1

By having

var VisibilityNewDevice;

you've declared local variable VisibilityNewDevice inside the function. By having

var VisibilityNewDevice = 0;

you are setting that local variable to zero. Not the outer one as you need.

Comments

0

This is call variable hoisting.

var x = 1;

function test(){
   console.log(x);
   var x = 3;
}

test();

this is same as

function test(){
       var x;
       console.log(x);
       x = 3;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.