<?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: Moisés Fernández Zárate</title>
    <description>The latest articles on DEV Community by Moisés Fernández Zárate (@moyfdzz).</description>
    <link>https://dev.to/moyfdzz</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%2F956310%2F59485b53-c221-4a1c-82cf-3aecf6821982.jpg</url>
      <title>DEV Community: Moisés Fernández Zárate</title>
      <link>https://dev.to/moyfdzz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/moyfdzz"/>
    <language>en</language>
    <item>
      <title>Asynchronous JavaScript</title>
      <dc:creator>Moisés Fernández Zárate</dc:creator>
      <pubDate>Thu, 08 Dec 2022 17:19:17 +0000</pubDate>
      <link>https://dev.to/moyfdzz/asynchronous-javascript-4o04</link>
      <guid>https://dev.to/moyfdzz/asynchronous-javascript-4o04</guid>
      <description>&lt;p&gt;JavaScript is a single threaded language, which means that it can only handle one process at a time, and it executes the code sequentially because it cannot run another instruction until it finishes executing the current instruction. This becomes a problem whenever tasks that are long-running tasks must be executed, such as HTTP requests or handling device settings, but this is when asynchronous programming comes in handy.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Asynchronous Programming?
&lt;/h2&gt;

&lt;p&gt;This is a technique that allows JavaScript to handle long-running tasks and run other events in parallel, instead of having to wait for the first task to be finished, and this has been done using callbacks, promises and recently async/await.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a callback?
&lt;/h2&gt;

&lt;p&gt;A callback is any function that is passed as an argument inside another function and then is invoked from within that function to perform a task. A good example to show this is with the use of &lt;code&gt;setTimeout()&lt;/code&gt; as shown 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 printHelloWorld() {
  console.log('Hello World');
}

setTimeout(printHelloWorld, 5000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function prints 'Hello World' after 5 seconds because of the callback it received. This is a simple example, but sometimes it becomes more complicated as in the example shown 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 firstFunction(callback) {
  console.log('This is the first message');
  setTimeout(callback, 2000);
}

function secondFunction() {
  console.log('This is the second message');
}

setTimeout(firstFunction, 5000);

setTimeout(firstFunction(secondFunction), 5000);

setTimeout(() =&amp;gt; firstFunction(secondFunction), 5000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first call of &lt;code&gt;setTimeout()&lt;/code&gt; prints 'This is the first message' after five seconds but doesn't execute the setTimeout() inside the &lt;code&gt;firstFunction()&lt;/code&gt; because it didn't receive the callback.&lt;/p&gt;

&lt;p&gt;The second call of &lt;code&gt;setTimeout()&lt;/code&gt; prints 'This is the first message' immediately because by opening up the parenthesis, it stopped being a callback and then prints 'This is the second message' after 2 seconds.&lt;/p&gt;

&lt;p&gt;The third call of &lt;code&gt;setTimeout()&lt;/code&gt; prints 'This is the first message' after five seconds because we made it back a callback with the arrow function, and then prints 'This is the second message' after 2 seconds.&lt;/p&gt;

&lt;p&gt;There were some cases where multiple calls were made in the code with many callbacks nested as in the example shown above, which had bad code readability and was not easy to main, this is called &lt;em&gt;Callback Hell&lt;/em&gt;, but this was solved with the introduction of &lt;em&gt;Promises&lt;/em&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is a Promise?
&lt;/h2&gt;

&lt;p&gt;A Promise in JavaScript is a special object which represents the eventual completion or failure of an asynchronous operation and its resulting value. &lt;/p&gt;

&lt;p&gt;A Promise object has the following two properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;PromiseStatus&lt;/li&gt;
&lt;li&gt;PromiseValue&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A Promise can only have one of the following three states:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;pending - initial state&lt;/li&gt;
&lt;li&gt;fulfilled - it means that the operation was completed successfully&lt;/li&gt;
&lt;li&gt;rejected - it means that the operation failed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When creating a Promise, two arguments must be sent as parameters, the first one is &lt;code&gt;resolve&lt;/code&gt; and the second one &lt;code&gt;reject&lt;/code&gt;, which are in charge of changing the PromiseStatus to fulfilled or rejected respectively.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise = new Promise(function(resolve, reject) {
  resolve('Hello World');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The methods &lt;code&gt;then&lt;/code&gt; and &lt;code&gt;catch&lt;/code&gt; are used to handle the two possible states of a promise, the first one can be used to handle both fulfillments and rejections, and the second one only to handle rejections, but usually both are used combined because of code readability as shown in the example 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 sumPositiveNumbers(number1, number2) {
  const promise = new Promise((resolve, reject) =&amp;gt; {
    if (number1 &amp;lt; 0 || number2 &amp;lt; 0) {
      reject('Both arguments must be positive numbers');
    }
    const result = number1 + number2;
    resolve(result);
  });
  return promise;
}

sumPositiveNumbers(1, 2)
  .then(value =&amp;gt; {
    console.log(value);
  });
// Expected output: 3

sumPositiveNumbers(-1, 1)
  .then(value =&amp;gt; {
    console.log(value);
    return sumPositiveNumbers(-1, 1);
  }, reason =&amp;gt; {
    console.log('Error: ' + reason);
  });
// Expected output:
// Error: Both arguments must be positive numbers

sumPositiveNumbers(5, 5)
  .then(value =&amp;gt; {
    console.log(value);
    return sumPositiveNumbers(1, -5);
  })
  .catch(error =&amp;gt; {
    console.log('Error: ' + error);
  });
// Expected output: 10
// Error: Both arguments must be positive numbers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When many promises are nested as in callbacks, a Promise Hell can be created and affect code readability and maintainability, but this can be solved by using the method &lt;code&gt;all()&lt;/code&gt;. This method can be used when the promises don't depend on each other and returns a fulfilled promise only if all promises where executed successfully and a rejected promise otherwise.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function firstPromiseFunction() {
  return new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; resolve('Cody'), 2000);
  });
}

function secondPromiseFunction() {
  return new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; resolve('Bruno'), 2000);
  });
}

function thirdPromiseFunction() {
  return new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; reject('Database error.'), 2000);
  });
}

Promise.all([firstPromiseFunction(), secondPromiseFunction()])
  .then((responses) =&amp;gt; {
    console.log(responses);
  })
  .catch((error) =&amp;gt; {
    console.error('Error ' + error);
  });
// Expected output: ["Cody", "Bruno"]

Promise.all([firstPromiseFunction(), secondPromiseFunction(), thirdPromiseFunction()])
  .then((responses) =&amp;gt; {
    console.log(responses);
  })
  .catch((error) =&amp;gt; {
    console.error('Error: ' + error);
  });
// Expected output: Error: Database error.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Async and Await
&lt;/h2&gt;

&lt;p&gt;These new keywords added in the ES6 Version made it simpler to work with asynchronous programming and promises in JavaScript. By adding the &lt;code&gt;async&lt;/code&gt; keyword JavaScript interprets the function as an asynchronous function. Inside an asynchronous function, the keyword &lt;code&gt;await&lt;/code&gt; can be used before a call to a function that returns a promise as in the example shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dogsDatabase = [
  {
    id: 1,
    name: 'Cody',
    age: 5,
    breed: 'Siberian Husky'
  },
  {
    id: 2,
    name: 'Timo',
    age: 12,
    breed: 'Poodle'
  },
  {
    id: 3,
    name: 'Bruno',
    age: 3,
    breed: 'Golden Retriever'
  },
];

function resolveAfter2Seconds() {
  return new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      console.log('Here is the dogs information:');
      resolve(dogsDatabase);
    }, 2000)
  })
}

async function getDogs() {
  console.log('Sending request to get dogs information.');
  const result = await resolveAfter2Seconds();
  console.log(result);
}

getDogs();
// Expected output:
// Sending request to get dogs information.
// Here is the dogs information:
// * The list of dogs *
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The standard way to handle errors with they keywords &lt;code&gt;async/await&lt;/code&gt; is by using the block &lt;code&gt;try/catch&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sumPositiveNumbers(number1, number2) {
  return new Promise((resolve, reject) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      if (number1 &amp;lt; 0 || number2 &amp;lt; 0) {
        reject('Both numbers must be positive.')
      }
      resolve(number1 + number2)
    }, 2000)
  })
}

async function getSum(number1, number2) {
  let result;
  try {
    console.log('Sending request to sum numbers.');
    result = await sumPositiveNumbers(number1, number2);
    console.log('The result is: ' + result);
  } catch(error) {
    console.log(error);
  }
}

getSum(-1, 5);
// Expected output:
// Sending request to sum numbers.
// Both numbers must be positive.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>JavaScript | Mutability vs Immutability</title>
      <dc:creator>Moisés Fernández Zárate</dc:creator>
      <pubDate>Wed, 23 Nov 2022 18:03:13 +0000</pubDate>
      <link>https://dev.to/moyfdzz/javascript-mutability-vs-immutability-20on</link>
      <guid>https://dev.to/moyfdzz/javascript-mutability-vs-immutability-20on</guid>
      <description>&lt;p&gt;In JavaScript whether a variable is mutable or immutable it depends on its type and there are only two types of variables in which data is stored: primitive and reference.&lt;/p&gt;

&lt;h2&gt;
  
  
  Primitive Type (Immutability)
&lt;/h2&gt;

&lt;p&gt;All the JavaScript primitive types that are the atomic values stored to a variable, which are the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Number&lt;/li&gt;
&lt;li&gt;Boolean&lt;/li&gt;
&lt;li&gt;String&lt;/li&gt;
&lt;li&gt;Null&lt;/li&gt;
&lt;li&gt;Undefined&lt;/li&gt;
&lt;li&gt;Symbol&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Following is an example of how these primitive types are stored in JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let dog = "Chopper";
let dog2 = dog;

dog = "Cody";
console.log(dog2); // Expected output: Chopper
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The variable 'dog2' is created as a new space in memory and is allocated with the same value as the variable 'dog', it is not a reference. Modifying the first variable won't change the value stored in the second variable because it is not a reference. This is a perfect example of &lt;strong&gt;Immutability&lt;/strong&gt; in JavaScript.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reference Type (Mutability)
&lt;/h2&gt;

&lt;p&gt;This type is more complicated than simple and atomic values, they consist of multiple properties and are stored as references in memory. In JavaScript exist the following reference types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Array&lt;/li&gt;
&lt;li&gt;Object&lt;/li&gt;
&lt;li&gt;Function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Following is an example of how these reference types are stored in JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let dog = {name: 'Chopper', age: '5'};
let dog2 = dog;

dog.name = "Cody";
console.log(dog2); // Expected output: {name: "Cody", age: "5"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The variable 'dog2' is created as a new variable, but only as a reference to the first object. Modifying the first variable affects the value shown when printing the second variable because it is a reference to the first object. This is a perfect example of &lt;strong&gt;Mutability&lt;/strong&gt; in JavaScript.&lt;/p&gt;

</description>
      <category>docker</category>
    </item>
    <item>
      <title>JavaScript Fundamentals</title>
      <dc:creator>Moisés Fernández Zárate</dc:creator>
      <pubDate>Mon, 31 Oct 2022 17:32:08 +0000</pubDate>
      <link>https://dev.to/moyfdzz/javascript-fundamentals-44l7</link>
      <guid>https://dev.to/moyfdzz/javascript-fundamentals-44l7</guid>
      <description>&lt;h1&gt;
  
  
  Differences between var, let and const
&lt;/h1&gt;

&lt;p&gt;Variables declared using &lt;code&gt;var&lt;/code&gt; can be used within the whole function where they were initialized, but variables declared using &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; can only be inside the block where they were created.&lt;/p&gt;

&lt;p&gt;The values of variables declared using &lt;code&gt;var&lt;/code&gt; and &lt;code&gt;let&lt;/code&gt; can be reassigned, but in the case of &lt;code&gt;const&lt;/code&gt; that's not possible.&lt;/p&gt;

&lt;p&gt;Variables declared with &lt;code&gt;var&lt;/code&gt; can have the same name, but in the case of &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; it's not possible and you will get a Syntax Error. It's only possible to do it for the latter options if they are declared in a different scope.&lt;/p&gt;

&lt;p&gt;Variables declared with &lt;code&gt;var&lt;/code&gt; and &lt;code&gt;let&lt;/code&gt; without an initial value will have &lt;code&gt;undefined&lt;/code&gt; assigned as default. In the case of &lt;code&gt;const&lt;/code&gt; it's not possible to declare a variable and not assign a value to it, JavaScript will return a Syntax Error.&lt;/p&gt;

&lt;p&gt;Variables declared with &lt;code&gt;var&lt;/code&gt; are assigned as a property of the global object, unlike in the case of &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Hoisting
&lt;/h1&gt;

&lt;p&gt;Variables declared using &lt;code&gt;var&lt;/code&gt; are read by the JavaScript interpreter as if they were declared at the beginning of the function or scope. This means that the value of the variable can be referenced before it is declared in the code.&lt;/p&gt;

&lt;p&gt;The same thing goes for &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; but in these cases they are declared without an initial value until they have an assigned value in the code. This time between the beginning of the scope and the assignment of a value to the variable is called &lt;strong&gt;Temporal Dead Zone&lt;/strong&gt;. During this time a variable can't be referenced until a value is assigned to it.&lt;/p&gt;

&lt;p&gt;This is possible because JavaScript saves in memory in the &lt;strong&gt;Lexical Environment&lt;/strong&gt; the references to the declarations as undefined and then assign the value to it later when they are initialized in the code. This is only possible for the following cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Class&lt;/li&gt;
&lt;li&gt;Function&lt;/li&gt;
&lt;li&gt;Const&lt;/li&gt;
&lt;li&gt;Let&lt;/li&gt;
&lt;li&gt;Var&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Scope
&lt;/h1&gt;

&lt;p&gt;This is an important concept because it manages the accessibility of variables in the code depending on how we handle their declaration. There are three type of scopes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Global&lt;/li&gt;
&lt;li&gt;Function &amp;amp; Local&lt;/li&gt;
&lt;li&gt;Block&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Global Scope
&lt;/h2&gt;

&lt;p&gt;This is the scope outside a function, all variables declared here can be used anywhere in the code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Function &amp;amp; Local Scope
&lt;/h2&gt;

&lt;p&gt;This is the scope inside a function, all variables declared here can only be used inside the scope of the function.&lt;/p&gt;

&lt;h2&gt;
  
  
  Block Scope
&lt;/h2&gt;

&lt;p&gt;This is the scope inside a pair of curly braces since JavaScript ES6, all variables declared here, except for &lt;code&gt;var&lt;/code&gt;, can only be used inside this block.&lt;/p&gt;

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