javascript null comparison different on chrome and firefox - javascript

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

Related

Why JavaScript null check doesn't working?

function readProperty(property)
{
console.log(localStorage[property]) //Alerts “null”
if(localStorage[property] == null)
{
console.log('Null chek')
return false;
}
return localStorage[property];
}
log outputs "null", but 'if()' doesn't work. I try with ===, its not work too. Help please.
UPD: Thanks everyone this change helped me if(localStorage[property] == 'null')
The keys and the values stored with localStorage are always in the
UTF-16 string format, which uses two bytes per character. As with
objects, integer keys are automatically converted to strings.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Try:
localStorage[property] === 'null'
Although: console.log(localStorage[property]) may report null, the actual value is undefined.
So, in your if statement, if you test against undefined, you'll get a match.
Better yet though, just test for the existence or non existence of a value with:
if(localStorage[property])... // Tests for any "truthy" value
or
if(!localStorage[property])... // Tests for any "falsey" value
Well, I don't know if you're trying to use the global localStorage or if it's a defined variable in your code.
If you're using the localStorage API, you should check if a key exists like this...
if (!localStorage.getItem("my-item")) {
console.log("item doesn't exist.");
}
The .getItem() method returns null when the key isn't defined so checking using ! or item !== null work.
.getItem() reference from MDN, https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem.
you have to get item from localStorage using getItem() function like that
if(!localStorage.getItem(property) || localStorage.getItem(property)===null){
// there is no item in localStorage with the property name
}

How can I refer to local storage as empty?

I have a series of if and else if statements and what I want is to determine a scenario in terms of local storage being empty.
I've tried:
(if localStorage.getItem('example') == localStorage.clear()) {
//Do something if that local storage item is empty
}
I am aware the program may think I'm assigning the local storage to clear out it's contents. So would I do something like:
(if localStorage.getItem('example') == localStorage()) {
//Do something if that local storage item is empty
}
If not, how can I refer to the local storage as an empty object so the program doesn't get confused thinking that I'd like to clear the contents in the storage?
You can check to see if it is null.
if(localStorage.getItem('example') === null){
console.log("x");
}
Ok both answers posted are right. However, I want to explain a few things that I have experienced. Undefined is returned if you are referring to the object as so and it has nothing in it:
localStorage.key; //will be undefined if not set
localStorage.getItem() returns null if nothing is in it (as I have experienced).
localStorage.getItem('key'); //will return null if not set
And yes, all you have to do is check if it is null or undefined (depending on the method you use)
if(localStorage.getItem('key') === null){
//do stuff here
}
or
if(localStorage.key === undefined){
//do stuff here
}
or you can use the ! operator like so:
if(!localStorage.getItem('key')){
//do stuff here
}
or
if(!localStorage.key){
//do stuff here
}
The reason for this is because both null and undefined are falsely values, and the ! operator checks for falsely values
You can just check if localStorage.getItem() is undefined. Here's an example:
function isCleared(item) {
return !localStorage.getItem(item)
}

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 statement boolean strict

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);

JSON key exists but returns false

First of all, all my code is done in node.js but this can all be applied to javascript too.
This is my code I use to check if the keys exist, the problem is that it always returns false. So I added in the console.log to shows what the values are:
if(!choice.name || !choice.realm || !choice.region || !choice.roll){
console.log(choice);
console.log(choice.name);
console.log(choice.realm);
console.log(choice.region);
console.log(choice.roll);
return false;
}
This is the output of that:
{"name":"Imacactus","realm":"Velen","region":"US","roll":"DPS"}
undefined
undefined
undefined
undefined
I'm guessing it has something to do with the quotes? but I've never heard of quotes messing it up. Is this a node.js problem? I've also tried .hasOwnProperty('realm') and it still failed.
This is most of the code with all the functions: http://pastebin.com/DUN9VdHr
You need to parse your json into a javascript object before you can reference its properties.
You can use JSON.parse
var choiceobj = JSON.parse(choice);
if(!choiceobj.name || !choiceobj.realm || !choiceobj.region || !choiceobj.roll){
console.log(choiceobj);
console.log(choiceobj.name);
console.log(choicepbj.realm);
console.log(choiceobj.region);
console.log(choiceobj.roll);
return false;
}
The problem is that the quotes is part of the key so to access it you have to do something like:
console.log(choice['"name"']);

Categories