Brownman Revival Brownman Revival - 3 months ago 9
Javascript Question

access data in json not getting the key



var data = [{
"error": false,
"date": "09-02-2016",
"day": "5",
"checkin": "20:29:11",
"checkout": null,
"break_timein": null,
"break_timeout": null,
"checkin_remarks": "test",
"checkout_remarks": null,
"break_time_remarks": null
}];



console.log(data[0].checkin)
console.log(data[0].break_timein)
console.log(data[0].break_timein.length > 0 || data[0].break_timein != null)





For
break_timein
when i console.log it, it returns null but when I get the length it returns
Cannot read property 'length' of null


Why is this?

Answer

I understand that it only appears when there is not property break_timein but it is there its just null

You drew the wrong conclusion here. The error doesn't have anything to do with whether a property exists or not.

When a property doesn't exist and you are trying to access a property on it you are getting the following error:

var foo = {};
foo.bar.baz;
// Uncaught TypeError: Cannot read property 'baz' of undefined

The "undefined" in this sentence doesn't refer to the existence of the property, it refers to the value undefined. In JavaScript, when accessing a property doesn't exist, accessing it will return the value undefined:

foo.bar
// undefined

There are other situations where undefined is created, e.g. when you define a variable without an initial value:

var abc;
abc;
// undefined

Knowing that we can test what happens when we directly access a property on undefined:

undefined.foo
//  Uncaught TypeError: Cannot read property 'foo' of undefined

This throws the same error as above, so it doesn't have anything to do with property access.


So now we have established that undefined cannot be used in a property access context.

null is another value that is just like that:

null.foo
// Uncaught TypeError: Cannot read property 'foo' of null

What makes null and undefined different from other primitive values (string, number, boolean) that they show this behavior?

null and undefined are actually values of two unique data types: Null and Undefined.

Those data types do not have an object wrapper. Strings, Numbers and Boolean values can exist in two forms: as primitive values and as object value:

var primitive = "foo";
var object = new String("foo");

When you are accessing a property on a primitive value, e.g. "foo".length, JavaScript automatically converts the primitive value to a temporary object value, similar to new String("foo").length.

But since there is no object equivalent for Nulland Undefined (evident by the fact that there is no Null or Undefined function), this cannot be done, so an error is thrown.