<?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>DEV Community: Rodolfo Machirica</title>
    <description>The latest articles on DEV Community by Rodolfo Machirica (@rmachirica).</description>
    <link>https://dev.to/rmachirica</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%2F773386%2F117e86c4-fcfb-41d5-8568-31235a54ceb0.jpeg</url>
      <title>DEV Community: Rodolfo Machirica</title>
      <link>https://dev.to/rmachirica</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rmachirica"/>
    <language>en</language>
    <item>
      <title>Asynchronous Coding in JavaScript</title>
      <dc:creator>Rodolfo Machirica</dc:creator>
      <pubDate>Mon, 14 Feb 2022 14:59:14 +0000</pubDate>
      <link>https://dev.to/rmachirica/asynchronous-coding-in-javascript-2p93</link>
      <guid>https://dev.to/rmachirica/asynchronous-coding-in-javascript-2p93</guid>
      <description>&lt;p&gt;&lt;a href="https://media.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%2Fh4bjuxfrnnfcdcrra261.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fh4bjuxfrnnfcdcrra261.png" alt="Synchronous vs asynchronous operations"&gt;&lt;/a&gt;In this post we are going to explore and learn some concepts about asynchronous programming. We will talk about what asynchronous coding is and the importance of it in web development, and async operations using callbacks.&lt;/p&gt;

&lt;p&gt;JavaScript is a synchronous programming language. The execution of a JavaScript program occurs in a single thread, line by line, without skipping any line of code. Single threadiness, however, exposes an issue: different lines or blocks of code in functions take different amount of time to run, thus, there would be a long wait time when time expensive operations are reached. So, this is where asynchronous approach come in to save the day! Asynchronous JavaScript makes possible for multiple and complex actions to happen while the program is running but without blocking the main thread.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Asynchronous coding
&lt;/h2&gt;

&lt;p&gt;According to Javin Paul on Top 5 Programming languages for Web development in 2022, Jan 13, 2021, on medium.com, most web development is done with JavaScript. Asynchronous coding is particularly relevant for frontend development. The problematic of time lag (mentioned in the paragraph above) that occurs when heavy duty programs are in execution or a request to an API is made, in the context of web development, is very important as it affects the user experiences with the UI. A user considers a website to be slow if the response for any action they perform on it takes more than 100ms, said Divyanshu Bhatnagar in a blog post titled How to Optimize Long Tasks (Blocking Javascript) in Browsers on, Jul 11, 2021, on medium.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling asynchronous events
&lt;/h2&gt;

&lt;p&gt;In JavaScript, there are various ways in which code can run asynchronously. The most commonly used in these recent years are: &lt;strong&gt;Promises and Async/await&lt;/strong&gt;; but for matters of legacy, we are going to talk about the old and classic way of handling asynchronous code - &lt;strong&gt;callbacks.&lt;/strong&gt; &lt;br&gt;
Callback functions which simply in this context refer to functions that are passed into other functions as parameters or arguments, with the purpose of running when an event associated with that callback is initiated or some operation finishes. See bellow an example of an asynchronous code using the callback approach:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const btn = document.createElement('&amp;lt;button&amp;gt;&amp;lt;/button&amp;gt;');
  btn.textContent = "Click to register";
  btn.addEventListener.on("click", ()=&amp;gt;{
    console.log("Welcome, you are now a member");
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;addEventListener is our function that is taking in an event of type "click" and an anonymous callback function that sits there waiting for the event "click" to occur and then it executes and returns the result of that operation to the addEventListener function which then gives the response back to the user. &lt;br&gt;
The example above is a typical occurrence in webpage or interactive UI applications where users can perform a varied set of actions from clicking buttons, making requests to a server for data, etc. Here is an example of an asynchronous program using a callback for requesting data from a server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  //we create a variable to hold an image tag
  const $img = $('img');
  // we make our a.jax call 
  $.ajax({
    url: "http://fakeimageapi.img", 
    dataType: {json: true},
    //callback to run if the request is successful
    success: ((data) =&amp;gt; { 
    $img.append(result.url);
   }),
    error: () =&amp;gt; {console.log ("image not found")}
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Callbacks are great and they help us run programs asynchronously. However, they present a major drawback: in cases of nested callbacks, which does happen, they can confuse readers and even the author of the code, and for this reason alone, we have Promises and Async/await, concepts to be covered in the next article. &lt;/p&gt;

&lt;h2&gt;
  
  
  conclusion
&lt;/h2&gt;

&lt;p&gt;Asynchronous coding is extremely important in the web development as it addresses the issue of UI freezing caused by the complex and time expensive operations.   &lt;/p&gt;

&lt;p&gt;Sources consulted: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://iq.opengenus.org/asynchronous-programming-in-javascript/" rel="noopener noreferrer"&gt;https://iq.opengenus.org/asynchronous-programming-in-javascript/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.i-programmer.info/programming/theory/8864-managing-asynchronous-code-callbacks-promises-a-asyncawait.html" rel="noopener noreferrer"&gt;https://www.i-programmer.info/programming/theory/8864-managing-asynchronous-code-callbacks-promises-a-asyncawait.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.logrocket.com/understanding-asynchronous-javascript/" rel="noopener noreferrer"&gt;https://blog.logrocket.com/understanding-asynchronous-javascript/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://eloquentjavascript.net/11_async.html" rel="noopener noreferrer"&gt;https://eloquentjavascript.net/11_async.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.webucator.com/article/how-to-use-the-callback-function-in-ajax/" rel="noopener noreferrer"&gt;https://www.webucator.com/article/how-to-use-the-callback-function-in-ajax/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee" rel="noopener noreferrer"&gt;https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.twilio.com/blog/asynchronous-javascript-understanding-callbacks" rel="noopener noreferrer"&gt;https://www.twilio.com/blog/asynchronous-javascript-understanding-callbacks&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>asynchronous</category>
    </item>
    <item>
      <title>Passing by Value vs Passing by Reference</title>
      <dc:creator>Rodolfo Machirica</dc:creator>
      <pubDate>Mon, 20 Dec 2021 23:34:19 +0000</pubDate>
      <link>https://dev.to/rmachirica/passing-by-value-vs-passing-by-reference-ili</link>
      <guid>https://dev.to/rmachirica/passing-by-value-vs-passing-by-reference-ili</guid>
      <description>&lt;p&gt;To talk about passing/copying values in JavaScript we need to talk about data types.&lt;br&gt;
JavaScript data types can be grouped into two categories:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Simple data types&lt;/li&gt;
&lt;li&gt;Complex data types&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;
  
  
  Simple data types vs complex data types
&lt;/h3&gt;

&lt;p&gt;The concept of copying/passing data by reference or copying/passing data by value occurs in the face of the difference between these two data types when it comes to assigning variables to variables and data mutation.&lt;/p&gt;
&lt;h4&gt;
  
  
  Copying by value
&lt;/h4&gt;

&lt;p&gt;Primitive data types like strings, numbers, Booleans, undefined, null, BigInt and symbol are copied by value; that is, two different variables holding primitive values cannot have the same memory address. Let us observe the example bellow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myName = "Elijah Gabriel"; // name is pointing at the value "Elijah Gabriel".
let yourName = myName; 
console.log(yourName); //prints =&amp;gt; "Elijah Gabriel", a copy of myName.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see, while yourName and myName hold the same value, they aren't the same thing in memory. myName has a unique memory address and so does yourName, have its own unique memory address.&lt;/p&gt;

&lt;h4&gt;
  
  
  Copying by reference
&lt;/h4&gt;

&lt;p&gt;Unlike primitive types, complex data types like arrays and objects in JavaScript are copied or passed by reference; meaning, two different variable names can point to the same data. When an object intended as an object literal or an array object is created, a reference to that object is created and allocated an address in the memory. So, if you create an object and assign it to a new variable, an object reference will be created and both variables will now be pointing at the reference object in memory address.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let reference = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]; // creates a reference array with a memory address
let refCopy = reference;// now both reference and refCopy are referencing the same array.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Image by Arnav Aggarwal, October 2017.&lt;br&gt;
! &lt;a href="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/norvt1zz9hnxukgyr8tj.png"&gt;diagram showing a referenced data&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;reference and Copy are pointing at the same array (reference) share the same memory address. This allows us to change properties in one objects or entries in one array and the change will be reflected in all variables pointing at the same reference. This is how it would look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;copy.pop();// 
console.log(reCopy) //prints to the console =&amp;gt; ["Monday", "Tuesday", "Wednesday", "Thursday"];
console.log(reference); // prints to the console =&amp;gt; ["Monday", "Tuesday", "Wednesday", "Thursday"];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we could see, all changes made to the variable copy affected the variable reference in the same manner, and it would be true vice-versa. &lt;/p&gt;

&lt;p&gt;Let us look at an example with objects intended as object literal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const users = {
   firstUser : {firstName: "Tinache",
                 lastName: "Sabonete",
      },
  secondUser : { firstName: "Clayde",
                  lastName:  "Magarrafa",
     },                       
};

const usersCopy = users;// both users and usersCopy are pointing at the same object in memory address.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if we change any of the properties in one of the objects, that change will automatically be made in the other object as well, and this is because these two objects share the same reference at this moment. Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;usersCopy.firstUser = "online";
console.log(users);// prints=&amp;gt; {
   firstUser : "online",
  secondUser : { firstName: "Clayde",
                  lastName:  "Magarrafa",
     },                       
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We changed copyUsers, but that change was also reflected on users, and that is because they share a reference.&lt;/p&gt;

&lt;h4&gt;
  
  
  Breaking reference between arrays or object literals.
&lt;/h4&gt;

&lt;p&gt;Here is a way to break a reference: if the copy variable or the variable reference is assigned to a completely new value, then the reference will be broken, and a new reference-to-be will be created for each of the arrays. Now let's see:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;reference = [{weekend: ["Saturday", "Sunday"]}];
console.log(reference);//prints=&amp;gt; [{weekend: ["Saturday", "Sunday"]}].
console.log(copy)// prints =&amp;gt; ["Monday", "Tuesday", "Wednesday", "Thursday"].

users = {age: 23, occupation: "student"}
console.log(usersCopy);// prints=&amp;gt; {
   firstUser : "online",
  secondUser : { firstName: "Clayde",
                  lastName:  "Magarrafa",
     },                       
};// users and usersCopy are now totally different objects and are //stored in different addresses in memory.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The shared reference data between the variable reference and variable copy was broken; copy is still pointing to what the variable reference pointed to when it was created, and now reference points to a totally new value and have a new address in memory. &lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Simple data types variables have unique memory address, therefore they are passed by value and don't create a reference variable. Complex data type variables are passed by reference because during the variable assignment phase a reference object or object array is created, allowing for multiple variables to share a dwelling address in memory!&lt;/p&gt;

&lt;h4&gt;
  
  
  Consulted sources:
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://dustinpfister.github.io/2017/11/13/js-copying-vs-referencing-objects-in-javascript/"&gt;https://dustinpfister.github.io/2017/11/13/js-copying-vs-referencing-objects-in-javascript/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0"&gt;https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.freecodecamp.org/news/understanding-by-reference-vs-by-value-d49139beb1c4/"&gt;https://www.freecodecamp.org/news/understanding-by-reference-vs-by-value-d49139beb1c4/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0"&gt;https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0&lt;/a&gt; .&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
