How to check if the value passed to the JavaScript function is defined or its length> = 0?

I have the following javascript code:

function changeButtonState(targetSelector, action, iconClass) { var $target = $(targetSelector); var $targetSpan = $(targetSelector + ' span'); $targetSpan.removeClass('sprite-blank').addClass(iconClass); } 

How can I do this so that $targetSpan.removeClass(..).addClass only iconClass if iconClass matters when the function is called. I suppose I'm embarrassed, I check if this is defined, or I check if it has a length of 0 or more?

+4
source share
6 answers

Just use the if statement:

 if (iconClass){} 

Or, typeof :

 if (typeof iconClass != 'undefined') {} 
+4
source
 if (typeof(iconClass)=='undefined') { // nothing was passed } 
+1
source

Live demo

 if ( 'undefined' != typeof iconClass ) { /**/ } 
+1
source

In your use case, you should assume that iconClass is a string. In this case, I would suggest the first if condition. The second option is probably too restrictive; it is usually used only if the person calling the function does not actually pass the third parameter or pass undefined. But if the caller skips an empty or empty line, the first if condition will also capture these conditions. This is the easiest way to write, and it is very easy in Javascript to just check if (variable) { } , because it will catch a lot more and will be very easy to read and write.

 if (iconClass) { // Executes if iconClass is not null, not undefined, not 0, and not empty string } if (typeof iconClass != 'undefined') { // WILL execute if iconClass is null, 0, empty string // Only will not execute if iconClass is undefined! } 
+1
source

Presumably, iconClass should be a string (class name), so you should check if it is a string:

 if (typeof iconClass == 'string') 

or you can use regex to verify that it is a valid class name at the same time:

 if (/^[az][a-z0-9]*$/i.test(iconClass)) 

The regular expression probably needs more characters to check (at least for the hyphen), I will leave it to you. Accepted Answer What characters are allowed in CSS class names? may I help.

0
source
 if(iconClass.length > 0){ $targetSpan.removeClass('sprite-blank').addClass(iconClass); } 
-1
source

All Articles