<?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: Manoj</title>
    <description>The latest articles on Forem by Manoj (@manojravi).</description>
    <link>https://forem.com/manojravi</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%2F2285426%2Fdd09b6b9-a82c-4d20-8778-47b76eb2ca57.jpeg</url>
      <title>Forem: Manoj</title>
      <link>https://forem.com/manojravi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/manojravi"/>
    <language>en</language>
    <item>
      <title>Event Loop — JavaScript</title>
      <dc:creator>Manoj</dc:creator>
      <pubDate>Tue, 03 Dec 2024 06:06:49 +0000</pubDate>
      <link>https://forem.com/manojravi/event-loop-javascript-2i4n</link>
      <guid>https://forem.com/manojravi/event-loop-javascript-2i4n</guid>
      <description>&lt;p&gt;Event loop is the loop that maintains the execution order (handling asynchronous operations without blocking the main thread) of JavaScript code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Things to know before diving into event loop:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Call Stack: This is where JavaScript executes our code. It follows a Last In, First Out (LIFO) structure. When a function is called, a new execution context is created and it gets pushed onto the stack. When the function ends, it’s popped off.&lt;/li&gt;
&lt;li&gt;MicroTasks Queue: Special queue dedicated to &lt;strong&gt;&lt;em&gt;queueMicroTask&lt;/em&gt;&lt;/strong&gt; methods, &lt;strong&gt;&lt;em&gt;Promise&lt;/em&gt;&lt;/strong&gt; handlers, &lt;strong&gt;&lt;em&gt;await&lt;/em&gt;&lt;/strong&gt; callbacks and &lt;strong&gt;&lt;em&gt;MutationObserver&lt;/em&gt;&lt;/strong&gt; (interface provides the ability to watch for changes being made to the DOM tree).&lt;/li&gt;
&lt;li&gt;MacroTasks Queue: All other callbacks from Web APIs (&lt;strong&gt;&lt;em&gt;setTimeout&lt;/em&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;em&gt;setInterval&lt;/em&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;em&gt;DOM APIs&lt;/em&gt;&lt;/strong&gt;, &lt;strong&gt;&lt;em&gt;fetch&lt;/em&gt;&lt;/strong&gt;) enters the macroTasks queue.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What is Event Loop?
&lt;/h2&gt;

&lt;p&gt;It’s an endless loop that waits for tasks and pushes them into call stack for execution. Since JavaScript is single-threaded, it maintains an execution order to handle both synchronous asynchronous operations based on priority.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Regular JS code:&lt;/strong&gt; Synchronous code runs first and fills the call stack.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MicroTasks:&lt;/strong&gt; Tasks queued in microTasks queue gets executed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;MacroTasks:&lt;/strong&gt; Tasks queued in macroTasks queue gets executed.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Programmatic way of how the event loop processes tasks
while (true) {
  // Step 1: Execute tasks in the call stack
  while (!callStack.isEmpty()) {
    const currentTask = callStack.pop();
    currentTask(); // Executes the task
  }
  // Step 2: Process all microtasks
  while (!microTasksQueue.isEmpty()) {
    const microTask = microTasksQueue.shift();
    callStack.push(microTask); // Push microtask to call stack for execution
  }
  // Step 3: Process one macrotask if available
  if (!macroTasksQueue.isEmpty()) {
    const macroTask = macroTasksQueue.shift();
    callStack.push(macroTask); // Push macrotask to call stack for execution
  }
  // Break if there's nothing left to process
  if (callStack.isEmpty() &amp;amp;&amp;amp; microTasksQueue.isEmpty() &amp;amp;&amp;amp; macroTasksQueue.isEmpty()) {
    break;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s go through an example to understand the workflow better&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1.  setTimeout(() =&amp;gt; console.log(1), 2000);
2.  Promise.resolve().then(() =&amp;gt; {
3.      console.log(2);
4.      queueMicroTask(() =&amp;gt; console.log(3));
5.  });
6.  Promise.resolve().then(() =&amp;gt; {
7.      console.log(4);
8.      setTimeout(() =&amp;gt; console.log(5));
9.  });
10. setTimeout(() =&amp;gt; console.log(6));
11. console.log(7);

// 7 2 4 3 6 5 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s assume we have a 2 queues &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; and &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt;. When the code starts executing,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;() =&amp;gt; console.log(1)&lt;/code&gt; gets pushed into the &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt; queue in 2000ms.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;() =&amp;gt; { console.log(2); queueMicroTask(() =&amp;gt; console.log(3)); })&lt;/code&gt; gets pushed into the &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;() =&amp;gt; { console.log(4); setTimeout(() =&amp;gt; console.log(5)); })&lt;/code&gt; gets pushed into the &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;() =&amp;gt; console.log(6)&lt;/code&gt; gets pushed into the &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt; queue in 0ms.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;console.log(7)&lt;/code&gt; executes and prints &lt;code&gt;7&lt;/code&gt; in console.&lt;/li&gt;
&lt;li&gt;Now the event loop checks the &lt;em&gt;&lt;strong&gt;microTasks&lt;/strong&gt;&lt;/em&gt; queue for tasks and takes &lt;code&gt;() =&amp;gt; { console.log(2); queueMicroTask(() =&amp;gt; console.log(3)); })&lt;/code&gt; task and prints &lt;code&gt;2&lt;/code&gt; in console and pushes &lt;code&gt;() =&amp;gt; console.log(3)&lt;/code&gt; into &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue.&lt;/li&gt;
&lt;li&gt;Next, the event loop checks &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue and takes &lt;code&gt;() =&amp;gt; { console.log(4); setTimeout(() =&amp;gt; console.log(5)); })&lt;/code&gt; task and prints &lt;code&gt;4&lt;/code&gt; and pushes &lt;code&gt;() =&amp;gt; console.log(5)&lt;/code&gt; into &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt; queue in 0ms.&lt;/li&gt;
&lt;li&gt;Again, the event loop checks &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue and takes &lt;code&gt;() =&amp;gt; console.log(3))&lt;/code&gt; task and prints &lt;code&gt;3&lt;/code&gt; in console.&lt;/li&gt;
&lt;li&gt;Since the &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue is empty now, the event loop checks the macroTaskQueue and takes &lt;code&gt;() =&amp;gt; console.log(6)&lt;/code&gt; and prints &lt;code&gt;6&lt;/code&gt; in console.&lt;/li&gt;
&lt;li&gt;Event loop takes the next task &lt;code&gt;() =&amp;gt; console.log(5)&lt;/code&gt; from the &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt; after ensuring that there isn’t any tasks in &lt;strong&gt;&lt;em&gt;microTasks&lt;/em&gt;&lt;/strong&gt; queue and prints &lt;code&gt;5&lt;/code&gt; in console.&lt;/li&gt;
&lt;li&gt;Event loop takes the next task &lt;code&gt;() =&amp;gt; console.log(1)&lt;/code&gt; from the &lt;strong&gt;&lt;em&gt;macroTasks&lt;/em&gt;&lt;/strong&gt; and prints &lt;code&gt;1&lt;/code&gt; in console.&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>learning</category>
    </item>
    <item>
      <title>Closures - Javascript</title>
      <dc:creator>Manoj</dc:creator>
      <pubDate>Sun, 10 Nov 2024 06:13:25 +0000</pubDate>
      <link>https://forem.com/manojravi/closures-javascript-44m1</link>
      <guid>https://forem.com/manojravi/closures-javascript-44m1</guid>
      <description>&lt;p&gt;You know what? In JavaScript, all functions are naturally closures (with only one exception). Really, let’s go through to understand how this works.&lt;/p&gt;

&lt;p&gt;Closure are functions bundled together with its lexical references. While that’s the formal definition, what do closures really mean? Before diving into closures, understanding &lt;strong&gt;first-class functions&lt;/strong&gt; is beneficial, as it provides foundational knowledge that helps you grasp how closures work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Concepts to Know First:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. First-class functions:&lt;/strong&gt; Functions that can be assigned to variables, passed as an argument and returned from functions.&lt;br&gt;
&lt;strong&gt;2. Function scope:&lt;/strong&gt; Functions can access variables from their own scope and from the surrounding (outer) scope.&lt;br&gt;
&lt;strong&gt;3. Execution context:&lt;/strong&gt; Each time a function is invoked, a new execution context is created. This includes the variable environment and the scope chain.&lt;/p&gt;

&lt;p&gt;In general, variables created within a function are scoped to that function and are destroyed immediately after the function completes execution. For example, consider a function named &lt;em&gt;premiumContentAccess&lt;/em&gt; that contains two variables: &lt;em&gt;articlesAllowedToAccess&lt;/em&gt; and &lt;em&gt;currentlyAccessed&lt;/em&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 premiumContentAccess() {
  let articlesAllowedToAccess = 3;
  let currentlyAccessed = 0;
}

premiumContentAccess();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When &lt;em&gt;premiumContentAccess&lt;/em&gt; is executed, the local variables &lt;em&gt;articlesAllowedToAccess&lt;/em&gt; and &lt;em&gt;currentlyAccessed&lt;/em&gt; are created. Once the function execution completes, these variables go out of scope and are eligible for garbage collection, meaning they are effectively destroyed and cannot be accessed afterward.&lt;/p&gt;

&lt;p&gt;Is it possible to retain access to these variables even after the execution of &lt;em&gt;premiumContentAccess&lt;/em&gt;? Here comes the closure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Closure?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A closure is formed when a function is returned (or created) that has access to its surrounding (outer) variables. These variables references are bundled together with the function, allowing them to persist.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function premiumContentAccess() {
  let articlesAllowedToAccess = 3;
  let currentlyAccessed = 0;  

  function accessArticle() {
    if (currentlyAccessed &amp;gt;= articlesAllowedToAccess) {
      return 'Premium Article Access Reached';
    }
    currentlyAccessed++;
    return 'Article accessed';
  }
  return accessArticle;
}

let accessArticle = premiumContentAccess();

console.log(accessArticle()); // Outputs: Article accessed
console.log(accessArticle()); // Outputs: Article accessed
console.log(accessArticle()); // Outputs: Article accessed
console.log(accessArticle()); // Outputs: Premium Article Access Reached
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Breakdown of the Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Outer Function:&lt;/strong&gt; &lt;em&gt;premiumContentAccess()&lt;/em&gt; is the outer function that defines the variables &lt;em&gt;articlesAllowedToAccess&lt;/em&gt; and &lt;em&gt;currentlyAccessed&lt;/em&gt;.&lt;br&gt;
&lt;strong&gt;2. Inner Function:&lt;/strong&gt; &lt;em&gt;accessArticle&lt;/em&gt; is the inner function that accesses the variables from its lexical scope, which is defined in the outer function.&lt;br&gt;
&lt;strong&gt;3. Closure:&lt;/strong&gt; When &lt;em&gt;premiumContentAccess()&lt;/em&gt; is called, it returns the &lt;em&gt;accessArticle&lt;/em&gt; function retaining access to the variables &lt;em&gt;articlesAllowedToAccess&lt;/em&gt; and &lt;em&gt;currentlyAccessed&lt;/em&gt;, even after the outer function has finished executing.&lt;br&gt;
&lt;strong&gt;4. State Retention:&lt;/strong&gt; The closure allows accessArticle to maintain its own state regarding how many articles have been accessed. Each call to &lt;em&gt;accessArticle&lt;/em&gt; modifies &lt;em&gt;currentlyAccessed&lt;/em&gt;, which is preserved due to the closure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;All Functions Are Closures:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we mentioned at start, all functions are naturally closures.&lt;/p&gt;

&lt;p&gt;That is: they automatically retain a reference to their creation context through a hidden &lt;em&gt;[[Environment]]&lt;/em&gt; property, allowing their code to access outer variables.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exception:&lt;/strong&gt; Functions created using the new Function constructor set the &lt;em&gt;[[Environment]]&lt;/em&gt; to the global context instead of the creation context.&lt;/p&gt;




&lt;p&gt;Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>learning</category>
    </item>
    <item>
      <title>Writing polyfills — Javascript</title>
      <dc:creator>Manoj</dc:creator>
      <pubDate>Sun, 03 Nov 2024 12:30:00 +0000</pubDate>
      <link>https://forem.com/manojravi/writing-polyfills-javascript-4kap</link>
      <guid>https://forem.com/manojravi/writing-polyfills-javascript-4kap</guid>
      <description>&lt;p&gt;A piece of code that provides functionality that is not natively supported by certain browsers or environments. In simple terms, a browser falback.&lt;/p&gt;

&lt;p&gt;Before writing polyfills for the &lt;strong&gt;call()&lt;/strong&gt;, &lt;strong&gt;apply()&lt;/strong&gt; and &lt;strong&gt;bind()&lt;/strong&gt; methods, please check the functionality of call, apply and bind.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let details = {
  name: 'Manoj',
  location: 'Chennai'
}

let getDetails = function (...args) {
  return `${this.name} from ${this.location}${args.join(', ') ? `, ${args.join(', ')}` : ''}`;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1. Call Method:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s create a polyfill for &lt;strong&gt;call()&lt;/strong&gt;. We'll add a custom &lt;strong&gt;call&lt;/strong&gt; method to the &lt;strong&gt;Function.prototype&lt;/strong&gt; to make it accessible to all functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getDetails.call(details, 'Tamil Nadu', 'India');  // Manoj from Chennai, Tamil Nadu, India

// Polyfill
Function.prototype.myCall = function (ref, ...args) {
  if (typeof Function.prototype.call === 'function') {  // Checks whether the browser supports call method
    return this.call(ref, ...args);
  } else {
    ref = ref || globalThis;
    let funcName = Math.random();  // Random is used to overwriting a function name
    while (ref.funcName) {
      funcName = Math.random();
    }
    ref[funcName] = this;
    let result = ref[funcName](...args);
    delete ref[funcName];
    return result;
  }
}

getDetails.myCall(details, 'Tamil Nadu', 'India');  // Manoj from Chennai, Tamil Nadu, India
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Apply Method:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s create a polyfill for &lt;strong&gt;apply()&lt;/strong&gt;. We’ll add a custom &lt;strong&gt;apply&lt;/strong&gt; method to the &lt;strong&gt;Function.prototype&lt;/strong&gt; to make it accessible to all functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getDetails.apply(details, ['Tamil Nadu', 'India']);  // Manoj from Chennai, Tamil Nadu, India

// Polyfill
Function.prototype.myApply = function (ref, args) {
  if (typeof Function.prototype.apply === 'function') {  // Checks whether the browser supports call method
    this.apply(ref, args);
  } else {
    ref = ref || globalThis;
    let funcName = Math.random();  // Random is to avoid duplication
    while (ref.funcName) {
      funcName = Math.random();
    }
    ref[funcName] = this;
    let result = ref[funcName](args);
    delete ref[funcName];
    return result;
  }
}

getDetails.myApply(details, 'Tamil Nadu', 'India');  // Manoj from Chennai, Tamil Nadu, India
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Bind method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s create a polyfill for &lt;strong&gt;bind()&lt;/strong&gt;. We’ll add a custom &lt;strong&gt;bind&lt;/strong&gt; method to the &lt;strong&gt;Function.prototype&lt;/strong&gt; to make it accessible to all functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let getFullDetails = getDetails.bind(details, 'Tamil Nadu');
getFullDetails();  // Manoj from Chennai, Tamil Nadu
getFullDetails('India');  // Manoj from Chennai, Tamil Nadu, India

// Polyfill
Function.prototype.myBind = function (ref, ...args) {
  if (typeof Function.prototype.bind === 'function') {
    return this.bind(ref, ...args);
  } else {
    let fn = this;
    return function (...args2) {
        return fn.apply(ref, [...args, ...args2]);  // Merge and apply arguments
    }
  }
}

let getFullDetails = getDetails.myBind(details, 'Tamil Nadu');  // Manoj from Chennai, Tamil Nadu
getFullDetails('India');  // Manoj from Chennai, Tamil Nadu, India
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Call, Apply &amp; Bind Methods — Javascript</title>
      <dc:creator>Manoj</dc:creator>
      <pubDate>Fri, 01 Nov 2024 09:53:11 +0000</pubDate>
      <link>https://forem.com/manojravi/call-apply-bind-methods-javascript-kh4</link>
      <guid>https://forem.com/manojravi/call-apply-bind-methods-javascript-kh4</guid>
      <description>&lt;p&gt;Each and every function in JS has access to this keyword.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Call&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It’s similar to function borrowing, where we can use functions / borrow functions from one object and use them with another object instead of redeclaring them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi',
  fullName: function (district, state) {
    return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
  }
};

let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

name.fullName('Chennai', 'TN');  // Manoj Ravi from Chennai, TN.
getFullDetails.call(name, 'Chennai', 'TN');  // Manoj Ravi from Chennai, TN.

let name2 = {
  firstnName: 'Sanjay',
  secondName: 'Ravi',
};

name.fullName.call(name2, 'Coimbatore', 'TN');  // Sanjay Ravi from Coimbatore, TN.
getFullDetails.call(name2, 'Coimbatore', 'TN');  // Sanjay Ravi from Coimbatore, TN.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additional parameters can be shared in a comma-separated format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Apply&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similar to call, the only difference is the way we pass arguments. Instead of passing them individually (in a comma-separated format), we pass them as an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi'
};
getFullDetails.call(name, ['Chennai', 'TN']);  // Manoj Ravi from Chennai, TN.

let name2 = {
  firstnName: 'Sanjay',
  secondName: 'Ravi'
};
getFullDetails.call(name2, ['Coimbatore', 'TN']);  // Sanjay Ravi from Coimbatore, TN.

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Bind&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similar to call, this method does not invoke the function immediately; instead, it binds the function's reference and returns a new function that can be called later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let getFullDetails = function(district, state) {
  return `${this.firstName} ${this.secondName} from ${district}, ${state}.`;
};

let name = {
  firstnName: 'Manoj',
  secondName: 'Ravi'
};


let printDetails = getFullDetails(name, 'Chennai', 'TN');
printDetails();  // Manoj Ravi from Chennai, TN.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Object Creation Methods — JavaScript</title>
      <dc:creator>Manoj</dc:creator>
      <pubDate>Sun, 27 Oct 2024 12:30:00 +0000</pubDate>
      <link>https://forem.com/manojravi/object-creation-methods-javascript-3d7e</link>
      <guid>https://forem.com/manojravi/object-creation-methods-javascript-3d7e</guid>
      <description>&lt;p&gt;In JavaScript, almost “everything” is an object. Understanding how to create and work with objects effectively is fundamental to becoming proficient in JavaScript development.&lt;/p&gt;

&lt;p&gt;All the objects created inherits directly from the built-in Object.prototype by default.&lt;/p&gt;

&lt;p&gt;There are several ways to create object in JavaScript. Here are some common methods:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Object Literals&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Simple and Straightforward way to create a object without specifying a prototype explicitly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
    property1: "value1",
    property2: "value2"
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Using the new keyword with Object Constructor&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can create objects using the built-in Object constructor function along with the new keyword.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = new Object();
obj.key1 = value1;
obj.key2 = value2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Object.create() Method&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Unlike other object creating methods Object.create() allows us to explicitly specify the prototype of the newly created object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const prototypeObject = {}; // Prototype object
const obj = Object.create(prototypeObject);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Prototype chain of the new object will include the prototypeobject provided as an argument, and ultimately, it will inherit from Object.prototype.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Factory Functions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A simpler approach to create objects by encapsulating the object creation process within a function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function myFunction(key1, key2) {
    return {
        key1: key1,
        key2: key2
    };
}

const obj = myFunction(value1, value2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Using Function Constructors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We can define a constructor function and then create objects from it using the new keyword which is useful for creating multiple objects with the same structure.&lt;/p&gt;

&lt;p&gt;Constructor functions typically start with a capital letter by convention.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function MyObject(key1, key2) {
    this.key1 = key1;
    this.key2 = key2;
}
const obj = new MyObject(value1, value2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Using ES6 Classes&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Introduced in ES6, class syntax allows us to define object blueprints more clearly.&lt;/p&gt;

&lt;p&gt;Classes are primarily syntactical sugar over JavaScript’s existing prototype-based inheritance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MyClass {
    constructor(key1, key2) {
        this.key1 = key1;
        this.key2 = key2;
    }
}
const obj = new MyClass(value1, value2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quick Question: Is it possible to create an object with no prototype methods?&lt;/p&gt;




&lt;p&gt;Thank you for reading! I hope you found this blog informative and engaging. If you notice any inaccuracies or have any feedback, please don’t hesitate to let me know.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>learning</category>
      <category>objects</category>
    </item>
  </channel>
</rss>
