Test if something is not undefined in JavaScript - javascript

I'm checking if(response[0].title !== undefined), but I get the error:
Uncaught TypeError: Cannot read property 'title' of undefined.

response[0] is not defined, check if it is defined and then check for its property title.
if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}

Just check if response[0] is undefined:
if(response[0] !== undefined) { ... }
If you still need to explicitly check the title, do so after the initial check:
if(response[0] !== undefined && response[0].title !== undefined){ ... }

I had trouble with all of the other code examples above. In Chrome, this was the condition that worked for me:
typeof possiblyUndefinedVariable !== "undefined"
I will have to test that in other browsers and see how things go I suppose.

Actually you must surround it with an Try/Catch block so your code won't stop from working.
Like this:
try{
if(typeof response[0].title !== 'undefined') {
doSomething();
}
}catch(e){
console.log('responde[0].title is undefined');
}

typeof:
var foo;
if (typeof foo == "undefined"){
//do stuff
}

It'll be because response[0] itself is undefined.

Check if condition == null;
It will resolve the problem

Check if you're response[0] actually exists, the error seems to suggest it doesn't.

You must first check whether response[0] is undefined, and only if it's not, check for the rest. That means that in your case, response[0] is undefined.

I know i went here 7 months late, but I found this questions and it looks interesting. I tried this on my browser console.
try{x,true}catch(e){false}
If variable x is undefined, error is catched and it will be false, if not, it will return true. So you can use eval function to set the value to a variable
var isxdefined = eval('try{x,true}catch(e){false}')

In some of these answers there is a fundamental misunderstanding about how to use typeof.
Incorrect
if (typeof myVar === undefined) {
Correct
if (typeof myVar === 'undefined') {
The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.
Addendum
Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.
let undefined = 42;
And here is an example of how you can use this to prove the first method is incorrect:
https://jsfiddle.net/p6zha5dm/

Related

How can avoid !! comparation in JavaScript?

I am using this "!!" comparation in order to compare with "undefined". However, is there any other way to do it?
isWidgetTemplatesLoaded: function(widgetName) {
return !!templates[widgetName];
}
Thanks
You could use typeof to check for undefined:
(typeof templates[widgetName] !== 'undefined')
typeof always returns a string. It returns "undefined" if the value of the variable is undefined or the variable does not exist.
You can use the typeof operator
typeof templates[widgetName];
else you can also use like this
if (templates[widgetName] === undefined) {
// rest of code
}
else {
// rest of code
}
To check for undefined you can just use the no-conversion equal/different operators:
if (x !== undefined) { ... }
if (y === undefined) { ... }
note however that this doesn't have the exact same meaning of !!. The double-negation for example returns true even for false, null, 0 or "" despite the fact that these values are not undefined.
By the way in Javascript you should basically always use === and !== instead of == and !=, unless you really need the crazy implicit conversion that equality/different operators do (and no one needs that). Good Javascript editors will warn you about any use of == or != as they are just bug-hiding places.
In the specific of your question code the !! logic seems wrong on a philosophical level because an empty template could be "" and this function would say that the template has not been loaded while instead it has been loaded and simply happens to be the empty string.
You could use the in operator, if you know, if the property exist with some value, other than undefined.
return widgetName in templates;

Javascript: check for key in array that might not exist

Say boundEvents is an array that might or might not exist. If it doesn't exist, then the following code will return 'undefined':
console.log(typeof boundEvents);
Fine. That is exactly what I want. Now say I want to check that theoretical array for the existence of a key which might or might not exist.
console.log(typeof boundEvents['click']);
Uh oh:
Uncaught TypeError: Cannot read property 'click' of undefined
Fair enough, javascript. So let's check to see if the array exists, before we check for the key:
if(typeof boundEvents != 'undefined'){
console.log(typeof boundEvents['click']);
}
Working again, but I'm wondering if there is a way to eliminate the if statement and just check on the existence of boundEvents['click'] directly, in one step?
Thanks!
EDIT: complete answer, combined from below:
var boundEvents = boundEvents || {};
console.log(boundEvents.hasOwnProperty('click'));
You can do:
boundEvents = boundEvents || {};
console.log(boundEvents['click']);
or in a single line:
console.log((boundEvents || {})['click']);
If you want an explicit true / false then:
(boundEvents || {}).hasOwnProperty('click')
You can check each layer ending on the variable you want. This will default to undefined if everything is false.
( (typeof boundEvents !== "undefined") && boundEvents['click']) || undefined

Why doesn't this simple javascript statement work to check if the variable exists?

I'm processing some return JSON data.
Sometimes the JSON will return something I can access via
var new_insert_id = data['internal']['new_insert_id'];
But sometimes this part of the json array data will not be returned at all, and so I need to skip this variable being set.
So I've written a simple check to make sure this data exists before trying to set the variable:
if(typeof data['internal']['new_insert_id'] != 'undefined')
{
// if data['internal']['new_insert_id'] is defined, then..
var new_insert_id = data['internal']['new_insert_id'];
}
But when the JSON returns and there is no new_insert_id I am getting the following error:
Uncaught TypeError: Cannot read property 'new_insert_id' of undefined
And the line of code it points to as the culprit is the line of my if statement.
What am I missing? I thought my if statement would check if it exists or not, or do I need to do something else when working with arrays?
Besides you can firstly check for existence of data['internal'], but you can also use the pythonic way, i.e. apply try/catch block:
try {
var new_insert_id = data['internal']['new_insert_id'];
} catch (e) {}
The statement you've written checks if new_insert_id property exists in 'internal', but it doesn't check if 'internal' exists in data variable.
This should work better:
if(typeof data['internal'] != 'undefined' && typeof data['internal']['new_insert_id'] != 'undefined')
{
var new_insert_id = data['internal']['new_insert_id'];
}
the error message says, that data['internal'] is already undefined. you need to check that before:
if(typeof(data['internal']) != 'undefined' && typeof data['internal']['new_insert_id'] != 'undefined')
You need to check data['internal'] !== undefined first :)
in your test, you are testing if the property ['new_insert_id'] of data['internal'] is undefined then you have trouble accessing it because data['internal'] is undefined hence the error you get.
You have first to check if data['internal'] is undefined.
I think it because data['internal'] is undefined.
So you need check data['internal'] first.
if(data['internal'] && data['internal']['new_insert_id'])
{
// if data['internal']['new_insert_id'] is defined, then..
var new_insert_id = data['internal']['new_insert_id'];
}

Why is this check throwing an error, even if I check whether it’s undefined beforehand?

I passed in a series of JSON objects with an AJAX call. Some of the data sets include the field C and some do not. When I include the following code, it crashes. I have tried undefined and null. Both crash.
if (myJsonObjects[i].C == undefined) {
// …
}
When you say crash I presume you mean TypeError: cannot read property of undefined value
The reason it crashes is because in the line
if(myJsonObjects[i].C == undefined){
We actually have myJSONObject[i] === undefined
So really you need to check your array bounds or make sure your array is not sparse
if(myJsonObjects[i].C == undefined){
is the similar as
if(myJsonObjects[i] && myJsonObjects[i].C){
but with mine line, you check is myJsonObjects[i] and myJsonObjects[i].c are null or undefined.
The caveat being if myJsonObjects[i].c holds false, "", 0, NaN
Try this:
if (typeof myJsonObjects[i].C == 'undefined') {}
I guess you could test the waters a little before jumping right in:
if( i in myJsonObjects && myJsonObjects[i] && !( "C" in myJsonObjects[i] ) ) { }
However your original code should not crash and shouldn't throw error either if myJsonObjects[i] is defined and is not null
How about
if ('C' in myJsonObjects[i]) { do_your_magic() }

if statement running on false?

using javascript
I have a function
function test(variable)
{
if(variable != 'undefined')
{
console.log('variable is not set');
console.log('variable', where);
}
}
i call it using test();
yet in the console I get
'where is not set'
'where is set as undefined'
why?
Update
This function is not what i am actually using.
The function should not do anything if the variable is undefined.
the example was to show the if statement not working.
But the issue was actually me using if variable != 'undefined' instead of variable != undefined
You have both console.log calls in the same if branch. Do this instead:
function test(variable)
{
if(variable != 'undefined')
{
console.log('where is not set');
}
else
{
console.log('where is set as ', where);
}
}
Besides that: If you want to test if a variable is undefined, use the typeof operator to test the type: typeof variable != 'undefined'. Currently you just test if variable is not equal to the string value 'undefined'.
You are testing whether variable has the string content of "undefined".
What you probably want is
if(typeof variable != 'undefined')
The rest of the function is not making sense to me yet, either. Where does where come from?
I don't quite understand your question but try using different paramater name instead of "variable". See if the error still there.
Plus call the function like this: test(paramterValueHere);
Best

Categories