<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Uriel Rodriguez on Medium]]></title>
        <description><![CDATA[Stories by Uriel Rodriguez on Medium]]></description>
        <link>https://medium.com/@codenameuriel28?source=rss-157b4a09debc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Uriel Rodriguez on Medium</title>
            <link>https://medium.com/@codenameuriel28?source=rss-157b4a09debc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:52:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codenameuriel28/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Modules in Node.js]]></title>
            <link>https://codenameuriel28.medium.com/modules-in-node-js-f666642206c3?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f666642206c3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 02:40:52 GMT</pubDate>
            <atom:updated>2021-03-07T02:40:52.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bc9pmTiyKR0WNPka2w3e0Q.png" /></figure><p>It can be said that the building blocks of an application are modules. Modules are isolated pieces of code that when put together construct the larger functioning application. Node.js accomplishes this abstraction through the CommonJS standard, which provides a system of using files to encapsulate code and make code available to other files. Through a module system, files can be imported, exported, and plugged into other files to carry out some function in constructing the overall application. Modules also help solve the old issues JavaScript had with code existing within a global scope. Let’s take a look at how this is done with CommonJS.</p><p>The main idea of modules is to break down large pieces of code into smaller pieces. So by storing relevant code in individual files, code can be plugged into other portions of an application via importing. Importing a file means loading in code that is made available for use within the file. A simple import statement with CommonJS would be something like the following.</p><pre>const sample = require(&#39;./sample.js&#39;);</pre><pre>// if sample.js provided a function<br>sample();</pre><pre>// if sample.js provided a variable<br>console.log(sample);</pre><pre>// etc</pre><p>Very simply expressed, the first step in utilizing modules is importing the code within a file, in this case, “./sample.js” and storing it in a variable. Afterward, depending on what the imported code is, whether a function, variable, object, or anything else, it is used like any other piece of code. In CommonJS, importing a file involves using the require() function, which takes in a module identifier, and loads in that module within the current module. Imported code can have three different origins: core modules which are the modules natively provided by Node.js, modules within a project directory, and third-party packages, or installed modules. In this example, a file from within the project directory is imported, which can be identified by the relative path module identifier that is passed into the require() function, “./sample.js”. When importing the built-in or third-party modules, the process is the same, a single word module identifier is passed into require().</p><pre>// built-in module used for creating HTTP servers<br>const http = require(&#39;http&#39;);</pre><pre>// third-party package used for making HTTP requests<br>const axios = require(&#39;axios&#39;);</pre><p>The other side of this process is the exportation of code so that other modules can access it within their scope. Node.js makes that possible by providing files with a “module” object which represents the file. Within the module object is an “exports” property that serves to capture the code that is to be made available to other files or modules.</p><pre>// sample.js</pre><pre>const sample = &#39;sample variable string&#39;;<br>const sample2 = &#39;sample2 variable string&#39;;</pre><pre>module.exports = sample;</pre><pre><br>// importing module<br>const sample = require(&#39;./sample.js&#39;);<br>console.log(sample); // =&gt; sample variable string<br>console.log(sample2); // =&gt; Reference error</pre><p>Expanding on the example above, here we see the structure within “sample.js” that allows other modules to import its API for use. Any code that is defined within a module is private to other modules unless it is explicitly exported. When I tried to log the “sample2” variable, a reference error was thrown because it was not explicitly exported via assignment to the “exports” property on the module object. This is how Node.js allows files access to encapsulated code. Node.js also provides the same exporting functionality via the shorthand “exports” object.</p><pre>// sample.js</pre><pre>const sample = &#39;sample variable string&#39;;</pre><pre>exports.sample = sample;</pre><p>Just as in the first example where the “sample” variable was assigned to module.exports, in this example, the equivalence when working solely with exports is to assign a property on exports. If exports is redefined by assigning it to some code, then the module.exports functionality will be overwritten and will not work.</p><pre>exports = sample; // will cause failure</pre><p>As of Node.js version 14.x, the standard JavaScript module system, ES modules, has also be adopted and provides alternatives to utilizing modules along with some key differences. The ES module system utilizes the “import” statement to import modules and does so asynchronously as opposed to the synchronous require() function. For example:</p><pre>// importing with ES Modules</pre><pre>import sample from &#39;./sample.mjs&#39;;</pre><p>Unlike CommonJS, using ES modules does not require explicitly defining a variable to store the exported code, and takes in a URL as the module identifier. This process is carried out for core modules and third-party packages. When exporting code from a module, it is also handled differently than with CommonJS, for example:</p><pre>// sample.mjs</pre><pre>export const sample = &#39;a sample&#39;;<br>export default const sample2 = &#39;a second sample&#39;;</pre><p>Here we are exporting both variables from sample.js in two different manners, the first being a named export and the second being a default export. Named exports are identified by a single “export” statement prefixed to some code, and can be done many times within a single module. The importing module accesses the exports via the name of the variables, hence named exports.</p><pre>// sample.mjs</pre><pre>export const sample = &#39;a sample&#39;;<br>export const sample2 = &#39;a second sample&#39;;</pre><pre>// importing sample.js</pre><pre>import { sample, sample2 } from &#39;./sample.mjs&#39;;</pre><p>The second kind of export is the default export illustrated above by prefixing “export default” to some code. This kind of export can only be carried out once per module and is generally reserved for modules that export a single piece of code, such as a class or function.</p><p>Aside from the syntactical differences, CommonJS and ES modules provide other key differences. Like the “module” object which is injected by default into each CommonJS module by Node, other values are made available within the modules. The __filename and __dirname are variables that are made available within every CommonJS module, useful for various configurations.</p><pre>// within a CommonJS module<br>// by default .js extension</pre><pre>console.log(__filename, __dirname); // double underscore</pre><p>When working with ES modules, these variables are not available and need to be computed. This is carried out by the only value that is injected within ES modules, the “import.meta” property which helps identify the URL which maps to the current module.</p><pre>// sample.mjs<br>// .mjs extension is used for ES modules</pre><pre>import { fileURLToPath } from &#39;url&#39;;<br>import { dirname } from &#39;path&#39;;</pre><pre>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = dirname(__filename);</pre><pre>console.log(__filename, __dirname);</pre><p>As mentioned before the ES module takes a URL as the module identifier so the injected import.meta provides access to a “url” property that computes the module’s URL. From the computed URL, the file name can be determined, and subsequently, the directory name as well. Another thing to take note of when using ES modules is the file extension, “.mjs”. The default module system for Node.js is CommonJS which defaults to file extension “.js”. This default module system can be replaced via the package.json file by adding a “type” field and specifying “module” for ES modules, or “commonjs”.</p><pre>{<br>  &quot;type&quot;: &quot;module&quot; or &quot;commonjs&quot;<br>}</pre><p>Since Node.js’ inception, JavaScript has progressed and adopted new functionality which Node.js continues to incorporate into its ecosystem. As a result, Node.js provides various ways to utilize modules, include CommonJS and ES modules. Understanding the differences between these module systems is important in knowing when one module is ideal over the other. To learn more Node.js and its module system, check out the link below for great information.</p><ul><li><a href="https://nodejs.org/api/modules.html">Modules: CommonJS modules | Node.js v23.11.0 Documentation</a></li><li><a href="https://nodejs.org/api/esm.html">Modules: ECMAScript modules | Node.js v24.1.0 Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f666642206c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js And Its Event-Driven Architecture]]></title>
            <link>https://codenameuriel28.medium.com/node-js-and-its-event-driven-architecture-2ea4a520f6fa?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ea4a520f6fa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Sun, 28 Feb 2021 00:24:14 GMT</pubDate>
            <atom:updated>2021-02-28T00:24:14.686Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bc9pmTiyKR0WNPka2w3e0Q.png" /></figure><p>Lately, as I have been focused on Node.js development, I have spent time learning about the underlying ideas that power the platform. Node.js departs from more traditional methods of handling I/O operations via the usage of threads, accomplishing efficiency and speed with its non-blocking I/O design. This non-blocking design is made possible through asynchronous handling of operations, by utilizing what’s known as an event-driven model. What this means is that at the core, Node.js uses events to set processes in motion and executes and completes them only when they are ready.</p><p>An event can be understood as some sort of action occurring, and another piece of code responding to the action. Node.js implements this idea through a special object known as the EventEmitter. The EventEmitter object is at the core of the event-driven architecture and lends other event-based implementations the ability to create and respond to events.</p><pre>// reminder.mjs - .mjs file extension used to implement ES Modules</pre><pre>import EventEmitter from &#39;events&#39;;</pre><pre>class Reminder extends EventEmitter {<br>  constructor(time) {<br>    super();<br>    this.time = time;<br>  }</pre><pre>  remind() {<br>    setInterval(() =&gt; {<br>      this.emit(&#39;reminder&#39;);<br>    }, this.time);<br>  }<br>}</pre><pre>const minToMilliSecs = min =&gt; 60,000 * min;</pre><pre>const breakReminder = new Reminder(minToMilliSecs(20));<br>breakReminder.on(&#39;reminder&#39;, () =&gt; console.log(&#39;take a break&#39;));<br>breakReminder.remind();</pre><p>In this example, we can see how Node.js utilizes the EventEmitter object, mainly how it provides other objects the ability to create and respond to events. First, the EventEmitter object is imported from the core modules, “events”. After this, an object can inherit the ability to create events via the emit() method and respond to events via the on() method. Here I created a Reminder class that gives instances the ability to create reminder events utilizing the time provided when creating the reminder instance. After 20 minutes have passed, the Reminder instance, “breakReminder”, is set to disperse or emit an event, the “reminder” event. This is accomplished via the emit() method which takes an event name as its first argument and can be set to anything. In addition, the break reminder is also configured to listen to the “reminder” event and to log to the console via the on() method which takes the event name it should respond to, and an event handler to perform some action on that event.</p><p>So how does this event-driven process contribute to the speed and efficiency of Node.js? The process created by the setInterval function, emitting after some time, is ongoing and so it is handled in the background by a separate structure, allowing the application to resume execution. In this way, operations that require time to process, such as I/O operations, like accessing data from a database, can be handled while preventing the application from stopping due to I/O processing time. Events are then used to inform that some time-consuming process has completed, and is ready for the application to process its data. This idea is implemented in web servers via Node.js’ HTTPServer and HTTPClient objects.</p><p>Aside from being foundational to web applications, the HTTPServer object help to further understand the event-driven architecture in Node.js. As an event emitter, the HTTPServer object listens for events, a “request” from the client, and on that event, emits its own event, the “response” which the client listens for and processes.</p><pre>// server.mjs</pre><pre>import * as http from &#39;http&#39;;</pre><pre>const server = http.createServer();</pre><pre>server.on(&#39;request&#39;, (req, res) =&gt; {<br>  res.writeHead(...);<br>  res.end(...server response);<br>});</pre><pre>server.listen(port, someURL);</pre><p>This example further demonstrates the idea behind events and their implementations in Node.js with servers. Here we are instantiating a server object that is configured to handle an event, “request”, created by the client, which is also an event emitter. The server object is configured to listen for a specific client and its request via the listen() and the specified URL. Once the specified client emits the “request” event, the server can then emit its own event, the “response” which the client will listen for. Something to note about this example is that the lower level implementations expressed in the Reminder class example, where the emit() method is used to send out an event, are abstracted away within the HTTP module, but the functionality remains the same.</p><p>At this point, we can understand the idea of events and handlers but what goes on behind the scenes and what we don’t see is very important. I/O operations, like making requests to a server, are handled asynchronously and events are the mechanism used to determine when the process is ready to return some value or output. Any asynchronous operation is outsourced, to other structures within the platform, allowing the script to continue execution thus avoiding blocking. When outsourced, the asynchronous process continues running until it emits an event that signals its completion. Once this is the case, the event and the handler function provided with the asynchronous process, the callback, are transferred over to an event queue. At this point, the event loop iterates over the events, which represent completed asynchronous processes, and pushes the event handler or callback to the call stack where it can be finally executed.</p><p>Despite the complexities of the internal structures that handle the asynchronous processes and events, the central idea remains: events are key to allowing fast and efficient processing. By understanding this, applications can be implemented in ways that take advantage of the structures that handle time-consuming tasks and avoid blocking the server. For example, carrying out computationally taxing tasks, such as large mathematical computations, especially in a synchronous manner could block the server and prevent users from carrying out other tasks. This is where an event-driven approach would aid to distribute the computation to operate in the background while the application is free to carry out further processes. Learning how Node.js operates behind the scenes is important for efficient implementations. To learn more, check out Node.js official documentation on events.</p><p><a href="https://nodejs.org/api/events.html">Events | Node.js v25.7.0 Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ea4a520f6fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in JavaScript]]></title>
            <link>https://codenameuriel28.medium.com/functional-programming-in-javascript-821a1302cb97?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/821a1302cb97</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 03:47:20 GMT</pubDate>
            <atom:updated>2021-02-26T19:12:27.476Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>When we think of programming paradigms, the one that receives the most coverage is Object-Oriented Programming. This is to say, a programming paradigm is how code is implemented and executed, and in the case of OOP, it is via the use of classes and objects. However, aside from the OOP paradigm, the functional programming paradigm is one that is gaining popularity, as it is seen extensively within React and other libraries. JavaScript enables such a style because functions can be used as data, and passed around within a program. In order to implement a functional approach, certain key concepts must be followed, so let’s explore them.</p><p>The most important aspect of a functional programming approach is the ability for functions to be versatile, and JavaScript accomplishes that by making functions first-class members. This means that functions can be used as data, and passed around within a program, such as when stored within variables, data structures like array or objects, passed as arguments to other functions, or returned from function calls.</p><pre>// non-functional approach<br>let message;<br>console.log(message);</pre><pre>// functional approach<br>const log = message =&gt; console.log(message);</pre><pre>message = &quot;log me&quot;<br>console.log(message)<br>log(message)</pre><p>In the example above, the console.log() call utilizes an element of OOP by invoking the log method on the console object. The functional equivalence is by strictly using functions and so a function object is stored within the log variable and simply invoked by passing a “message” argument to it. Another functional programming concept that the example above is implementing is the use of a declarative approach versus an imperative one. The first way a message is logged details how it is done, by invoking the log method on the console object. Albeit not many steps are involved, this form of logging a message is imperative or descriptive of the process. The functional approach is declarative, where the details for logging a message are not important. The actual implementation of invoking the log method on the console object is abstracted away within the log() function.</p><p>Another key concept in functional programming is the <em>immutability</em> of data, or that data should not be mutated. In practice, any argument passed to a function should not be transformed, but rather a changed copy should be returned.</p><pre>const initialState = () =&gt; {};<br>const updateState = (updates, state) =&gt; {...state, ...updates}</pre><pre>const state = initialState()<br>const updatedState = updateState({ prop: &quot;someProp&quot; }, state)</pre><pre>console.log(state) // =&gt; {}<br>console.log(updatedState) // =&gt; { prop: &quot;someProp&quot; }</pre><p>This example demonstrates the idea of utilizing functions for every step in a process, in this case, invoking the initialState() function to return an empty object. Afterward, we add properties to the initial state object by passing it as an argument to the updateState() function along with the updates and return a new object containing the added properties. Again this example demonstrates a declarative approach, abstracting away the method of obtaining an object, and updating it.</p><p>In the previous example, the updateState() function maintained the immutability of its arguments. It also demonstrated another key concept: <em>pure functions </em>which state that functions should compute a return value based solely on the arguments it receives and should not cause side effects.</p><pre>// functional approach<br>const log = message =&gt; console.log(message);</pre><p>Taking a look back at the first example, the log() function is not a pure function. It causes the side effect of logging to the console while returning a value, undefined, that is not computed by its “message” argument. And because pure functions return values are based on their arguments, they are predictable and easy to implement tests for.</p><pre>const increaseByOne = num =&gt; num + 1</pre><pre>const num = 1<br>const newNum = increaseByOne(num) // =&gt; 2<br>console.log(num) // =&gt; 1</pre><p>Because the increaseByOne() function is pure, returning a value that is base on the computation made its “num” argument and does produce any side effects, it can easily be tested. A test can be written where an assertion is made that when a number of 5 is passed into the increaseByOne() function, a value of 6 is expected. The test will also consistently prove this assertion because the function follows the guidelines of a pure function.</p><p>Now, going back to the idea of functions being first-class members, JavaScript enables functions to operate on other functions by passing them as arguments and even returning functions from function calls. Functions that accept functions as arguments or return functions are known as <em>higher-order functions</em> and are another key concept of functional programming.</p><pre>const sum = (a,b) =&gt; a + b<br>const average = (fn, ...nums) =&gt; nums.reduce(fn) / nums.length</pre><pre>const numsAvg = average(sum, 1, 2, 3) // =&gt; 2</pre><p>In this example, two pure functions are defined sum() and average(), which take in some arguments, and do not mutate the arguments but compute a return value based on them. The average() function is a higher-order function that takes in a function, sum(), as an argument and computes a return value by passing it into another higher-order function, reduce(), as the reducer. Next, an arbitrary amount of numbers are passed to the rest parameter and aggregated into a “nums” array. Finally, the array of numbers are reduced and divided by the total amount of numbers passed into the average() function to return the average.</p><p>So far, we’ve seen how functional programming truly relies on functions to execute any and all processes. In keeping with this approach, iterations are another process that can also be tackled with functions with <em>recursion</em>. For example:</p><pre>// non-functional approach</pre><pre>const nums = [1, 2, 3]<br>let total = 0<br>for (let i = 0; i &lt; nums.length; i++) {<br>  total += nums[i]<br>}</pre><pre>console.log(total) // =&gt; 6</pre><pre>// functional recursive approach</pre><pre>function addRecursively(nums) {<br>  return !nums.length ? 0 : nums[0] + addRecursively(nums.slice(1))<br>}</pre><pre>console.log(addRecursively(nums)) // =&gt; 6</pre><p>The first approach utilizes a for-loop which again is not entirely functional so it is replaced with the recursive function addRecursively(). Like the for-loop which operates on an array, the recursive function takes in an array of numbers and begins adding the first to the subsequent one. It also establishes a base case of returning 0 if all the numbers have been added, which is checked by assessing if the array of numbers length is 0.</p><p>Finally, because functional programming involves implementing various highly specialized functions, in order to carry out larger processes they need to be assembled. Functions can be composed, or aggregated in a certain order within another larger function to execute in sequence to carry out an overall process. <em>Composition</em> is another key concept of functional programming and there are many variations or patterns all of which involve assembling pure functions to execute a larger process.</p><pre>const add = (a,b) =&gt; a + b<br>const compare = num =&gt; num % 2 === 0</pre><pre>const sum = add(1, 2)<br>const isEven = compare(sum)</pre><pre>// using composition</pre><pre>const add = (a,b) =&gt; a + b<br>const compare = num =&gt; num % 2 === 0<br>const operation = fn =&gt; (...nums) =&gt; nums.reduce(fn)<br>const compose = (...funcs) =&gt; {<br>  return arg =&gt; {<br>    return funcs.reduce((composedArg, func) =&gt; {<br>      return func(composedArg)<br>    }, arg)<br>  } <br>}</pre><pre>const addNums = operation(add)</pre><pre>const createComposition = compose(addNums, compare)<br>const isEven = createComposition(1, 2, 3, 4, 5)</pre><p>The first part of this example shows a simple approach to calculate if a number is even, by invoking two separate functions. Another approach to this problem is by aggregating every function call into one function call to simplify the process. First, a compose() function is defined in which it takes any amount of functions as arguments and returns a function that takes a single argument to be used as a starting point in a series of calculations. The arbitrary amount of functions are aggregated into an array and then iterated over, reducing and transforming the single argument by passing it to each function in the aggregated function array. Next, a custom function is created by invoking the higher-order operation() function, passing in the add() function. After this, a composition is created in which a series of function calls are established by passing in the functions to compose(). The compose() function call returns a function that receives the starting point argument which will be passed to each function argument, in the order that the functions are passed into the compose() functions. The numbers are first added via addNums(), then the return value is passed to the compare() function returning a Boolean value. When processes become large enough to warrant multiple steps and function calls, composition is a powerful way to compute an otherwise modular process.</p><p>In conclusion, these key concepts, the immutability of data, pure functions, higher-order functions, recursion, and composition, create the foundation for functional programming. By relying on the power of functions, programs can be written in a manner that enables the testing of discreet components in a reliable manner. And as popularity continues to grow, more and more libraries will begin incorporating this programming approach. To learn more about functional programming, the article below provides great information.</p><p><a href="https://www.geeksforgeeks.org/functional-programming-paradigm/">Functional Programming Paradigm - GeeksforGeeks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821a1302cb97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with JavaScript’s Built-in Function Methods]]></title>
            <link>https://codenameuriel28.medium.com/working-with-javascripts-built-in-function-methods-875c2fc009e3?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/875c2fc009e3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 03:42:35 GMT</pubDate>
            <atom:updated>2021-02-13T03:42:35.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>In JavaScript, anything that is not a primitive value such as strings or integers is an object. What this means is that functions are actually objects or at least specialized objects. This also means that functions have access to properties and methods like all other objects do. JavaScript defines built-in properties and methods on functions like the name property which returns the name of the function declaration or the variable name that binds to the function object within function expressions.</p><pre>function thisFunc() {<br>  ...<br>}<br>console.log(thisFunc.name) // =&gt; thisFunc</pre><pre>const thatFunc = () =&gt; ...<br>console.log(thatFunc.name) // =&gt; thatFunc</pre><p>Included in these built-in properties, are the call(), apply() and bind() methods. These methods allow functions to work like methods on objects without needing to be defined as methods within the objects.</p><h3><strong>Call()</strong></h3><pre>function addProperty(name, value) {<br>  this[name] = value<br>}</pre><pre>const myObj = {}</pre><pre>addProperty.call(myObj, &quot;myProp&quot;, &quot;myValue&quot;)</pre><pre>console.log(myObj) // =&gt; { myProp: &quot;myValue&quot; }</pre><p>In this example, a function “addProperty” is defined which references an object via the “this” value, and sets a property on that object using the passed arguments. Ordinarily, within a function declaration like the one above, the invocation context usually is the global object and if “addProperty” is invoked like a normal function, it will set a property on the global object. However, the “addProperty” function is invoked indirectly by invoking its call() method instead, which takes as its first argument an object, or a “this” value. By providing the “myObj” object to the call() method, we define the “this” value within the “addProperty” function. After the first “this” argument, call() receives the arguments that the function it is invoked expects, in this case, “addProperty” function expects a “name” and “value” argument.</p><h3><strong>Apply()</strong></h3><p>Similar to the call() method, apply() also defines a “this” value for the function it is invoked on. But unlike call() which receives further arguments as individual values, apply() takes in arguments as elements in an array. This is a convenient way to provide an indeterminate amount of arguments to a function. For example:</p><pre>const nums = [3, 4, 6, 7, 9]</pre><pre>let max = Math.max(nums)</pre><pre>let maxNum = Math.max.apply(null, nums)</pre><pre>console.log(max) // =&gt; NaN<br>console.log(maxNum) // =&gt; 9</pre><p>In this example, you can see that invoking Math.max() with an array of numbers produces the value “NaN”. This is because Math.max() expects an arbitrary amount of integer arguments and returns the max value from them. Those integer arguments must be provided as single arguments and not within an array structure. By invoking apply() on Math.max(), we are able to get around that issue, because apply takes in arguments in the form of an array and then distributes them within the function it is invoked on. One thing to note is that this issue can also be handled with the spread operator, as it&#39;s the more modern approach.</p><pre>const nums = [3, 4, 6, 7, 9]</pre><pre>let maxNum = Math.max(...nums)</pre><pre>console.log(maxNum) // =&gt; 9</pre><p>Another thing to note is that the “this” value in the apply() invocation is set to null because in this case, the function we are invoking apply() on, Math.max() does not make use or computes on a “this” value.</p><h3><strong>Bind()</strong></h3><p>Finally, the last of the function methods trio is the bind() method which behaves similarly to the call() or apply() methods in that it is used to have a function act on an object. However, the big difference with bind() is that it permanently binds a function to an object, and returns a new function that will always operate on the object it was bound to. This is the case even if the function returned from invoking bind is assign as a method in another object.</p><pre>const person = { age: 20 }</pre><pre>function increaseAge() {<br>  this.age++<br>}</pre><pre>const growOlder = increaseAge.bind(person) // =&gt; returns a function</pre><pre>growOlder()<br>console.log(person.age) // =&gt; 21</pre><pre>growOlder()<br>console.log(person.age) // =&gt; 22</pre><pre>---------</pre><pre>const newPerson = { age: 25, growOlder }<br>newPerson.growOlder()</pre><pre>console.log(newPerson.age) // =&gt; 25<br>console.log(person.age) // =&gt; 23</pre><pre>console.log(newPerson) <br>// =&gt; { age: 25, growOlder: [Function: bound increaseAge] }</pre><p>As you can see, invoking bind() on a function ties that function to the object that is passed in as the argument. It returns a function that can be invoked to carry out the bound function’s operation on the object. And because the function is permanently bound to the object, even if the returned function is assigned as a new property or used in any other context, it will always refer to the “this” it was bound to.</p><p>Another functionality of the bind() method is that of binding additional arguments to the parameters of the function bind() is invoked on, also known as “currying”. For example:</p><pre>const multiply = (x, y) =&gt; x * y</pre><pre>const double = multiply.bind(null, 2)</pre><pre>console.log(double(3)) // =&gt; 6<br>console.log(double(12)) // =&gt; 24</pre><pre>const triple = multiply.bind(null, 3)</pre><pre>console.log(triple(4)) // =&gt; 12</pre><p>This example demonstrates currying, in that the additional arguments after the first argument designated for the “this” value are bound to function, and in this case, to the parameters of the function bind() is invoked on. The first argument passed to bind() is null because the function multiply() does not work with the “this” value. The following argument provided is the number 2 which is bound to the “x” parameter, returning a new function that simply only requires a value for the “y” parameter.</p><p>Although you have seen how these function methods allow the redefining of a function’s “this” value, they do not work with arrow functions. Arrow functions inherit the “this” value from the environment or namespace in which they are defined. This inheriting feature of arrow functions can not be overwritten with these function methods. With that being said, common usage for the bind() method includes making regular functions behave like arrow functions, except by explicitly binding the function to a particular “this” value.</p><p>With this, you can now see the additional functionalities JavaScript functions provide. These methods provide function objects additional flexibilities for varying applications. To learn more about functions and their methods, particularly call(), apply() and bind(), JavaScript MDN has great documentation.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#">Function.prototype.bind()</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875c2fc009e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Closures in JavaScript cont.]]></title>
            <link>https://codenameuriel28.medium.com/exploring-closures-in-javascript-cont-3a33f1a5a5f3?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a33f1a5a5f3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 23:22:36 GMT</pubDate>
            <atom:updated>2021-02-06T23:22:36.052Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>To recap my last blog, <a href="https://codenameuriel28.medium.com/exploring-closures-with-javascript-functions-cd14d1c2cec">“Exploring Closures with JavaScript Functions”</a>, to understand closures, it’s essential to remember that functions create an enclosed environment known as a namespace. Namespaces allow you to work with variables that have been defined within other namespaces or scopes without overwriting them. Now here is the critical part, when a function is defined, the function object that is created not only contains the code defined within its code block but also a reference to the namespace it was defined in, and the variable bindings within the namespace.</p><pre>function outerFunc() {<br>  const outerFuncScope = &quot;outerFunc&quot;;<br>  return () =&gt; console.log(outerFuncScope;<br>}</pre><pre>outerFunc()(); // =&gt; outerFunc</pre><p>When the anonymous function is returned from the outerFunc() call, it maintains access to the outerFuncScope variable binding because it was defined within the outerFunc() namespace and so it keeps a reference to that namespace and all the variable bindings within it.</p><p>Again, utilizing closures allow for very some powerful programming. In fact, closures are a big component in functional programming which is essentially how the React UI library is built. Let’s take a look at some ideas that are powered by closures.</p><p>One idea that I find very interesting is that of using closures to maintain a private state useful in creating caches. For example:</p><pre>function generateUniqueRandNum(range) {<br>  const randomNums = [];</pre><pre>  return function generate() {<br>    // base case<br>    if (randomNums.length === range) {<br>      console.log(`All unique random numbers for range: ${range}  have been returned`);<br>      return;<br>    }</pre><pre>    const randNum = Math.floor(Math.random() * range);</pre><pre>    if (randomNums.includes(randNum)) {<br>      console.log(`random number: ${randNum} has been returned. Randomizing again`);<br>      generate();  // recurse<br>    } else {<br>      randomNums.push(randNum);<br>      console.log(`returning unique number: ${randNum}`);<br>      return randNum;<br>    }<br>  }<br>}</pre><pre>const randNum = generateUniqueRandNum(5);</pre><pre>randNum(); // =&gt; returning unique number: 2<br>randNum(); // =&gt; returning unique number: 4<br>randNum(); // =&gt; returning unique number: 3<br>randNum(); // =&gt; returning unique number: 1<br>randNum(); // =&gt; random number: 4 has been returned. Randomizing again<br>randNum(); // =&gt; returning unique number: 0<br>randNum(); // =&gt; All unique random numbers for range: 5 have been returned</pre><p>The example above defines a higher-order function, a function that takes in a function as an argument, and/or returns a function. generateUniqueRandNum() takes in a “range” to generate a random number and returns another function generate(). When invoked, generate() first checks if all the possible random numbers within the given range have been cached and returned, if so, it logs this fact and returns, ending potential recursive calls. If there are still unique random numbers that have not been returned, then a random number is generated. A check is performed for the generated number. If the number was generated before, cached, and returned, then that fact is logged and the generate() function recursively calls itself. If the generated number was not cached, then it was not returned and is then cached, pushed in the “randomNums” array, and then returned. This example shows how the inner generate() function uses its closure to access the “range” parameter and the “randomNums” array, in other words, the variable bindings found within the generateUniqueRandNum() function, or the namespace it was defined in. The generate() function is able to access the private state, the “randomNums” array which is used as a cache for previously generated random numbers, and recurse based upon its data, or update it accordingly.</p><p>Besides the more commonly implemented single closure, like the example above, multiple closures can also be implemented, that is multiple functions accessing a single private variable.</p><pre>function counter() {<br>  let currCount = 0;<br>  return {<br>    count: () =&gt; currCount++,<br>    reset: () =&gt; currCount = 0<br>  };<br>}</pre><pre>const counterOne = counter(); // { 2 methods }<br>const counterTwo = counter(); </pre><pre>counterOne.count(); // =&gt; 0<br>counterTwo.count(); // =&gt; 0<br>counterOne.reset(); // =&gt; currCount set to 0<br>counterOne.count(); // 0<br>counterTwo.count(); // =&gt; 1</pre><p>In this example, there are two closures, the count() and reset() methods which both retain references to the private variable “currCount”. In addition, each time the counter() function is invoked, a new counter object is created with its own unique namespace, so that each object returned has access to its own private “currCount” variable binding.</p><p>Another way to establish closures is through the use of block scopes. Any block scope can create a closure, including conditional statements or even loops.</p><pre>function outerFunc() {<br>  let scope = &quot;funcScope&quot;;<br>  <br>   if (true) {<br>     let scope = &quot;ifScope&quot;;<br>     <br>     return () =&gt; {<br>       console.log(scope);<br>     };<br>   }<br>}</pre><pre>outerFunc()(); // ifScope</pre><p>So far every example has shown how the inner functions retain a reference to the variable bindings of the function namespace it was defined within. However, in this example, although technically the return function is defined within the outerFunc() namespace which has a defined “scope” variable, it is defined within an inner namespace, that of the if conditional statement. The if-statement defines its own “scope” variable, and because the returned function is defined within this namespace, it logs that defined value, “ifScope”.</p><p>One important thing to note about closures is that functions maintain a reference to the variable bindings of the namespace they were defined in. When working with the “this” keyword, because it is a keyword and not a variable, careful attention is needed when referring to “this”. So for example:</p><pre>const sampleObj = {<br>  type: &quot;sampleObj&quot;,<br>  props() {<br>    console.log(this.type);<br>    return function() {<br>      console.log(this.type);<br>    }<br>   }<br>};</pre><pre>sampleObj.props(); // sampleObj<br>sampleObj.props()(); // undefined (strict mode)</pre><p>The first call to props() logged the “type” for the sampleObj which is the invocation context for props(), or “this” value. Next, an anonymous function is defined and returned which, when invoked, also attempts to log the “type” property for the sampleObj. And although the returned function is defined within the props() namespace which has access to the correct “this” value, because “this” is a keyword and not a variable, it does not have a reference to it via its closure. The solution is of course to use an arrow function that inherits the “this” value of its enclosing props() function.</p><p>With this, we have a closer look at closures and their capabilities. Much more can be done with closures, especially when using a functional programming implementation. If you haven’t checked out my previous blog, it provides an introduction to closures and also links to some resources that help to get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a33f1a5a5f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Closures with JavaScript Functions]]></title>
            <link>https://codenameuriel28.medium.com/exploring-closures-with-javascript-functions-cd14d1c2cec?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd14d1c2cec</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 17:49:08 GMT</pubDate>
            <atom:updated>2021-02-02T17:49:08.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>Continuing with the theme of functions and their many lesser-known features, closures are one of the more important and powerful features to be aware of. In understanding them, we first have to start with the idea of a namespace, which is a space where variables bindings are made. These bindings are protected from any outer bindings that may share the same variable names and risk overwriting the bindings.</p><pre>// global namespace<br>let scope = &quot;global&quot;; // first variable binding</pre><pre>if (true) { // if statement namespace<br>  let scope = &quot;local&quot;;<br>  console.log(scope); // =&gt; local<br>}</pre><pre>console.log(scope); // =&gt; global</pre><p>In this example, a variable binding is made in the global namespace, however another variable binding is made with the same variable name “scope.” Because the second “scope” variable binding is made in a nested if-statement namespace, it does not affect the global namespace variable binding. In other words, a namespace can be thought of as an environment which is made up of variable bindings, also known as a scope. These scopes are defined by the block syntax which encapsulates code making anything defined within that block unique to that namespace.</p><pre>{ // block syntax }</pre><p>Control logic, like if-statements, loops, all create namespaces which again, encapsulates variable bindings and make them unique to that environment. Functions also create namespaces, or scopes which can be remembered by their curly brackets block syntax. When a function is declared, if that function is defined with a parameter and other local variables, then those variables become a part of that function’s namespace.</p><pre>let scope = &quot;global&quot;;</pre><pre>function funcScope(scope) {<br>  scope += &quot; scope&quot;;</pre><pre>  console.log(scope);<br>}</pre><pre>console.log(scope);  // =&gt; global<br>funcScope(&quot;func&quot;);  // =&gt; func scope</pre><p>The function funcScope() defined its own “scope” variable and manipulated it to concatenate the “ scope” string and it did not affect the outer global namespace variable binding. Again, this is to iterate that namespaces create a protected environment but also establishes a scope.</p><p>Another important idea to understand is that of lexical scoping. In short, this means that functions refer to the variable bindings that were in place when they were defined, and not the variable bindings that are in place when they are invoked. So, an example:</p><pre>let scope = &quot;global&quot;;</pre><pre>function funcScope(scope) {<br>  console.log(scope);<br>}</pre><pre>funcScope(); // =&gt; undefined</pre><p>By default when a parameter is defined or declared, like any other variable, JavaScript assigns it the value of “undefined”. When funcScope() is invoked, it referred to variable binding that was present during its definition, its own “scope” variable, the parameter. Because the value was left at the default value or “undefine”, it referred to that variable binding when invoked.</p><pre>let scope = &quot;global&quot;;</pre><pre>function funcScope() {<br>  console.log(scope);<br>}</pre><pre>funcScope(); // =&gt; global</pre><p>In this example, because the only “scope” variable binding present during the funcScope() definition is the global namespace “scope” variable binding, it refers to that value when invoked and logs it.</p><p>Functions are able to keep tract of the variable bindings present during their definitions which help them to refer back to those bindings when invoked. The combination of a function, it’s block code and its reference to the variable bindings, or the scope in which it is defined, is known as a <em>closure</em>.</p><pre>let scope = &quot;global&quot;;</pre><pre>function outerFunc() {<br>  let scope = &quot;outerFunc&quot;;<br>  return () =&gt; console.log(scope);<br>}</pre><pre>outFunc()(); // =&gt; outerFunc</pre><p>This example demonstrates a closure, which is the environment is the combination of the inner function’s code block which logs to the console and the variable bindings present during the functions definition. The return inner function maintain a reference to its scope, when it is defined, which includes the “scope” variable binding to the value “outerFunc.” And so, despite the fact that when the inner function is invoked, there exists a “scope” variable binding to “global”, it will log the variable binding value present during its definition.</p><p>Before JavaScript had a built-in system for modules, closures were used to create them. In fact closures are foundational to functional programming which is how modern React is carried out. Understanding closures help to carry out many powerful techniques, including protecting data from outside manipulation. To read more about closures, the link below which provides great documentation, and helps to get you started.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Closures - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd14d1c2cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Parameters and Arguments]]></title>
            <link>https://medium.com/swlh/javascript-parameters-and-arguments-ade31df9fbac?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade31df9fbac</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 03:20:52 GMT</pubDate>
            <atom:updated>2021-02-01T08:56:27.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>In programming, functions are foundational. They modularized logic which creates reusability and cleaner code. Sometimes, functions are able to carry out their logic with outside input known as arguments. Arguments are then used within a function’s body to compute a return value. Functions are able to utilize arguments through function defined local variables called parameters. JavaScript functions also allow many ways to work with parameters and arguments, some of which are not too familiar.</p><p>When working with parameters and arguments, the simplest variation is a function that expects a single argument.</p><pre>function greet(greeting) {<br>  console.log(greeting);<br>}</pre><pre>greet(&quot;hello&quot;); // =&gt; hello</pre><p>However, because JavaScript functions do not check for argument types, or if an argument was passed to a function that expected one, unexpected results can happen.</p><pre>greet(); // =&gt; undefined<br>greet(3); // =&gt; 3</pre><p>To prevent these sort of situations from happening, we can define what are known as parameter default values. The default values allow to provide an adequate argument to the function invocation in the event that a function is invoked without a necessary argument.</p><pre>function greet(greeting = &quot;hello&quot;) {<br>  console.log(greeting);<br>}</pre><pre>greet(); // =&gt; hello<br>greet(&quot;good morning&quot;); // =&gt; good morning</pre><p>In the event of passing an argument of a data type not intended for the parameter, we can manually check for the type and produce an error message if the wrong data type is passed.</p><pre>function greet(greeting = &quot;hello&quot;) {<br>  if (typeof greeting !== &quot;string&quot;) {<br>    throw new Error(&quot;greet() argument is not a string&quot;);<br>  }<br>  console.log(greeting);<br>}</pre><pre>greet(3); // =&gt; Error: greet() argument is not a string<br>greet(&quot;hi&quot;); // =&gt; hi</pre><p>This example shows how type checking can be accomplished with JavaScript but it is more commonly handled with a language extension called TypeScript which adds type checking functionality to JavaScript.</p><p>JavaScript functions also allows for parameter default values to be computed by variables, function invocations and even other parameters. So for example:</p><pre>const myObj = {};<br>function greet(greeting = &quot;sup&quot;) { <br>  if (typeof greeting !== &quot;string&quot;) {<br>    throw new Error(&quot;greet() argument is not a string&quot;);<br>  }<br>  console.log(greeting);<br>  return greeting;<br>}</pre><pre>function newPerson(obj = myObj, greeting = greet()) {<br>  obj.greeting = () =&gt; console.log(greeting);<br>  return obj;<br>}</pre><pre>// provide no arguments<br>const firstPerson = newPerson();<br>console.log(firstPerson); // =&gt; { greeting: [Function (anonymous)] }<br>firstPerson.greeting(); // =&gt; sup</pre><p>The example show that the newPerson() function sets the “myObj” variable’s value as the default value for the parameter “obj” and sets the default parameter value of the “greeting” argument to the return value of greet(). In addition, parameters can be used to set other parameters such as in the following example.</p><pre>const rectangle = (width, height = width * 2) =&gt; ({ width, height });</pre><p>The function expression mandatorily receives one argument, “width” which is then optionally used to calculate the “height” property on the returned rectangle object. If a “height” argument is provided, then that argument is used instead.</p><p>Another feature of parameters and arguments in JavaScript can be seen when a function is passed more arguments than defined parameters. In that case, the excess arguments are simply ignored, as long as the defined parameters were provided with values or arguments.</p><pre>function eat(food) {<br>  console.log(&quot;eating &quot; + food);<br>}</pre><pre>eat(&quot;eggs&quot;, &quot;toast&quot;); // =&gt; eating eggs</pre><p>Actually, the remaining arguments are not simply ignored although it seems that way. Within every function declaration body, there is another hidden value, aside from the others which were mention in my previous blog <a href="https://codenameuriel28.medium.com/understanding-the-invocation-context-in-javascript-266556674b11">“Understanding the Invocation Context in JavaScript”</a> , that is the “arguments” array-like object. The “arguments” object is an iterable object that contains every argument passed to the function. It stores the arguments using numerical, array-like index and can be iterated over using array iterators like the for-of loop.</p><pre>function eat(food) {<br>  console.log(&quot;eating &quot; + food);<br>  console.log(arguments);<br>}</pre><pre>eat(&quot;eggs&quot;, &quot;toast&quot;);<br>// =&gt; eating eggs<br>// =&gt; { &#39;0&#39;: &#39;eggs&#39;, &#39;1&#39;: &#39;toast&#39; }</pre><p>The “arguments” keyword is reserved and cannot be used as a parameter name or within the function body as a local variable. This feature was designed to allow an arbitrary amount of arguments when invoking a function without having to specify an arbitrary amount of parameters in the function definition. It is also an outdated way to utilize multiple arguments and is less efficient than the modern rest parameters method.</p><pre>function eat(...food) {<br>  for (let item in food) {<br>    console.log(&quot;eating &quot; + item);<br>  } <br>  // log the rest parameter<br>  console.log(food);<br>}</pre><pre>eat(&quot;eggs&quot;, &quot;toast&quot;, &quot;bacon&quot;);<br>// =&gt; eating eggs<br>// =&gt; eating toast<br>// =&gt; eating bacon<br>// =&gt; [ &#39;eggs&#39;, &#39;toast&#39;, &#39;bacon&#39; ]</pre><p>In the example above, the “…” special syntax in the “food” parameter definition is used to indicate that an arbitrary amount of arguments will be accepted when invoking the function. It also aggregates all the arguments passed to the function within an actual array, unlike the array-like object with “arguments”. It is useful to note that when using the “…” notation within a function definition, it establishes the rest parameters array within the function body and which will default to an empty array in case no arguments are provided. Because of this, the rest parameter does not require a default value, it will default to the empty array.</p><p>A common way to utilize the rest parameter is with the spread operator which is a point of confusion because it share the same “…” special syntax. For example:</p><pre>function max(...numbers) {<br>  // provide a starting point<br>  let maxVal = -Infinity;<br>  for (let num of numbers) {<br>    typeof num === &quot;number&quot; ? continue : throw new Error(&quot;max()   arguments must be numbers&quot;);</pre><pre>    maxVal = num &gt; maxVal ? num : maxVal;<br>  }<br>  return maxVal;<br>}</pre><pre>const nums = [1, 2, 3];<br>max(...nums); // =&gt; 3</pre><p>In this example, the function is defined with a rest parameter, accepting an arbitrary amount of integer arguments. The function also ensures that integers are provided as arguments to produce an appropriate return value for the “maxVal”. When the max() function is invoked, the argument provided is spread, in this case the array “nums” has its elements spread as arguments and gathered by the rest parameter “…numbers”.</p><p>In addition to spreading out arguments or gathering them into a single array, arguments can be destructured or have their properties extracted into variables which can then be used within the function.</p><pre>function multiply({ num1, num2 }) {<br>  console.log(num1 * num2);<br>}</pre><pre>const numbers = { num1: 3, num2: 5 };<br>multiply(numbers); // =&gt; 15</pre><p>This example is shows a function definition with a destructuring syntax to define the parameters of the function. The function expects an object as an argument containing a “num1” and “num2” property within it. It then logs the product of the two properties. Also, the two properties expected are expressed in the destructuring syntax using variables of the same name as the properties of the expected argument object. Other variables can be used to represent the expected properties by using another syntax. But finally, the multiply() function is then invoked with the “numbers” object containing the two expected properties.</p><pre>// rename expected properties for function body implementation<br>function multiply({ num1: x, num2: y }) {<br>  console.log(x * y);<br>}</pre><pre>const numbers = { num1: 3, num2: 5 };<br>multiply(numbers); // =&gt; 15</pre><pre><br>// destructuring works with arrays as well<br>function divide([ ele1, ele2 ]) {<br>  console.log(ele2 / ele1);<br>}</pre><pre>const nums = [3, 15];<br>divide(nums); // =&gt; 5</pre><p>Unlike destructuring objects which expect exact property names, destructuring arrays do not require exact names so elements can be represented with any variable name.</p><p>With that, you can see how dynamic functions can be and we have only focused on their parameters and arguments. These techniques can assist in writing more efficient and cleaner functions. To learn more about JavaScript’s parameters and arguments, Mozilla has excellent documentation.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">The arguments object - JavaScript | MDN</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade31df9fbac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/javascript-parameters-and-arguments-ade31df9fbac">JavaScript Parameters and Arguments</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Invocation Context in JavaScript]]></title>
            <link>https://codenameuriel28.medium.com/understanding-the-invocation-context-in-javascript-266556674b11?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/266556674b11</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 18:53:28 GMT</pubDate>
            <atom:updated>2021-01-19T18:53:28.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>In JavaScript, functions are objects which provide a modular way to define a set of procedures or operations that can be used many times within a program. By using functions, code is abstracted away reducing potential repetitive logic and helping to maintain legibility. But when working with functions, it is important to know a few things about them, like the fact that they have access to many values that affect how the function can be used. For example, a common value that functions have access to are parameters, which are used as local variables within the code block of the function. Parameters are used to store input data which are then used within the function’s code block. Another not so common value that functions have access to are same name variables used to store the function object itself. This value is useful in recursion, but simply put, if a function has a name, then the function’s code block will implicitly contain a variable of the same name storing the function object which can be used to reference itself.</p><pre>// function is named &quot;factorial&quot;<br>function factorial(x) {<br>  if (x &lt;= 1) return 1;<br>  // &quot;factorial&quot; variable contain the function object<br>  else return x * factorial(x-1);<br>}</pre><p>The example above demonstrates how the variable with the same name as the function is used within the function’s body to recurse or call the function object.</p><p>Another important value that functions have access to is what is known as the function’s invocation context, or the “this” keyword of the function object. Depending on where the function is defined, the “this” keyword for the function will have different values. When functions are defined within an object, as properties, they are known as methods. Because a method is defined within the context of a defined object, the invocation context for the method refers to the defined object.</p><pre>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() { console.log(this.name + &quot; howls!&quot;); } <br>};</pre><pre>wolf.howl(); // =&gt; Balto howls!</pre><p>In this example, the howl() method, or function defined as a property within the “wolf” object accesses its invocation context, “this” keyword, which refers to the object it is defined within. The howl() method then logs to the console the name of the object “this.name” or “Balto” and concatenates the string “ howls!”. However, issues do occur when a nested function is thought to share the same “this” as the outer level method. For example:</p><pre>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() { <br>    function gaze() {<br>      console.log(this.name + &quot; gazes at the moon&quot;);<br>    } <br>    console.log(this.name + &quot; howls!&quot;);<br>    gaze();<br>  }    <br>};</pre><pre>wolf.howl(); <br>// =&gt; Balto howls!<br>// =&gt; undefined gazes at the moon</pre><p>In this example, the nested gaze() function within the howl() method is trying to utilize its invocation context as if it were the same as the howl() method invocation context. However, because the gaze() function is defined in the context of another function, the howl() method’s “this”, depending on whether the code is executing in strict mode or non-strict mode, will be either undefined or the global object.</p><p>Prior to arrow functions, many workarounds were used for this issue which consisted of storing the outer level function or method’s “this” in a variable to be used within any nested functions. Another workaround included expressing the nested function as an IIFE or immediately invoked function expression and binding the “this” of the outer level method. For example:</p><pre>// using bind() method with IIFE<br>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() { <br>    const gaze = (function() {<br>      console.log(this.name + &quot; gazes at the moon&quot;);<br>    }).bind(this);<br> <br>    console.log(this.name + &quot; howls!&quot;);<br>    gaze();<br>  }    <br>};</pre><pre>wolf.howl();<br>// =&gt; Balto howls!<br>// =&gt; Balto gazes at the moon</pre><pre>// without using IIFE<br>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() { <br>    function gaze() {<br>      console.log(this.name + &quot; gazes at the moon&quot;);<br>    }<br> <br>    console.log(this.name + &quot; howls!&quot;);<br>    gaze.bind(this)();<br>  }    <br>};</pre><pre>wolf.howl();<br>// =&gt; Balto howls!<br>// =&gt; Balto gazes at the moon</pre><pre>// storing &quot;this&quot; inside variable<br>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() { <br>    const self = this;</pre><pre>    function gaze() {<br>      console.log(self.name + &quot; gazes at the moon&quot;);<br>    }</pre><pre>    console.log(this.name + &quot; howls!&quot;);<br>    gaze();<br>  }    <br>};</pre><pre>wolf.howl();<br>// =&gt; Balto howls!<br>// =&gt; Balto gazes at the moon</pre><p>In these examples, you can see mainly how nested functions were able to maintain the invocation context of the outer method in which they were defined. However, arrow functions simplified this problem due to the value of their “this”. Unlike functions defined with the “function” keyword, arrow functions do not define their own “this” and instead inherit the invocation context of the environment in which they are defined, like an object’s method. So using the example above:</p><pre>const wolf = {<br>  name: &quot;Balto&quot;,<br>  howl() {<br>    const gaze = () =&gt; (<br>      console.log(this.name + &quot; gazes at the moon&quot;)<br>    );</pre><pre>    console.log(this.name + &quot; howls!&quot;);<br>    gaze();<br>  }    <br>};</pre><pre>wolf.howl();<br>// =&gt; Balto howls!<br>// =&gt; Balto gazes at the moon</pre><p>Because the arrow function expression gaze() does not define its own “this” and instead inherits the outer method howl() invocation context, it can refer to the wolf object and access its name property. This makes arrow functions great for use as callbacks in order to maintain the desired “this” but it also makes them the wrong choice for defining methods. For example:</p><pre>const wolf = {<br> ...<br> bark: () =&gt; { console.log(this.name + &quot; refuses to bark&quot;); }<br>};</pre><pre>wolf.bark();</pre><pre>// strict mode<br>// =&gt; undefined refuses to bark</pre><p>Because the arrow function is defined within the context of the wolf object and not within a method with a defined “this” that points to the wolf object, it inherits an invocation context that points to the global object in non-strict mode, or undefined in strict mode.</p><p>In general, arrow functions are the modern approach if you need to include some nested functions, perhaps helper functions that require access to the invocation context of the outer method. It is also useful to understand how the “this” differs depending on the context of the function’s definition, and the various approaches that aid in guarding against referring to the unintended “this”. For example, if working in React, arrow functions are highly useful when passed to event listeners, especially if they need to access the instance’ state. So with that, next time you’re working with the “this” keyword of a function, remember the context of the function’s definition and avoid any frustrations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=266556674b11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending Objects in JavaScript, Immutably]]></title>
            <link>https://medium.com/swlh/extending-objects-in-javascript-immutably-7e7f28c2458d?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7f28c2458d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 03:06:30 GMT</pubDate>
            <atom:updated>2021-01-18T20:16:48.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>Working with data can take two forms, either some work is done directly to it resulting in the data being fundamentally changed or it can be copied, and then have some work done to the copy. Most, if not all of the time, working with data in an immutable way is the preferred way because it increases the efficiency of being able to follow the flow of data and the changes made to it. For example, the React library uses this concept of maintaining immutability when working with state. The state of a component, or the data that describes the component at any given time, is only updated in a manner that keeps the old state intact. So, in order to begin working with data immutably, it must first be copied. For example:</p><pre>let obj = { x: 1, y: 2, z: 3 };<br>let copy = {};<br>for (let key of Object.keys(obj)) {<br>  obj[key] = copy[key];<br>}</pre><p>In this example, we are first copying the properties from the “obj” object into the “copy” object. Of course, there are other ways to do this, and sometimes depending on the library or framework being used, there are even built-in methods that assist with this need. JavaScript provides a dedicated way to extend or copy properties from one object to another, with the Object.assign() static method. So let’s see how that method works:</p><pre>let obj = { x: 1, y: 2, z: 3 };<br>let copy = {};<br>Object.assign(copy, obj);</pre><p>Using the Object.assign() static method, we provided two object arguments, the first is considered the “target” object which will receive all the properties from the second argument, the “source” object. So in this case, the properties from the “obj” object are copied into the “copy” object. If the “copy” had properties that shared the same name, then those properties would be overwritten.</p><pre>let target = { prop: &quot;target prop&quot; };<br>let source = { prop: &quot;source prop&quot;, anotherProp: &quot;anotherSourceProp&quot; };<br>Object.assign(target, source);</pre><pre>target // =&gt; { prop: &quot;source prop&quot;, anotherProp: &quot;anotherSourceProp&quot; };</pre><p>Any property names shared with the source object are overwritten. The Object.assign() static method also takes additional source objects, with each overwriting the properties from the previous source object argument.</p><pre>let obj = { a: 1, b: 2 };<br>let sourceOne = { a: 2, c: 3 };<br>let sourceTwo = { a: 3, b: 4 };<br>Object.assign(obj, sourceOne, sourceTwo);<br>obj // =&gt; { a: 3, b: 4, c: 3 };</pre><p>Another and more modern way to extend an object is using the spread operator … which provides a short-cut way to iterating and aggregating the values of a data structure into another specified structure.</p><pre>let obj = { a: 1, b: 2 };<br>let newObj = {...obj}; //=&gt; { a: 1, b: 2 }</pre><pre>// another example<br>let obj = { a: 1, b: 2 };<br>let sourceOne = { a: 2, c: 3 };<br>let sourceTwo = { a: 3, b: 4 };<br>let newObj = {...obj, ...sourceOne, ...sourceTwo};<br>newObj // =&gt; { a: 3, b: 4, c: 3 }</pre><p>Just like in the example using Object.assign(), using the spread operator allows the copying of properties, and overwriting of same name properties. The last object that is spread into the final object will overwrite any properties with the same name that came before it, so order matters.</p><p>So far, extending objects is relatively simple to do given the tools JavaScript provides. However, going back to the example with React, whether updating state, or extending an object, these updates, or copies are only carried out shallowly. Shallow copies are made when properties that reference primitive data types, such as numbers, strings, booleans, and so on, are copied. If a property points to a reference data type such as an object or an array, then the techniques used above to extend an object will not produce an entirely, or deeply copied object. For example:</p><pre>const obj = { a: 1, b: 2, c: { d: 3 } };<br>const shallowCopy = {...obj};<br>obj.c; // =&gt; { d: 3 }<br>shallowCopy.c; // =&gt; { d: 3 }</pre><pre>obj.c = { d: 5 };<br>obj.c; // =&gt; { d: 5 }<br>shallowCopy.c; // =&gt; { d: 5 }</pre><p>In the “shallowCopy” object, each property was recreated and assigned the same value as the values within the original “obj” object. But, because the object assigned to property “c” is only a reference to an object in memory, the same reference was also assigned to the new property within “shallowCopy.” Therefore, any changes made to the original “c” property, would affect the “c” property in the new “shallowCopy” object, and vice-versa. In order to deeply copy a data structure, any potential nesting of reference type properties must be accounted for.</p><pre>const original = {<br>  x:4,<br>  y: 5,<br>  z: 6,<br>  obj: {<br>    a: 23,<br>    b: {<br>      name: &quot;inner&quot;,<br>      another: {<br>        val: 38<br>      }<br>    }<br>  },<br>  arr: [<br>    1, 2, 3, [<br>      9, 10<br>    ]<br>  ]<br>};</pre><pre>// define a function that will search for reference type properties and copy them returning a deep copy</pre><pre>function deepCopy(obj) {<br>  const copy = {};<br>  const isArray = val =&gt; Array.isArray(val);<br>  const isObject = val =&gt; typeof val === &quot;object&quot; &amp;&amp;   !Array.isArray(val);</pre><pre>  function deepCopyArray(arr) {<br>    return Array.from(arr, ele =&gt; {<br>      if (isObject(ele)) {<br>        return deepCopy(ele);<br>      } else if (isArray(ele)) {<br>        return deepCopyArray(ele);<br>      } else return ele;<br>    });<br>  }</pre><pre>  for (let [k,v] of Object.entries(obj)) {<br>    if (isObject(v)) {<br>      copy[k] = deepCopy(v);<br>    } else if (isArray(v)) {<br>      copy[k] = deepCopyArray(v);<br>    } else {<br>      copy[k] = v;<br>    }<br>  }<br>  return copy;<br>}</pre><pre>// deeply copy original object</pre><pre>const newObj = deepCopy(original);<br>original.obj.b.name = &quot;original name&quot;;<br>original.obj; // =&gt; { a: 23, b: { name: &quot;original name&quot;, another: {<br>  val: 38 }}};<br>newObj.obj; // =&gt; { a: 23, b: { name: &quot;inner&quot;, another: { val: 38    }}};</pre><pre>newObj.arr[3] = 4;<br>newObj.arr; // =&gt; [1, 2, 3, 4];<br>original.arr; // =&gt; [1, 2, 3, [9, 10]]</pre><p>With this implementation, iterating over primitive data type properties on the first level are simply copied into the new object. However, when a property is identified as an array or an object, then the function recursively calls itself or a helper function, which in return recursively ensures the return of a deeply copied reference type object. After deeply copying the “original” object, changing any values to its reference type properties do not alter the new deep copy, “newObj”, and vice-versa.</p><p>Understanding that working with data immutably undertakes potentially complicated processes like copying nested properties is important. Keeping immutable data helps the debugging process by maintaining clarity with the data flow and how it changes given various processes. JavaScript provides many ways to extend and maintain immutability but further steps are needed to ensure thorough data replication. To learn more about the pros of data immutability, you can give the article below a read.</p><p><a href="https://www.geeksforgeeks.org/why-is-immutability-so-important-in-javascript/">https://www.geeksforgeeks.org/why-is-immutability-so-important-in-javascript/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7f28c2458d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/extending-objects-in-javascript-immutably-7e7f28c2458d">Extending Objects in JavaScript, Immutably</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Objects Iterable in JavaScript]]></title>
            <link>https://medium.com/swlh/making-objects-iterable-in-javascript-252d9e270be6?source=rss-157b4a09debc------2</link>
            <guid isPermaLink="false">https://medium.com/p/252d9e270be6</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Uriel Rodriguez]]></dc:creator>
            <pubDate>Tue, 05 Jan 2021 04:45:35 GMT</pubDate>
            <atom:updated>2021-01-11T08:20:54.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ahbWjp_g9hqhaTDSJOL1Q.png" /></figure><p>Usually when we think of a data structure being iterable, we think of arrays and strings. JavaScript provides many ways to iterate over an array or string, ranging from the standard for-loop to more modern variation like the ES6 for/of loop. However, because objects are not inheritently iterable, JavaScript has defined the for/in loop which is specifically for iterating over objects. The for/in loop iterates over each property name or key in the object, by which then you could access the value. The following examples show how an object can be iterated over using both the for/of and the for/in loop.</p><pre>const obj = { someProp: &quot;someValue&quot;, anotherProp: &quot;anotherValue&quot; };</pre><pre>for (let key of Object.keys(objKeys)) {<br>  console.log(obj[key]);<br>}</pre><pre>for (let key in obj) {<br>  console.log(obj[key]);<br>}</pre><p>These examples show the more common ways an object can be iterated over. If there wasn’t a concern or need to access an object’s property name, then the for/of loop could be utilized in with the static method entries() which provides an iterable structure, an array of arrays in which the values could be accessed directly.</p><pre>const obj = { someProp: &quot;someValue&quot;, anotherProp: &quot;anotherValue&quot; };</pre><pre>for (let [k, v] of Object.entries(obj)) {<br>  // iterate over the returned array from Object.entries <br>  // destructure the current element, an array with two elements,  the key and value of the object &quot;obj&quot;</pre><pre>  console.log(v);<br>}</pre><p>In this manner, we can iterate over the object and only work with the values and avoid having to write out the object property access notation. These examples show how to iterate over objects, but the objects were not iterated over directly as arrays, or strings would have. For example:</p><pre>const arr = [1, 2, 3];<br>const str = &quot;string&quot;;</pre><pre>for (let num of arr) {<br>  console.log(num);<br>}</pre><pre>for (let char of str) {<br>  console.log(char);<br>}</pre><p>For a data structure to be considered iterable, the for/of loop must be able to iterate over it. This example shows how the array and string were directly iterated over, as opposed to the examples with the object which only worked with the for/of loop using a returned array from Object.keys or Object.entries. In order to make objects iterable, we need to first understand how iteration work in JavaScript.</p><p>When an iterable data structure, like an array, string, array of arrays, and so on, are iterated over with the for/of loop, a special method within their definition is invoked, the [Symbol.iterator]() method. First, to demystify this particular syntax, the brackets around the “Symbol.iterator” is a computed property name, or a value that is returned when JavaScript accesses “Symbol.iterator”. So the method name is computed by JavaScript, and the returned value is the method’s name that is used, but which is not known in order to hard code it. The presence of this method is what makes a data structure iterable, and it does so because the method returns the iterator interface.</p><p>Passing an array to the for/of loop invokes the [Symbol.iterator]() method which returns the iterator interface, or an object which accesses the values of the iterable data structure, the array. The iterator object, the “iterator” is what iterates over the data structure by invoking a next() method which returns another object containing the desired value, or element in the case of an array. For example:</p><pre>let arr = [1, 2, 3];</pre><pre>for (let num of arr) {<br>  console.log(num);<br>}</pre><pre>// under the hood<br>arr[Symbol.iterator]();</pre><pre>// returns an iterator - an object<br>let arrIterator = arr[Symbol.iterator]();</pre><pre>// the iterator object or interface invokes a next method<br>arrIterator.next(); </pre><pre>// returns another object - iteration result containing the element<br>arrIterator.next(); //=&gt; { value: 1, done: false }</pre><pre>// the &quot;value&quot; property on the returned iteration result object is assigned to the &quot;num&quot; variable within the for/of loop<br>num = arrIterator.next().value;<br>console.log(num);</pre><p>When the array is passed to the for/of loop, it triggers the process above. The actual iteration is performed by the returned iterator object from the [Symbol.iterator]() method. The iterator invokes the next() method and the iterator result’s value property is then logged. The other property within the iterator result, the “done” property specifies whether the iteration is complete, or if there are no longer any values to return.</p><p>We can now apply this understanding to making objects iterable. The most important thing that is needed is defining the [Symbol.iterator]() method within the object, because this is what triggers the iterator.</p><pre>let obj = { <br>  prop: &quot;value&quot;, <br>  someProp: &quot;someValue&quot;, <br>  anotherProp: &quot;anotherValue&quot;,<br>  [Symbol.iterator]() {<br>    return Object.values(this);<br>  }<br>};</pre><pre>for (let val of obj) {<br>  console.log(val);<br>}</pre><pre>// alternative - simulates a for/in loop<br>let obj = {<br>  ...<br>  [Symbol.iterator]() {<br>    return Object.keys(this);<br>  }<br>};</pre><pre>for (let key of obj) {<br>  console.log(obj[key]);<br>}</pre><p>By defining the special iterator method, we have made the object iterable. It works directly with with for/of loop and without having to utilize a return from another method invocation like Object.keys, Object.values, Object.entries, and so on. When the object is iterated, the [Symbol.iterator]() is invoked and an array is returned which invokes</p><p>A more involved way to make an object iterable is to redefine the iterator method by returning a custom iterator object and definining a next() method within it.</p><pre>let obj = { <br>  prop: &quot;value&quot;, <br>  someProp: &quot;someValue&quot;, <br>  anotherProp: &quot;anotherValue&quot;,<br>  [Symbol.iterator]() {<br>    let values = Object.values(this);<br>    let index = 0;<br>    return {<br>      next() {<br>        if (index &lt; values.length) {<br>          let val = values[index];<br>          index++;<br>          return { value: val, done: false };<br>        } else return { done: true };<br>      }<br>    };<br>  }<br>};</pre><p>This approach takes advantage of closures, by which the iterator object accesses the scope of the [Symbol.iterator]() method after invocation and uses its defined variables “values” and “index” in its own method body.</p><p>After following these examples, the main takeaway is that JavaScript uses a specific mechanism to carry out the iteration process. It all begins with invoking the [Symbol.iterator]() method on the data structure, and is followed by the returned iterator object invoking its defined next() method. In understanding this mechanism, you can create your own data structures, or classes of objects that are iterable and return specific values from the iterative process. To learn more about the iteration mechanism, I recommend reading <em>Eloquent JavaScript </em>and <em>JavaScript The Definitive Guide.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252d9e270be6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/making-objects-iterable-in-javascript-252d9e270be6">Making Objects Iterable in JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>