Common jQuery function for conditional undefined variable - javascript

Suppose, I'm doing something like below in the same javascript file (eg. app.js):
// triggers in both add and edit mode
var purchase = $('.purchase-selector').doSomething();
// triggers only on edit mode where, purchase_data is available
if( typeof purchase_data !== 'undefined' ) {
purchase.anotherThing(purchase_data);
}
// triggers in both add and edit mode
var sales = $('.sales-selector').doSomething();
// triggers only on edit mode where, sales_data is available
if( typeof sales_data !== 'undefined' ) {
sales.anotherThing(sales_data);
}
The issue is, without the Purchase Edit mode there's no purchase_data variable is available. Same is true for the sales_data where it's only available on the Sales Edit mode.
The code is working fine, but actually, I'm doing it against the DRY principle (my code is a way too lengthy). So I tried making a simple method to remove the DRY.
var the_thing = function(selector, edit_data) {
var thing = selector.doSomething();
if( typeof edit_data !== 'undefined' ) {
thing.anotherThing(edit_data);
}
};
the_thing($('.purchase-selector'), purchase_data);
the_thing($('.sales-selector'), sales_data);
But the issue is it's generating Uncaught ReferenceError: purchase_data is not defined (same for the sales_data too).
So I tried something like below:
if( typeof purchase_data === 'undefined' ) {
var purchase_data;
}
the_thing($('.purchase-selector'), purchase_data);
if( typeof sales_data === 'undefined' ) {
var sales_data;
}
the_thing($('.sales-selector'), sales_data);
But it's making the purchase_data (object) to undefined as well.
In edit mode:
console.log(typeof purchase_data);
is returning:
object
but with the following code:
console.log(typeof purchase_data);
if( typeof purchase_data === 'undefined' ) {
var purchase_data;
}
console.log(typeof purchase_data);
It's showing:
undefined
undefined
Can't I use a concept of function in this case?

You are getting the error because your purchase_data and sales_data variables need to be defined before they can be used (even when checking to see if they were assigned a value).
What you can do is, create a function to check if a variable has been assigned a value:
function isUndefined(valor) {
return (typeof valor === 'undefined');
}
Then, among your other code, you need to define said variabled before they are used in any function:
var purchase_data;
var sales_data;
Then you can make reference to the variables in which if no values have been assigned, they will be of type undefined which you can check using the above function:
var the_thing = function(selector, edit_data) {
var thing = selector.doSomething();
if(!isUndefined(edit_data)) {
thing.anotherThing(edit_data);
}
};
the_thing($('.purchase-selector'), purchase_data);
the_thing($('.sales-selector'), sales_data);

The variable purchase_data has to be defined for using it as an argument for the function. Because it is not defined, it cannot be evaluated before the actual call of the function. This causes the error.
When you say var purchase_data;, the variable is known, so it can be used as an argument. But it still has no value, so typeof is undefined.

Related

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

JavaScript API Response - Check if variable exists

In an API response, I want to check if a variable exists. If it doesn't, I want to assign it a blank value:
if(!data3.fields[i+2].values.value[0]) {
data3.fields[i+2].values.value[0] = "";
} else {
break;
}
Error in the console is:
Uncaught TypeError: Cannot read property 'value' of undefined
This confuses me because I thought that's exactly what my if the statement was checking. Any ideas what's going on here?
The if check won't protect you from trying to use an undefined variable. In your instance the values property is undefined. If you wanted to test for that you would need to first check that specific property
if(data3.fields[i+2].values !== undefined && data3.fields[i+2].values.value[0]){
//do something with data3.fields[i+2].values.value[0]
}
additionally, if you are in a scenario where you don't even know if data3 exists (for example you are checking for the existence of a third party script, or something else in your environment) you would need to use the typeof operator to be safe. E.G.
if(typeof(ga) !== 'undefined'){ //typeof returns a string. This would be testing for google analytics on a page.
It doesnt work like PHP does (which checks the whole 'chain'). In your example, you actually check if .value[0] of values exists, but dont check if values exists. The full version should be:
if( data3 && && data3.fields[i+2] && data3.fields[i+2].values && !data3.fields[i+2].values.value[0]) {}
In your code ata3.fields[i+2].values is undefined, and you're trying to access value[0] of 'undefined'
Or slightly more simplefied, if you wand to test if d has a value, you have to make sure that a, b and c aldo have a value:
if( a && a.b && a.b.c && !a.b.c.d){ /* ... */ }
You can remove checks on the left side of the checks if you are sure those exist. E.g.: If you know that a.b always exist, you can simplefy:
if( a.b.c && !a.b.c.d){ /* ... */ }
If you really want to make sure the complete property chain is not undefined you have to check every single step and the later ones won't be executed if at least && condition is false.
if (data3 && data3.fields && data3.fields[i+2] && data3.fields[i+2].values && data3.fields[i+2].values.value && data3.fields[i + 2].values.value[0]) {
data3.fields[i + 2].values.value[0] = "";
} else {
break;
}
Another way would be to just do it and catch the exception:
try {
data3.fields[i + 2].values.value[0] = "";
} catch (e) {
break;
}
The error is telling you that data3.fields[i+2].values is undefined. You can't check for a property .value on undefined.
You'd need to verify each property/index belongs along the way if you always want that nested path to default to an empty string.
if (data3.fields[i+2] === undefined) {
data.fields[i+2] = {};
}
if (data3.fields[i+2].values === undefined) {
data3.fields[i+2].values = {};
}
if (data3.fields[i+2].values.value === undefined) {
data3.fields[i+2].values.value = [];
}
// and finally your empty string assignment
if (data3.fields[i+2].values.value[0] === undefined) {
data3.fields[i+2].values.value[0] = '';
}
Depending on your requirements, you might be able to get away with assigning a stub as soon as you know data3.fields[i+2] is undefined.
if (data3.fields[i+2] === undefined) {
data3.fields[i+2] = {
values: {
value: ['']
}
};
}

JavaScript null check

I've come across the following code:
function test(data) {
if (data != null && data !== undefined) {
// some code here
}
}
I'm somewhat new to JavaScript, but, from other questions I've been reading here, I'm under the impression that this code does not make much sense.
In particular, this answer states that
You'll get an error if you access an undefined variable in any context other than typeof.
Update: The (quote of the) answer above may be misleading. It should say «an undeclared variable», instead of «an undefined variable».
As I found out, in the answers by Ryan ♦, maerics, and nwellnhof, even when no arguments are provided to a function, its variables for the arguments are always declared. This fact also proves wrong the first item in the list below.
From my understanding, the following scenarios may be experienced:
The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.
The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.
The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.
Q: Is my understanding correct?
I've tried the following, in Firefox's console:
--
[15:31:31.057] false != null
[15:31:31.061] true
--
[15:31:37.985] false !== undefined
[15:31:37.989] true
--
[15:32:59.934] null != null
[15:32:59.937] false
--
[15:33:05.221] undefined != null
[15:33:05.225] false
--
[15:35:12.231] "" != null
[15:35:12.235] true
--
[15:35:19.214] "" !== undefined
[15:35:19.218] true
I can't figure out a case where the data !== undefined after data != null might be of any use.
An “undefined variable” is different from the value undefined.
An undefined variable:
var a;
alert(b); // ReferenceError: b is not defined
A variable with the value undefined:
var a;
alert(a); // Alerts “undefined”
When a function takes an argument, that argument is always declared even if its value is undefined, and so there won’t be any error. You are right about != null followed by !== undefined being useless, though.
In JavaScript, null is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the === operator to avoid confusing type coercion:
var a = null;
alert(a === null); // true
As #rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x) is the string "undefined", even if "x" is not a declared variable:
alert(typeof(x) === 'undefined'); // true
Also, variables can have the "undefined value" if they are not initialized:
var y;
alert(typeof(y) === 'undefined'); // true
Putting it all together, your check should look like this:
if ((typeof(data) !== 'undefined') && (data !== null)) {
// ...
However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".
function(data) {
if ((data !== undefined) && (data !== null)) {
// ...
This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."
In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
function test(data) {
if (data != null) {
console.log('Data: ', data);
}
}
test(); // the data=undefined
test(null); // the data=null
test(undefined); // the data=undefined
test(0);
test(false);
test('something');
Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
Q: The function was called with no arguments, thus making data an undefined variable, and raising an error on data != null.
A: Yes, data will be set to undefined. See section 10.5 Declaration Binding Instantiation of the spec. But accessing an undefined value does not raise an error. You're probably confusing this with accessing an undeclared variable in strict mode which does raise an error.
Q: The function was called specifically with null (or undefined), as its argument, in which case data != null already protects the inner code, rendering && data !== undefined useless.
Q: The function was called with a non-null argument, in which case it will trivially pass both data != null and data !== undefined.
A: Correct. Note that the following tests are equivalent:
data != null
data != undefined
data !== null && data !== undefined
See section 11.9.3 The Abstract Equality Comparison Algorithm and section 11.9.6 The Strict Equality Comparison Algorithm of the spec.
typeof foo === "undefined" is different from foo === undefined, never confuse them. typeof foo === "undefined" is what you really need. Also, use !== in place of !=
So the statement can be written as
function (data) {
if (typeof data !== "undefined" && data !== null) {
// some code here
}
}
Edit:
You can not use foo === undefined for undeclared variables.
var t1;
if(typeof t1 === "undefined")
{
alert("cp1");
}
if(t1 === undefined)
{
alert("cp2");
}
if(typeof t2 === "undefined")
{
alert("cp3");
}
if(t2 === undefined) // fails as t2 is never declared
{
alert("cp4");
}
I think, testing variables for values you do not expect is not a good idea in general. Because the test as your you can consider as writing a blacklist of forbidden values. But what if you forget to list all the forbidden values? Someone, even you, can crack your code with passing an unexpected value. So a more appropriate approach is something like whitelisting - testing variables only for the expected values, not unexpected. For example, if you expect the data value to be a string, instead of this:
function (data) {
if (data != null && data !== undefined) {
// some code here
// but what if data === false?
// or data === '' - empty string?
}
}
do something like this:
function (data) {
if (typeof data === 'string' && data.length) {
// consume string here, it is here for sure
// cleaner, it is obvious what type you expect
// safer, less error prone due to implicit coercion
}
}
The simple way to do your test is :
function (data) {
if (data) { // check if null, undefined, empty ...
// some code here
}
}
var a;
alert(a); //Value is undefined
var b = "Volvo";
alert(b); //Value is Volvo
var c = null;
alert(c); //Value is null

How to determine if a static variable has been used?

According to the IE Debugger my static variable
link_update.previous_element
is set to undefined, the first time through the function.
However when I add in a test for undefined or 'undefined' in parantheses it does not select it properly as I show in the code below.
How do I detect first use of a static variable?
function link_update( link_display )
{
current_element = document.getElementById( link_display )
current_element.style.opacity = 1;
if( link_update.previous_element != undefined)
{
link_update.previous_element.style.opacity = 0;
}
link_update.previous_element = current_element;
}
Use typeof:
if(typeof link_update.previous_element != 'undefined')
You may also like to remove the semicolon.

How to check if function exists in 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
*/

Categories

Resources