<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Elchonon Klafter</title>
    <description>The latest articles on Forem by Elchonon Klafter (@klaftech).</description>
    <link>https://forem.com/klaftech</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2295210%2F0d7f90df-bf24-4603-8f2f-09649a5ae9f1.png</url>
      <title>Forem: Elchonon Klafter</title>
      <link>https://forem.com/klaftech</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/klaftech"/>
    <language>en</language>
    <item>
      <title>Using a Directed Acyclic Graph algorithm to predict productivity</title>
      <dc:creator>Elchonon Klafter</dc:creator>
      <pubDate>Mon, 10 Feb 2025 01:00:12 +0000</pubDate>
      <link>https://forem.com/klaftech/using-a-directed-acyclic-graph-algorithm-to-predict-productivity-kkp</link>
      <guid>https://forem.com/klaftech/using-a-directed-acyclic-graph-algorithm-to-predict-productivity-kkp</guid>
      <description>&lt;p&gt;The world is empowered by productivity. Society, financial markets and economics are driven by the measure of it's productive output. Therefore, methods and frameworks designed to maximize output and efficiency by optimizing time management, task prioritization, and workflow are essential for both individuals and organizations striving for success. &lt;/p&gt;

&lt;p&gt;In an era where automation and AI-driven tools are reshaping industries, the application of value-adding algorithms and processes are an important part the future of software. &lt;br&gt;
In the following article I will demonstrate how using a Directed Acyclic Graph (DAG) can accurately predict task completion and project timelines. &lt;/p&gt;

&lt;p&gt;A Directed Acyclic Graph (DAG) represents a structured workflow where tasks (nodes) are connected by dependencies (edges) in a clear, one-way sequence, ensuring no circular dependencies or infinite loops. This structure is crucial in project planning where certain tasks must be completed before others can begin. For example, in software development, "Design UI" must precede "Implement UI," which then must precede "Testing." Since DAGs maintain a topological order, they enable efficient scheduling, parallel execution of independent tasks, and prevention of deadlocks, ensuring smooth and optimized project execution.&lt;/p&gt;

&lt;p&gt;Using the following example dataset:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;tasks = [
    { 
        "id": 1, 
        "name": "Design UI", 
        "days_length": 3, 
        "dependencies": [] 
    },
    { 
        "id": 2, 
        "name": "Implement UI", 
        "days_length": 7, 
        "dependencies": [1] 
    },
    { 
        "id": 3, 
        "name": "Testing", 
        "days_length": 2, 
        "dependencies": [2] 
    },
    { 
        "id": 4, 
        "name": "Project Documentation", 
        "days_length": 4, 
        "dependencies": [] 
    }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To determine the correct order of tasks, we need to perform a topological sort of the tasks which will ensure that dependent tasks are performed before their edges. The first step of the process is to build an adjacency list containing each task and their in-degrees (tasks dependent on it). Once we have this we can begin ordering the schedule of tasks by adding in all tasks without any incoming edges. Using our sample data, this will be &lt;strong&gt;Project Documentation&lt;/strong&gt; and &lt;strong&gt;Design UI&lt;/strong&gt;. Once we have added these to our list, we can iterate over each of those tasks and then add each of their dependencies to our schedule.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from collections import defaultdict, deque
from datetime import datetime, timedelta, time

def topological_sort(self, tasks):
    # Step 1: Calculate in-degrees and construct the adjacency list
    in_degree = defaultdict(int)
    adjacency_list = defaultdict(list) 
    for task in tasks.values():
        # Initialize in-degree for the current task
        in_degree[task.id] = in_degree.get(task.id, 0)
        for dependency in task.dependencies:
            adjacency_list[dependency.id].append(task)
            in_degree[task.id] += 1

    # Step 2: Collect all tasks with in-degree 0 (tasks with no dependencies) for initial adding
    zero_in_degree = deque([task for task in tasks.values() if in_degree[task.id] == 0])

    # Step 3: Process tasks with in-degree 0
    top_order = []
    while zero_in_degree:
        # 3.1: add tasks that have no dependencies
        current_task = zero_in_degree.popleft()
        top_order.append(current_task)

        # Reduce the in-degree of dependent tasks
        # 3.2: process dependent tasks 
        # get list of tasks that point to this task
        for dependent_task in adjacency_list[current_task.id]:
            # subtract -1 to account for the parent task that points to this
            in_degree[dependent_task.id] -= 1  # Step 1: Reduce the in-degree of each dependent task

            # this dependent task has no other dependencies
            if in_degree[dependent_task.id] == 0: # Step 2: Check if this dependent task now has no incoming edges (all depedendencies are resolved)
                zero_in_degree.append(tasks[dependent_task.id]) # Step 3: Add it to the processing queue (tasks with no incoming edges)

    return top_order
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While the code example above will order all tasks in their required order, by adding logic to determine start and end dates for each tasks based on anticipated task length, we can extrapolate the anticipate completion date of each task and accurately predict project timeframe and completion.&lt;/p&gt;

</description>
      <category>algorithms</category>
      <category>flask</category>
      <category>backend</category>
    </item>
    <item>
      <title>Hashing, Salting, Cryptography. Help!</title>
      <dc:creator>Elchonon Klafter</dc:creator>
      <pubDate>Thu, 16 Jan 2025 23:57:36 +0000</pubDate>
      <link>https://forem.com/klaftech/hashing-salting-cryptography-help-53cm</link>
      <guid>https://forem.com/klaftech/hashing-salting-cryptography-help-53cm</guid>
      <description>&lt;p&gt;Writing secure software is essential in today’s cyber landscape, where threats evolve every day. Security considerations must be integrated from the very beginning of the development lifecycle. While larger teams may have dedicated roles like Security Analysts, Engineers, or Penetration Testers, smaller teams without these specializations must still adopt basic measures to safeguard their systems. &lt;br&gt;
In the article below, I will discuss some of the most basic security considerations and concepts that every developer should be familiar with.&lt;/p&gt;

&lt;h2&gt;
  
  
  Identity and Access Management (IAM)
&lt;/h2&gt;

&lt;p&gt;Proper authentication of a user and implementing correct authorization is key to securing a system and to ensure that data is not accessed by unauthorized actors.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authorization Patterns
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Role-Based Access Control (RBAC) &lt;/li&gt;
&lt;li&gt;Attribute-Based Access Control (ABAC) &lt;/li&gt;
&lt;li&gt;Policy-Based Access Control (PBAC) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The best approach often depends on the system requirement and may involve combining multiple patterns for optimal security.&lt;/p&gt;

&lt;h3&gt;
  
  
  Authentication Methods
&lt;/h3&gt;

&lt;p&gt;While proper Access Control ensures that the resources accessed aligns with policy, authentication is key to ensure that the actor is valid. &lt;br&gt;
Common authentication procedures include: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Password authentication &lt;/li&gt;
&lt;li&gt;Single Sign-On (SSO) &lt;/li&gt;
&lt;li&gt;Biometric identifiers such a fingerprint, voice or retina pattern&lt;/li&gt;
&lt;li&gt;Two-Factor Authentication (2FA)&lt;/li&gt;
&lt;li&gt;Hardware or Token-Based authentication&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By combining robust authentication with effective access control, a developer can significantly reduce the risk of unauthorized access and maintain system security.&lt;/p&gt;

&lt;h2&gt;
  
  
  Web Application Security Vulnerabilities
&lt;/h2&gt;

&lt;p&gt;Web applications are powerful tools, but without proper security measures, they can be exploited to compromise user data or perform unauthorized actions. These common vulnerabilities potentially can have a serious impact on your system.&lt;/p&gt;

&lt;h3&gt;
  
  
  CORS (Cross-Origin Resource Sharing)
&lt;/h3&gt;

&lt;p&gt;When improperly configured, this can be exploited to allow unauthorized users to access resources and sensitive data.&lt;/p&gt;

&lt;h3&gt;
  
  
  XSS (Cross-Site Scripting)
&lt;/h3&gt;

&lt;p&gt;By injecting malicious JavaScript code onto an infected website, which is executed in the user's browser, this can potentially steal user's information or perform unauthorized actions on their behalf.&lt;/p&gt;

&lt;h3&gt;
  
  
  CSRF (Cross-Site Request Forgery)
&lt;/h3&gt;

&lt;p&gt;This attack tricks the user into unknowingly running malicious actions on an authenticated website, the attack exploits cookies and session data to perform unauthorized actions on the users behalf. &lt;/p&gt;

&lt;p&gt;These sort of attacks can be easily mitigated by implementing input validation, basic protections and secure coding practices.&lt;/p&gt;

&lt;h2&gt;
  
  
  Data Security
&lt;/h2&gt;

&lt;p&gt;When authentication fails or systems are exploited, safeguards must be in place to preserve the integrity and security of the data.&lt;br&gt;
These can include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;encryption &lt;/li&gt;
&lt;li&gt;timeout and session management &lt;/li&gt;
&lt;li&gt;rate limiting &lt;/li&gt;
&lt;li&gt;audit logs &lt;/li&gt;
&lt;li&gt;Intrusion Detection and Prevention Systems (IDPS) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To summarize, security is a complex multi-faceted responsibilty that must be implemented at every stage. There are many resources and tools that a developer may utilize to keep their systems safe and secure.&lt;/p&gt;

</description>
      <category>devops</category>
      <category>security</category>
      <category>software</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Decorators &amp; Class Property in Python</title>
      <dc:creator>Elchonon Klafter</dc:creator>
      <pubDate>Tue, 17 Dec 2024 16:57:12 +0000</pubDate>
      <link>https://forem.com/klaftech/decorators-class-property-in-python-14fa</link>
      <guid>https://forem.com/klaftech/decorators-class-property-in-python-14fa</guid>
      <description>&lt;p&gt;In this post I will discuss the common usage of function decorators, specifically the class property decorator as well as the difference between using the decorator or the class method directly.&lt;/p&gt;

&lt;h1&gt;
  
  
  Usage
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm4rnodcoi97rdcw1jyzo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm4rnodcoi97rdcw1jyzo.png" alt="Code snippet of class using @property decorator" width="800" height="549"&gt;&lt;/a&gt;Looks familiar, doesn't it?&lt;br&gt;
The ubiquitous &lt;code&gt;@propery&lt;/code&gt; decorator is found everywhere, but how does it actually work?&lt;br&gt;
What are the differences between using &lt;code&gt;@property&lt;/code&gt; or using the &lt;code&gt;property()&lt;/code&gt; class method directly?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcbn0rgrwssf67gyzz0j3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcbn0rgrwssf67gyzz0j3.png" alt="Code snippet of class using property method" width="800" height="583"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  How do decorators even work?
&lt;/h1&gt;

&lt;p&gt;Here's an example of a standard decorator function.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Famrsgnpylywk2oed8sen.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Famrsgnpylywk2oed8sen.png" alt="decorator function example" width="800" height="649"&gt;&lt;/a&gt;&lt;br&gt;
Under the Python hood, the function that calls the decorator (ie. the outer function) gets wrapped with additional code by calling the decorator and passing the outer function as a parameter. The decorator will create a wrapped function with all it's new logic and return it as the value of the outer function.&lt;/p&gt;
&lt;h1&gt;
  
  
  Understanding the property method
&lt;/h1&gt;

&lt;p&gt;The class property method is a built-in Python function that that allows us to define getter, setter and deleter methods for class attributes, and binds them to the class default magic methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def get_my_value(self):
    return self._my_value
my_value = property(get_my_value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is understood by the Python compiler as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __get__(self,obj):
    return self.fget(obj)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Essentially, the &lt;code&gt;property()&lt;/code&gt; method creates an object that acts as a proxy between the attribute name and the underlying data. It therefore allows us to add custom behavior and validation logic that wouldn't be possible with the default magic methods.&lt;/p&gt;

&lt;h1&gt;
  
  
  The @property Decorator
&lt;/h1&gt;

&lt;p&gt;As we see above, the property method allows us to overwrite the default magic method and extent its functionality. We've also demonstrated how a decorator wraps functional logic within a new function. When a getter, setter or deleter method is called with the @property decorator, Python translates it into a call to the &lt;code&gt;property()&lt;/code&gt; method internally, and creates a property object that wraps the method to a function that can overwrite the default magic methods.&lt;/p&gt;

&lt;h1&gt;
  
  
  Decorator Benefits
&lt;/h1&gt;

&lt;p&gt;While we have demonstrated that using the &lt;code&gt;@property&lt;/code&gt; decorator or &lt;code&gt;property()&lt;/code&gt; method are equivalent, the decorator offers a simpler use, and allows the code within the class to be more readable. It is therefore considered best practice and coding convention and the decorator should be used unless there is a specific scenario requirement.&lt;/p&gt;

&lt;h4&gt;
  
  
  Credits:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/python-property-decorator-property/" rel="noopener noreferrer"&gt;https://www.geeksforgeeks.org/python-property-decorator-property/&lt;/a&gt;&lt;br&gt;
&lt;a href="https://ogimagemaker.com/" rel="noopener noreferrer"&gt;Blog post header image generator&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.ray.so/" rel="noopener noreferrer"&gt;Code snippet maker&lt;/a&gt;&lt;/p&gt;

</description>
      <category>python</category>
      <category>oop</category>
      <category>developer</category>
    </item>
    <item>
      <title>Why prop drilling is bad...</title>
      <dc:creator>Elchonon Klafter</dc:creator>
      <pubDate>Tue, 26 Nov 2024 23:39:30 +0000</pubDate>
      <link>https://forem.com/klaftech/why-prop-drilling-is-bad-5b4o</link>
      <guid>https://forem.com/klaftech/why-prop-drilling-is-bad-5b4o</guid>
      <description>&lt;p&gt;&lt;strong&gt;React is cool.&lt;/strong&gt; &lt;br&gt;
Actually all frameworks are cool.&lt;br&gt;
They handle the tedious work of coding and allow developers to focus on optimizing workflows and logic, and deliver better code, even faster. However, along with these benefits come new anti-patterns and pitfalls. &lt;br&gt;
Today I will discuss Prop Drilling in React and why it should be avoided.&lt;/p&gt;
&lt;h2&gt;
  
  
  What is Prop Drilling
&lt;/h2&gt;

&lt;p&gt;Prop drilling is what developers refer to the practice of passing props down through multiple levels of components to reach a deeply nested child component.&lt;/p&gt;

&lt;p&gt;Wait. Isn't passing props down to components the correct usage of React? &lt;br&gt;
Correct, however it becomes an anti-pattern when the props are carried down to very deeply nested components simply because of the component structure.&lt;/p&gt;
&lt;h2&gt;
  
  
  Code Example
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Top-level component
const App = () =&amp;gt; {
  const user = { name: 'John Doe', age: 30 };

  return &amp;lt;Parent user={user} /&amp;gt;;
};

const Parent = ({ user }) =&amp;gt; {
  return &amp;lt;Child user={user} /&amp;gt;;
};

const Child = ({ user }) =&amp;gt; {
  return &amp;lt;Grandchild user={user} /&amp;gt;;
};

const Grandchild = ({ user }) =&amp;gt; {
  return &amp;lt;h1&amp;gt;{`Hello, ${user.name}!`}&amp;lt;/h1&amp;gt;;
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  Why is this a problem?
&lt;/h2&gt;
&lt;h4&gt;
  
  
  Complexity and Reusability
&lt;/h4&gt;

&lt;p&gt;In this basic example, because we are passing down the &lt;code&gt;user&lt;/code&gt; prop through the intermediate components (&lt;code&gt;Parent&lt;/code&gt;, &lt;code&gt;Child&lt;/code&gt;), these components must now explicitly declare and pass down the &lt;code&gt;user&lt;/code&gt; prop. This causes them to loose the inherent benefit of React that allows components to be reusable.&lt;/p&gt;
&lt;h4&gt;
  
  
  Tight Coupling
&lt;/h4&gt;

&lt;p&gt;Additionally, this practice makes components dependent on props that they don't actually use. This is especially apparent when making changes to a prop, the cascading changes inside of each intermediate component causes these updates to be time-consuming.&lt;/p&gt;
&lt;h4&gt;
  
  
  Mistakes Happen
&lt;/h4&gt;

&lt;p&gt;Yes, we all make them sometimes...&lt;br&gt;
As changes to the props requires updating multiple levels of components, this increase the chances of introducing errors into the codebase.&lt;/p&gt;
&lt;h2&gt;
  
  
  Alternatives
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Restructuring Component Tree - Composition vs Inheritance
&lt;/h3&gt;

&lt;p&gt;Prop drilling can occur when using the &lt;em&gt;inheritance&lt;/em&gt; technique which allows each component to inherit, duplicate and extend the higher component's props. However, &lt;em&gt;composition&lt;/em&gt; allows us to write our components to simply pass down their children without knowing them ahead of time. This eliminates the need to specify the props for each intermediate component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = () =&amp;gt; {
  const user = { name: 'John Doe', age: 30 };

  return (
    &amp;lt;Parent&amp;gt;;
      &amp;lt;Child&amp;gt;;
        &amp;lt;Grandchild user={user} /&amp;gt;;
      &amp;lt;/Child&amp;gt;;
    &amp;lt;/Parent&amp;gt;;
  )
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Parent =&amp;gt; (props) {
  return (
    &amp;lt;div className={'parent'}&amp;gt;
     {props.children}
   &amp;lt;/div&amp;gt;
  )
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Context API
&lt;/h3&gt;

&lt;p&gt;Another solution to avoid this anti-pattern is to use the Context API and useContext hook to wrap components that need access to a shared piece of data. However, context in React should ideally only be used for application-wide data, not simply to avoid prop drilling.&lt;/p&gt;

&lt;p&gt;Hopefully, this post helped you understand the issues with prop drilling and gave you a better understanding of proper component structuring in React.&lt;/p&gt;

&lt;p&gt;You can find even more details in the &lt;a href="https://legacy.reactjs.org/docs/composition-vs-inheritance.html" rel="noopener noreferrer"&gt;React documentation&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Arrow Functions =&gt; What's wrong with the regular ones?</title>
      <dc:creator>Elchonon Klafter</dc:creator>
      <pubDate>Mon, 11 Nov 2024 23:22:43 +0000</pubDate>
      <link>https://forem.com/klaftech/arrow-functions-whats-wrong-with-the-regular-ones-252m</link>
      <guid>https://forem.com/klaftech/arrow-functions-whats-wrong-with-the-regular-ones-252m</guid>
      <description>&lt;p&gt;If you are expanding your knowledge of JavaScript and wondering &lt;em&gt;why&lt;/em&gt; they would ever add Arrow Functions in ECMAScript 2015 (ES6), you are not alone. As I built on my knowledge of the language and its intricacies and quirks, I found myself wondering the same thing. In this post, I will lay out the differences, benefits and reasons why it was added and when you should use it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's talk differences
&lt;/h2&gt;

&lt;p&gt;Before arrow functions were introduced, functions had to be declared in the traditional format as below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function add(x, y) {
  return x + y;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or declared as an expression:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const addFunction = function add(x, y) {
  return x + y;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;with the introduction of arrow functions, this can be written as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const addFunction = (x,y) =&amp;gt; x + y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Concise Syntax
&lt;/h2&gt;

&lt;p&gt;From the example above, we can easily see that by using an arrow function and leveraging its implicit return feature, the function can be quickly refactored to a single line. The resulting code is more concise, cleaner, and easier to read, resulting in smoother development and faster debugging.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hoisting
&lt;/h2&gt;

&lt;p&gt;The JavaScript runtime by default will hoist all functions and variable declarations to the top of their scope upon the creation of the Execution Context. For example, within the global scope this ensures that all functions and variables declared will be available to all functions that are later called. However, arrow functions are never hoisted, thereby allowing greater control over the precise location of where a function is executed and the variables that it has access to.&lt;/p&gt;

&lt;h2&gt;
  
  
  Context
&lt;/h2&gt;

&lt;p&gt;Every time a JavaScript function is executed, it creates an Execution Context which includes information about the environment in which the function is running, including the value of &lt;em&gt;this&lt;/em&gt;. While a traditional function gets executed in its own context, an arrow function will always inherit the context of the function which called it. &lt;br&gt;
Using the code below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person {
    constructor(){
        this.name = "George";
        this.greetings = ["Good Morning,","Hello!","Howdy!"];
    }

    printGreetings(){
        this.greetings.forEach(function print(greet){
            console.log(`${greet} ${this.name}`);
        });
    }
}

let person = new Person();
person.printGreetings();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;we would get an error saying: &lt;code&gt;Cannot read property 'forEach' of undefined&lt;/code&gt;, this is because although the &lt;code&gt;printGreetings&lt;/code&gt; function is within the context of the Person class and inherits it's context, nonetheless the forEach function &lt;em&gt;(even though its a built-in JavaScript function)&lt;/em&gt; runs in its own context which doesn't contain the &lt;code&gt;this.name&lt;/code&gt; property, therefore resulting in a lookup error.&lt;br&gt;&lt;br&gt;
However, an arrow function will never run in its own context, and by rewriting the function above using an arrow function...&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;printGreetings(){
    this.greetings.forEach((greet) =&amp;gt; {
        console.log(`${greet} ${this.name}`);
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the result will be as expected&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Good Morning, George
Hello! George
Howdy! George
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;To summarize the benefits of arrow functions; they allow shorter and more concise code; offers implicit return of function block code; doesn't hoist to the top of Execution Context and maintains it's exact location in code; finally, they inherit the context of the function that called it without executing it's own context, allowing a more predictable use of &lt;code&gt;this&lt;/code&gt; keyword.&lt;/p&gt;

&lt;p&gt;Hopefully this post helped you better understand the differences and benefits of traditional functions verses arrow function, and got you one step further in your JavaScript journey!&lt;/p&gt;

&lt;p&gt;Further reading: &lt;br&gt;
&lt;a href="https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/" rel="noopener noreferrer"&gt;Dmitri Pavlutin Blog - Differences between arrow &amp;amp; regular functions&lt;/a&gt;&lt;br&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noopener noreferrer"&gt;MDN Reference Docs - Arrow Functions&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
