localStorage null even after null-check? - javascript

In my current project I'm using javascripts localStorage in order to store some data. Since this data is parsed afterwards, I need to set it to a default-value if it isn't existing yet. To do so I'm using a simple if-check: Unfortunately, it doesnt work. Here is my code:
localStorage.setItem("myItem", null); //Test for the if-check. But even without it isnt working.
if(localStorage.getItem("myItem") == undefined || localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == ""){
console.log("is null");
localStorage.setItem("myItem", "myDefaultContent");
}
console.log(localStorage.getItem("myItem")); //null!
How can I solve this problem?

When you set localStorage.setItem("myItem", null); you really set myItem to the string "null", not null type. Remember that localStorage value is always String. In your case null gets converted to string, before it's stored.
So the check
localStorage.getItem("myItem") == null || localStorage.getItem("myItem") == undefined
is false, of course, and default value is never set.
If you set myItem to be "null" string then you should check against string too:
localStorage.getItem("myItem") === "null"
Or better, don't set null in the first place and null/undefined comparisons will work as expected.

Related

Check of object length in Javascript

I want to check if my object is null or the length is 0. I have tried something like this without any luck.
if (this.get('goodie.pincodes.firstObject') == null || this.get('goodie.pincodes.firstObject.pin').length == 0) {
I solved this in a different way. Making sure that entries with no length allways returns null. Then only asking if the object is null.
this.get('goodie.pincodes.firstObject') == null

Check for array in JS

I'm trying to check a value in JS that on page load is returned as a single-element array and after an ajax function returns as a string. I don't know why it's doing this but I'm trying to role with it.
So, using console.log(value) I get array ['Scranton'] on page load, and the ajax even returns string "Scranton"
When trying to check this variable, this does not work as I intended:
if ( value === 'Scranton' || value === ['Scranton']){
...
}
Any help is appreciated!
This would probably work but I would try and fix the underlying issue instead of working around it.
if ( value === 'Scranton' || value[0] === 'Scranton'){
...
}
You can use indexOf for both an array and a string, so value.indexOf("Scranton") !== -1 will work (just tested this on the console).
However you must first check for null/false/undefined or it will error.
if (value && value.indexOf("Scranton") !== -1) {}
EDIT: As Felix said, this will also be true for any string containing "Scranton". If this is a problem, then you can check for indexOf == 0 instead, which will be true for any string starting with "Scranton". It really depends on your concrete problem if this solution fits you. Use with care.
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.indexOf('Scranton') != -1) {
/* */
}
} else {
if (value === 'Scranton') {
/* */
}
}
Edit 1:
First, you need to check if "value" is an array. If it's an array and contains the string "Scranton", you can find it using value.indexOf().
And if "value" is not an array, you can directly compare it with the string 'Scranton'.
What does "after an ajax function" mean? The page loads with a default variable that has been assigned an array value, and then an Ajax request is made, which changes this default variable, and instead of an array being assigned, it assigns a string? Assuming this "ajax function" changes the default variable to the response text from the server, there is your problem: Ajax--like any other request--is text-based, so it is a string. If you are responding to the Ajax request with a JSON string, built on the server, it needs to be parsed in the browser, so it can be reinterpreted as an array. See the JSON.parse method.

Checking if undefined in jQuery/Javascript

I have the following:
var currentQuestion = $(this).closest(".question")
I have tried everything suggested in this, this and this question:
if(currentQuestion !== undefined)
if(currentQuestion !== "undefined")
if(typeof currentQuestion !== undefined)
if(typeof currentQuestion !== "undefined")
if(currentQuestion !== null)
if(currentQuestion != undefined)
if(currentQuestion != "undefined")
if(currentQuestion.data("index") !== null)
if(currentQuestion.data("index") !== undefined)
if(typeof currentQuestion.data("index") !== undefined)
But it keeps going inside the if statement...
I have this inside the if:
console.log("nextQ: " + currentQuestion.data("index"));
and nextQ: undefined is getting print out
any other ideas?
EDIT:
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the one similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.
The result will never be undefined, it's always a jQuery object. If the operation didn't find any elements, the jQuery object will be empty, so you check how many element there are in it to see if found anything:
if (currentQuestion.length > 0)
After you have checked that there is actually any element in the jQuery object, you can check if there is any data associated to the element.
If no data is associated with an element, the data method will return undefined when you try to read the value. So, to check if there is no data, you should check the type of the value that the data method returns:
if (typeof currentQuestion.data("index") != "undefined")
If you want to check any elements exist, then check the length.
var currentQuestion = $(this).closest(".question");
if (currentQuestion.length > 0) {
console.log("nextQ: " + currentQuestion.data("index"));
}
if (currentQuestion.length) {
Should work fine. If it goes in there, it found something. And instead of looking at the if statement you need to look at your html and see what it found.
What you want is currentQuestion.length.
jQuery selectors return an array of elements matching the selector. To test for values in an array, you should use length:
Boolean([].length); //false
Because 0 evaluates to false, you can just use if (currentQuestion.length).
If you're trying to check for it when it is false, use !:
if (!currentQuestion.length)
For your question of why != worked but not !==, I would suggest this question: Difference between == and === in JavaScript
Basically, currentQuestion.data('index') is not strictly equal to null, but it could evaluate to null: same as [] == 0 evaluates to true, but [] === 0 evaluates to false.
It is probably not the most elegant solution. But somehow
currentQuestion.data("index") != null
worked out. If you check all the options I tried before, the most similar to this one had this comparison element: !== and not !=. That change made the difference. If someone can explain why, I'll grant him/her the correct answer.

javascript undefined not null, not empty issue

Is the statement:
if(attachmentId!=null && attachmentId.length>0&& attachmentId !='undefined'){
//do something
}
equivalent to:
if (attchmentId) {
//do something
}
thanks for the help
Writing :
if (attchmentId)
is the equivalent of:
if(
attchmentId != undefined &&//NO QUOTE
attchmentId != '' &&
attchmentId != null &&
attchmentId != false &&
attchmentId != 0
)
They're not equivalent but the third test attachmentId !='undefined' was probably an error (did you want attachmentId !=undefined ?).
Another example of difference is that 0 doesn't pass the first test but pass the second one.
You must decide what's important to you before you try to write the test. If you know you start with a string and you want to test if it's defined and not empty, then you may use the second test.
It can be reduced to this:
if (attachmentId && attachmentId.length > 0) {
//do something
}
This will do for arrays and more complex objects that happen to have a length property. If attachmentId is supposed to be a string the code above will work the same, but the second part will basically be a noop, so you can just go with:
if (attachmentId) {
//do something
}
I am assuming the comparison against 'undefined' was a mistake - do that and you're not checking if something is actually undefined. You're checking it it is different from a literal string that says "undefined".
Also you check the variable first due to the short circuit rule. It it's either null or not defined you don't care about the rest. Otherwise, if you tried evaluating the length before checking if it's undefined or null you could throw an error there.

JQuery - write conditional when object property is blank

I'm trying to write a conditional for when an object property's value is blank, but it is not triggering. This is my code. Any idea how I should write this?
console.log(vid);
if (vid.video == undefined){
//DO STUFF HERE - Doesn't work
}
The "object" in the screenshot is referenced in the code above as variable vid. I also tried undefined in the conditional.
I see some misunderstading here:
You say when an object property's value is blank but your coded if (vid.video != ""){.
I think you need if (!vid.video) {
use this:
vid.video == undefined
Also what Andrew said. If you want to DO STUFF when the attribute is empty, you should Use "==", and not "!="
if(vid.video != "")
Are you looking to only execute code when video doesn't equal "" but if you want to execute code when it is equal to "" you need
if(vid.video == "")
However if you want to check to see if its undefined you'll need to do
if(vid.video === undefined){
vid.video is not defined here
}
or
if(vid.video){
vid.video is defined here
}

Categories

Resources