How to check length of variable with property 'length' of undefined? [duplicate] - javascript

This question already has answers here:
Javascript check if object property exists, even when object is undefined
(4 answers)
Closed 6 years ago.
I have an variable, lets call it myNiceVar, I need to check myNiceVar value & length, myNiceVar variable is just undefined, which for JavaScript compiler this means the variable is defined but does not have any value yet
var myNiceVar;
if(myNiceVar.length){
console.log("I have value!");
}else{
console.log("I am empty");
}
Now JavaScript returns:
Uncaught TypeError: Cannot read property 'length' of undefined
How to check something like that and do not getting any error

You could check for typeof equals 'object' and if length is a key.
Do not forget to check for null first, because null is an object without properties.
var myNiceVar;
if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
console.log("I have value!");
} else {
console.log("I am empty");
}

Try this one
var myNiceVar;
if (myNiceVar !== null && typeof myNiceVar === 'object' && 'length' in myNiceVar) {
console.log("I have value!");
} else {...}

An item of type undefined (and it is a type) has no length property - only items of type string and array do. Therefore, as #redneb notes, extend your condition to check for a non-falsy value before checking length.
if (myVar && myVar.length) { ... }

Related

How to check whether a JSON object key is an object or string? [duplicate]

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Check if a variable is a string in JavaScript
(30 answers)
Closed 2 years ago.
So right now, I created an example of a JSON object where:
var myObj = {
address: {
0: ["41 Lake Avenue"]
},
name: "jake"
}
myObj itself as a whole is a JSON object, and inside it, I have two keys which are address and name respectively. So the value of the address key is also an Object since its in braces, where as the name key value is just a string.
I want to write a simple check in javascript to check whether or not the keys in myObj is an object or a string. So if its an object, it returns true where as if its not an object it returns false. Therefore for address, it would be true while for name, it would be false.
I tried looking around for some isObject() method similar to isArray() but apparently i couldn't find so I'd like some help on this so i wrote a pseudocode below for the logic:
for (i=0;i<2;i++) {
if myObj[i] is Object {
return true;}
else{
return false;}
}
You can use typeof.
Note: The question is not clear and does not explains what will happen if there multiple keys with value as an object. Since the below function will return as soon as it comes across a key whose value is a object
var myObj = {
address: {
0: ["41 Lake Avenue"]
},
name: "jake"
}
function isObject(obj) {
for (let keys in obj) {
if (typeof obj[keys] === 'object' && obj[keys] !== null) {
return true
}
}
}
console.log(isObject(myObj))
if (typeof varible === 'object') {
// is object
}
But Null is also recognized as object. So you could also proove that.
You need to use the typeof(var) operator :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
For object:
typeof yourVariable === 'object' && yourVariable !== null
For string:
typeof yourVariable === 'string'

How to handle undefined object property in angular 5

I tried to fix the undefined error by setting the object property value to an empty string but its still giving the error as mentioned below:
ERROR TypeError: Cannot read property 'notes' of undefined
TS
let notes;
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
notes = '';
} else {
notes = manufacturer_field.manufacturer_guidelines[0].notes;
}
HTML
<p *ngIf="field.notes?.length">{{field.notes}}</p>
I referred this answer but that didn't work: How to handle 'undefined' in javascript
If notes array element 0 is undefined, then this will throw an error:
if (typeof manufacturer_field.manufacturer_guidelines[0].notes == undefined){
because you are checking if the property is undefined, when what is actually undefined is the .manufacturer_guidelines[0] item.
instead, you can do:
if (!manufacturer_field.manufacturer_guidelines[0]){
manufacturer_field.manufacturer_guidelines[0] = (assign it whatever value belong to this sort of item, and then once you know it is valid, then add notes)
}
Also, you are assigning the string to "notes" variable, not the actual array item.
So lets say i had a cars array:
if (!cars[0]) {
cars[0] = <Car>{};
cars[0].color = "blue";
}

Checking if object not null before accessing property [duplicate]

This question already has answers here:
Test for existence of nested JavaScript object key
(64 answers)
Closed 6 years ago.
var how = $('how');
var id = $('myId');
if ((how != null && !how.value.blank()) || myId != null) {
return true;
} else {
alert('Error');
}
Is there an easier way to check for not null and checking if the value of that element is blank without having to do both != null and then calling value?
Since null is falsy, a slightly shorter version would be
if((how && !how.value.blank()) || myId != null) {
...
}
Note that the above code and your own snippet both assume that if how exists, it will have a property called value, and will throw an exception if this is not the case.

Check for existence of key in multidimensional array in javascript

Hopefully an easy question.
Why is that checking for existence of a key in a multidimensional array:
a = new Array(Array());
a[0][0]='1';
a[0][1]='2';
if(a[1][2] == undefined){
alert("sorry, that key doesn't exist");
} else {alert('good, your key exists');
}
seems not to be working in general, but it works when I check for a first index (in this case, '0') that is 'defined' by a[0][x]. For example, when I ask for a[0][2] (which is not defined), it shows the first alert. However, when I ask for a[1][0], I get:
"Uncaught TypeError: Cannot read property '0' of undefined"
How can I solve this problem?
Thanks
Check first if the first dimension exists then if the key in the second dimension exists
The logic will return false if the first test returns false, and tests the second dimension only if the first one is true.
if(a[1] == undefined && a[1][2] == undefined)
With the first three assignments your array actually looks like this:
a = [['1','2']]
Reading a[0][2] just returns undefined because a[0] exists but its property '0' is not defined.
But trying to read a[1][0] throws a TypeError because a[1] is already undefined and isn’t an object and thus doesn’t have any properties. This is also what your error message says:
Cannot read property '0' of undefined.
You can solve this problem by first checking for a[1] and then checking for a[1][0] using the typeof operator:
if (typeof a[1] !== 'undefined' && typeof a[1][0] !== 'undefined')
On supported platforms, We can just do:
if(a[3]?.[3]){
// Do something
}
a = Array(Array())
does not define a multi-dimensional array. It just defines an array with one item, which happens to be another (empty) array. There are no built-in multidimensional arrays in javascript, so you will have to handle things more manually.
You just need to further qualify the conditional. Since the [1] index of the array is undefined you can't test for values in it.
if(a[1] === undefined || a[1][2] === undefined)
Assuming explicitly arr[i][j] = undefined is not done
Try the below:
(Used last 2nd one today)
if (arr[i]?.[j] === 100) {
// value at i & j is 100
}
if (arr[i]?.[j] !== undefined) {
// value at i & j exists
}
if (arr[i]?.[j] === undefined) {
// value at i & j does not exist
}
if ([100, 200].includes(arr[i]?.[j])) {
// value at i & j is 100 or 200
}
if ([undefined, 100].includes(arr[i]?.[j])) {
// value at i & j does not exist
// Or, value exists & it is 100
}
if ([undefined, 100, 200].includes(arr[i]?.[j])) {
// value at i & j does not exist
// Or, value exists & it is 100 or 200
}
var a = Array(Array());
a[0][0]='1';
a[0][1]='2';
if(a[1] === undefined || a[1][2] === undefined) {
alert("sorry, that key doesn't exist");
} else {
alert('good, your key exists');
}

Javascript array value is undefined ... how do I test for that [duplicate]

This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 6 years ago.
I am trying to test to see whether a Javascript variable is undefined.
You will see that I am not expecting the value of predQuery[preId] to be 'undefined' if I don't first get an alert saying "its unbelievable". But I often do, so I am guessing that my statement
predQuery[preId]=='undefined')
is not matching the undefined elements properly.
if((predQuery.length < preId) || (predQuery[preId]=="") || (predQuery[preId]=='undefined')){
alert("its unbelievable");
alert(predQuery[preId]);
queryPreds[variables] = preId;
queryObjs[variables] = objId;
predQuery[preId] = variables;
}
else {
alert(predQuery[preId]);
var predIndex = predQuery[preId];
queryPreds[predIndex] = preId;
queryObjs[predIndex] = objId;
}
I can add more code if needed.
array[index] == 'undefined' compares the value of the array index to the string "undefined".
You're probably looking for typeof array[index] == 'undefined', which compares the type.
You are checking it the array index contains a string "undefined", you should either use the typeof operator:
typeof predQuery[preId] == 'undefined'
Or use the undefined global property:
predQuery[preId] === undefined
The first way is safer, because the undefined global property is writable, and it can be changed to any other value.
predQuery[preId]=='undefined'
You're testing against the string 'undefined'; you've confused this test with the typeof test which would return a string. You probably mean to be testing against the special value undefined:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined.
However there are two ways you can get an undefined value: either preId isn't a member of predQuery, or it is a member but has a value set to the special undefined value. Often, you only want to check whether it's present or not; in that case the in operator is more appropriate:
!(preId in predQuery)
There are more (many) ways to Rome:
//=>considering predQuery[preId] is undefined:
predQuery[preId] === undefined; //=> true
undefined === predQuery[preId] //=> true
predQuery[preId] || 'it\'s unbelievable!' //=> it's unbelievable
var isdef = predQuery[preId] ? predQuery[preId] : null //=> isdef = null
cheers!
Check for
if (predQuery[preId] === undefined)
Use the strict equal to operator. See comparison operators
try: typeof(predQuery[preId])=='undefined'
or more generally: typeof(yourArray[yourIndex])=='undefined'
You're comparing "undefined" to undefined, which returns false =)
This code works very well
function isUndefined(array, index) {
return ((String(array[index]) == "undefined") ? "Yes" : "No");
}

Categories