JavaScript function optional parameter | 3 Ways Examples code

You can declare a function with optional parameter using Logical OR operator (‘||’) or Assignment operator (“=”), etc in JavaScript.

JavaScript function optional parameter can do it in 3 ways:-

  • Undefined property
  • OR (||) operator
  • The assignment operator (“=”)

Declare optional function parameters in JavaScript Example

Let’s see all method examples in HTML:-

Using undefined property

Undefined property indicates that a value is not assigned to a variable.

<!DOCTYPE html>
<html>
<body>
	<script>

    function browseBlog(blogURL, type) {    
         
       if(blogURL === undefined)    
       {    
          blogURL = "DefaultURL";    
       }    
        
       if(type === undefined)    
       {    
          type = "DefaultType";    
       }    
        
       alert(blogURL);    
       alert(blogType);    
    }  
    //Test cases
    browseBlog("www.abc.com", "EyeHunts");  
    browseBlog("www.abc.com"); 


</script>
</body>
</html>

Output:

JavaScript function optional parameter Undefined

OR (||) operator

In the example the optional parameter is ‘b’:

The optional parameter is Logically OR with the default value within the body of the function and should always come at the end of the parameter list.

Pre ES2015,

<!DOCTYPE html>
<html>
<body>
	

	<script> 
		function check(a, b) { 
			b = b || 0; 
			console.log(a, b);
		} 
		// Test cases
		check(1, 2); 
		check(10);  
	</script> 

</body>
</html>

Output:

JavaScript function optional parameter OR operator

The assignment operator (“=”)

The optional variable is assigned the default value in the declaration statement itself and should end on the parameter list.

From ES6/ES2015, default parameters are in the language specification.

<script> 
	function check(a, b = 0) {  
		console.log(a, b);
	} 
	// Test cases
	check(1, 2); 
	check(10);  
</script> 

Output:

1 2
10 0

Do comment if you have any doubts and suggestion on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.