This question already has answers here:
JavaScript isset() equivalent
(28 answers)
Closed 6 years ago.
Is there something in javascript/jQuery to check whether variable is set/available or not? In php, we use isset($variable) to check something like this.
thanks.
Try this expression:
typeof(variable) != "undefined" && variable !== null
This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.
You can use it like this:
if(typeof(variable) != "undefined" && variable !== null) {
bla();
}
JavaScript isset() on PHP JS
function isset () {
// discuss at: http://phpjs.org/functions/isset
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: FremyCompany
// + improved by: Onno Marsman
// + improved by: Rafał Kukawski
// * example 1: isset( undefined, true);
// * returns 1: false
// * example 2: isset( 'Kevin van Zonneveld' );
// * returns 2: true
var a = arguments,
l = a.length,
i = 0,
undef;
if (l === 0) {
throw new Error('Empty isset');
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false;
}
i++;
}
return true;
}
typeof will serve the purpose I think
if(typeof foo != "undefined"){}
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window object) this can work well for checking if values have been declared.
Some parts of each of these answers work. I compiled them all down into a function "isset" just like the question was asking and works like it does in PHP.
// isset helper function
var isset = function(variable){
return typeof(variable) !== "undefined" && variable !== null && variable !== '';
}
Here is a usage example of how to use it:
var example = 'this is an example';
if(isset(example)){
console.log('the example variable has a value set');
}
It depends on the situation you need it for but let me break down what each part does:
typeof(variable) !== "undefined" checks if the variable is defined at all
variable !== null checks if the variable is null (some people explicitly set null and don't think if it is set to null that that is correct, in that case, remove this part)
variable !== '' checks if the variable is set to an empty string, you can remove this if an empty string counts as set for your use case
Hope this helps someone :)
Not naturally, no... However, a googling of the thing gave this: http://phpjs.org/functions/isset:454
http://phpjs.org/functions/isset:454
phpjs project is a trusted source. Lots of js equivalent php functions available there. I have been using since a long time and found no issues so far.
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Here :)
function isSet(iVal){
return (iVal!=="" && iVal!=null && iVal!==undefined && typeof(iVal) != "undefined") ? 1 : 0;
} // Returns 1 if set, 0 false
in addition to #emil-vikström's answer, checking for variable!=null would be true for variable!==null as well as for variable!==undefined (or typeof(variable)!="undefined").
You can just:
if(variable||variable===0){
//Yes it is set
//do something
}
else {
//No it is not set
//Or its null
//do something else
}
Related
This error comes up a lot in javascript development.
cannot read property join of undefined
Is there a best way of dealing with this issue?
Some of the techniques I've used are:
Initialisation
question.tags = question.tags || [];
console.log(question.tags.join(', ');
If statements
if(question.tags) {
console.log(question.tags.join(', ');
}
You can use if..else, Object.hasOwnProperty(), Array.isArray() to determine if question exists and object has property tags and question.tags is an array
if (typeof question === "object"
&& question.hasOwnProperty("tags")
&& Array.isArray(question.tags)) {
//do stuff
} else {
// do other stuff, e.g
// question = {};
// question.tags = [];
}
There is no specific and exact way to do it. If there is an instance of the Array or Object or String, it inhertits the prototypal functions. Like an instance of array has a splice(), String instance has a replace ().
Now when this instance is undefined, it throws JS error. Lets assume a is supposedly an array. You can put a dirty check either by a logical ||
(a || []).length;
or a if block or a ternary property
return a ? a.length || undefined;
or a type check
(Array.isArray(a) || []).length
question.tags ? question.tags : []
You can use === and !== operators in if condition like
if(object.property !== undefined)
{
///write your code here
}
This operator will match your value + type so its easy to identify if mentioned property is undefined or not..hope this will help:)
I was wondering what is the value of an ignored parameter in JS. Lets say that a function takes 2 values as parameters and we only provide one on the call. What is the value of the other one? I thought it would be undefined but the following piece of code only displays "1".
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2.toString());
if(typeof par2 === "undefined"){
document.write('undefined');
}
};
test(1);
the following code would work:
var test = function(par1, par2){
document.write(par1.toString());
document.write(par2);
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
When parameter is not supplied, its value is undefined. Note that variable itself is available (after all, its name is already supplied to a function via arguments list, and it's the name that counts in JavaScript), so there's no need to check it via typeof var === 'undefined' to avoid those pesky ReferenceErrors.
undefined is a special value in JavaScript. While you cannot call any method on it (fails with undefined is not an object Error), you still can use it in expressions and function calls. In this particular case document.write will implicitly convert this value to String before displaying it; the result will be a String - 'undefined'.
Demo.
Try:
var test = function(par1, par2){
if(par2 === undefined){
document.write('undefined');
}
};
test(1);
Working demo
You can also check, if your attributes are set. Example:
var test = function(par1, par2){
if(par1 === undefined){
document.write('par1 is undefined');
}else{
document.write('par1 is set');
}
if(par2 === undefined){
document.write('par2 is undefined');
}else{
document.write('par2 is set');
}
};
test(1);
And output will be:
par1 is set
par2 is undefined
Demo 2
Hope it'll help :)
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing) Then
End If
I need to convert this to javascript. Is that enough to check null?
This was my lead's answer, plz verify this,
if(typeof $(data).find("BigGroupType").text() != "undefined" && $(data).find("BigGroupType").text() != null) {
}
JavaScript has two values which mean "nothing", undefined and null. undefined has a much stronger "nothing" meaning than null because it is the default value of every variable. No variable can be null unless it is set to null, but variables are undefined by default.
var x;
console.log(x === undefined); // => true
var X = { foo: 'bar' };
console.log(X.baz); // => undefined
If you want to check to see if something is undefined, you should use === because == isn't good enough to distinguish it from null.
var x = null;
console.log(x == undefined); // => true
console.log(x === undefined); // => false
However, this can be useful because sometimes you want to know if something is undefined or null, so you can just do if (value == null) to test if it is either.
Finally, if you want to test whether a variable even exists in scope, you can use typeof. This can be helpful when testing for built-ins which may not exist in older browsers, such as JSON.
if (typeof JSON == 'undefined') {
// Either no variable named JSON exists, or it exists and
// its value is undefined.
}
You need to check for both null and undefined, this implicitly does so
if( oResponse.selectSingleNode("BigGroupType") != null ) {
}
It is the equivalent of:
var node = oResponse.selectSingleNode("BigGroupType");
if( node !== null &&
node !== void 0 ) {
}
void 0 being a bulletproof expression to get undefined
In JavaScript equvalent for Nothing is undefined
if(oResponse.selectSingleNode("BigGroupType") != undefined){
}
This logic:
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing)
Can be written like this in JavaScript:
if (typeof oResponse.selectSingleNode("BigGroupType") != 'undefined')
Nothing would equal undefined, but checking against undefined is not recommended for several reasons, it’s generally safer to use typeof.
However, if the selectSingleNode can return other falsy values such as null, it’s probably OK to just do a simple check if it is truthy:
if (oResponse.selectSingleNode("BigGroupType"))
JavaScript:-
(document.getElementById(“BigGroupType”) == undefined) // Returns true
JQuery:-
($(“#BigGroupType”).val() === “undefined”) // Returns true
Note in above examples undefined is a keyword in JavaScript, where as in JQuery it is just a string.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript test for existence of nested object key
I'm attempting to construct an error message for a formset by testing if a certain object is not undefined, and if it's not undefined, then I end up populating it with that error message. The main problem is that I have to validate if each nested object is undefined, which results in some pretty ugly code. Here's the example:
errorsForField: function(fieldName, formsetName, formNumber) {
if (typeof this.model.errors != 'undefined'){
var fieldError = document.createElement('span');
$(fieldError).addClass('field-error');
// THE FOLLOWING LINE THROWS ERROR.
if (formsetName && _.isUndefined(this.model.errors[formsetName][fieldName]) != true) {
$(fieldError).text(this.model.errors[formsetname][fieldName]);
} else if (typeof this.model.errors[fieldName] != "undefined"){
$(fieldError).text(this.model.errors[fieldName]);
}
this.errors[fieldName] = fieldError.outerHTML;
return fieldError.outerHTML;
}
return false;
},
I get an error stating that I cannot determine [fieldName] of an undefined object this.model.errors[formsetName]. In other words, I have to first determine if this.model.errors[formsetName] is empty and then test if [fieldname] is undefined.
This seems like a really cumbersome solution. Any suggestions for changing this?
You can create a library function that takes property names as parameters and returns the final value if it exists, or null:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
return names.length ? null : o;
}
Call it like:
var err = TryGetPropertyValue(this.model.errors, formsetName, fieldName) ||
TryGetPropertyValue(this.model.errors, fieldName);
if (err != null) {
$(fieldError).text(err);
}
If you want it to return undefined instead of null if the field is not found, you can change the function slightly:
function TryGetPropertyValue(o, propertyName1 /*, ... propertyNameN */) {
var names = [].slice.call(arguments, 1);
while (o && names.length) {
o = o[names.shift()];
}
if (names.length == 0) {
return o;
}
}
http://jsfiddle.net/HbggQ/
As Paul suggested, this is an inherent limitation of Javascript. Even Coffeescript (which is just a layer of syntactic sugar on top of JS) doesn't really solve the problem; it just hides the workaround under it's syntactic sugar (which admittedly is really handy)
If you want to stick to Javascript, you basically have two options: use ternary operators, or use boolean operators. Here's examples of each that check A.B.C.D (where A, B, C or D might not exist):
// Returns A.B.C.D, if it exists; otherwise returns false (via ternary)
return !A ? false :
!A.B ? false :
!A.B.C ? false :
A.B.C.D ? A.B.C.D : false;
// Returns A.B.C.D, if it exists; otherwise returns false (via booleans)
return A && A.B && A.B.C && A.B.C.D;
Obviously the latter is a lot shorter. Both solutions rely on Javascript's "truthiness" (ie. that the values 0, "", null, and undefined count as false). This should be fine for your case, as none of those values will have an errors property. However, if you did need to distinguish between (say) 0 and undefined, you could use the ternary style, and replace !A with typeof(A) == 'undefined'.
How do I verify the existence of an object in JavaScript?
The following works:
if (!null)
alert("GOT HERE");
But this throws an Error:
if (!maybeObject)
alert("GOT HERE");
The Error:
maybeObject is not defined.
You can safely use the typeof operator on undefined variables.
If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.
Therefore
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
There are a lot of half-truths here, so I thought I make some things clearer.
Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).
The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined
var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)
So both a variable that exists and another one that doesn't can report you the undefined type.
As for #Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.
If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.
The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.
You can use:
if (typeof objectName == 'object') {
//do something
}
Two ways:
typeof for local variables
You can test for a local object using typeof:
if (typeof object !== "undefined") {}
window for global variables
You can test for a global object (one defined on the global scope) by inspecting the window object:
if (window.FormData) {}
If that's a global object, you can use if (!window.maybeObject)
You could use "typeof".
if(typeof maybeObject != "undefined")
alert("GOT HERE");
If you care about its existence only ( has it been declared ? ), the approved answer is enough :
if (typeof maybeObject != "undefined") {
alert("GOT THERE");
}
If you care about it having an actual value, you should add:
if (typeof maybeObject != "undefined" && maybeObject != null ) {
alert("GOT THERE");
}
As typeof( null ) == "object"
e.g. bar = { x: 1, y: 2, z: null}
typeof( bar.z ) == "object"
typeof( bar.not_present ) == "undefined"
this way you check that it's neither null or undefined, and since typeof does not error if value does not exist plus && short circuits, you will never get a run-time error.
Personally, I'd suggest adding a helper fn somewhere (and let's not trust typeof() ):
function exists(data){
data !== null && data !== undefined
}
if( exists( maybeObject ) ){
alert("Got here!");
}
I used to just do a if(maybeObject) as the null check in my javascripts.
if(maybeObject){
alert("GOT HERE");
}
So only if maybeObject - is an object, the alert would be shown.
I have an example in my site.
https://sites.google.com/site/javaerrorsandsolutions/home/javascript-dynamic-checkboxes
The thread was opened quite some time ago. I think in the meanwhile the usage of a ternary operator is the simplest option:
maybeObject ? console.log(maybeObject.id) : ""
I've just tested the typeOf examples from above and none worked for me, so instead I've used this:
btnAdd = document.getElementById("elementNotLoadedYet");
if (btnAdd) {
btnAdd.textContent = "Some text here";
} else {
alert("not detected!");
}
Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.
Example of function that checks, provides alternative, and catch errors.
function fillForm(obj) {
try {
var output;
output = (typeof obj !== 'undefined') ? obj : '';
return (output);
}
catch (err) {
// If an error was thrown, sent it as an alert
// to help with debugging any problems
alert(err.toString());
// If the obj doesn't exist or it's empty
// I want to fill the form with ""
return ('');
} // catch End
} // fillForm End
I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.
I hope it helps. (BTW, I am novice with JS)
for me this worked for a DOM-object:
if(document.getElementsById('IDname').length != 0 ){
alert("object exist");
}
if (n === Object(n)) {
// code
}
if (maybeObject !== undefined)
alert("Got here!");
set Textbox value to one frame to inline frame using div alignmnt tabbed panel.
So first of all, before set the value we need check selected tabbed panels frame available or not using following codes:
Javascript Code :
/////////////////////////////////////////
<script>
function set_TextID()
{
try
{
if(!parent.frames["entry"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["entry"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["education"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["education"].document.getElementById("form_id").value=setText;
}
if(!parent.frames["contact"])
{
alert("Frame object not found");
}
else
{
var setText=document.getElementById("formx").value;
parent.frames["contact"].document.getElementById("form_id").value=setText;
}
}catch(exception){}
}
</script>
zero and null are implicit pointers. If you arn't doing arithmetic, comparing, or printing '0' to screen there is no need to actually type it. Its implicit. As in implied. Typeof is also not required for the same reason. Watch.
if(obj) console.log("exists");
I didn't see request for a not or else there for it is not included as. As much as i love extra content which doesn't fit into the question. Lets keep it simple.
Think it's easiest like this
if(myobject_or_myvar)
alert('it exists');
else
alert("what the hell you'll talking about");
Or, you can all start using my exclusive exists() method instead and be able to do things considered impossible. i.e.:
Things like: exists("blabla"), or even: exists("foreignObject.guessedProperty.guessNext.propertyNeeded") are also possible...