Check of object length in Javascript - 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

Related

How to verify if array exist and its length in fewest steps?

I have some if statement, where I want to verify the length of an array. Let's say it is the following:
if (object.someArray.length > 1){
doSomething()
}
However, when someArray is not defined (maybe it is not defined for some object, which is possible), I get an error:
Cannot read property 'length' of null
Which makes sense, as object.someArray is not defined.
My question is: what is the best way to verify that the array exists AND its length, in fewest steps?
Thanks!
The very generic and full test : if array exist and is not empty
if(object && object.someArray && object.someArray.length)
For your case :
if(object.someArray && object.someArray.length > 1)
Edit : For those who don't know this is called duck-typing : we aren't checking really if the object is an array, we're considering that if that object has a property length, it is an array. Lot of library do that. As long as you don't store different types of javascript object (string/array/object) in the same variable, this code is safe.
Try to check array through Array.isArray
if (Array.isArray(object.someArray) && object.someArray.length > 1)
You can do it in one single condition like
if (object.someArray && object.someArray.length > 1){
//Do Something
}
if object.someArray is undefined, it will return false and the next condition will not be evaluated
the best way to verify that the array exists AND its length
The best way is to do exactly as you wrote:
if (array && array.length > 0 { ... }
You can check it this way.
if(object.someArray && object.someArray.length > 1) {
doSomething();
}
If the someArray does not exist then it will be false and it will never check for its length because of the short-circuit.

localStorage null even after null-check?

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.

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.

If statement throwing error for nonexistent object

The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined

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