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)
}
Related
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
}
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.
I'm using Jquery.cookies plugin but I can't seem to find the information i'm looking for.
I have the cookie object which contains keys and values for cookies that are set on the page.
Want I need to do is loop through the object and check to see if a value exists inside the object and if it does log it to the console.
$.cookie().each(function() {
if (index == ratingsID) {
console.log(index)
}
});
With the above code I get an error that says undefined is not a function.
Can anyone point me in the right direction?
Thanks
if($.cookie("MyCookie") != null){
cookie = JSON.parse($.cookie("MyCookie"));
cookie.forEach(function(elem){
console.log(elem);
});
}
Try this
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
Before anyone asks, I have already search existing questions and found this question, but the answer was that undefined was being set to null, which is not the case here.
Here is my code:
check_availability = function () {
var value = $('#contact_type').val();
if (value !== undefined) {
// do some stuff
}
}
Simple huh? I have a <select id="contact_type"></select> with options populated via ajaxy stuff. Initially the options list is empty, so the jQuery val() returns undefined.
So far so good.
Except that the code within the if block always executes. I stick a breakpoint in FireBug on the 3rd line and I get this:
Can anyone tell me what's going on?
P.S. This is Firefox 4.0
EDIT: I know there are a number of ways I can achieve the same result, I'm more interested in why value is undefined according to FireBug, but then is !== undefined.
Just check the truthiness of value.
if (value) {
// sexy times
}
BTW, jQuery returns null, not undefined, when the <select> contains no <option>s. http://jsfiddle.net/mattball/cQ83z/
The val() is never undefined: http://jsfiddle.net/ThiefMaster/UmZhG/
If the <select> has no options, it is null; otherwise there's always an option selected.
Fyi, value == undefined is true since null == undefined (even though null !== undefined)
Try this:
if (typeof(value) != 'undefined') {
// do some stuff
}
Hope that helps.
the === operator doesn't do type conversions which may causing the error. try == instead. or compare against null.
try in this way...
if (value != undefined) {
// do some stuff
}
Use this:
if($("#contact_type").val() != ""){
//does have a value
}else{
//No value there
}