Thursday, August 9, 2018

Handling undefined & null parameters in JavaScript

Here with a given example is enough to make it understand


 function foo(DivID, color) {  
   if (!color) { // the correct test here should be 'typeof color == "undefined"'  
     color = "green";  
   }  
   DivID.style.backgroundColor = color;  
 }  
 foo(div_color, "red"); //set the background color to red  
 foo(div_color); //set the background color to the default green  
 foo(div_color, "");​ //remove the background color !This will fail!  

Total Pageviews