<nav class="navbar-container" id="navbar">
	<header class="nav-header">JavaScript Functions</header>
	<div id="navTop" class="nav-top">
		<a href="#Introduction" accesskey="i" class="nav-link">Introduction</a>
		<a href="#Principal" accesskey="p" class="nav-link">Principal</a>
		<a href="#Hoisting" accesskey="h" class="nav-link">Hoisting</a>
		<a href="#Scope" accesskey="s" class="nav-link">Scope</a>
		<a href="#Arguments" accesskey="a" class="nav-link">Arguments</a>
		<a href="#Factories" accesskey="f" class="nav-link">Factories</a>
		<a href="#Using_Factories" accesskey="u" class="nav-link">Using Factories</a>
		<a href="#Conclusion" accesskey="c" class="nav-link">Conclusion</a>
		<a href="#References" accesskey="r" class="nav-link">References</a>
	</div>
	<div id="navBottom" class="nav-bot">
		<a target='_blank' href="https://twitter.com/intent/tweet?text=Check+out+this+article+on+JavaScript+functions!%0D+https%3A%2F%2Fcodepen.io%2Fvtox%2Ffull%2FjKxPpK%2F"><i class="fa fa-twitter"></i></a>
		<a href="#" id="dropdown" class="nav-drop"><i class="fa fa-bars"></i></a>
	</div>
</nav>
<div id="dropContain" class="drop-menu"></div>
<main id="main-doc">
	<section id="Introduction" class="main-section">
		<header>Introduction</header>
		<p>The function is an important building block in most programming languages. In JavaScript, it is a first-class object that is first defined and then called to execute its contents. We call it an object because in JavaScript the function descends from the top-level <code>Object</code> and inherits properties from <code>Object</code>. We refer to it as first-class because, like other objects, it can have properties and methods.</p>
		<code id="codeblock">
function myFunction(){       //declare a function
  var number = 2;            //'number' is a property
  function displayNumber(){  //'displayNumber' is a method
    console.log(number);
  }
}
		</code>
		<p>The above example is a basic implementation of a JavaScript function. In this discussion, we will examine the use of functions in JavaScript, with a final focus on making 'factory-functions'. In short, a factory-function is a function that is designed to create other functions or objects with shared properties and methods.</p>
		<p>This discussion assumes that the reader is already familiar with programming and basic JavaScript concepts.</p>
	</section>
	<section id="Principal" class="main-section">
		<header>Principal</header>
		<p>Earlier, we mentioned the <code>Object</code> as an important part of the JavaScript language. In fact, nearly all constructs in JavaScript inherit from <code>Object</code>. In other languages, like C and Java, constructs are defined with a class by the programmer. JavaScript does not use classes, but instead uses object inheritance. Properties and methods can be added by the programmer.</p>
		<p>The <code>function</code> is used ubiquitously in JavaScript to change other objects and variables, and to complete tasks at runtime. In addition, it can be used to build new objects and functions that share features. This can save time for the programmer, reduce confusion during testing and in some cases improve security.</p>
	</section>
	<section id="Hoisting" class="main-section">
		<header>Hoisting</header>
		<p>JavaScript is a single threaded asynchronous language. A simplified explanation follows: We say single-threaded because when your script executes, all commands are placed onto a 'call stack' and executed one after the other. We say asynchronous because JavaScript does not multitask or execute more than one of its command synchronously. <i>However, JavaScript is made capable of processing commands concurrently by its environment, your browser, for example.</i> The runtime behaviour of JavaScript is more complex, though it is beyond the scope of this discussion. A more in-depth look can be found <a href="https://medium.com/@gaurav.pandvia/understanding-javascript-function-executions-tasks-event-loop-call-stack-more-part-1-5683dea1f5ec" target='_blank'>here</a>.</p>
		<p>JavaScript's asynchronous behaviour dictates the way we write our code. For functions, we must initialize before we can use, meaning that we have to tell JavaScript what our function does. Alternatively, we can use the <code>function</code> constructor and give our functiona a variable name. When JavaScript compiles, it sends all of its variables within each scope to the top of the call stack <i>without their initilizations</i>. (We will revisit the concept of scope soon.) If we attach a function to a variable, the variable will also be sent to the top. If we want our defined function to go with it, we need to construct the function along with the variable. This is called <b>hoisting</b>. Let's look at some examples:</p>
		<code>
let myFunc1 = function(){
  console.log("Execute myFunc1");
}
			
function myFunc2(){
  console.log("Execute myFunc2");
}
		</code>
		<p>Above we have two simple functions, yet they are different in an important way. <code>myFunc1</code> is a variable name to which we initialize an anonymous function. We can call the <code>myFunc1</code> after it is initialized, and it will return <code>Execute myFunc1</code>. But if we call it before it is declared, like so:</p>
		<code>
myFunc1();
			
let myFunc1 = function(){
  console.log("Execute myFunc1");
}
		</code>
		<p>We get an error: <code>myFunc1 is not a function</code>. This is because JavaScript hoisted the variable, but not the initializing statement. However, if we do the same with <code>myFunc2</code>:</p>
		<code>
myFunc2();
			
function myFunc2(){
  console.log("Execute myFunc2");
}
		</code>
		<p>JavaScript returns <code>Execute myFunc2</code>. In this case, we used the constructor, and JavaScript hoisted the constructed function along with its name.</p>
	</section>
	<section id="Scope" class="main-section">
		<header>Scope</header>
		<p>In the last section, we mentioned scope. By <b>scope</b>, we mean the access level of variables for JavaScript. When you add a variable to an empty JavaScript file or command prompt, you are adding the variable to the <b>global</b> scope.</p><p>A metaphor for scope is a police officer directing traffic: The officer sees all the cars at the intersection, and can control which cars move through it. But the officer does not control what people are doing <i>inside</i> the cars. Furthermore, the people in the cars have access to the communication of the officer, so they can follow the officer's instructions - even though the officer cannot see them.</p><p>Functions work in much the same way. Functions can contain variables, but declarations and statements outside of those functions cannot see their variables. Meanwhile, all functions can see variables outside of their <b>closure</b>. By closure, we mean the entire lexical environmnet inside the function's brackets.</p>
		<code>
var a = 'phoo';
function foo(){
  var b = 'foo';
  function bar(){
    var c = 'bar';
    function yom(){
      console.log(a+b+c);
    }
    yom();
  }
  bar();
}
foo();
		</code>
		<p>The above code initializes and calls a function inside a function <i>inside</i> another function. It also declares a variable at each level down. When we call the top-level function, <code>foo()</code>, JavaScript will return the concatonated variables <code>a</code>, <code>b</code>, and <code>c</code>: "phoofoobar". What if we refer to the variable, <code>b</code> after calling <code>foo()</code>? We get an error. This is because of the local scope, or closure, of <code>foo()</code>. We likewise get an error if we call variable <code>c</code> outside of <code>bar()</code> or the function <code>yom()</code> in the global scope. <i>We can see outside constructs from the inside, but we cannot see inside constructs from the outside.</i></p>
	</section>
	<section id="Arguments" class="main-section">
		<header>Arguments</header>
		<p>Functions can use variables from the global scope. They can also declare new variables within their local scope. There is a third option: Passing variables into a function. When we initialize a function, we can declare variables as arguments.</p>
		<code>
function mouse(name, weight){
  console.log(name + " is a mouse that weighs " + weight + " grams.");
}
		</code>
		<p>We hoist a function and give it two required arguments: <code>name</code> and <code>weight</code>. If we call the function, we must pass in values:</p>
		<ul>
			<li>name: "Mr. Jingles"</li>
			<li>weight: 11</li>
		</ul>
		<code>
mouse("Mr. Jingles", 11);
			
// Console: Mr. Jingles is a mouse that weighs 11 grams.
		</code>
		<p>We do not always have to declare our arguments. JavaScript wraps passed arguments into an <code>arguments</code> object that is similar to an array.</p>
		<code>
function cat(){
  for (var i in arguments){
  console.log("The cat ate " + arguments[i] + ".");
  }
  return "The cat ate " + arguments.length + " things.";
}

cat("spiders", "fish", "Mr. Jingles");

/* Console:
The cat ate spiders.
The cat ate fish.
The cat ate Mr. Jingles.
*/
		</code>
		<p>In the above code, we used the <code>arguments</code> keyword to access the list of arguments passed into the function. We do not have to know how many arguments will be used to do this. Now, note that we used the keyword <code>return</code> this time. Not only did we pass values into the function, but the function passed a value back to us. We might not do anything with the returned data. But we can if we want.</p>
		<code>
console.log(cat("spiders", "fish", "Mr. Jingles"));

// Console: The cat ate 3 things.
		</code>
		<p>We just called the <code>cat()</code> function again, but this time we logged its return value to the console. The <code>return</code> keyword will be important in our next section.</p>
	</section>
	<section id="Factories" class="main-section">
		<header>Factories</header>
		<p>Since ECMAScript 6, new functionality has been provided with <code>Class</code> to allow JavaScript to <b>instantiate</b> objects similar to the way that languages like Java and C do. However, while <code>Class</code> appears to work like its namesake in other programming languages, it does not escape the object tree that is central to JavaScript. There are some sacrifices that come with the use of <code>Class</code>. A more in-depth discussion can be found <a href="https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e" target='_blank'>here</a>.</p>
		<p>Classes and constructor functions will not be discussed here. Instead, we will apply the earlier concepts to the concept of the factory function.</p>
		<code>
function moose(name){
  var mooseName = name;
  var hooves = 4;
  var antlers = 2;
  return{
    fall: function(){
      antlers = 0;
		return antlers;
    },
    spring: function(){
      antlers = 2;
      return antlers;
    }
  }
}
		</code>
		<p>We've used several concepts together in the above block of code, including a new concept in the return block. Let's review it step-by-step. We are hoisting a function, <code>moose()</code>, which requires one argument, <code>name</code> to be passed. Inside this function, we declare and initialize three variables: <code>mooseName</code>, <code>hooves</code>, and <code>antlers</code>. We see that <code>mooseName</code> is initialized using the argument that was passed. The function has a return statement, followed by what appears to be an object. Immediately, we know the following:</p>
		<ul>
			<li><code>moose(name)</code> can be called at any place in the code; it has been hoisted.</li>
			<li><code>mooseName</code>, <code>hooves</code>, and <code>antlers</code> are all in the local scope, and cannot be accessed by outside statements.</li>
			<li>If we initialize a variable to the called <code>moose(name)</code>, the variable will get what is in the <code>return</code> statement.</li>
		</ul>
		<p>What happens in the case of our last point?</p>
		<code>
const bill = moose('Bill');

console.log(bill);
			
// Console: Object { fall: fall(), spring: spring() }
		</code>
		<p>We see <code>bill</code> is now an object, and it has been given two methods.</p>
		<code>
console.log(bill.fall());

// Console: 0
		</code>
		<p>When we call the method <code>fall()</code>, which was passed to <code>bill</code>, it returns <code>0</code>. This is expected, as both <code>fall()</code> and <code>spring()</code> return the <code>antlers</code> local variable (referred to as a property).</p>
		<p></p>
	</section>
	<section id="Using_Factories" class="main-section">
		<header>Using Factories</header>
		<p>Interestingly, we cannot access <code>antlers</code> without using one of the two methods, and then only to receive the resulting value - never to make alternative changes. This will become important when an unintended change can cause downstream issues. For example, we would not want Bill to have 26 antlers. Such a thing could keep Bill from doing his normal routine.</p>
		<p>When programs get big, they often use common functions and objects many times. In advanced cases, that means a function may run hundreds or thousands of times, and some objects may be repeated thousands of times with slight differences for each object. Consider a game in which the player controls a group of characters:</p>
		<code>
function Character(n){
  var name = n;
  var xp = 0;
  var level = 1;
  return{
    get name(){
      return name;
    },
    get xp(){
      return xp;
    },
    set xp(x){
      xp = x;
      if ((5**level)*10&lt;=xp){
        xp-=(5**level)*10;
        level+=1;
      }
    },
    get level(){
      return level;
    }
  }
}
		</code>
		<p>Above, we've hoisted a new function, <code>Character</code>. Note that we capitalized it, as per putative naming conventions. A factory function works somewhat like a class, as it is a function for creating new objects and functions with inherited methods and properties. However, it does not implement inheritance in the classical sense. In fact, when we call the function and initialize its return value on a variable, we are essentially giving the variable the lexical environment (or closure) of the called function.</p>
		<p>In our <code>Character</code> factory function, we initialize three private variables: <code>name</code> (which will be passed the argument, <code>n</code>), <code>xp</code> and <code>level</code>. We return four methods. These are special methods because they use the <code>get</code> and <code>set</code> syntax to call a function. This allows us to use the attached methods as we would a variable.</p>
		<code>
var mrjingles = Character("Mr. Jingles");

console.log(mrjingles.name + " fooled the cat.");

// Console: Mr. Jingles fooled the cat.
		</code>
		<p>By implementing the <code>get</code> method for our character's name, we can grant access to the <code>name</code> variable within the scope of <code>Character</code>. But what happens if we try to change it?</p>
		<code>
mrjingles.name = 'Steve';
console.log(mrjingles.name);

Console: Mr. Jingles
		</code>
		<p>Nothing happens. There is no <code>set</code> method for <code>mrjingles.name</code>, so JavaScript ignores our command. Since Mr. Jingles survived the encounter with the cat, we want to add experience. We give him 30 experience for surviving the cat, and 25 experience for using his 'fool' technique.</p>
		<code>
mrjingles.xp += 30;

console.log(mrjingles.xp);

// Console: 30

mrjingles.xp += 25;

console.log(mrjingles.xp);

// Console: 5

console.log(mrjingles.level);

//Console: 2
		</code>
		<p>The <code>get</code> and <code>set</code> methods allowed us to change the <code>xp</code> property, view its final value, and subsequently view the result that our leveling algorithm had on the <code>level</code> property. Now, we might have simply made Mr. Jingles an object from the start, and given him his own properties and methods. However, Mr. Jingles is only one of our characters. Assuming we prompt the end user to provide five names for a group of heroes:</p>
		<code>
const names = ['Michelangelo', 
		'Donatello', 
		'Leonardo', 
		'Raphael', 
		'Casey Jones'];
const characters = {};
			
for (var i in names){
  characters[names[i]] = Character(names[i]);
}

console.log(characters['Leonardo']);

// Console: Object { name: Getter, 
		xp: Getter &amp; Setter, 
		level: Getter }
		</code>
		<p>The above code illustrates the reason we call our <code>Character</code> function a 'factory function'. We can use it to produce not just five new objects, but perhaps thousands.</p>
	</section>
	<section id="Conclusion" class="main-section">
		<header>Conclusion</header>
		<p>In this technical discussion, we reviewed some of the basic aspects of functions, and applied those aspects to the concept of the factory function. Hopefully, you found this discussion illuminating and, perhaps, inspiring. Other concepts in JavaScript can be applied to the factory function, making it a powerful option for augmenting your next project.</p>
	</section>
	<section id="References" class="main-section">
		<header>References</header>
		<ol>
			<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions" target='_blank'>Functions</a>, Mozilla and individual contributors, 2018</li>
			<li><a href="https://en.wikipedia.org/wiki/JavaScript" target='_blank'>JavaScript</a>, Wikipedia</li>
			<li><a href="https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1" target='_blank'>JavaScript Factory Functions with ES6+</a>, Eric Elliott, 2018</li>
			<li><a href="https://www.sitepoint.com/factory-functions-javascript/" target='_blank'>Quick Tip: What Are Factory Functions in JavaScript</a>, Dan Prince, SitePoint Pty. Ltd., 2016</li>
			<li><a href="https://www.youtube.com/watch?v=ImwrezYhw4w" target='_blank'>Factory Functions in JavaScript</a>, Mattias Petter Johansson, YouTube, 2015</li>
		</ol>
	</section>
</main>
body{
	background: floralwhite;
	color: midnightblue;
}
a{
	text-decoration: none;
	color: midnightblue;
}
nav{
	position: fixed;
	top: 0;
	left: 0;
	z-index: 1000;
	
	background: lavenderblush;
	font-family: sans-serif;
	font-size: 1.2em;
	line-height: 1.4em;
	display: flex;
	padding: 0;
	
	border: solid 1px midnightblue;
	box-shadow: 0px 1px 4px 2px dimgray;
}
.nav-header{
	flex-basis: 5%;
	padding: 5px 0 0 7px;
}
.nav-top > a >h3{
	margin: 0;
	word-wrap: normal;
}
.nav-top{
	display:flex;
	flex-basis: 85%;
}
.nav-top > a{
	color: midnightblue;
	padding: 7px 10px 7px 10px;
}
.nav-bot{
	display:flex;
	flex-basis: 10%;
}
.nav-bot > a{
	color: midnightblue;
	padding: 7px 10px 7px 10px;
}
.nav-top > a:hover, .nav-bot > a:hover{
	background: midnightblue;
	color: floralwhite;
}
.nav-bot .nav-drop{
	display: none;
}
.drop-menu{
	display: none;
}
section{
}
section > h1{
	font-family: "Trebuchet MS", Helvetica, sans-serif;
	font-size: 2em;
	margin: 4px 0 4px 0;
}
header{
	font-family: "Trebuchet MS", Helvetica, sans-serif;
	font-size: 2em;
	font-weight: 600;
	margin: 4px 0 4px 0;
}
nav > header{
	font-size: 1.2em;
}
section > p{
	text-align: justify;
	font-size: 1.1em;
}
#main-doc{
	position: absolute;
	max-width: 800px;
	margin-right: 30px;
}
p > code, li > code{
	display: inline;
	margin: 0;
	padding: 0;
}
code{
	position: relative;
	display: block;
	width: 80%;
	margin: auto;
	white-space: pre;
	padding: 4px 40px 4px 40px;
	line-height: 1.6em;
	overflow-x: auto;
	background-color:whitesmoke;
	color: black;
}
p > a, li > a{
	color: darkred;
	font-weight: 500;
	text-decoration: underline dotted;
}
p > a:hover, li > a:hover{
	background: darkred;
	color: lavenderblush;
	border-radius: 4px;
}

@media (min-width: 611px){
	nav{
		width: 150px;
		bottom: 0;
		flex-direction: column;
	}
	.nav-top{
		flex-direction: column;
		padding-top: 16px;
	}
	.nav-bot{
		flex-direction: column;
		padding-bottom: 16px;
	}
	#main-doc{
		left: 230px;
		max-width: 60%;
	}
}
@media (min-width: 930px){
	#main-doc{
		left: 260px;
		max-width: 800px;
	}
}
@media (max-width: 610px){
	nav{
		bottom: none;
		right: 0px;
		flex-direction: row;
	}
	.drop-menu.responsive{
		position: absolute;
		right: 5px;
		left: 5px;
		top: 50px;
		display: flex;
		flex-direction: column;
		background: floralwhite;
		margin-top: 5px;
		box-shadow: 0 0 4px 2px gray;
		z-index: 999;
	}
	.drop-menu.responsive a{
		color: midnightblue;
		min-height: 40px;
		line-height: 20px;
		font-family: sans-serif;
		font-size: 1.2em;
		line-height: 1.4em;
		padding: 10px 16px 0px 16px;
		text-align: center;
	}
	.nav-bot{
		flex-direction: row;
		flex-basis: 34%;
		padding-right: 5px;
	}
	.nav-top{
		flex-direction: row;
		flex-basis: 1%;
		padding-left: 5px;
	}
	.drop-menu.responsive a:hover{
		background: midnightblue;
		color: floralwhite;
	}
	.nav-bot .nav-drop{
		display: block;
	}
	main{
		top: 60px;
		margin: auto;
		width: 90%;
	}
	section > p{
		font-size: 1em;
	}
	.nav-header{
		font-size: 1.1em;
		flex-basis: 65%;
	}
	
}
var smallScreen = window.matchMedia("(max-width: 610px)");
var largeScreen = window.matchMedia("(min-width: 611px)");

function respondScreenMini(mini){
	if (mini.matches){
		var x = document.getElementById("navTop");
		var y = document.getElementById("dropContain");
		while (x.children.length>0){
			y.appendChild(x.children[0]);
		}
	}
}
function respondScreenMaxi(maxi){
	if (maxi.matches){
		var x = document.getElementById("navTop");
		var y = document.getElementById("dropContain");
		while (y.children.length > 0) {
			x.appendChild(y.children[0]);
		}
	}
}

function navDropSwitch(self=this) {
	this.preventDefault;
	var y = document.getElementById("dropContain");
	if (y.className === "drop-menu") {
		y.className += " responsive";
	} else {
		y.className = "drop-menu";
	}
}


document.addEventListener("DOMContentLoaded", function(){
	respondScreenMini(smallScreen);
	smallScreen.addListener(respondScreenMini);
	respondScreenMaxi(largeScreen);
	largeScreen.addListener(respondScreenMaxi);
	document.getElementById('dropdown').addEventListener('click', navDropSwitch);

})


/*
SOURCES:
https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1
https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e
https://www.sitepoint.com/factory-functions-javascript/
https://www.youtube.com/watch?v=ImwrezYhw4w
https://medium.freecodecamp.org/class-vs-factory-function-exploring-the-way-forward-73258b6a8d15
https://stackoverflow.com/questions/8698726/constructor-function-vs-factory-functions
https://developer.mozilla.org/en-US/docs/Glossary/Function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions
https://medium.com/@gaurav.pandvia/understanding-javascript-function-executions-tasks-event-loop-call-stack-more-part-1-5683dea1f5ec
*/
Run Pen

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

External JavaScript

  1. https://gitcdn.link/repo/freeCodeCamp/testable-projects-fcc/master/build/bundle.js