{"id":1264,"date":"2023-12-30T13:00:00","date_gmt":"2023-12-30T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1264"},"modified":"2024-01-02T06:26:53","modified_gmt":"2024-01-02T06:26:53","slug":"javascript-optional-parameters","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/javascript-optional-parameters\/","title":{"rendered":"Declaring Optional Parameters in Javascript (with code)"},"content":{"rendered":"\n<p>JavaScript is the most popular programming language with various features to make it easier for us to work with it. One such feature is the ability to declare the optional function parameters. In this article, we will learn about the optional parameters and the different approaches to declaring them in JavaScript.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What are Optional Parameters in JavaScript?<\/strong><\/h2>\n\n\n\n<p>While calling the function, we pass several parameters. But in some cases, some of the variables are not required. Instead of passing garbage values in place of them, we can use optional parameters.&nbsp;<\/p>\n\n\n\n<p><strong>Optional parameters in JavaScript are the function parameters that are not mandatory to pass when calling a function. We can assign default values to these variables, which can be used if no value or undefined is passed for those parameters.<\/strong><\/p>\n\n\n\n<p>In JavaScript, we define the parameters of a function within the parentheses of a function declaration. The parameters are by default considered mandatory. That is, we are required to pass a value for each of them. If we want to avoid providing the values of these variables while calling the function, we can use the optional parameters.<\/p>\n\n\n\n<p>For example, Let\u2019s say we have a function that calculates the area of a rectangle and a square. In the case of a square, we only need a single parameter, i.e. side of the square. While in the case of a rectangle length and breadth are required.<\/p>\n\n\n\n<p>To use our function for both shapes, we can make the breadth parameter optional by providing it a default value of 1. Hence, it is needed to be used for squares, we can pass only 1 parameter, else 2 parameters for rectangles.<\/p>\n\n\n\n<p>We can declare optional parameters using different methods. Let\u2019s see them one by one.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>1) Using the Default Value Approach<\/strong><\/h2>\n\n\n\n<p>The simplest way to declare optional parameters is by providing the default values to them. This default value will be used if no value or undefined is passed for the parameters. We can provide the default values by using the assignment operator (=) in the function definition.\u00a0<\/p>\n\n\n\n<p>Let us see an example of the same:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Defining a function with optional parameters\nfunction greet(name = &quot;user&quot;) {\n  console.log(`Hello ${name}, Welcome to favtutor!`);\n}\n\n\/\/ Not providing the value of optional parameters\ngreet();\n\n\/\/ Providing the value of optional parameters\ngreet(&quot;Joy&quot;);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Hello user, Welcome to favtutor!\nHello Joy, Welcome to favtutor!\n<\/code><\/pre>\n\n\n\n<p>In the above function, we have made the name parameter the optional parameter by simply assigning it the value of \u201cuser\u201d. Now, we can provide the name in function calls or skip it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Rule for Declaring the Optional Parameters<\/strong><\/h3>\n\n\n\n<p>We need to follow a rule while declaring the optional parameters using this approach. <strong>The optional parameters with default values should come after the required parameters. <\/strong>In the function definition, we should first write the required parameters that do not have any default values, and then the parameters with the default values.<\/p>\n\n\n\n<p>We can understand it better with an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Defining a function with optional parameters\nfunction sendMessage(sender, message = 'Default message') {\n    console.log(`Message from ${sender}: ${message}`);\n}\n\n\/\/ Not Providing the value of optional parameters\nsendMessage(&quot;John&quot;);\n\n\/\/ Providing the value of optional parameters\nsendMessage(&quot;John&quot;, &quot;Hello Roy&quot;)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Message from John: Default message\nMessage from John: Hello Roy\n<\/code><\/pre>\n\n\n\n<p>As we can see in the above example, we have first written the parameter sender as it is the required parameter, and then the second parameter message. This works fine.<\/p>\n\n\n\n<p>But, what if we first write the optional parameter and then the required parameter? Let\u2019s try and run our code.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Defining a function with optional parameters\nfunction sendMessage(message = 'Default message', sender) {\n    console.log(`Message from ${sender}: ${message}`);\n}\n\n\/\/ Not Providing the value of optional parameters\nsendMessage(&quot;John&quot;);\n\n\/\/ Providing the value of optional parameters\nsendMessage(&quot;Hello Roy&quot;, &quot;John&quot;);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Message from undefined: John\nMessage from John: Hello Roy\n<\/code><\/pre>\n\n\n\n<p>We can see that when we first called the function without providing the value for the default parameter, it printed <strong>undefined <\/strong>in place of it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>2) Using the Arguments Variable<\/strong><\/h2>\n\n\n\n<p>When compared to the above method, it is a complex one. Instead of providing default values in the function definition, we will check for the values of the arguments passed. This can be done using the implicit <em>arguments <\/em>variable.&nbsp;<\/p>\n\n\n\n<p><strong>Every function has access to this arguments variable, which holds an array-like object containing the values of all the arguments passed to the function. <\/strong>We can simply check the length of the arguments object to know the number of arguments passed and with help of it, we can handle the optional parameters.<\/p>\n\n\n\n<p>Let\u2019s check an example of it:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Defining a function with optional parameters\nfunction sum(a, b) {\n  if (arguments.length === 0) {\n    \/\/ If no argument is passed\n    return 0;\n  } \n  else if (arguments.length === 1) {\n    \/\/ If single argument is passed\n    return a;\n  } \n  else {\n    \/\/ If both the arguments are passed\n    return a + b;\n  }\n}\n\n\/\/ Not passing values for any parameter\nconsole.log(sum());\n\n\/\/ Passing value for first parameter only\nconsole.log(sum(5));\n\n\/\/ Passing values for both the parameters\nconsole.log(sum(2, 3));<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>0\n5\n5\n<\/code><\/pre>\n\n\n\n<p>In this example, we have checked the length of the argument object and used it to find the number of parameters passed to the sum function. According to different cases, we have returned the result of the function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>The Optional Parameters in JavaScript is a powerful feature that allows us to define the default values for functional parameters. This feature simplifies the code and provides us flexibility while calling the functions. Another great feature you need to learn is the <a href=\"https:\/\/favtutor.com\/articles\/arrow-function-javascript\/\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/articles\/arrow-function-javascript\/\">Arrow function in JavaScript<\/a>, which is very important for beginners to master.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand what are optional parameters in JavaScript,  its use cases, and different methods to declare it.<\/p>\n","protected":false},"author":9,"featured_media":1266,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1264","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1264","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1264"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1264\/revisions"}],"predecessor-version":[{"id":1282,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1264\/revisions\/1282"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1266"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1264"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1264"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1264"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}