1

I'm following the solution from https://stackoverflow.com/a/519157/18736427.

However, the console gives me an error that the object I wanna test is undefined...

I wanna test if the object exists, if not, then console.log('False');, but it gives me an error of 'undefined'

Therefore the code after the check cannot be executed...How do I fix this?

const btn = document.querySelector('.test');

//const data1 = {
  //apple: 'red'
//}

const data2 = {
  banana: 'yellow'
}

btn.addEventListener('click', function() {
  if (typeof data1['apple'] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
<button class="test">Check</button>
nakar20966
  • 123
  • 9
  • 1
    `red` is undefined – Lee Taylor Apr 23 '22 at 14:42
  • @LeeTaylor Yes, that's where I wanna test...If the property of the object exists, then do something, if not, do another thing. – nakar20966 Apr 23 '22 at 14:44
  • 1
    But using `red` as you have done causes an error and the rest of your script will not run. – Lee Taylor Apr 23 '22 at 14:46
  • @LeeTaylor I'm sorry it's my mistake, I didn't mean that...Edited question – nakar20966 Apr 23 '22 at 14:51
  • 2
    You now have the same issue with `banana`. This is undefined. – Lee Taylor Apr 23 '22 at 14:54
  • @LeeTaylor I don't understand...I already assign a value ( the string `yellow` ) for the property banana, why it's undefined? Can you explain please – nakar20966 Apr 23 '22 at 14:55
  • You either mean `typeof data2["banana"]` or you mean `let banana = "banana"; typeof data2[banana]`, but not what you have. – Lee Taylor Apr 23 '22 at 14:57
  • @LeeTaylor But what if I wanna test the object that doesn't exist? It still gives me an error of `undefined`...If the object doesn't exist, I expect the `console.log('False')`Please see the updated question...I'm sorry because I'm learning JavaScript – nakar20966 Apr 23 '22 at 15:00
  • 2
    I'd suggest that you don't keep editing your question so often. You probably need to go away, have a think about what you're trying to do, then remove this question and ask another one with more thought behind it. – Lee Taylor Apr 23 '22 at 15:01
  • @LeeTaylor Cannot delete already, I'm sorry, this time the question should be precise – nakar20966 Apr 23 '22 at 15:02
  • @nakar20966 you seem like you want to test if the variable has been declared, which would be the same thing that you would do in your linked question: `typeof data1 !== 'undefined'`. It isn't very common that you need to do this, because most of the time, you should know what is declared and what isn't in your program. – Nick Parsons Apr 23 '22 at 15:13
  • @NickParsons I need to test this because the data is coming from a third party...If the object is not defined, I wanna skip the everything inside the `if` statement, but it just doesn't work here – nakar20966 Apr 23 '22 at 15:14
  • @nakar20966 If the data is coming from a third party (like an API call), then you're the one who still creates the variable to hold the data/object, so you should know what variable you've created and not need to check if it exists using `typeof someVar !== 'undefined'` – Nick Parsons Apr 23 '22 at 15:17
  • @NickParsons Thanks for the info. But in fact, the data is pulled on condition. For example, if a user is logged in, then pull the data. And this is why the object will not be defined for users that are not logged in, and hence I need to put something inside the `if` statement, if user is not logged in, the code after it should be executed... – nakar20966 Apr 23 '22 at 15:21
  • You might be confusing not declared vs `undefined`. The `typeof` check if usually done to when you don't know if a variable exists in your code. If you type `console.log(someVariable)`, your code will crash because `someVariable` doesn't exist as a variable in your code. On the other hand, if you create `someVariable` first by doing `let someVariable;` and you try and use it in your code `console.log(someVariable)`, your code won't crash, instead `someVariable` defaults to a value of `undefined`, you can check if the variable holds a value by using `if(someVariable !== undefined)` – Nick Parsons Apr 23 '22 at 15:22
  • @NickParsons May I know what I need to do to check if a variable is **declared**? – nakar20966 Apr 23 '22 at 15:26
  • If you don't know if the variable is declared, use typeof: `if(typeof data1 !== 'undefined')`, if you know the variable is declared, but are unsure if it holds a value, then you can check for undefined: `if(data1 !== undefined)`. Based on what you're saying though, you should know if you're variable is declared. A little hard to tell what the exact problem is without more context. – Nick Parsons Apr 23 '22 at 15:28
  • 1
    @NickParsons I've posted an answer, thanks for helping me! You've made my day – nakar20966 Apr 23 '22 at 15:35

5 Answers5

0

try:

const btn = document.getElementsByClassName('test');

if (typeof data["apple"] !== 'undefined') {
    console.log('Yes');
  }

you should use data.apple or data["apple"].

Hesam
  • 450
  • 2
  • 11
0

Check if you really need to provide red and apple variables.

Instead use a strings for keys

const btn = document.querySelector('.test');
const data = {
 apple: "red"
}

btn.addEventListener('click', function() {
  if (typeof data["apple"] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
0

If a object variable does not definied, the javascript really do not throw error. But if you write the red variable, the browser try assigns the real value the red variable. So, the method really works: the red varible undefinied.

const btn = document.querySelector('.test');
const data = {
   //do not define apple
}

btn.addEventListener('click', function() {
  if (typeof data['apple'] !== 'undefined') {
    console.log('Yes');
  }
  
  console.log('False');
});
<button class="test">Check</button>
user17517503
  • 155
  • 11
0

EDITED:

Since, the below line of code is commented out.

//const data1 = {
 //apple: 'red'
//}

JavaScript engine doesn't find data1 Object. So, obviously you are getting an error at this point.

To test your data1 object, you have to uncomment it first.

Then to check whether the object really exits we can count the keys.

If Object.keys(data1).length > 0, then object data1 exists with at least one property.

Or you can simply check :

if(data1) {
  console.log("Yes")
}else{
  console.log("Object doesn't exist")
}

However you can check whether a variable is defined or not by directly using typeof.

 if(typeof data1 !== 'undefined) {
   console.log('Data1 exists');
 }

Please refer to the GeeksForGeeks Website:

GEEKS FOR GEEKS

Note that you cannot check an object or variable which hasn't been declared in the code. It is an error.

data1 is not defined

const btn = document.querySelector('.test');

const data1 = {
  apple: 'red'
}

const data2 = {
  banana: 'yellow'
}

btn.addEventListener('click', function() {
  if (data1) {
    console.log('Yes');
  }else {
    console.log("Data1 object doesn't exist")
  }
});
<button class="test">Check</button>
Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
  • Please have a look at the edited question...I'm sorry The intention is to test an object that is not defined, the `console.log('False')` should be expected – nakar20966 Apr 23 '22 at 15:09
  • Oh I see, So, you want to check whether an object exists or not. Right? Is there your query friend? – Imran Rafiq Rather Apr 23 '22 at 15:12
  • I have updated my answer based on what I feel is your requirement. – Imran Rafiq Rather Apr 23 '22 at 15:17
  • The reason I commented on the `data1` is to pretend it doesn't exist... – nakar20966 Apr 23 '22 at 15:27
  • Then how can we test its existence when it already doesn't exist my Friend. How does JavaScript even know that it is even a variable. Rule of Programming is that `our variables must be defined first` for them to exist in memory and on top of that we perform operations – Imran Rafiq Rather Apr 23 '22 at 15:29
  • Oh, I think I got your question, You just want to check whether a variable is defined or not in the code. If yes then we indeed need `type of` operator to check that in a proper way – Imran Rafiq Rather Apr 23 '22 at 15:32
  • 1
    I finally got the answer from @Nick Parsons, but I will up-vote your answer for your hard work. Thank you so much, my friend! – nakar20966 Apr 23 '22 at 15:34
  • 1
    https://www.geeksforgeeks.org/javascript-check-the-existence-of-variable/#:~:text=The%20typeof%20operator%20will%20check,null%20will%20return%20an%20object. Here you can see, we must first define our variable and only then we can check for its assignment within. – Imran Rafiq Rather Apr 23 '22 at 15:36
  • Or great that you got your answer, However do read the above link that I have shared. It covers your query 100% and also you will learn more knowledge :) Happy Coding – Imran Rafiq Rather Apr 23 '22 at 15:44
0

There are multiple ways to do it. I am just making a little change in your code and now it is working.

const btn = document.querySelector('.test');
const data = {
   //do not define apple

}

btn.addEventListener('click', function() {
    
  if (!!data['apple']) {
    console.log('Apple Exist');
  }
  else{
    console.log('Apple does not Exist');
  }
  
});
SayAz
  • 751
  • 1
  • 9
  • 16