What am I overlooking here

What am I overlooking here
0

#1

Guys (and gals) what am I overlooking here. To me logically the following code with the variable bool set to false shouldn’t allow my hideMe() to run, but you’ve guessed it, it does.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

var bool = false;

function hideMe(){
  if (bool = true){
    $("p").click(function(){
        $(this).hide();
    });
  }
}

hideMe();

});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>


#2

Your If statement logic is incorrect.

With bool = true, you are setting the variable bool to true.

For validating. use bool === true.

Or, you can use if(bool){} it will execute if bool is true.

Recommended coding standard

Validating for true

if(bool){
...
} 

Validating for false

if(!bool){
...
} 

#3

Hey you made a typo, by saying if(bool = true) you set bool to true. It should be if(bool == true) with 2 ='s. But you can use the shorter version: if(bool).

EDIT: Exactlywhat @jamesperrin said…


#4

Thanks @jamesperrin

Always the glaringly obvious, time for bed I think.


#5

Thanks @BenGitter, time for a rest I think