How to check if function exists in JavaScript? - javascript
My code is
function getID( swfID ){
if(navigator.appName.indexOf("Microsoft") != -1){
me = window[swfID];
}else{
me = document[swfID];
}
}
function js_to_as( str ){
me.onChange(str);
}
However, sometimes my onChange does not load. Firebug errors with
me.onChange is not a function
I want to degrade gracefully because this is not the most important feature in my program. typeof gives the same error.
Any suggestions on how to make sure that it exists and then only execute onChange?
(None of the methods below except try catch one work)
Try something like this:
if (typeof me.onChange !== "undefined") {
// safe to use the function
}
or better yet (as per UpTheCreek upvoted comment)
if (typeof me.onChange === "function") {
// safe to use the function
}
I had this problem. if (obj && typeof obj === 'function') { ... } kept throwing a reference error if obj happened to be undefined, so in the end I did the following:
if (typeof obj !== 'undefined' && typeof obj === 'function') { ... }
However, a colleague pointed out to me that checking if it's !== 'undefined' and then === 'function' is redundant, thus:
Simpler:
if (typeof obj === 'function') { ... }
Much cleaner and works great.
Modern JavaScript to the rescue!
me.onChange?.(str)
The Optional Chaining syntax (?.) solves this
in JavaScript since ES2020
in Typescript since version 3.7
In the example above, if a me.onChange property exists and is a function, it is called.
If no me.onChange property exists, nothing happens: the expression just returns undefined.
Note - if a me.onChange property exists but is not a function, a TypeError will be thrown just like when you call any non-function as a function in JavaScript. Optional Chaining doesn't do any magic to make this go away.
How about:
if('functionName' in Obj){
//code
}
e.g.
var color1 = new String("green");
"length" in color1 // returns true
"indexOf" in color1 // returns true
"blablabla" in color1 // returns false
or as for your case:
if('onChange' in me){
//code
}
See MDN docs.
If you're using eval to convert a string to function, and you want to check if this eval'd method exists, you'll want to use typeof and your function string inside an eval:
var functionString = "nonexsitantFunction"
eval("typeof " + functionString) // returns "undefined" or "function"
Don't reverse this and try a typeof on eval. If you do a ReferenceError will be thrown:
var functionString = "nonexsitantFunction"
typeof(eval(functionString)) // returns ReferenceError: [function] is not defined
Try typeof -- Look for 'undefined' to say it doesn't exist, 'function' for a function. JSFiddle for this code
function thisishere() {
return false;
}
alert("thisishere() is a " + typeof thisishere);
alert("thisisnthere() is " + typeof thisisnthere);
Or as an if:
if (typeof thisishere === 'function') {
// function exists
}
Or with a return value, on a single line:
var exists = (typeof thisishere === 'function') ? "Value if true" : "Value if false";
var exists = (typeof thisishere === 'function') // Returns true or false
Didn't see this suggested:
me.onChange && me.onChange(str);
Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).
You can even go further and do:
me && me.onChange && me.onChange(str);
in case me is async as well.
For me the easiest way :
function func_exists(fname)
{
return (typeof window[fname] === 'function');
}
Put double exclamation mark i.e !! before the function name that you want to check. If it exists, it will return true.
function abc(){
}
!!window.abc; // return true
!!window.abcd; // return false
//Simple function that will tell if the function is defined or not
function is_function(func) {
return typeof window[func] !== 'undefined' && $.isFunction(window[func]);
}
//usage
if (is_function("myFunction") {
alert("myFunction defined");
} else {
alert("myFunction not defined");
}
function function_exists(function_name)
{
return eval('typeof ' + function_name) === 'function';
}
alert(function_exists('test'));
alert(function_exists('function_exists'));
OR
function function_exists(func_name) {
// discuss at: http://phpjs.org/functions/function_exists/
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Steve Clay
// improved by: Legaev Andrey
// improved by: Brett Zamir (http://brett-zamir.me)
// example 1: function_exists('isFinite');
// returns 1: true
if (typeof func_name === 'string') {
func_name = this.window[func_name];
}
return typeof func_name === 'function';
}
function js_to_as( str ){
if (me && me.onChange)
me.onChange(str);
}
I'll go 1 step further to make sure the property is indeed a function
function js_to_as( str ){
if (me && me.onChange && typeof me.onChange === 'function') {
me.onChange(str);
}
}
I like using this method:
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
Usage:
if ( isFunction(me.onChange) ) {
me.onChange(str); // call the function with params
}
I had the case where the name of the function varied according to a variable (var 'x' in this case) added to the functions name. This works:
if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); }
The Underscore.js library defines it in the isFunction method as this (which comments suggest may cater for some browser bugs)
typeof obj == 'function' || false
http://underscorejs.org/docs/underscore.html#section-143
If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction
if (typeof $.fn.mask === 'function') {
$('.zip').mask('00000');
}
Here is a working and simple solution for checking existence of a function and triggering that function dynamically by another function;
Trigger function
function runDynamicFunction(functionname){
if (typeof window[functionname] == "function") { //check availability
window[functionname]("this is from the function it"); // run function and pass a parameter to it
}
}
and you can now generate the function dynamically maybe using php like this
function runThis_func(my_Parameter){
alert(my_Parameter +" triggerd");
}
now you can call the function using dynamically generated event
<?php
$name_frm_somware ="runThis_func";
echo "<input type='button' value='Button' onclick='runDynamicFunction(\"".$name_frm_somware."\");'>";
?>
the exact HTML code you need is
<input type="button" value="Button" onclick="runDynamicFunction('runThis_func');">
In a few words: catch the exception.
I am really surprised nobody answered or commented about Exception Catch on this post yet.
Detail: Here goes an example where I try to match a function which is prefixed by mask_ and suffixed by the form field "name". When JavaScript does not find the function, it should throw an ReferenceError which you can handle as you wish on the catch section.
function inputMask(input) {
try {
let maskedInput = eval("mask_"+input.name);
if(typeof maskedInput === "undefined")
return input.value;
else
return eval("mask_"+input.name)(input);
} catch(e) {
if (e instanceof ReferenceError) {
return input.value;
}
}
}
With no conditions
me.onChange=function(){};
function getID( swfID ){
if(navigator.appName.indexOf("Microsoft") != -1){
me = window[swfID];
}else{
me = document[swfID];
}
}
function js_to_as( str ){
me.onChange(str);
}
I would suspect that me is not getting correctly assigned onload.
Moving the get_ID call into the onclick event should take care of it.
Obviously you can further trap as previously mentioned:
function js_to_as( str) {
var me = get_ID('jsExample');
if (me && me.onChange) {
me.onChange(str);
}
}
I always check like this:
if(!myFunction){return false;}
just place it before any code that uses this function
This simple jQuery code should do the trick:
if (jQuery.isFunction(functionName)) {
functionName();
}
I have tried the accepted answer; however:
console.log(typeof me.onChange);
returns 'undefined'.
I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).
Changing the original accepted answer to the following worked for me:
if (typeof me.onchange === "function") {
// safe to use the function
}
I have also been looking for an elegant solution to this problem. After much reflection, I found this approach best.
const func = me.onChange || (str => {});
func(str);
I would suggest using:
function hasMethod(subject, methodName) {
return subject != null && typeof subject[methodName] == "function";
}
The first check subject != null filters out nullish values (null and undefined) which don't have any properties. Without this check subject[methodName] could throw an error:
TypeError: (undefined|null) has no properties
Checking for only a truthy value isn't enough, since 0 and "" are both falsy but do have properties.
After validating that subject is not nullish you can safely access the property and check if it matches typeof subject[methodName] == "function".
Applying this to your code you can now do:
if (hasMethod(me, "onChange")) {
me.onChange(str);
}
function sum(nb1,nb2){
return nb1+nb2;
}
try{
if(sum() != undefined){/*test if the function is defined before call it*/
sum(3,5); /*once the function is exist you can call it */
}
}catch(e){
console.log("function not defined");/*the function is not defined or does not exists*/
}
And then there is this...
( document.exitPointerLock || Function )();
Try this one:
Window.function_exists=function(function_name,scope){
//Setting default scope of none is provided
If(typeof scope === 'undefined') scope=window;
//Checking if function name is defined
If (typeof function_name === 'undefined') throw new
Error('You have to provide an valid function name!');
//The type container
var fn= (typeof scope[function_name]);
//Function type
If(fn === 'function') return true;
//Function object type
if(fn.indexOf('function')!== false) return true;
return false;
}
Be aware that I've write this with my cellphone
Might contain some uppercase issues and/or other corrections needed like for example functions name
If you want a function like PHP to check if the var is set:
Window.isset=function (variable_con){
If(typeof variable_con !== 'undefined') return true;
return false;
}
To illustrate the preceding answers, here a quick JSFiddle snippet :
function test () {
console.log()
}
console.log(typeof test) // >> "function"
// implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as :
// var test = false
if(test){ console.log(true)}
else{console.log(false)}
// test by the typeof method
if( typeof test === "function"){ console.log(true)}
else{console.log(false)}
// confirm that the test is effective :
// - entity with false value
var test2 = false
if(test2){ console.log(true)}
else{console.log(false)}
// confirm that the test is effective :
// - typeof entity
if( typeof test ==="foo"){ console.log(true)}
else{console.log(false)}
/* Expected :
function
true
true
false
false
*/
Related
Is there something similar to nullish coalescing operator but for if statements? [duplicate]
How do I determine if variable is undefined or null? My code is as follows: var EmpName = $("div#esd-names div#name").attr('class'); if(EmpName == 'undefined'){ // DO SOMETHING }; <div id="esd-names"> <div id="name"></div> </div> But if I do this, the JavaScript interpreter halts execution.
You can use the qualities of the abstract equality operator to do this: if (variable == null){ // your code here. } Because null == undefined is true, the above code will catch both null and undefined.
The standard way to catch null and undefined simultaneously is this: if (variable == null) { // do something } --which is 100% equivalent to the more explicit but less concise: if (variable === undefined || variable === null) { // do something } When writing professional JS, it's taken for granted that type equality and the behavior of == vs === is understood. Therefore we use == and only compare to null. Edit again The comments suggesting the use of typeof are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catch if you are working with input you don't have control over. You should not have any references to undeclared variables in your code.
Combining the above answers, it seems the most complete answer would be: if( typeof variable === 'undefined' || variable === null ){ // Do stuff } This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.
if (variable == null) { // Do stuff, will only match null or undefined, this won't match false }
if (typeof EmpName != 'undefined' && EmpName) { will evaluate to true if value is not: null undefined NaN empty string ("") 0 false
Probably the shortest way to do this is: if(EmpName == null) { /* DO SOMETHING */ }; Here is proof: function check(EmpName) { if(EmpName == null) { return true; }; return false; } var log = (t,a) => console.log(`${t} -> ${check(a)}`); log('null', null); log('undefined', undefined); log('NaN', NaN); log('""', ""); log('{}', {}); log('[]', []); log('[1]', [1]); log('[0]', [0]); log('[[]]', [[]]); log('true', true); log('false', false); log('"true"', "true"); log('"false"', "false"); log('Infinity', Infinity); log('-Infinity', -Infinity); log('1', 1); log('0', 0); log('-1', -1); log('"1"', "1"); log('"0"', "0"); log('"-1"', "-1"); // "void 0" case console.log('---\n"true" is:', true); console.log('"void 0" is:', void 0); log(void 0,void 0); // "void 0" is "undefined" And here are more details about == (source here) BONUS: reason why === is more clear than == (look on agc answer)
jQuery attr() function returns either a blank string or the actual value (and never null or undefined). The only time it returns undefined is when your selector didn't return any element. So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this: if (!EmpName) { //do something }
Edited answer: In my opinion, you shouldn't use the function from my below old answer. Instead, you should probably know the type of your variable and use the according to check directly (for example, wondering if an array is empty? just do if(arr.length===0){} etc.). This answer doesn't even answer OP's question. I've come to write my own function for this. JavaScript is weird. It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note. function empty(v) { let type = typeof v; if (type === 'undefined') { return true; } if (type === 'boolean') { return !v; } if (v === null) { return true; } if (v === undefined) { return true; } if (v instanceof Array) { if (v.length < 1) { return true; } } else if (type === 'string') { if (v.length < 1) { return true; } if (v === '0') { return true; } } else if (type === 'object') { if (Object.keys(v).length < 1) { return true; } } else if (type === 'number') { if (v === 0) { return true; } } return false; } TypeScript-compatible. This function should do exactly the same thing like PHP's empty() function (see RETURN VALUES) Considers undefined, null, false, 0, 0.0, "0" {}, [] as empty. "0.0", NaN, " ", true are considered non-empty.
The shortest and easiest: if(!EmpName ){ // DO SOMETHING } this will evaluate true if EmpName is: null undefined NaN empty string ("") 0 false
If the variable you want to check is a global, do if (window.yourVarName) { // Your code here } This way to check will not throw an error even if the yourVarName variable doesn't exist. Example: I want to know if my browser supports History API if (window.history) { history.back(); } How this works: window is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history doesn't exist then window.history returns undefined. undefined is falsey, so code in an if(undefined){} block won't run.
In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below. if (variable === undefined){ } if (variable === null){ } if (variable === ''){ } Check all conditions: if(variable === undefined || variable === null || variable === ''){ }
Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function. var s; // undefined jQuery.isEmptyObject(s); // will return true; s = null; // defined as null jQuery.isEmptyObject(s); // will return true; // usage if(jQuery.isEmptyObject(s)){ alert('Either variable: s is undefined or its value is null'); }else{ alert('variable: s has value ' + s); } s = 'something'; // defined with some value jQuery.isEmptyObject(s); // will return false;
I've just had this problem i.e. checking if an object is null. I simply use this: if (object) { // Your code } For example: if (document.getElementById("enterJob")) { document.getElementById("enterJob").className += ' current'; }
You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code). if (x === null || x === undefined) { // Add your response code here, etc. } source: https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
jQuery check element not null: var dvElement = $('#dvElement'); if (dvElement.length > 0) { // Do something } else{ // Else do something else }
With the newest javascript changes, you can use the new logical operator ??= to check if the left operand is null or undefined and if so assign the value of right operand. SO, if(EmpName == null){ // if Variable EmpName null or undefined EmpName = 'some value'; }; Is equivalent to: EmpName ??= 'some value';
The easiest way to check is: if(!variable) { // If the variable is null or undefined then execution of code will enter here. }
I run this test in the Chrome console. Using (void 0) you can check undefined: var c; undefined if (c === void 0) alert(); // output = undefined var c = 1; // output = undefined if (c === void 0) alert(); // output = undefined // check c value c // output = 1 if (c === void 0) alert(); // output = undefined c = undefined; // output = undefined if (c === void 0) alert(); // output = undefined
With the solution below: const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val; const isDeepEqual = (a, b) => getType(a) === getType(b); console.log(isDeepEqual(1, 1)); // true console.log(isDeepEqual(null, null)); // true console.log(isDeepEqual([], [])); // true console.log(isDeepEqual(1, "1")); // false etc... I'm able to check for the following: null undefined NaN empty string ("") 0 false
To test if a variable is null or undefined I use the below code. if(typeof sVal === 'undefined' || sVal === null || sVal === ''){ console.log('variable is undefined or null'); }
if you create a function to check it: export function isEmpty (v) { if (typeof v === "undefined") { return true; } if (v === null) { return true; } if (typeof v === "object" && Object.keys(v).length === 0) { return true; } if (Array.isArray(v) && v.length === 0) { return true; } if (typeof v === "string" && v.trim().length === 0) { return true; } return false; }
(null == undefined) // true (null === undefined) // false Because === checks for both the type and value. Type of both are different but value is the same.
Let's look at this, let apple; // Only declare the variable as apple alert(apple); // undefined In the above, the variable is only declared as apple. In this case, if we call method alert it will display undefined. let apple = null; /* Declare the variable as apple and initialized but the value is null */ alert(apple); // null In the second one it displays null, because variable of apple value is null. So you can check whether a value is undefined or null. if(apple !== undefined || apple !== null) { // Can use variable without any error }
The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint... The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined. Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used: if (foo === void 0 || foo === null) { ... }
You can do something like this, I think its more efficient for multiple value check on the same variable in one condition const x = undefined; const y = null; const z = 'test'; if ([undefined, null].includes(x)) { // Will return true } if ([undefined, null].includes(y)) { // Will return true } if ([undefined, null].includes(z)) { // Will return false }
No one seems to have to posted this yet, so here we go: a?.valueOf() === undefined works reliably for either null or undefined. The following works pretty much like a == null or a == undefined, but it could be more attractive for purists who don't like == 😎 function check(a) { const value = a?.valueOf(); if (value === undefined) { console.log("a is null or undefined"); } else { console.log(value); } } check(null); check(undefined); check(0); check(""); check({}); check([]); On a side note, a?.constructor works too: function check(a) { if (a?.constructor === undefined) { console.log("a is null or undefined"); } } check(null); check(undefined); check(0); check(""); check({}); check([]);
Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.
var x; if (x === undefined) { alert ("only declared, but not defined.") }; if (typeof y === "undefined") { alert ("not even declared.") }; You can only use second one: as it will check for both definition and declaration
var i; if (i === null || typeof i === 'undefined') { console.log(i, 'i is undefined or null') } else { console.log(i, 'i has some value') }
I still think the best/safe way to test these two conditions is to cast the value to a string: var EmpName = $("div#esd-names div#name").attr('class'); // Undefined check if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){ // Do something with your code } // Nullcheck if (Object.prototype.toString.call(EmpName) === '[object Null]'){ // Do something with your code }
Checking if variable exist JavaScript & jQuery in best and quick and smallest way
Hey guys i have an some jQuery-JavaScript code and its made by some undefined variable. I trying to skip (undefined) error by doing this code : if(typeof undefined_var !== "undefined"){ /*My code is here*/ }else{ /*create variable*/ /*My code is here*/ } But the problem is i have a lot of variable and i have to use a big code like this : if(typeof undefined_var1 !== "undefined" && typeof undefined_var2 !== "undefined" && typeof undefined_var3 !== "undefined" /* && more */ ){ And its not optimized i looking for something better than it like this : if(undefined_var1 && undefined_var2 && undefined_var3) Is there anyway?
You can make an array containing all those variables and then make a function which takes that array as an argument. Then inside the function loop through the array using the conditional (if statement) to determine if any are false. For example arr.reduce((bln, myVar) => typeof myVar === 'undefined' && bln, true). Call the function and it will return true or false depending on if any were undefined. var _0; var _1; var _2 = 'not undefined'; var _3 = 'again not undefined'; const test0 = [_0, _1]; //should return true (contains undefined) const test1 = [_2, _3]; //should return false (doesn't contain undefined) const test2 = [_0, _1, _2, _3]; //should return true (contains undefined) function containsUndefined(arr){ //loop array to determine if any are undefined return arr.reduce((bln, myVar) => typeof myVar == 'undefined' && bln, true); } console.log('test0', containsUndefined(test0)); console.log('test1', containsUndefined(test1)); console.log('test2', containsUndefined(test2));
At whatever point that the variables are defined, put them onto a single object instead, then all you have to do is check if the object exists yet: if (!window.myObj) { // Define properties: window.myObj = { prop1: 'val1', prop2: 'val2', // ... }; } // proceed to use `window.myObj.prop1`, etc
Concept: Discern between Array, Pseudo-Array, and Object in JavaScript
Often while using JavaScript you run into silly problems. One such problems is discerning between Object types. Is there a way to create a function with this functionality? See Below: _discern = function () { [ function code ] }; _discern({}); // Logs: Object _discern([]); // Logs: Array _discern(document); // Logs: Pseudo-Object _discern(document.querySelectorAll("*")); // Logs: Pseudo-Array I've already tried creating a function that checks for array-likeness, but that didn't work as good as I had hoped: isArrLike = function (_) { _[0] = 0; return [].slice.call(_).length >= Object.values(_).length; }; And I've tried using that behavior into another function. All failures. Is there a way?
Looks like you want to know if something behaves like an array, instead of looking for the actual type/constructor. If that's the case, it should be enough to check if something is iterable: function isIterable(obj) { // checks for null and undefined if (obj == null) { return false; } return typeof obj[Symbol.iterator] === 'function'; }
All of these are objects: is array → return x instanceof Array or Array.isArray(x) is function → return typeof x === 'function' is HTML element → return x instanceof HTMLElement is plain object → return typeof x === 'object' && /* ... is not array, not function, not HTML element */
Thanks to Logain's answer, I can solve the problem. Here's my approach: kind = function (a) { let u = toString.call(a.valueOf()).slice(8, -1); if (a == null || u == "String" || u == "Number" || u == "Boolean") { return u; } else if (typeof a[Symbol.iterator] == "function") { return u != "Array" ? "Array-Like" : u; } else { return u; } };
Javascript test ( object && object !== "null" && object !== "undefined" )
I seem to be using this test a lot if( object && object !== "null" && object !== "undefined" ){ doSomething(); } on objects I get back from a service call or from reading cookies (since different browsers return the different values null, undefined, "null", or "undefined"). Is there an easier/more efficient way of doing this check?
I don't think you can make that any simpler, but you could certainly refactor that logic into a function: function isRealValue(obj) { return obj && obj !== 'null' && obj !== 'undefined'; } Then, at least your code becomes: if (isRealValue(yourObject)) { doSomething(); }
If you have jQuery, you could use $.isEmptyObject(). $.isEmptyObject(null) $.isEmptyObject(undefined) var obj = {} $.isEmptyObject(obj) All these calls will return true. Hope it helps
if(!!object){ doSomething(); }
If object is truthy, we already know that it is not null or undefined (assuming that the string values are a mistake). I assume that a not null and not undefined test is wanted. If so, a simple comparison to null or undefined is to compare != null. if( object != null ){ doSomething(); } The doSomething function will run only if object is neither null nor undefined.
Maybe like this: var myObj = {}; var isEmptyObj = !Object.keys(myObj).length; if(isEmptyObj) { // true } else {
maybe like this if (typeof object !== "undefined" || object !== null) // do something
This should work without any issue. if(object){ // checks for null and undefined doSomething(); }
The best way to check if an object is empty is by using a utility function like the one below. create a function function isEmpty(obj) { for(var key in obj) { if(obj.hasOwnProperty(key)) return false; } return true; } Use above function following way:- So if you have an empty object, you can check whether it is empty by using the above function. var myObj = {}; // Empty Object if(isEmpty(myObj)) { // Object is empty (Would return true in this example) } else { // Object is NOT empty }
I think you could simplify a bit your logic with the following: if (object != null && typeof(object) == "object") { doSomething(); } The main problem is that if you just check typeof(object) == "object", it will return true if object is null since null's type is "object". However, if you first check that object != null, you can be sure you are having something that is neither undefined nor null.
another simple way is if (eval(object)) doSomething(); You can use eval to cast any type including string and be executed by javascript, here is eval documentation
If you want an Object, that is not an Array, and is not null, you might have to do some work, as all 3 will have the same typeof value. if ( typeof maybeObject === 'object' && maybeObject !== null && !Array.isArray(maybeObject)) { }
How to check 'undefined' value in jQuery
Possible Duplicate: Detecting an undefined object property in JavaScript javascript undefined compare How we can add a check for an undefined variable, like: function A(val) { if (val == undefined) // do this else // do this }
JQuery library was developed specifically to simplify and to unify certain JavaScript functionality. However if you need to check a variable against undefined value, there is no need to invent any special method, since JavaScript has a typeof operator, which is simple, fast and cross-platform: if (typeof value === "undefined") { // ... } It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to if (value === undefined) { ... }, is that typeof will never raise an exception in case if variable value does not exist.
In this case you can use a === undefined comparison: if(val === undefined) This works because val always exists (it's a function argument). If you wanted to test an arbitrary variable that is not an argument, i.e. might not be defined at all, you'd have to use if(typeof val === 'undefined') to avoid an exception in case val didn't exist.
Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all. function A(val){ if(typeof(val) === "undefined") //do this else //do this }
I know I am late to answer the function but jquery have a in build function to do this if(jQuery.type(val) === "undefined"){ //Some code goes here } Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.
You can use shorthand technique to check whether it is undefined or null function A(val) { if(val || "") //do this else //do this } hope this will help you
when I am testing "typeof obj === undefined", the alert(typeof obj) returning object, even though obj is undefined. Since obj is type of Object its returning Object, not undefined. So after hours of testing I opted below technique. if(document.getElementById(obj) !== null){ //do... }else{ //do... } I am not sure why the first technique didn't work.But I get done my work using this.
If you have names of the element and not id we can achieve the undefined check on all text elements (for example) as below and fill them with a default value say 0.0: var aFieldsCannotBeNull=['ast_chkacc_bwr','ast_savacc_bwr']; jQuery.each(aFieldsCannotBeNull,function(nShowIndex,sShowKey) { var $_oField = jQuery("input[name='"+sShowKey+"']"); if($_oField.val().trim().length === 0){ $_oField.val('0.0') } })
I am not sure it is the best solution, but it works fine: if($someObject['length']!=0){ //do someting }
function isValue(value, def, is_return) { if ( $.type(value) == 'null' || $.type(value) == 'undefined' || $.trim(value) == '' || ($.type(value) == 'number' && !$.isNumeric(value)) || ($.type(value) == 'array' && value.length == 0) || ($.type(value) == 'object' && $.isEmptyObject(value)) ) { return ($.type(def) != 'undefined') ? def : false; } else { return ($.type(is_return) == 'boolean' && is_return === true ? value : true); } } try this~ all type checker
Check if undefined or not if(typeof myVal === "undefined") { //some code } Check if undefined or null or empty or false or 0 if(!myVal) { // some code } else { // myVal is flawless }