{"id":279,"date":"2018-04-11T15:43:53","date_gmt":"2018-04-11T15:43:53","guid":{"rendered":"https:\/\/tinjurewp.com\/jsblog\/?p=279"},"modified":"2018-04-11T15:43:53","modified_gmt":"2018-04-11T15:43:53","slug":"javascript-functions-declaration-and-expression","status":"publish","type":"post","link":"https:\/\/learncode.tinjurewp.com\/javascript-functions-declaration-and-expression\/","title":{"rendered":"JavaScript Functions &#8211; Declaration and Expression"},"content":{"rendered":"<p class=\"note\"><em>This post is work-in-progress learning-note and still in active development and updated regularl<\/em>y.<\/p>\n<p>In my another post, <a href=\"https:\/\/tinjurewp.com\/jsblog\/understanding-javascript-functions-the-basics\/\" target=\"_blank\" rel=\"noopener\">Understanding JavaScript Functions \u2013 The Basics<\/a>,\u00a0 common ways of defining a function, their basic syntax and some examples were discussed. In this post, I will focus on difference between the function declaration &amp; function expression with some examples.<\/p>\n<h5>Function Declaration &amp; Function Expression Overview<\/h5>\n<h6>Basic Syntax: Function Declaration<\/h6>\n<pre><code class=\"language-javascript\">\/\/initialize function greeting (1) with single parameter\nfunction greeting(name) { \n  console.log(`Hello ${name}, How are you?`);\n}\n\n\/\/Invoke function Greeting (2) with &#039;Robert&#039; as argument\ngreeting(&#039;Robert&#039;);\n\n\/\/OUTPUT (3)\nHello Robert, How are you?<\/code><\/pre>\n<p>Some key features of <strong>function declaration<\/strong>:<\/p>\n<ul>\n<li>Start with <code>function<\/code> keyword<\/li>\n<li>function definition should have a <code>functionName<\/code> followed by parentheses: <code>( )<\/code><\/li>\n<li>Blocks of code to be executed are placed inside curly braces: <code>{ }<\/code><\/li>\n<li>Declared functions are always <em>stand-alone<\/em> (can&#8217;t be part of non-functional blocks).<\/li>\n<\/ul>\n<h6>Basic syntax: function expression<\/h6>\n<p>Lets write the above <code>greeting()<\/code> function in function expression syntax, which looks like as follows:<\/p>\n<pre><code class=\"language-javascript\">\/\/initialize function greeting (1) with single parameter\nlet greeting = function (name) { \n  console.log(`Hello ${name}, you are welcome!`);\n}\n\n\/\/invoke greeting function (2) with &#039;Robert&#039; argument\ngreeting(&#039;Robert&#039;);\n\n\/\/OUTPUT (3)\nHello Robert, you are welcome!<\/code><\/pre>\n<p>Some key features of <strong>function expression<\/strong>:<\/p>\n<ul>\n<li>Does not start with <code>function<\/code> keyword<\/li>\n<li>Function created inside an expression or another syntax construct (i.e. code can be part of non-functional code blocks)<\/li>\n<li>In the following example, the <code>function<\/code> is created at the right side of the assignment expression <code>=<\/code> (typically function is assigned to a variable)<\/li>\n<li>Function can be created with or without <code>functionName<\/code> (anonymous)<\/li>\n<li>After close curly braces\u00a0 <code>}<\/code> there is semicolon <code>;<\/code><\/li>\n<\/ul>\n<p>Although, in both the function declaration and function expression, function is invoked in similar way <code>greeting(&#039;Robert&#039;);<\/code> however when JS engine reads, they are read differently. That is what we will explored next!<\/p>\n<h5>Difference Between Function Declaration &amp;\u00a0 Expression<\/h5>\n<h6>1. Function Declaration are Hoisted<\/h6>\n<pre><code class=\"language-javascript\">\/\/Invoke greeting function (1) with &#039;Robert&#039; as argument\ngreeting(&#039;Robert&#039;);\n\n\/\/initialize function greeting (2) with parameter\nfunction greeting (name) { \n  console.log(`Hello ${name}, you are welcome!`);\n}\n\n\/\/OUTPUT\nHello Robert, you are welcome!<\/code><\/pre>\n<p>In the above example, greeting( &#8216;Robert&#8217; ) function was invoked (1) before it was declared (2). To quote from <a href=\"http:\/\/javascript.info\/function-expressions-arrows\" target=\"_blank\" rel=\"noopener\">The Modern JavaScript Tutorial<\/a>: &#8220;<em>when JavaScript prepares to run the script or a code block, it first looks for <strong>Function Declarations<\/strong> in it and creates the functions. We can think of it as an \u201cinitialization stage\u201d. And after all of the Function Declarations are processed, the execution goes on. As a result, a function declared as a Function Declaration can be called earlier than it is defined<\/em>.&#8221;<\/p>\n<p class=\"tip\"><em>Tip<\/em>: A Function Declaration is usable in the whole script\/code block &#8211; <a href=\"https:\/\/javascript.info\/function-expressions-arrows\" target=\"_blank\" rel=\"noopener\"><em>The Modern JavaScript tutorial<\/em><\/a>.<\/p>\n<h6>2. Function Expression are NOT Hoisted<\/h6>\n<p>To quote again from <a href=\"https:\/\/javascript.info\/function-expressions-arrows\" target=\"_blank\" rel=\"noopener\">The Modern JavaScript Tutoria<\/a>l: &#8220;<em>Function Expression is created when the execution reaches it and is usable from then on. Once the execution flow passes to the right side of the assignment <code>let greeting = function (name)<\/code> \u2013 the function is created and can be used (assigned, called etc) from now on.<\/em>&#8221;<\/p>\n<pre><code class=\"language-javascript\">\/\/Invoke greeting function (1) with &#039;Robert&#039; argument\ngreeting(&#039;Robert&#039;);\n\n\/\/initialize function greeting (2) with one parameter\nlet greeting = function (name) { \n  console.log(`Hello ${name}, you are welcome!`);\n}\n\n\/\/OUTPUT (error with following message)\n\/\/Chrome\ngreeting is not defined  \n\/\/Firefox\ncan not access lexical declaration `greeting&#039; before initialization <\/code><\/pre>\n<p>Lets look at the above function and walk through how JS engine executes these codes. <a href=\"https:\/\/codeburst.io\/javascript-demystified-variable-hoisting-c3c4d2e8fd40\" target=\"_blank\" rel=\"noopener\">Misa Ogura explains this process very clearly in her post<\/a>. First, JS engine encounters the <code>let<\/code> or <code>var<\/code> keyword and expects variable declaration follow and hoist the variable with a value of: <code>undefined.<\/code> <em>It does not hoist the variable initiation<\/em>. Now, Misa&#8217;s explanation start making sense:<\/p>\n<ul>\n<li>When the JS engine encountered the variable declaration let <code>greeting (name)<\/code> in (2), it was hoisted as variable hoisting with a value: <code>undefined<\/code>.<\/li>\n<li>The variable initialization (i.e. <code>= function (name) { console.log(`Hello ${name}, you are welcome!`); }<\/code> was not hoisted.<\/li>\n<li>When the execution reached line (1) and tried to invoke <code>greeting(&#039;Robert&#039;)<\/code> it failed because <code>undefined<\/code> (hoisted value) is not a function.<\/li>\n<li>When the function <code>greeting(&#039;Robert&#039;)<\/code> was called in (3) (see above previous section) only after assignment of <code>greeting (name)<\/code> to function expression in line (2), <code>greeting(&#039;Robert&#039;)<\/code> was successfully invoke.<\/li>\n<\/ul>\n<p class=\"tip\"><em>Tip<\/em>: A Function Expression is created when the execution reaches it and is usable from then on- <a href=\"https:\/\/javascript.info\/function-expressions-arrows\" target=\"_blank\" rel=\"noopener\"><em>The Modern JavaScript tutorial<\/em><\/a>.<\/p>\n<h5>Conditionally Created Functions<\/h5>\n<p>This process can be confusing. To quote Dmitri Pavlutin from <a href=\"https:\/\/dmitripavlutin.com\/6-ways-to-declare-javascript-functions\/\" target=\"_blank\" rel=\"noopener\">his post<\/a> &#8220;<em>some JavaScript environments can throw a reference error when invoking a function whose declaration appears within blocks {&#8230;} of if, for or while statements.\u00a0 Let&#8217;s enable the strict mode and see what happens when a function is declared in a conditional:<\/em>&#8221;<\/p>\n<pre><code class=\"language-javascript\">\/\/ Example from Dmitri Pavlutn\n&#039;use strict&#039;;\n  if (true) {\n    function ok() {\n      return &#039;true ok&#039;;\n    }\n  } else {\n    function ok() {\n      return &#039;false ok&#039;;\n    }\n  }\n  console.log(typeof ok === &#039;undefined&#039;); \/\/ =&gt; true\n  console.log(ok()); \/\/ Throws &quot;ReferenceError: ok is not defined&quot;<\/code><\/pre>\n<p>In the above Dmitri&#8217;s example, function declaration was made inside a conditional block, therefore when <code>ok()<\/code> was called JS throws &#8220;<code>ReferenceError: ok is not defined<\/code>&#8221; error. It becomes even more confusing, if we use the same code under &#8216;<em>non-strict<\/em>&#8216; mode then it works and does not through error as shown below:<\/p>\n<pre><code class=\"language-javascript\">\/\/Testted under NON-STRICT mode\nif (true) {\n    ok = function() {\n      return &#039;true ok&#039;;\n    };\n  } else {\n    ok = function() {\n      return &#039;false ok&#039;;\n    };\n  }\n  console.log(typeof ok === &#039;function&#039;); \/\/ =&gt; true\n  console.log(ok()); \/\/ =&gt; &#039;true ok&#039;<\/code><\/pre>\n<p>Again quoting from Dmitri&#8217;s post &#8220;<em>as a general rule for these situations, when a function should be create based on some conditions &#8211; use a function expression. Let&#8217;s see how it is possible:<\/em>&#8221;<\/p>\n<pre><code class=\"language-javascript\">\/\/Example from Dmitri Pavlutin\n&#039;use strict&#039;;\n  let ok;\n  if (true) {\n    ok = function() {\n      return &#039;true ok&#039;;\n    };\n  } else {\n    ok = function() {\n      return &#039;false ok&#039;;\n    };\n  }\n  console.log(typeof ok === &#039;function&#039;); \/\/ =&gt; true\n  console.log(ok()); \/\/ =&gt; &#039;true ok&#039;<\/code><\/pre>\n<p>Because the function is a regular object, it is fine to assign it to a variable depending on a condition (<a href=\"https:\/\/dmitripavlutin.com\/6-ways-to-declare-javascript-functions\/\" target=\"_blank\" rel=\"noopener\">Dmitri<\/a>). Invoking <code>ok()<\/code> works fine and does not throw any errors.<\/p>\n<p class=\"tip\"><em>Tip<\/em>: MDN function declaration reference suggests avoiding function declaration in conditionals in production because of inconsistent results. For conditional function creation, use function expressions instead.<\/p>\n<h5>Benefits of Using Function expression<\/h5>\n<ul>\n<li>Because function expression are not hoisted,<\/li>\n<li>Because they are also anonymous function, they can used as closures, or arguments to other function.<\/li>\n<li>They are also preferred because they are considered to more cleaner &amp; readable codes.<\/li>\n<li>They are preferred in conditional use, as shown in examples above.<\/li>\n<\/ul>\n<h5>Resources &amp; Further Reading:<\/h5>\n<p>While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.<\/p>\n<ul>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Operators\/function\" target=\"_blank\" rel=\"noopener\">Function Expression<\/a> &#8211; Mozilla Developer Network<\/li>\n<li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Statements\/function\" target=\"_blank\" rel=\"noopener\">Function Declaration<\/a> &#8211; Mozilla Developer Network<\/li>\n<li><a href=\"https:\/\/javascript.info\/function-expressions-arrows\" target=\"_blank\" rel=\"noopener\">Function expressions and arrows<\/a> &#8211; The Modern JavaScript Tutorial<\/li>\n<li><a href=\"https:\/\/dmitripavlutin.com\/6-ways-to-declare-javascript-functions\/\" target=\"_blank\" rel=\"noopener\">6 ways to declare JavaScript functions<\/a> &#8211; <a href=\"https:\/\/dmitripavlutin.com\/\" target=\"_blank\" rel=\"noopener\">Dmitri Pavlutin\u00a0<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>This post is work-in-progress learning-note and still in active development and updated regularly. In my another post, Understanding JavaScript Functions \u2013 The Basics,\u00a0 common ways of defining a function, their basic syntax and some examples were discussed. In this post, I will focus on difference between the function declaration &amp; function expression with some examples. [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[41,4],"tags":[],"class_list":["post-279","post","type-post","status-publish","format-standard","hentry","category-functions","category-javascript"],"_links":{"self":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/279","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/comments?post=279"}],"version-history":[{"count":0,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/posts\/279\/revisions"}],"wp:attachment":[{"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/media?parent=279"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/categories?post=279"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learncode.tinjurewp.com\/wp-json\/wp\/v2\/tags?post=279"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}