4

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 make it so that the $targetSpan.removeClass(..).addClass only work if the iconClass has a value when the function is called. I guess what I am confused about is do I check if it is defined or do I check if it has a length of 0 or more?

Wyck
  • 10,311
  • 6
  • 39
  • 60
Epik
  • 3,327
  • 4
  • 17
  • 23

6 Answers6

4

Just use an if statement:

if (iconClass){}

Or, typeof:

if (typeof iconClass != 'undefined') {}
Rene Pot
  • 24,681
  • 7
  • 68
  • 92
1
if (typeof(iconClass)=='undefined') {
  // nothing was passed
}
CrayonViolent
  • 32,111
  • 5
  • 56
  • 79
1

LIVE DEMO

if ( 'undefined' != typeof iconClass ) {  /**/  }
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

Your use case you must assume that iconClass is a string. In which case I would suggest the first if condition. The second one is probably too restrictive, it usually is only used if the person calling the function does not actually pass a 3rd parameter, or passes undefined. But if the caller passes null or empty string, the first if condition will catch those conditions as well. It is the easiest one to write and it is very common in Javascript to simply check if (variable) { } because it will catch a lot more and is 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!
}
codefactor
  • 1,616
  • 2
  • 18
  • 41
0

Presumably, iconClass should be a string (a class name), so you should test to see if it's a string:

if (typeof iconClass == 'string') 

or you could use a regular expression to test that it's a valid class name at the same time:

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

The regular expression likely needs more characters to test for (hyphen at least), I'll leave that to you. The accepted answer to What characters are valid in CSS class names? may help.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209
-1
if(iconClass.length > 0){
    $targetSpan.removeClass('sprite-blank').addClass(iconClass);
}
Pankucins
  • 1,690
  • 1
  • 16
  • 25
  • this is bad, if nothing was passed `.length` will throw an error – CrayonViolent Feb 05 '13 at 00:03
  • The more succinct way to do it, is to just check the length property. if(something && something.length){} That way if it's undefined it will short circuit. If the length is gt 0 it will pass, if the length == 0, it coerces to false, and if length is undefined it will short circuit. – Jon Jaques Feb 05 '13 at 01:09