Javascript ifDefined helper method? - javascript

Is there a helper method, or similar, in Javascript for isDefined? I just found this in a utility file I inherited:
'use strict';
var me = {
ifDefined : ifDefined,
ifDef : ifDefined,
isDefined : isDefined,
isDef : isDefined,
};
function isDefined (value) {
return (typeof value != 'undefined');
}
function ifDefined (value, defaultValue) {
return isDefined(value) ? defaultValue : value;
}
module.exports = me;
It appears the author is using it to have a shorthand method for the typeof check:
environment.u = isDef(envInfo.u, environment.u);
environment.x = isDef(envInfo.x, environment.x);
environment.s = isDef(envInfo.s, environment.s);

Is there a helper method, or similar, in Javascript for isDefined?
No, there exists no builtin function for this.
Just using value !== undefined or value != null is short enough, it didn't warrant an extra utility function. The only native "typechecking" methods I am aware of are Array.isArray, isNaN and isFinite (and their Number.is… equivalents).

There is not. If I had to do this, I wouldn't create a utility file for it. You could save just as much space in your code by using a shorthand variable and the ternary operator:
var udef = undefined;
environment.u = envInfo.u == udef ? environment.u : envInfo.u;
environment.x = envInfo.x == udef ? environment.x : envInfo.x;
environment.s = envInfo.s == udef ? environment.s : envInfo.s;
For comparison:

What this function seems to do is check if a value is undefined, and if it is, returns a default value. Otherwise it returns the original value. The name is somewhat misleading, and I don't believe there is anything directly built in to JavaScript that mimics the functionality of your ifDefined function.
If what you are looking for is to simply check if something is defined or not, using typeof is unnecessary - you can simply compare against the global undefined object:
var x;
if(x !== undefined){
console.log('this will not run');
}
else{
console.log('this will run');
}
Some extra reading, if interested:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

Related

Typescript Function Weird Void || && Behaviour

Why is returnObjectcausing an compilation TypeError returnObject2 isn't?
Normally, void || something should return something while void && something should return void.
But in Typescript, it's the opposite that occurs.
var returnVoid = function(){};
var returnObject = function(){ //Typescript compilation TypeError.
//No best common type exists among return expressions.
if(Math.random() < 0.5)
return new Error();
return returnVoid() || null; //always return null
}
var returnObject2 = function(){ //works
if(Math.random() < 0.5)
return new Error();
return returnVoid() && null; //always return undefined
}
Note: TypeError occurs during the compilation, not in the runtime.
EDIT: I did another test. Shouldn't returnNum2 be () => number too considering (undefined || something) === something? Note: Same behaviour for void 0.
var returnNum = function(){ //() => number
return undefined || 0;
}
var returnVoid = function(){};
var returnNum2 = function(){ //() => void | number
return returnVoid() || 0;
}
It's been pointed out in comments, but I think in general you just need to understand that function(){} will return undefined, which has specified behavior for logical operators.
For undefined && somevalue, undefined will always be returned. For undefined || somevalue, somevalue will be evaluated and returned.
Here's a good reference for more information: http://www.javascriptkit.com/jsref/comparison_operators.shtml
EDIT: The question isn't about what is returned for the logical operation, but why typescript gives error TS2354: No best common type exists among return expressions. on compilation.
This does seem like an error, but may make sense in the context. If you replace the logical operators with just a call to returnVoid() only, you'll get the same error in both functions. Static typing allows the && operator to short-circuit entirely for typing, since something && null will never evaluate to a type, but something || null could depending on what the something is.
Related to this, in typescript you cannot explicitly specify null or undefined as a return type for a function.
While I understand why this may be the case, I agree it is a little odd. It might be worth checking with the folks who make Typescript and filing a bug.
TypeScript doesn't special case expressions of the form undefined || T or void || T to be T because a) you shouldn't write that code (use the comma operator!) and b) it's not safe to write this code because return value contravariance means you're not guaranteed to have a falsy value just because you have a void-returning function reference.
Consider if you wrote code like this:
type callback = (arg: any) => void;
function doSomething(x: callback) {
return x(10) || 'Hello, world!';
}
var x = [];
var add = (arg: any) => x.push(arg);
console.log(doSomething(add)); // Prints '1', not 'Hello, world!'

string prototype custom method to make use of encodeURIComponent()

I am writing this method encodedURIComponentValue() for Javascript string:
the idea is to allow me to call : "some string".encodedURIComponentValue()
The code is as:
if (typeof String.prototype.encodedURIComponentValue != 'function') {
String.prototype.encodedURIComponentValue = function (str) {
if (str && str.length > 0)
return encodeURIComponent(str);
else
return "";
};
}
but in some case it does not work:
var encodedVal = $("body").find("option:selected").first().text().encodedURIComponentValue() // text() = "Option1"
console.log(encodedVal); // I only see "" (empty)
Any idea ?
You may find the following answer helpful as it explains prototype, constructor function and the value of this.
In this case I would not advice doing it like you do. You don't own String and modifying it breaks encapsulation. The only "valid" situation would be if you need to implement an existing method to support older browsers (like Object.create). More info on that here.
You could do what you're doing with:
encodeURIComponent(
$("body").find("option:selected").first().text()
);
So other then liking the other syntax there really isn't any reason for it.
OK, it is my stupid mistake - the str is the parameter which was never supplied.
So I changed to this and it works:
if (typeof String.prototype.encodedURIComponentValue != 'function') {
String.prototype.encodedURIComponentValue = function () {
if (this && this.length > 0)
return encodeURIComponent(this);
else
return "";
};
}
Hope I will understand more about this keyword in Js

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)) {
}

if Not undefined and indexOf ('foo') do something

So I'm trying to call where if not undefined and index is foo so I use:
if (typeof(getdata(js, 'box1')) != "undefined"
&& (getdata(js, 'box1')).indexOf('foo') >= 0) {
// Do something
}
This works fine but I dont want to call the getdata twice. Is there way to say if getdata is not undefined and the indexOf is foo then do something, without calling the getdata() function twice?
Alternative:
if (/foo/.test(getdata(js, "box1"))) {
// do something
}
While this allows you to get away with a single check, involving a regular expression for such a simple test could be frowned upon :)
You're better off using a local variable for storing the outcome of the function call:
var data = getdata(js, "box1");
if (data && data.indexOf("foo") ==! -1) {
// do something
}
Also note that typeof is an operator and not a function:
typeof something // instead of typeof(something)
Have you tried
var data = getdata(js, 'box1');
if(typeof(data) != 'undefined' && data.indexOf('foo') >= 0) {
}
You can read the indexOf of the value or an empty string if the value is undefined or null.
if ( (getdata(js, 'box1') || '').indexOf('foo') !=-1) {
// Do something
}
Hopefully your function will only return a string, undefined or null.

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