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
}
Related
So I want to get a variable from local storage. If it doesn't exist in local storage, then I want to create that variable. I was using if (x==null) to see if it existed, then I noticed if(!x) has the same result. Is it ok to use ! in this situation? I didn't know ! and null are the same here. Also when checking for null, should I use === or is == ok?
Here's two examples that give me the same results.
<script>
localStorage.clear();
a=localStorage.getItem('a');if (!a) a='hello';
alert(a);
x=localStorage.getItem('x');if (!x) x=0.7;
alert(x);
</script>
<script>
localStorage.clear();
a=localStorage.getItem('a');if (a==null) a='hello';
alert(a);
x=localStorage.getItem('x');if (x==null) x=0.7;
alert(x);
</script>
https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem
localStorage.getItem returns null if the key doesn't exist. So a === null would be the most specific check for if the key didn't exist. However, null is falsy in javascript. So you could reduce the check to this:
a = localStorage.getItem('a') || 'hello';
Which functions the same as your if with the not operator
Is not exactly the same... This !x is checking for a truthy value but anything between null, undefined, or even 0 will return false.
There is also a significant difference between == and === where == will try an automatic type conversion in order to check if the values are in some way compatible, but the === will check for an strict equality.
You can learn more about the JavaScript types and their interaction with the different operators in this link Values, Types, and Operators
I am receiving this JSON from server, and I need to check if it contains the key read.nores
if I do it like this
if (data[0]["read.nores"]) {
return;
}
it will crash because it does not contain that key.
How can I check if the key is there without a try/catch method, something like .has("read.nores")?
Reading an undefined key safely produces undefined, but reading a key from undefined will throw, so the problem will be specifically that data[0] doesn't exist, not that data[0]["read.nores"] doesn't exist.
To check for that, change it to:
if (data[0] && data[0]["read.nores"]) {
return;
}
It won't crash.
If you check any property of an object and it is not defined in the object it is by default undefined. So your if condition will work perfectly.
When declaring variables at the top of the JavaScript function, is it best practice to set them equal to null, or leave as 'undefined'? Another way to ask, what circumstances call for each option below?
Option A:
var a = null,
b = null;
Option B:
var a,
b;
It depends on the context.
"undefined" means this value does not exist. typeof returns "undefined"
"null" means this value exists with an empty value. When you use typeof to test for "null", you will see that it's an object. Other case when you serialize "null" value to backend server like asp.net mvc, the server will receive "null", but when you serialize "undefined", the server is unlikely to receive a value.
I declare them as undefined when I don't assign a value because they are undefined after all.
Generally, I use null for values that I know can have a "null" state; for example
if(jane.isManager == false){
jane.employees = null
}
Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.
Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.
I usually set it to whatever I expect to be returned from the function.
If a string, than i will set it to an empty string ='', same for object ={} and array=[], integers = 0.
using this method saves me the need to check for null / undefined. my function will know how to handle string/array/object regardless of the result.
The only time you need to set it (or not) is if you need to explicitly check that a variable a is set exactly to null or undefined.
if(a === null) {
}
...is not the same as:
if(a === undefined) {
}
That said, a == null && a == undefined will return true.
Fiddle
Be careful if you use this value to assign some object's property and call JSON.stringify later* - nulls will remain, but undefined properties will be omited, as in example below:
var a, b = null;
c = {a, b};
console.log(c);
console.log(JSON.stringify(c)) // a omited
*or some utility function/library that works in similar way or uses JSON.stringify underneath
There are two features of null we should understand:
null is an empty or non-existent value.
null must be assigned.
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
You can use ''; to declaring NULL variable in 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
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