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).
Related
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.
I am setting a mode in a script by passing a "truthy" boolean to a function. In the function a simple if statement checks if the param is true or false. I sometimes pass it as a string or a bool which has always worked, but for some reason it isn't for this:
setMode: function(Setting) {
if (Setting) {
console.log('Enabling mode');
} else {
console.log('Disabling mode');
}
}
For example when I pass it a string 'false' and log Setting to console, the console says false, yet the if statement thinks it's true.
I have to add this to the start of the function for it to work:
if (typeof Setting == 'string') {
Setting = (Setting == "true");
}
An example of it in use:
var inverted = $('INPUT[name="Mode"]').prop('checked');
app.setMode(inverted);
and another:
var mode = localStorage.getItem('Mode');
this.setMode(mode);
It's so bizarre since I've done this type of thing for years yet it's only starting now. Maybe because I'm using localStorage and .prop?
If you try to log 'false' it is obvious that console logs false(it is a string) and that the if statement sees true, because a not-empty string is a true boolean value.
If you want to check if the string is "true" or "false" you have to do it with normal operators. So you could add this line at the beginning of your function:
Setting = (typeof Setting === 'string') ? Setting === "true" : Setting;
To answer your question about string to boolean conversions:
ECMA SPEC:
The result [of this conversion] is false if the argument is the empty String (its length is zero);
otherwise the result is true.
So yes, if you pass the string "false" it will be converted to true, which means the only option you have is to manually check for the strings "true" or "false" and do the conversion by yourself.
However, the jQuery function .prop("checked") is supposed to return a boolean value (or undefined if the property is not defined). So I would say you should be able to actually do
if (elem.prop("checked"))
like here.
For example when I pass it a string 'false' and log it to console, the console says false, yet the if statement thinks it's true.
The console output is confusing, it is concealing the quotes and logging false both for the string "false" and the boolean false. Yet, these two are not equivalent, the string is not empty and indeed truthy.
Maybe because I'm using localStorage and .prop?
Yes. The .checked property returns a boolean and everything works well. In contrast, local storage only stores strings, and when you pass in a boolean you get back its stringification. You can undo that by using
var modeStr = localStorage.getItem('Mode');
var mode = JSON.parse(modeStr);
this.setMode(mode);
I have the following code:
var a=sessionStorage.getItem("Token");
alert(a==null);
The returned value is null (If I alert(a) it displays null). The problem is that the alert(a==null) display is TRUE on firefox and FALSE on safari and chrome. WTH? I have tried a===null with the same results as well as !a.
What am I doing wrong or what am I not aware of?
Thanks for any help.
You said in a comment: "I set Token with sessionStorage.setItem("Token",null);"
I believe the problem is that you are supposed to use session storage to store strings. When you pass null to setItem() it converts it to a string "null". Then when you retrieve it with getItem() you get back this string "null" which is of course not equal to an actual null value.
You can see this behaviour here: http://jsfiddle.net/CWVww/1/
If you want to remove a previously set item then do this:
sessionStorage.removeItem("Token");
...and then calls to .getItem("Token") will return null.
I don't know why Firefox behaved differently. From the MDN page on session storage: "Keep in mind that everything you store in any of the storages described in this page is converted to string using its .toString method before being stored."
Your code worked perfectly with me (tested on Chrome). However, I suggest you to use the ! operator and also check the type of the current value:
var a = sessionStorage.getItem("Token");
if(!a && typeof a!=='string'){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
The operator ! will return true either when a is null or undefined.
You could try String(a) == "null". However, if the value of the Token item is set to "null" (the string "null") the code won't work as expected, so we have to add another condition:
var a = sessionStorage.getItem("Token");
if(String(a)==="null" && typeof a!=="string"){ //a doesn't exist
//Do something
}else{ //a does exist
//Do something
}
This way, the condition will return true when the "stringified" value of a is "null" and the type of the a var is not string
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
when comparing string to see if it is empty, is there any difference between:
if($string==NULL){
//do work
}
and
if($string==""){
/do work
}
Just wondering beacuse I want to know which one is more effective in detecting blank input.
You're kind of asking several vaguely-related questions here. PHP and JavaScript aren't the same language, and you're referencing different operators in the question title and body. In any event:
PHP:
'' == null true
'' === null false
JavaScript:
'' == null false
'' === null false
You might want to consider these tests for general "did I get something in this string variable":
PHP:
if(!empty($string)) {
// do work
}
JavaScript:
if($string) {
// do work
}
Yes, there is a difference. Checking if $string==Null will actually check to see if the variable has been initialized at all, and $string=="" looks to see that the string actually exists, but that it just holds a 0-length string
To test in PHP:
<?php echo var_dump("" === NULL); ?>
To test in JavaScript:
console.log("" === null)
Both produce false, so you can't do that in either language.
Even if it worked, it is not obvious what you mean by comparing with null; this isn't C where it's constantly used for missing values. If you're going to get a string as input, comparing to the empty string is more clear.
I`am using empty() function in PHP. It is not depends on type of the variable. However, when comparing with "==" (not "==="!), NULL becomes empty string ("") when comparing to string.
does “”===null?
No.
Behold the power of testing... for javascript anyway.
alert("" === null);
In JavaScript, the answer is no. An empty string does not equal null, though both are falsey values.
Check the manual, "" is not identical to null because the former is a string and the latter is null, and === checks for equal types as well as equal values.
Take a look at this: http://php.net/manual/en/language.operators.comparison.php