By Default, What Is A JavaScript Variables's Boolean Value? - javascript

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

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;

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.

Related

testing whether property exists on an object and is equal to a certain value

let's say that we have an javascript object like below:
let obj = {name: 'firstName'};
which is a better way to test whether a property exists on an object and is equal to something:
1)
if (obj.address === 'someAddress')
or
2)
if (!!obj.address && obj.address === 'someAddress')
Can someone explain which is better/safer and why?
You asked "safer" and "better". "Better" is subjective as long as you don't define what qualities you're looking for, so I'll ignore that part.
Accessing a property that doesn't exist is valid in JavaScript, and simply returns undefined. So the second way is equivalent to:
const address = obj.address
if (!!address && address === 'someAddress') {
...
}
Now you can see that that's plain silly, because the second condition implies the first. In other words, there is no way that address === 'someAddress' can be true and !!address can be false, so there is no need to do the first check at all.
So the second approach is not safer than the first. Both have the same observable effect.
Nitpicker's corner: if you were checking for some falsy value like 0 or "" instead of the truthy string 'someAddress', then the second approach would not even work, because both conditions can never be true at the same time.
Also, if address is a property with an evil getter that may return a different value each time it's called, all bets are off. The first version could actually be safer because it only gets the value once, but presumably the value would be used inside the if block so the code is still broken.
1 is shorter :D and it works :D
Better is:
if (obj?.address === 'someAddress')
it checks both conditions

Calling a JavaScript function that returns a Boolean

* EDITED *
REF: Calling a JavaScript function that returns a Boolean [on hold]
function booleanFunction()
{
if (something) return true;
else return false;
}
My original question was "When calling a Boolean Function, is it correct to say?":
if (booleanFunction)
or
if (booleanFunction())
I had previously read that the first choice was correct. Your voluminous responses said otherwise.
Based on all that I have learned from all your responses, I conclude:
(1) if (booleanFunction) is truthy in the sense that this if statement will ALWAYS return true. In other words, this if statement is equivalent to asking if this booleanFunction EXISTS, independent of its correctness.
(2) to evaluate the value (true or false) returned by the booleanFunction, I need to say if (booleanFunction()).
Have I concluded correctly?
The text you quote is outright incorrect.
To call a function, use parentheses. If the function takes no arguments, the call looks like booleanFunction() and returns a value.
To evaluate a value, put it into parentheses. In an if-statement, while-loop, a value is converted to a boolean automatically, the same as (new Boolean( SOME_VALUE )).valueOf() or !! (SOME_VALUE). Refer to MDN for the full conversion rules. For instance,
if (booleanFunction()) {
is perfectly fine, but
if (booleanFunction) {
would convert the value of booleanFunction to boolean, and that is true, because any function object will be converted to true.
I have edited my original question. Hopefully, it is now totally clear.

Why are these undefined variables not equal javascript?

Suppose I have the following event handler:
function handleCsvDump(e) {
console.log(e.currentTarget.getAttribute('download'));
e.currentTarget.download = undefined;
console.log(e.currentTarget.getAttribute('download'));
console.log(e.currentTarget.getAttribute('download') === undefined);
The information logged to the console when the corresponding button is clicked is:
mycsv.csv
undefined
false
Why is the last value false? Since e.currentTarget.getAttribute('download') is undefined, shouldn't it be true? If this is the wrong way to go about this, how can I test whether a variable is undefined?
You have to be careful when setting things this way, often things are expected to be strings, and if you set a value that isn't a string, it will first be coerced to a string, then assigned.
The download attribute is indeed a DOMString, meaning that anything you assign to it will first be coerced to a string if it isn't already, so when you assign undefined, it's actually first coerced to "undefined" and that is stored.
When you get it back out, and compare it to undefined, you're actually doing:
console.log("undefined" === undefined)
Hence getting false. If you do actually want to remove it, which is implied by wanting to set it to undefined (or null), you can instead use removeAttribute:
e.currentTarget.removeAttribute('download')

outputting content based on whether variable object equals "true"

I thought this would be straight forward after reading through w3c tutorials etc! But I appear to have something incorrect as the code doesn't output anything!
The variable is set based on whether the user is logged in or not:
var theJSON={"LOGGEDIN":false};
var theJSON={"LOGGEDIN":true};
I am then trying to show on the front end whether the user is logged in or not:
$(document).ready(function() {
if (typeof(theJSON[LOGGEDIN]) == true ) {
document.write ("Logged in")
} else {
document.write ("Not logged in");
}
i must be missing/mistyping something so simple?
There a couple of things wrong in your code:
When you try to access the LOGGEDIN property of the object, you are missing quotation marks. The expression theJSON[LOGGEDIN] will first try to get the value of the variable LOGGEDIN to use its value as property name. If such a variable does not exist (like it is in your example), the code will throw an error.
Now, The value of theJSON['LOGGEDIN'] is true and the type of the value is a boolean. typeof(theJSON['LOGGEDIN']) == true will never be true, because the typeof operator returns a string with the name of the data type, i.e. typeof(theJSON['LOGGEDIN]') will return "boolean".
If you just want to test whether the value is true, do:
if (theJSON['LOGGEDIN'])
w3schools is really not the best site to start learning about JavaScript, have a look at http://eloquentjavascript.net/ and the MDN JavaScript Guide instead.
if (typeof(theJSON["LOGGEDIN]") == true )
or
if (typeof(theJSON.LOGGEDIN) == true )
BTW, better use === instead of ==
if the value is number 1 it will still pass the condition.
Firstly, your theJSON is an actual object as given, not a JSON string. If it was you'd need to parse it as suggested.
The expression theJSON[LOGGEDIN] is incorrect syntax, you can either say theJSON.LOGGEDIN or theJSON["LOGGEDIN"]. And as this is a boolean, typeof(theJSON.LOGGEDIN) == "boolean".
The expression is a boolean, but it's value is true, so you can just write if (theJSON.LOGGEDIN).

Javascript IF loop takes false and execute the true loop with jquery

Here is jquery code in rails app. The purpose of the code is to eval the value of #rfq_need_report and show the #rfq_report_language if need_report is true or hide if false:
$(document).ready(function() {
var rpt = $('#rfq_need_report').val();
alert(rpt);
if (rpt) {
alert(rpt);
$('#rfq_report_language').show();
alert('show');
} else {
$('#rfq_report_language').hide();
alert(rpt);
alert('hide');
}
}); // end ready
The alert here is just for debug. The rpt is false, however alert('show') gets executed. It seems that the if loop is taking false and decided to execute the loop for true. Sometime If loop is working and sometime it does not. What could cause this strange behavior? Thanks.
In HTML the value field of any input like value="something" is always evaluated as a string. My guess is that in javascript you either set that value to true or false but it is in fact set as "true" or "false" as strings. You could try what was answered on this topic : How can I convert a string to boolean in JavaScript?
rpt could be a string, therefore converting it into a boolean will help:
if(rpt === "false") { rpt = false; } else { rpt = true; }
I have to assume that $('#rfq_need_report').val() is not passing back an actual boolean value, but something that JavaScript considers 'truthy', which is why your if statement executes the truth clause.
There are two quick methods (that I use) to convert 'truthy' values to an actual boolean:
1: var bool = !!truthy;
2: var bool = truthy === 'true'
I use the second when expecting a string value, and the first when not expecting a string.
The first example may need an explanation, so...
The first ! "nots" the truthy value to an actual boolean, albeit the opposite of what I wanted, the second "nots" it right back to where it should be.
For more examples of truthy vs falsy, simply pop javascript truthy falsy into your favorite search engine and start reading. My personal quick reference is: Truthy and falsy in JavaScript

Categories