0

So i have a function, lets say:

function a(string).....

and i want to check if the string is undefind. if it is do something The code would look something like this:

function a(string){
 if(string == null){
 //do something
 }
 else{
 //do another thing
 }

The problem is it doesn't seem to work, even if the string isn't declared its still going to call the else. Maybe we could try doing

 if(string == "undefind"){
 //do something
 }
 else{
 //do something else
 }

but yet it doesn't seem to change anything. null and undefind seem to work in the same way. Is there a specific function from a library that allows the checking if an input is declared? is there a way you could check it directly from the input with something like

if(string.isDeclared()==true){
//do something
}
else{
//do something else
}
DcraftBg
  • 27
  • 5
  • typeof myVar === 'undefined' – Diego D Apr 04 '22 at 08:54
  • Check on strict equality of `undefined` – mardubbles Apr 04 '22 at 08:54
  • *"The problem is it doesn't seem to work, even if the string isn't declared its still going to call the else."* Yes, [that works](https://jsfiddle.net/tjcrowder/58zakdmb/). It will branch into the `if` branch if `string` is either `null` or `undefined`. `string == "undefined"` will only check if it's the **string** value `"undefined"`. – T.J. Crowder Apr 04 '22 at 08:55
  • Yes agree with @T.J.Crowder, the equality check must be on `undefined` outside of a string enclosure. Spelling mistakes with "undefind" not relevant when enclosed in quotes. – mardubbles Apr 04 '22 at 08:55
  • This topic is **very** well-covered by previous questions and answers, such as [this one](https://stackoverflow.com/questions/3390396/how-can-i-check-for-undefined-in-javascript) which is a duplicate of several others. – T.J. Crowder Apr 04 '22 at 08:57
  • ty i fixed it and now all works well :D – DcraftBg Apr 04 '22 at 08:59
  • and the suggestion to go bring undefined outside quotes it's not correct. You can check yourself on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined where it says it can be done also quoting undefined. – Diego D Apr 04 '22 at 09:00
  • @DiegoDeVita just followed your link. No where in it is `undefined` in quotes. There is mention of `type of` where quotes are allowed however. – mardubbles Apr 04 '22 at 09:02
  • @mardubbles check better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#typeof_operator_and_undefined – Diego D Apr 04 '22 at 09:03
  • OP doesn't use `type of` @DiegoDeVita – mardubbles Apr 04 '22 at 09:04

0 Answers0