Reputation: 3667
I am writing a script the utilizes a switch statement. When I declare the variables, they have a default boolean value of true, correct? Well, not so much when being utilized in a switch statement.
Here is the JavaScript I have: http://codepen.io/anon/pen/IDLqd/
Basically, what I am trying to do is ask the user what type of list-style they prefer based upon that data that is entered into a window.prompt() method. If they enter in a 1, 2, or 3, they will get a list based upon the directions in the prompt. But, if they do not enter in a valid integer, the variable validInput is set with a boolean value of false.
From here, an if statement is ran to check whether the validInput variable has a boolean value of true, if it does, then it outputs the values of the many variables to the screen, if not, it outputs text saying "Invalid Choice".
Why is it that the code will recognize validInput as only having a value of false in the if statement? When it is only assigned the value of false if a different value is entered into the prompt window? To get this program to run properly I have to explicitly define the validInput value as true in each switch case.
Why is this? Can someone explain, please?
Thank you! Aaron
Upvotes: 0
Views: 4944
Reputation: 3307
You are checking if the input is valid with
if (validInput == true) {
// Your code
}
The more common way of doing this would be
if (validInput) {
// Your code
}
What's the difference between these two?
The first checks if validInput
is equal to true
- nothing else will do (well, pretty much nothing else - you're using ==
rather than ===
, which can sometimes have surprising results because of javascript's type conversion algorithm, but that's another question altogether).
To understand the second, you need to understand javascript's concept of "truthiness". If you put a value into the condition of an if statement, then javascript decides is it's "truth-y" or "false-y", and acts accordingly.
true
is truthy, as is any non-zero number, any non-empty string, and any object. Other things are falsey, including false
, 0
, ""
, null
and undefined
.
The last of these is probably the most relevant to you, as variables are undefined
until you set them to something.
Upvotes: 2
Reputation: 4360
Javascript is a dynamic language and there is nothing like a default boolean value.
When you define a variable without a value it's default value is always undefined
:
var variable; // variable is undefined
So you have to set the value:
var variable = true;
// or
var variable = false;
If you want to toggle this boolean value, you can do the following:
variable = !variable;
Upvotes: 4