<?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"><channel><title><![CDATA[Code with tkssharma || blogs for developers]]></title><description><![CDATA[I’m Tarun, I am Publisher, Trainer Developer, working on Enterprise and open source Technologies JavaScript frameworks]]></description><link>https://articles.tkssharma.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 02:27:09 GMT</lastBuildDate><atom:link href="https://articles.tkssharma.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Crack Web developer  Interview Master series]]></title><description><![CDATA[Crack Interview Master series]]></description><link>https://articles.tkssharma.com/crack-web-developer-interview-master-series</link><guid isPermaLink="true">https://articles.tkssharma.com/crack-web-developer-interview-master-series</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[Web Developer]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Mon, 18 Nov 2024 11:31:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731929425765/2b2b3939-e47b-42f9-923a-5f3d397e55e3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-awesome-javascript-interviews">Awesome JavaScript Interviews</h1>
<p>https://www.youtube.com/embed/YSteqFk_Z5k?si=R-49qQPQ7ml0jngz</p>
<h2 id="heading-table-of-contents-of-this-readme-file">Table of Contents of this Readme file</h2>
<ol>
<li><p><a class="post-section-overview" href="#most-common-fundamental-javascript-interview-topics--questions">Most common Fundamental JavaScript Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-tricky-javascript-interview-topics--questions">Most common Tricky Javascript Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-asyncawait-and-promise-related-interview-topics--questions">Most common Async/Await and Promise related Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-node-interview-topics--questions">Most common Node Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-web-development-architecture-related-interview-topics--questions">Most common Web-Development Architecture related Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-react-interview-topics--questions">Most common React Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-redux-interview-topics--questions">Most common Redux Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-angular-interview-topics--questions">Most common Angular Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-mongodb-interview-topics--questions">Most common MongoDB Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-html-interview-topics--questions">Most common HTML Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-css-interview-topics--questions">Most common CSS Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-git-and-github-related-interview-topics--questions">Most common Git and Github related Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#understanding-the-theory-and-the-fundamentals-of-some-super-popular-algorithm-questions">Understanding the Theory and the fundamentals of some super-popular Algorithm questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#github-repositories-with-large-collections-of-problems-and-solutions-of-them-most-popular-interview-challenges">Github Repositories with large collections of problems-and-solutions of them most popular Interview challenges</a></p>
</li>
<li><p><a class="post-section-overview" href="#overall-multi-factor-approach-for-winning-this-huge-challenge-and-a-great-journey-of-getting-the-first-developer-job">Overall multi-factor approach for winning this huge challenge and a great journey of getting the first Developer Job</a></p>
</li>
<li><p><a class="post-section-overview" href="#other-important-resources">Other important resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#coding-challenge-practice-platforms">Coding Challenge Practice Platforms</a></p>
</li>
<li><p><a class="post-section-overview" href="#more-curated-list-of-general-resources-for-javascript-interviews">More curated list of general resources for JavaScript Interviews</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-frequently-asked-concepts-for-front-end-engineering-interview">Most frequently asked concepts for Front End Engineering Interview</a></p>
</li>
<li><p><a class="post-section-overview" href="#list-of-sites-where-you-can-hunt-for-a-developer-job">List of sites where you can hunt for a developer job</a></p>
</li>
<li><p><a class="post-section-overview" href="#want-a-startup-job">Want a startup job?</a></p>
</li>
<li><p><a class="post-section-overview" href="#best-places-to-job-hunt-for-remote-jobs">Best places to job hunt for remote jobs</a></p>
</li>
<li><p><a class="post-section-overview" href="#here-are-a-few-places-to-hunt-for-ios-react-vue-and-more">Here are a few places to hunt for ios, react, vue and more</a></p>
</li>
<li><p><a class="post-section-overview" href="#want-a-list-of-just-javascript-jobs">Want a list of just JavaScript jobs?</a></p>
</li>
<li><p><a class="post-section-overview" href="#are-you-looking-for-a-junior-dev-job">Are you looking for a junior dev job?</a></p>
</li>
<li><p><a class="post-section-overview" href="#women-focused-job-boards">Women focused job boards!</a></p>
</li>
<li><p><a class="post-section-overview" href="#want-a-job-as-a-freelance-dev-heres-a-list">Want a job as a freelance dev? Here's a list</a></p>
</li>
<li><p><a class="post-section-overview" href="#some-useful-websites-for-programmers">Some useful websites for programmers</a></p>
</li>
<li><p><a class="post-section-overview" href="#when-you-get-stuck">When you get stuck</a></p>
</li>
<li><p><a target="_blank" href="for-small-project-ideas">For small project ideas</a></p>
</li>
<li><p><a target="_blank" href="general-coding-advice">General Coding advice</a></p>
</li>
<li><p><a class="post-section-overview" href="#coding-style">Coding Style</a></p>
</li>
<li><p><a class="post-section-overview" href="#general-good-articles">General Good Articles</a></p>
</li>
<li><p><a class="post-section-overview" href="#collection-of-leetcode-problem-solution">Collection of Leetcode Problem solution</a></p>
</li>
<li><p><a class="post-section-overview" href="#collection-of-cracking-the-coding-interview-book-problem-solution">Collection of Cracking the Coding Interview Book Problem solution</a></p>
</li>
<li><p><a class="post-section-overview" href="#most-common-system-design-interview-topics--questions">Most common System-Design Interview Topics &amp; Questions</a></p>
</li>
<li><p><a class="post-section-overview" href="#system-design-related-topics-some-very-useful-articles">System-Design related topics-Some very useful articles</a></p>
</li>
<li><p><a class="post-section-overview" href="#system-design-company-engineering-blog">System-Design-Company engineering blog</a></p>
</li>
</ol>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-fundamental-javascript-interview-topics-amp-questions">Most common Fundamental JavaScript Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Javascript/event-delegation-propagation-bubbling.md">Explain event delegation</a></li>
<li><a target="_blank" href="Javascript/this-keyword/this-keyword-2nd-example-GREAT-Example.md">Explain how <code>this</code> works in JavaScript</a><ul>
<li><a target="_blank" href="Javascript/this-keyword/this-example-custom-Array-Prototype-method.md">more-on <code>this</code> keyword</a></li>
<li><a target="_blank" href="Javascript/this-keyword/this-keyword-simplest-catagories.md">more on <code>this</code> keyword</a></li>
<li><a target="_blank" href="Javascript/this-keyword/this-keyword-1.js">more-on-<code>this</code>-keyword</a></li>
</ul>
</li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/README.md">Explain how prototypal inheritance works</a><ul>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/how-to-get-prototype-of-an-object.md">how-to-get-prototype-of-an-object</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Inheritence-OOP-Class-vs-Prototypes-Example-BEST.md">Inheritance-OOP-Class-vs-Prototypes-Example</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Inheritence-OOP-Class-vs-Prototypes-Theory.md">Inheritance-OOP-Class-vs-Prototypes-Theory</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Inheritence-with-classes-super-keyword-SIMPLEST-EXHAUSTIVE.md">Inheritence-with-classes-super-keyword-Exhaustive-Explanation</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/OOP-Basics-1.md">OOP-Basics-1</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/OOP-basics-2.md">OOP-basics-2</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/OOP-Encapsulation-example-1.md">OOP-Encapsulation-example-1</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/OOP-Encapsulation-example-2.md">OOP-Encapsulation-example-2</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/OOP-Encapsulation-Theory-GOOD-Explanations-Private-Methods.md">OOP-Encapsulation-Theory-GOOD-Explanations-Private-Methods</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/print-All-Prototypes-of-Objects.js">print-All-Prototypes-of-Objects</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototype-Example-Really-GOOD-Explanations.js">Prototype-Example-Really-GOOD-Explanations</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototype-Example-1.js">Prototype-Example-1</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototype-Example-2.js">Prototype-Example-2</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/prototype-func-print-array-elements.js">prototype-func-print-array-elements</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototype-func-String-dasherize.js">Prototype-func-String-dasherize</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototypes-Benefits-Handling-Memory-Leaks.md">Prototypes-Benefits-Handling-Memory-Leaks</a></li>
<li><a target="_blank" href="Javascript/OOP-Prototypal-Inheritence/Prototypes-Prevents-Memory-Leaks-1-Good-Explanation.md">Prototypes-Prevents-Memory-Leaks-1-Good-Explanation</a></li>
</ul>
</li>
<li><a target="_blank" href="Javascript/call-apply-bind/call-function-basics-1.md">Explain the concepts around and the difference between Call, Apply and Bind</a><ul>
<li><a target="_blank" href="Javascript/call-apply-bind/call-function-basics-2.md">More on Call, Apply and Bind</a></li>
<li><a target="_blank" href="Javascript/call-apply-bind/call-function-basics-2.md">More on Call, Apply and Bind</a></li>
<li><a target="_blank" href="Javascript/call-apply-bind/call-vs-apply-vs-bind.md">call-vs-apply-vs-bind</a></li>
<li><a target="_blank" href="bind-why-its-needed">Why bind function is needed</a></li>
</ul>
</li>
<li><a target="_blank" href="Javascript/arrow-function/arrow-vs-regular-functions.md">arrow-vs-regular-functions</a></li>
<li><a target="_blank" href="Javascript/arrow-function/when-not-to-use-arrow-function.md">when-not-to-use-arrow-function</a></li>
<li><a target="_blank" href="arrow-function-and-this-keyword">arrow-function-and-this-keyword</a></li>
<li><a target="_blank" href="Javascript/ES6-Array-Helper-Methods/Destructuring_Geneal.md">Destructuring - some examples</a></li>
<li><a target="_blank" href="Javascript/ES6-Array-Helper-Methods/filter-implement.js">filter method implementation</a></li>
<li><a target="_blank" href="Javascript/ES6-Array-Helper-Methods/forEach-vs-map.md">forEach-vs-map</a></li>
<li><a target="_blank" href="Javascript/Functional-Programming_Pure-Function/Pure-functions-basics.md">Pure-functions-basics</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure.md">closure explanations</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-setTimeout-MOST-POPULAR.js">closure-MOST-POPULAR-Interview Question on setTimeout</a><ul>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-setTimeout.js">Basics closure concepts involving setTimeout</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-tricky-GREAT-EXAMPLE.JS">closure-tricky and great Example</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-use-case-create-private-variable.js">closure-use-case-for-creating-private-variable</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-why-its-needed.js">closure-why-its-needed at all</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closures-retains-values-of-outer-function-after-outer-returns.md">More on Closure</a></li>
</ul>
</li>
<li><a target="_blank" href="Javascript/js-basics/custom_Callback-1.js">Custom Callback Function-1</a></li>
<li><a target="_blank" href="Javascript/js-basics/custom_Callback-2.js">Custom Callback Function-2</a></li>
<li><a target="_blank" href="Javascript/js-basics/IIFE-10-ways.js">IIFE function in 10 different ways</a></li>
<li><a target="_blank" href="Javascript/IIFE.md">IIFE</a></li>
<li><a target="_blank" href="Javascript/js-basics/scope-basic-understanding.md">scope in JS - A basic-understanding</a></li>
<li><a target="_blank" href="Javascript/js-data-types/data-types.md">Data Types in JS</a><ul>
<li><a target="_blank" href="Javascript/js-data-types/BigInt-data-type.md">BigInt-data-type</a></li>
<li><a target="_blank" href="Javascript/js-data-types/check-data-type-with-typeof.js">check-data-type-with-typeof</a></li>
<li><a target="_blank" href="Javascript/js-data-types/data-type-mutability.md">data-type-mutability</a></li>
<li><a target="_blank" href="Javascript/js-data-types/data-types-Number-Famous-Question.md">data-types of Number-A very popular Interview Question</a></li>
<li><a target="_blank" href="Javascript/js-data-types/data-types-Number.md">More on data-types of Number</a></li>
<li><a target="_blank" href="Javascript/js-data-types/data-types-symbol.md">data-types-symbol</a></li>
<li><a target="_blank" href="Javascript/js-data-types/what-is-type-coercion.md">what-is-type-coercion</a></li>
<li><a target="_blank" href="Javascript/coercion.md">More on coercion</a></li>
</ul>
</li>
<li><a target="_blank" href="Javascript/rest-spread-destructuring/spread-operator-vs-rest-parameters.md">spread-operator-vs-rest-parameters</a></li>
<li><a target="_blank" href="Javascript/rest-spread-destructuring/rest-spread-basic-techniques.js">rest-spread-basic-techniques</a></li>
<li><a target="_blank" href="Javascript/rest-spread-destructuring/rest-spread-2.js">More on rest and spread operator</a></li>
<li><a target="_blank" href="Javascript/call-stack-good-example.md">Example of Call Stack</a></li>
<li><a target="_blank" href="Javascript/const-var-let.md">const-var-let</a></li>
<li><a target="_blank" href="Javascript/curried-function.md">curried-function</a></li>
<li><a target="_blank" href="Javascript/execution-context-call-stack.md">execution-context-call-stack.md</a></li>
<li><a target="_blank" href="Javascript/hashing-vs-encrypting.md">hashing-vs-encrypting.md</a></li>
<li><a target="_blank" href="Javascript/hoisting.md">Hoisting - The supre important concept</a></li>
<li><a target="_blank" href="Javascript/is-javascript-static-or-dynamically-typed.md">is-javascript-static-or-dynamically-typed</a></li>
<li><a target="_blank" href="Javascript/is-JS-block-scoped-or-function-scoped.md">is-JS-block-scoped-or-function-scoped</a></li>
<li><a target="_blank" href="Javascript/map-set-get.js">map-set-get</a></li>
<li><a target="_blank" href="Javascript/Null-Coalescing-operator.md">Null-Coalescing-operator</a></li>
<li><a target="_blank" href="Javascript/truthy-falsy-1.js">truthy-falsy-1</a></li>
<li><a target="_blank" href="Javascript/truthy-falsy-2.md">truthy-falsy-2</a></li>
<li><a target="_blank" href="Javascript/truthy-falsy-pass-by-value-vs-reference-strict-equality-use-case.js">truthy-falsy-pass-by-value-vs-reference-strict-equality-use-case</a></li>
<li><a target="_blank" href="Javascript/passing-by-value-and-by-reference.md">passing-by-value-and-by-reference</a></li>
<li><a target="_blank" href="Javascript/undefined-vs-not_defined.md">undefined-vs-not_defined</a></li>
<li><a target="_blank" href="Javascript/Why-eval-function-considered-dangerous.md">Why-eval-function-considered-dangerous</a></li>
<li><a target="_blank" href="Javascript/use-strict-describe.md">use-strict-describe</a></li>
<li><a target="_blank" href="Large-Collection-of-Popular-Problems-with-Solutions/Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/compare-two-objects.md">How would you compare two objects in JavaScript?</a></li>
<li><a target="_blank" href="Large-Collection-of-Popular-Problems-with-Solutions/Objects-Master-List-of-Problems-Super-Useful-Daily-Techniques/Memoize-a-function.md">Memoize a function</a></li>
<li><a target="_blank" href="Javascript/repaint-reflow.md">repaint-reflow</a></li>
<li><a target="_blank" href="Javascript/what-are-events.md">What are events?</a></li>
<li><a target="_blank" href="Javascript/What-are-the-options-in-a-cookie.md">What are the options in a cookie</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<hr />
<h2 id="heading-most-common-tricky-javascript-interview-topics-amp-questions">Most common Tricky Javascript Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/Collection-of-Tricky-JS-Questlions.md">Collection-of-Tricky-JS-Questlions</a></li>
<li><a target="_blank" href="Javascript/js-basics/Closure/closure-tricky-GREAT-EXAMPLE.js">closure-tricky and great Example</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/logical-and-operator.js">logical-and-operator-Tricky Question</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/value-of-null.js">Value of Null</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/pitfall-of-using-typeof.md">pitfall-of-using-typeof</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/What-is-the-value-of-Math.max_2_3_4_5_.md">What-is-the-value-of-Math.max([2,3,4,5])</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/not-not-operator-in-javascript.md">not-not-operator-in-javascript</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/why-does-adding-two-decimals-in-javascript-produce-a-wrong-result.md">why-does-adding-two-decimals-in-javascript-produce-a-wrong-result</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/typeof-NaN.md">typeof-NaN</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/typeof-null-why-its-object.md">If null is a primitive, why does typeof(null) return "object"?</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/null-vs-undefined.md">null-vs-undefined</a></li>
<li><a target="_blank" href="Javascript/Tricky-JS-Problems/Closures-Inside-Loops.md">Closures-Inside-Loops</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-asyncawait-and-promise-related-interview-topics-amp-questions">Most common Async/Await and Promise related Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/README.md">Async/Await - Understanding the fundamentals</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/asyn-await-how-its-called-asynchronous-when-it-makes-possible-to-execute-in-synchrounous-manner.md">asyn-await-how-its-called-asynchronous-when-it-makes-possible-to-execute-in-synchrounous-manner</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/async-await-1.js">Example async-await-1</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/async-await-2.js">Example async-await-2</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/async-await-3.js">Example async-await-3</a></li>
<li><a target="_blank" href="async-await-absolute-basics.js">async-await-absolute-basics</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/async-await-example-when-Promise-is-preferred.js">async-await-example-when-Promise-is-preferred</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/converting-callback-to-Promise-and-async-await-1.md">converting-callback-to-Promise-and-async-await-1</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/converting-callback-to-Promise-and-async-await-2.md">converting-callback-to-Promise-and-async-await-2</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/setTimeout-rate-limiting-api-calls-IMP-with-async-await-looping-over-apis-1.js">setTimeout-rate-limiting-api-calls-IMP-with-async-await-looping-over-apis-1</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/async-await-master-notes/setTimeout-rate-limiting-api-calls-IMP-with-async-await-looping-over-apis-2.js">setTimeout-rate-limiting-api-calls-IMP-with-async-await-looping-over-apis-2</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/README.md">Promise - Fundamental Understanding</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/calback-hell-resolved-with-promise.js">calback-hell-resolved-with-promise</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/callback-hell-examples.js">More callback-hell-examples</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/How-Promise-makes-code-Asynchronous-non-blocking.md">How-Promise-makes-code-Asynchronous-non-blocking</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/Promise-simple-Example.js">Promise Super simple-Examples</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-Super-Basic/absolute-super-basic-Promise-creation.md">More Promise Super simple Examples</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-Super-Basic/Promise-super-basic-implementation-Absolute-Basics.js">More Promise Super simple Examples</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-async-await-master-notes/then-in-Promise-GOOD-Explanations.md">Understanding then in Promise</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-Super-Basic/Promise-super-basic-example-transform-values-with-Promise.md">Promise-super-basic-example-transform-values-with-Promise</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/Promise-Super-Basic/Promise-super-basic-syntax-GOOD.md">Promise-Absolute basic-syntax</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/Async-await-API-call-Simple-Example-synchronous-Fetchl-Simple-Good-Example.md">Async-await-API-call-Simple-Example-synchronous-Fetch</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/Async-Event-Handler-both-async-await-and-with-Promise-1.md">Async-Event-Handler-both-async-await-and-with-Promise-1</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/multiple-API-calls-before-executing-next-function-in-React-Promise-2.md">multiple-API-calls-before-executing-next-function-in-React-Promise-2</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/multiple-API-fetch-before-executing-next-function-in-React-Promise-1.md">multiple-API-fetch-before-executing-next-function-in-React-Promise-1</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/multiple-sequential-axios-request.md">multiple-sequential-axios-request</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/sequential-execution-async-await-in-Express-routes.md">sequential-execution-async-await-in-Express-routes</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/sequential-execution-fundamental_working-THEORY.md">sequential-execution-fundamental_working-THEORY</a></li>
<li><a target="_blank" href="Promise-Async-Await-Sequential-Execution/sequential-execution-of-codes-React-Node-Context-Master-Notes/sequential-execution-plain-callback-in-Express-routes.md">sequential-execution-plain-callback-in-Express-routes</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-node-interview-topics-amp-questions">Most common Node Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Node-Express/why-nodejs-required-at-all-and-difference-vs-plain-js.md">why-nodejs-required-at-all-and-difference-vs-plain-js</a></li>
<li><a target="_blank" href="Node-Express/How-nodejs-works.md">How-nodejs-works</a></li>
<li><a target="_blank" href="Node-Express/What-is-an-error-first-callback.md">What-is-an-error-first-callback</a></li>
<li><a target="_blank" href="Node-Express/Authentication-vs-Authorization.md">Authentication vs Authorization</a></li>
<li><a target="_blank" href="Node-Express/app.use-Middleware-1.md">What is Middleware-1</a></li>
<li><a target="_blank" href="Node-Express/app.use-Middleware-2.md">What is Middleware-2</a></li>
<li><a target="_blank" href="Node-Express/app.use-vs-app.get.md">app.use-vs-app.get</a></li>
<li><a target="_blank" href="Node-Express/bcrypt-How-it-works-de-hashing.md">bcrypt-How-it-works-de-hashing</a></li>
<li><a target="_blank" href="Node-Express/bcrypt-manually-generate-a-salted-and-encrypted-password.md">bcrypt-manually-generate-a-salted-and-encrypted-password</a></li>
<li><a target="_blank" href="Node-Express/bodyParser_what-does-it-do.md">bodyParser_what-does-it-do</a></li>
<li><a target="_blank" href="Node-Express/buffer-class-what-is-it.md">buffer-class-what-is-it</a></li>
<li><a target="_blank" href="Node-Express/busboy-why-its-needed.md">busboy-why-its-needed</a><ul>
<li><a target="_blank" href="Node-Express/busboy-why-I-use-stream-to-upload-file.md">busboy-why-I-use-stream-to-upload-file</a></li>
</ul>
</li>
<li><a target="_blank" href="Node-Express/cookie-parser-what-does-it-do.md">cookie-parser-what-does-it-do</a></li>
<li><a target="_blank" href="Node-Express/cors_Why_its_needed.md">cors_Why_its_needed</a></li>
<li><a target="_blank" href="Node-Express/error-handling-in-node-Theory.md">error-handling-in-node-Theory</a></li>
<li><a target="_blank" href="Node-Express/error-handling-in-node.md">More on error-handling-in-node</a></li>
<li><a target="_blank" href="Node-Express/express-js-why-do-i-need-it.md">express-js-why-do-i-need-it</a></li>
<li><a target="_blank" href="Node-Express/gracefully-shut-down-node-app.md">gracefully-shut-down-node-app</a></li>
<li><a target="_blank" href="Node-Express/jwt-how-it-works.md">jwt-how-it-works</a></li>
<li><a target="_blank" href="Node-Express/jwt-where-to-save-localStorage-vs-sessionStorage-vs-cookie.md">jwt-where-to-save-localStorage-vs-sessionStorage-vs-cookie</a></li>
<li><a target="_blank" href="Node-Express/session-cookies-vs-JWT-Tokens-2-ways-to-authenticate.md">session-cookies-vs-JWT-Tokens-2-ways-to-authenticate</a></li>
<li><a target="_blank" href="Node-Express/sesstionStorage-vs-localStorage-vs-Cookie.md">sesstionStorage-vs-localStorage-vs-Cookie</a></li>
<li><a target="_blank" href="Node-Express/localForage-what-does-it-do.md">localForage-what-does-it-do</a></li>
<li><a target="_blank" href="Node-Express/node-debugging.md">How would you do node-debugging</a></li>
<li><a target="_blank" href="Node-Express/passport-authentication-middleware-BASIC-FLOW.md">passport-authentication-middleware-BASIC-FLOW</a></li>
<li><a target="_blank" href="Node-Express/passport-express-session-Fundamentals-and-params.md">passport-express-session-Fundamentals-and-params</a></li>
<li><a target="_blank" href="Node-Express/passport-express-session-how-it-works.md">passport-express-session-how-it-works</a></li>
<li><a target="_blank" href="Node-Express/passport-workflow-with-passport-local-strategy.md">passport-workflow-with-passport-local-strategy</a></li>
<li><a target="_blank" href="Node-Express/pipe-in-node.md">pipe concepts in node</a></li>
<li><a target="_blank" href="Node-Express/REST-architectural-concepts.md">REST-architectural-concepts</a></li>
<li><a target="_blank" href="Node-Express/significance-of-file-bin-www.md">significance-of-file-bin-www</a></li>
<li><a target="_blank" href="Node-Express/Streams.md">Streams Concepts in Node</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/node-js-interview-questions/">Node.js Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-web-development-architecture-related-interview-topics-amp-questions">Most common Web-Development Architecture related Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Web-Development-In-General/critical-render-path.md">critical-render-path</a></li>
<li><a target="_blank" href="Web-Development-In-General/How-to-Check-HTTP-Request-Response-on-Chrome.md">How-to-Check-HTTP-Request-Response-on-Chrome</a></li>
<li><a target="_blank" href="Web-Development-In-General/HTTP-and-TCP-Difference.md">HTTP-and-TCP-Difference</a></li>
<li><a target="_blank" href="Web-Development-In-General/HTTP-methods-put-vs-post.md">HTTP-methods-put-vs-post</a></li>
<li><a target="_blank" href="Web-Development-In-General/HTTP-Protocol.md">HTTP-Protocol</a></li>
<li><a target="_blank" href="Web-Development-In-General/HTTP-Status-Codes-Understanding-Express-res.status.md">HTTP-Status-Codes-Understanding-Express-res.status</a></li>
<li><a target="_blank" href="Web-Development-In-General/HTTP-Status-Codes.md">More on HTTP-Status-Codes</a></li>
<li><a target="_blank" href="Web-Development-In-General/http-vs-https.md">http-vs-https</a></li>
<li><a target="_blank" href="Web-Development-In-General/minimmize-page-load-time.md">minimize-page-load-time</a></li>
<li><a target="_blank" href="Web-Development-In-General/Postman-checking-protected-routes-from-backend.md">Postman-checking-protected-routes-from-backend</a></li>
<li><a target="_blank" href="Web-Development-In-General/websocket-basics.md">websocket-basics</a></li>
<li><a target="_blank" href="Web-Development-In-General/What-happens-when-you-navigate-to-an-URL.md">What-happens-when-you-navigate-to-an-URL</a></li>
<li><a target="_blank" href="Web-Development-In-General/What-happens-when-you-navigate-to-google.md">What-happens-when-you-navigate-to-google</a></li>
<li><a target="_blank" href="Web-Development-In-General/what-is-AJAX.md">what-is-AJAX</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/web-developer-interview-questions/">Web Developer Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-react-interview-topics-amp-questions">Most common React Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="React/Element-vs-Component-in-React.md">Element-vs-Component-in-React</a></li>
<li><a target="_blank" href="React/props-Absolute-Basics.md">What is a Prop - props-Absolute-Basics</a></li>
<li><a target="_blank" href="React/Component-Life-Cycle/README.md">Life-Cycle-Fundamentals</a></li>
<li><a target="_blank" href="React/Component-Life-Cycle/getDerivedStateFromProps.md">Life Cycle Methods - getDerivedStateFromProps</a></li>
<li><a target="_blank" href="React/Component-Life-Cycle/shouldComponentUpdate-what-does-it-do.md">Life Cycle Methods - shouldComponentUpdate-what-does-it-do</a></li>
<li><a target="_blank" href="React/Component-Life-Cycle/constructor-vs-componentwillmount.md">Life Cycle Methods - constructor-vs-componentwillmount</a></li>
<li><a target="_blank" href="React/Hooks/convert-ClassBasedForm-to-HooksBasedForm.md">React-Hooks-convert-ClassBasedForm-to-HooksBasedForm</a><ul>
<li><a target="_blank" href="React/Hooks/updateState-with-callback.md">hooks-updateState-with-callback</a></li>
<li><a target="_blank" href="React/Hooks/lifeCycle-methods-for-various-hooks.md">lifeCycle-methods-for-various-hooks</a></li>
<li><a target="_blank" href="React/Hooks/Shallow-comparison-React-useEffect-compare-array-in-second-argument.md">Shallow-comparison-React-useEffect-compare-array-in-second-argument</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-basics-1.md">useEffect-basics-1</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-api-call-with-async-inside-useEffect.md">useEffect-api-call-with-async-inside-useEffect</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-async-call-inside.md">More on useEffect-async-call-inside</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-compare-array-in-second-argument-replace-ComonentDidMount-with-useRef.md">useEffect-compare-array-in-second-argument-replace-ComonentDidMount-with-useRef</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-compare-array-in-second-argument-shallow.md">useEffect-compare-array-in-second-argument-shallow</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-replace-componentDidMount-and-Update.md">useEffect-replace-componentDidMount-and-Update</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-replace-componentWillUnmount.md">useEffect-replace-componentWillUnmount</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-running-callback-after-setState-IMPORTANT.md">useEffect-running-callback-after-setState-IMPORTANT</a></li>
<li><a target="_blank" href="React/Hooks/useEffect-with-Redux-actions-GOOD.md">useEffect-with-Redux-actions</a></li>
<li><a target="_blank" href="React/Hooks/useReducer-basics-1.md">useReducer-basics-1</a></li>
<li><a target="_blank" href="React/Hooks/userReducer-vs-redux-reducer.md">userReducer-vs-redux-reducer</a></li>
<li><a target="_blank" href="React/Hooks/useState-replace-componentWillReceiveProps-getDerivedStateFromProps.md">useState-replace-componentWillReceiveProps-getDerivedStateFromProps</a></li>
</ul>
</li>
<li><a target="_blank" href="React/React-Styled-Component/styled-component-basics.md">styled-component-basics</a></li>
<li><a target="_blank" href="React/React-Styled-Component/styled-component-a-clean-example.md">styled-component-a-clean-example</a></li>
<li><a target="_blank" href="React/React-Testing-Jest/Testing-react-shallow-renderer-basics.md">Testing-react-shallow-renderer-basics</a></li>
<li><a target="_blank" href="React/React-Testing-Jest/snapshot-testing.md">snapshot-testing</a></li>
<li><a target="_blank" href="React/React-Testing-Jest/where-should-enzyme-setup-file-be-written.md">React Testing - where-should-enzyme-setup-file-be-written</a></li>
<li><a target="_blank" href="React/refs-in-react/refs-in-React.md">refs-in-React</a><ul>
<li><a target="_blank" href="React/refs-in-react/refs-Call-child-method-from-parent.md">refs-Call-child-method-from-parent</a></li>
<li><a target="_blank" href="React/refs-in-react/execute-child-function-from-parent.md">execute-child-function-from-parent</a></li>
<li><a target="_blank" href="React/refs-in-react/refs-vs-keys-when-to-use-ref.md">refs-vs-keys-when-to-use-ref</a></li>
<li><a target="_blank" href="React/refs-in-react/useRef-basics.md">useRef-basics</a></li>
</ul>
</li>
<li><a target="_blank" href="React/context-api-basics.md">context-api-basics</a></li>
<li><a target="_blank" href="React/controlled-unContolled-Component.md">controlled-unContolled-Component</a></li>
<li><a target="_blank" href="React/Create-Class-avoiding-binding-in-constructor.md">Create-Class-avoiding-binding-in-constructor</a></li>
<li><a target="_blank" href="React/destructuring_basics-js.md">destructuring_basics-js</a></li>
<li><a target="_blank" href="React/destructuring_example.md">More destructuring_example</a></li>
<li><a target="_blank" href="React/Destructuring_General.md">More Destructuring explanations and examples</a></li>
<li><a target="_blank" href="React/destructuring_in_react-1.md">destructuring_in_react-1</a></li>
<li><a target="_blank" href="React/destructuring_in_react-2.md">More destructuring_in_react</a></li>
<li><a target="_blank" href="React/e.target.value.md">What is e.target.value</a></li>
<li><a target="_blank" href="React/Explain-whats-wrong-with-this-React-code.md">Explain-whats-wrong-with-this-React-code</a></li>
<li><a target="_blank" href="React/functional-component-declaration-syntax.md">functional-component-declaration-syntax</a></li>
<li><a target="_blank" href="React/functional-component-declaration-syntax-1.md">More examples on functional-component-declaration-syntax</a></li>
<li><a target="_blank" href="React/HOC.md">HOC - Higher Order Component</a></li>
<li><a target="_blank" href="React/how-react-decide-to-re-render-a-component.md">how-react-decide-to-re-render-a-component</a></li>
<li><a target="_blank" href="React/keys-for-li-elements-why-its-needed.md">Unique keys-for-li-elements-why-its-needed</a></li>
<li><a target="_blank" href="React/onChange-updating-state-from-child.md">onChange-updating-state-from-child</a></li>
<li><a target="_blank" href="React/pass-props-from-Parent-To-Child-Component-communication.md">pass-props-from-Parent-To-Child-Component-communication</a><ul>
<li><a target="_blank" href="React/pass-prop-to-component-rendered-by-React-Router.md">pass-prop-to-component-rendered-by-React-Router</a></li>
<li><a target="_blank" href="React/pass-props-from-Child-to-parent-Component-communication.md">More on pass-props-from-Child-to-parent-Component-communication</a></li>
<li><a target="_blank" href="React/pass-props-from-Child-to-parent-Component-communication-2.md">More on pass-props-from-Child-to-parent-Component-communication-2</a></li>
</ul>
</li>
<li><a target="_blank" href="React/preventDefault-in-React.md">preventDefault-in-React</a></li>
<li><a target="_blank" href="React/pureComponent.md">pureComponent - What they are</a></li>
<li><a target="_blank" href="React/pureComponent-Performance-benefit.md">pureComponent-Performance-benefit</a></li>
<li><a target="_blank" href="React/react-hot-loader.md">react-hot-loader</a></li>
<li><a target="_blank" href="React/React.Fragment.md">React.Fragment</a></li>
<li><a target="_blank" href="React/Redirect-from-react-router-dom.md">Redirect-from-react-router-dom</a></li>
<li><a target="_blank" href="React/server-side-rendering-react-app.md">server-side-rendering-react-app</a></li>
<li><a target="_blank" href="React/setState-what-does-it-do.md">setState-what-does-it-do</a></li>
<li><a target="_blank" href="&lt;React/super(props)-why-its-required.md&gt;">super(props)-why-its-required</a></li>
<li><a target="_blank" href="React/this.props.children.md">this.props.children</a></li>
<li><a target="_blank" href="React/Virtual-DOM-and-Reconciliation-Algorithm.md">Virtual-DOM-and-Reconciliation-Algorithm</a></li>
<li><a target="_blank" href="React/include-polyfills.md">What are the approaches to include polyfills in your create-react-app</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/react-interview-questions/">React Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-redux-interview-topics-amp-questions">Most common Redux Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Redux/Actions.md">What is Redux Actions</a></li>
<li><a target="_blank" href="Redux/actions-why-enclosed-in-curly-braces.md">actions-why-enclosed-in-curly-braces</a></li>
<li><a target="_blank" href="Redux/actions.payload.md">What are actions.payload</a></li>
<li><a target="_blank" href="Redux/applyMiddleware.md">What is applyMiddleware</a></li>
<li><a target="_blank" href="Redux/bindActionCreators.md">What is bindActionCreators</a></li>
<li><a target="_blank" href="Redux/combine-Recucer.md">What is combine-Reducer</a></li>
<li><a target="_blank" href="Redux/compose-function.md">What is compose-function</a></li>
<li><a target="_blank" href="Redux/Connect.md">What is Connect function</a></li>
<li><a target="_blank" href="Redux/container-component.md">What is container-component</a></li>
<li><a target="_blank" href="Redux/createStore.md">What is createStore</a></li>
<li><a target="_blank" href="Redux/currying.md">Example of Currying</a></li>
<li><a target="_blank" href="Redux/dispatch.md">What is dispatch</a></li>
<li><a target="_blank" href="Redux/flux-vs-redux.md">flux-vs-redux</a></li>
<li><a target="_blank" href="Redux/mapDispatchToProps.md">What is mapDispatchToProps</a></li>
<li><a target="_blank" href="Redux/mapStateToProps-basic-understanding-1.md">mapStateToProps-basic-understanding-1</a></li>
<li><a target="_blank" href="Redux/mapStateToProps-basic-understanding-2.md">mapStateToProps-basic-understanding-2</a></li>
<li><a target="_blank" href="Redux/mapStateToProps-how-exactly-it-gets-the-state-from-reducers.md">mapStateToProps-how-exactly-it-gets-the-state-from-reducers</a></li>
<li><a target="_blank" href="Redux/Provider.md">What is Provider</a></li>
<li><a target="_blank" href="Redux/Reducers.md">What is Reducers</a></li>
<li><a target="_blank" href="Redux/redux-thunk-basics.md">What is Redux Thunk</a></li>
<li><a target="_blank" href="Redux/redux-thunk-what-is-thunk-in-programming.md">what-is-thunk-in-programming</a></li>
<li><a target="_blank" href="Redux/Store.md">What is Store</a></li>
<li><a target="_blank" href="React/immutable-state-store-in-React-Redux/Why-Redux-needs-reducers-to-be-pure-functions-VERY-GOOD-EXPLANATIONS.md">Why-Redux-needs-reducers-to-be-pure functions</a></li>
<li><a target="_blank" href="React/immutable-state-store-in-React-Redux/immutable-state-store-in-React-Redux-2.md">immutable-state-store-in-React-Redux-2</a></li>
<li><a target="_blank" href="React/immutable-state-store-in-React-Redux/immutable-state-store-in-React-Redux-Pass-by-Reference-shallow-comapre.md">immutable-state-store-in-React-Redux-Pass-by-Reference-shallow-comapre</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/redux-interview-questions/">Redux Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-angular-interview-topics-amp-questions">Most common Angular Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Angular-Topics-Interview/AsyncPipe/AsyncPipe-fundamentals.md">AsyncPipe-fundamentals</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/AsyncPipe/AsyncPipe-basic-Oberservable-use-case.md">AsyncPipe-basic-Oberservable-use-case</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/AsyncPipe/converting-a-subscribe-to-asyncPipe-1.md">converting-a-subscribe-to-asyncPipe-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/AsyncPipe/converting-a-subscribe-to-asyncPipe-Simplest-use-case.md">converting-a-subscribe-to-asyncPipe-Simplest-use-case</a></li>
<li><a target="_blank" href="Converting-a-subscribe-to-asyncPipe-3">Converting-a-subscribe-to-asyncPipe-3</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Component-Data-Communications/Component-Communications-via-Input.md">Component-Communications-via-Input</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Component-Data-Communications/Component-Communications-via-Output-EventEmitter.md">Component-Communications-via-Output-EventEmitter</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/ContentChildren-basics.md">ContentChildren-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/decorators-basics-in-angular.md">decorators-basics-in-angular</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/decorators-basics-in-typescript.md">decorators-basics-in-typescript</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/Property-decorators-basics-in-angular-1.md">Property-decorators-basics-in-angular-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/Property-Decorators-Typescript-1.md">Property-Decorators-Typescript-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/Property-Decorators-Typescript-2.md">Property-Decorators-Typescript-2</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/QueryList-basics.md">QueryList-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/TemplateRef-basics-1.md">TemplateRef-basics-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/TemplateRef-basics-2.md">TemplateRef-basics-2</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Decorators/ViewChild-basics.md">ViewChild-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Life-Cycle-Hooks/AfterViewInit-hook.md">AfterViewInit-hook</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Life-Cycle-Hooks/ngOnChanges-Fundamentals.md">ngOnChanges-Fundamentals</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Life-Cycle-Hooks/ngOnChanges-SimpleChanges_interface.md">ngOnChanges-SimpleChanges_interface</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Life-Cycle-Hooks/ngOnInit-vs-Constructor.md">ngOnInit-vs-Constructor</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Life-Cycle-Hooks/ngOnInit-vs-ngAfterViewInit.md">ngOnInit-vs-ngAfterViewInit</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ng-Best_Practice/ngOnChange-BestPractice.md">ngOnChange-BestPractice</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/cold-vs-hot-observable.md">cold-vs-hot-observable</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/examples-cancellable-with-takeUntil.ts">examples-cancellable-with-takeUntil</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/examples-observable-is-Lazy.ts">examples-observable-is-Lazy</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/Observable-basics.md">Observable-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/Observable-simple-implementation-1.md">Observable-simple-implementation-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/Observable-vs-Promises.md">Observable-vs-Promises</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Observables/subscribe-method.md">subscribe-method</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Routing/Reading-Route-Parameters.md">Reading-Route-Parameters in Angular</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/best-practices-common-pattern/Dont-pass-streams-to-components-directly.md">rx-js-best-practice - Dont-pass-streams-to-components-directly</a></li>
<li><a target="_blank" href="&lt;Angular-Topics-Interview/rx-js/best-practices-common-pattern/subscribe_pattern-with-take(1).md&gt;">subscribe_pattern-with-take(1)</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/best-practices-common-pattern/when_using_async_pipe_no_need_to_unsubscribe.md">Best Practice - when_using_async_pipe_no_need_to_unsubscribe</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/angular-httpclient-unsubscribe.md">Is there a need to unsubscribe from the Observable the Angular HttpClient's methods return?</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/combineLatest-basics.md">combineLatest-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/debounceTime-usecase-input-validation.md">debounceTime-usecase-input-validation</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/pipe-basics-how-it-works-with-simple-good-example.md">pipe-basics-how-it-works-with-example</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/pipe-function-1.md">More on pipe-function-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/pipe-function-2.md">More on pipe-function-2</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/pipe-function-3.md">More on pipe-function-3</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/retryWhen-1.md">retryWhen - I want to retry an api call 10 times (waiting one second since it fails until next execution)</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/retryWhen-basics-2.md">More on retryWhen-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/switchMap-get-route-params.md">switchMap-get-route-params</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/rx-js/switchMap-good-example-for-user-input.md">switchMap-good-example-for-user-input</a></li>
<li><a target="_blank" href="&lt;Angular-Topics-Interview/rx-js/take(1).md&gt;">take(1)</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/TypeScript/Class-Definitions/class-in-typescript.md">class-in-typescript</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/TypeScript/Class-Definitions/generic-typescript-class-definition.md">generic-typescript-class-definition</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/TypeScript/Class-Definitions/get-method-in-typescript.md">get-method-in-typescript</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/TypeScript/Class-Definitions/proxy-in-ts.md">proxy-in-typescript</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/Useful_Pattern_Observable/when-a-method-returns-boolean.md">typescript - when-a-method-returns-boolean</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ViewEncapsulation/ViewEncapsulation-Basics.md">ViewEncapsulation-Basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ViewEncapsulation/ViewEncapsulation-None.md">ViewEncapsulation-None</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/component-selectors-different-way.md">component-selectors-different-way</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ControlValueAccessor_basics.md">ControlValueAccessor_basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/directive-basics.md">directive-basics</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/host-selector.md">host-selector</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ng-content.md">ng-content</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ngModel-basics-1.md">ngModel-basics-1</a></li>
<li><a target="_blank" href="Angular-Topics-Interview/ngModel-basics-2.md">ngModel-basics-2</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/angular-interview-questions/">Angular Interview Questions</a></li>
<li><a target="_blank" href="https://dev.to/alishaas11/javascript-vs-typescript-know-the-difference-4dg6">JavaScript vs Typescript:</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-mongodb-interview-topics-amp-questions">Most common MongoDB Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="MongoDB/aggregation-in-mongodb.md">aggregation-in-mongodb</a></li>
<li><a target="_blank" href="MongoDB/delete-single-document-from-collection.md">delete-single-document-from-collection</a></li>
<li><a target="_blank" href="MongoDB/GridFS-storing-files-in-mongo.md">GridFS-storing-files-in-mongo</a></li>
<li><a target="_blank" href="MongoDB/indexing-in-mongo.md">indexing-in-mongo</a></li>
<li><a target="_blank" href="MongoDB/mongodb-quick-comands-cheat-sheet.md">mongodb-quick-comands-cheat-sheet</a></li>
<li><a target="_blank" href="MongoDB/mongoose-exec-method.md">mongoose-exec-method</a></li>
<li><a target="_blank" href="MongoDB/populate-method-mongoose-referencing-other-model.md">referencing-other-model-populate-method-mongoose</a></li>
<li><a target="_blank" href="MongoDB/referencing-another-schema-in-Mongoose-1.md">referencing-another-schema-in-Mongoose-1</a></li>
<li><a target="_blank" href="MongoDB/referencing-another-schema-in-Mongoose-2.md">More on referencing-another-schema-in-Mongoose-1</a></li>
<li><a target="_blank" href="MongoDB/sharding-in-mongodb.md">sharding-in-mongodb</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/mongodb-interview-questions/">MongpDB Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-html-interview-topics-amp-questions">Most common HTML Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="HTML/Collection-of-HTML-Interview-Questions.md">Collection-of-HTML-Interview-Questions</a></li>
<li><a target="_blank" href="HTML/DOM-fundamentals.md">DOM-fundamentals</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/html-interview-questions/">HTML Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-css-interview-topics-amp-questions">Most common CSS Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="CSS/Collection-of-CSS-Questions.md">Collection-of-CSS-Questions</a></li>
<li><a target="_blank" href="BEM-Model">BEM-Model</a></li>
<li><a target="_blank" href="box-Model">box-Model</a></li>
<li><a target="_blank" href="CSS/flexbox.md">flexbox</a></li>
<li><a target="_blank" href="CSS/flexbox-example-centerting-elements.md">flexbox-example-centering-elements</a></li>
<li><a target="_blank" href="CSS/Grid-Layout.md">Grid-Layout</a></li>
<li><a target="_blank" href="CSS/left-vs-margin-left.md">left-vs-margin-left</a></li>
<li><a target="_blank" href="CSS/not-pseudo-class-selector.md">not-pseudo-class-selector</a></li>
<li><a target="_blank" href="CSS/pseudo-class.md">pseudo-class</a></li>
<li><a target="_blank" href="CSS/relative-absolute-fixed-position.md">relative-absolute-fixed-position</a></li>
<li><a target="_blank" href="CSS/relative-positioning-basic-good-notes.md">relative-positioning-basic-good-notes</a></li>
<li><a target="_blank" href="CSS/rem-unit-basics-and-converting-px.md">rem-unit-basics-and-converting-px</a></li>
<li><a target="_blank" href="CSS/z-index.md">z-index</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/css-interview-questions/">CSS Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-common-git-and-github-related-interview-topics-amp-questions">Most common Git and Github related Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="Git-and-Github/git-stash.md">What is git stash</a></li>
<li><a target="_blank" href="Git-and-Github/git-rebase/git-rebase.md">What is git rebase</a></li>
<li><a target="_blank" href="Git-and-Github/git-rebase/git-rebase-Resolving-merge-conflicts.md">Resolving-merge-conflicts during git-rebase-</a></li>
<li><a target="_blank" href="Git-and-Github/PR-Flow/git-squash-many-commits-to-a-single-one-before-PR.md">git-squash-many-commits-to-a-single-one-before-PR</a></li>
<li><a target="_blank" href="Git-and-Github/PR-Flow/Pull-Requst-Steps-to-take-in-a-team-before-submitting-PR.md">Pull-Requst-Steps-to-take-in-a-team-before-submitting-PR</a></li>
<li><a target="_blank" href="Git-and-Github/PR-Flow/Update-cloned-repo-in-local-machine-with-latest-master-branch.md">Update-cloned-repo-in-local-machine-with-latest-master-branch</a></li>
<li><a target="_blank" href="Git-and-Github/git-staging-area.md">git-staging-area</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/git-interview-questions/">Git Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-understanding-the-theory-and-the-fundamentals-of-some-super-popular-algorithm-questions">Understanding the Theory and the fundamentals of some super-popular Algorithm questions</h2>
<ul>
<li>:link: <a target="_blank" href="http://bigocheatsheet.com/">Big O Cheatsheet</a>
:link: <a target="_blank" href="https://medium.com/@jayshah_84248/big-o-for-coding-interviews-e6ca8897f926">Quick Big O understanding for coding interviews</a></li>
<li>:link: <a target="_blank" href="https://www.toptal.com/developers/sorting-algorithms">developers/sorting-algorithms</a></li>
<li>:link: <a target="_blank" href="https://medium.com/@yanganif/tackling-javascript-algorithms-66f1ac9770dc">tackling-javascript-algorithms</a></li>
<li>:link: <a target="_blank" href="https://github.com/benoitvallon/computer-science-in-javascript/tree/master/sorting-algorithms-in-javascript">sorting-algorithms-in-javascript</a></li>
<li>:link: <a target="_blank" href="https://github.com/Algorithm-archive/Learn-Data_Structure-Algorithm-by-Javascript">Learn-Data_Structure-Algorithm-by-Javascript</a></li>
<li>:book: <a target="_blank" href="https://www.goodreads.com/book/show/22847284-grokking-algorithms-an-illustrated-guide-for-programmers-and-other-curio">Grokking Algorithms</a></li>
<li>:link: <a target="_blank" href="https://www.cs.usfca.edu/~galles/visualization/Algorithms.html">Algorithms Visualization</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/coding-interviews-for-dummies-5e048933b82b">coding-interviews-for-dummies</a></li>
<li>:link: <a target="_blank" href="https://www.educative.io/collection/page/5642554087309312/5679846214598656/240002">educative.io/collection/page/</a></li>
<li>:link: <a target="_blank" href="https://www.wikiwand.com/en/Rabin%E2%80%93Karp_algorithm">Karp_algorithm</a></li>
<li>:link: <a target="_blank" href="https://www.geeksforgeeks.org/top-algorithms-and-data-structures-for-competitive-programming/">www.geeksforgeeks.org/top-algorithms-and-data-structures-for-competitive-programming/</a></li>
<li>:link: <a target="_blank" href="https://github.com/trekhleb/javascript-algorithms">best javascript-algorithms github repo</a></li>
<li>:link: <a target="_blank" href="https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed">14-patterns-to-ace-any-coding-interview-question</a></li>
<li>:link: <a target="_blank" href="https://www.educative.io/collection/5668639101419520/5671464854355968">Grokking the Coding Interview: Patterns for Coding Questions</a></li>
<li>:link: <a target="_blank" href="https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript">https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript</a></li>
<li>:link: <a target="_blank" href="https://github.com/jwasham/coding-interview-university">coding-interview-university</a></li>
<li>:link: <a target="_blank" href="https://github.com/sudheerj/reactjs-interview-questions">reactjs-interview-questions</a></li>
<li>:link: <a target="_blank" href="https://github.com/h5bp/Front-end-Developer-Interview-Questions">Front-end-Developer-Interview-Questions</a></li>
<li>:link: <a target="_blank" href="https://github.com/yangshun/front-end-interview-handbook">front-end-interview-handbook</a> - Almost complete answers to "Front-end Job Interview Questions" which you can use to interview potential candidates, test yourself or completely ignore</li>
<li>:link: <a target="_blank" href="https://www.interviewbit.com/algorithm-interview-questions/">Algorithm Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-github-repositories-with-large-collections-of-problems-and-solutions-of-them-most-popular-interview-challenges">Github Repositories with large collections of problems-and-solutions of them most popular Interview challenges</h2>
<ul>
<li>:link: <a target="_blank" href="https://github.com/ignacio-chiazzo/Algorithms-Leetcode-Javascript">Algorithms-Leetcode-Javascript</a></li>
<li>:link: <a target="_blank" href="https://github.com/rohan-paul/Algorithm-in-JavaScript">Algorithm-in-JavaScript</a></li>
<li>:link: <a target="_blank" href="https://github.com/rohan-paul/Javascript-Challenges">Javascript-Challenges</a></li>
<li>:link: <a target="_blank" href="https://github.com/rohan-paul/The-Hacking-School-Full-Stack-Bootcamp-Projects/tree/master/JS-Challenges">JS-Challenges</a></li>
<li>:link: <a target="_blank" href="https://github.com/mkshen/code-problems-solutions">code-problems-solutions</a></li>
<li>:link: <a target="_blank" href="https://gist.github.com/Smakar20?page=1">some common problems</a></li>
<li>:link: <a target="_blank" href="https://github.com/careercup/CtCI-6th-Edition-JavaScript">Cracking the Coding Interview - Javascript</a></li>
<li>:link: <a target="_blank" href="https://github.com/kennymkchan/interview-questions-in-javascript">interview-questions-in-javascript</a></li>
<li>:link: <a target="_blank" href="https://github.com/sudheerj/javascript-interview-questions">javascript-interview-questions</a></li>
<li>:link: <a target="_blank" href="https://github.com/kolodny/exercises">javascript-Exercises</a></li>
<li>:link: <a target="_blank" href="https://github.com/30-seconds/30-seconds-of-interviews">30-seconds-of-interview</a></li>
<li>:link: <a target="_blank" href="https://github.com/vvscode/js--interview-questions">js--interview-questions</a></li>
<li>:link: <a target="_blank" href="https://github.com/sadanandpai/javascript-code-challenges">JavaScript-Code-Challenges</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-overall-multi-factor-approach-for-winning-this-huge-challenge-and-a-great-journey-of-getting-the-first-developer-job">Overall multi-factor approach for winning this huge challenge and a great journey of getting the first Developer Job</h2>
<ul>
<li>:link: <a target="_blank" href="https://medium.com/javascript-scene/every-developer-needs-a-code-portfolio-cc79c3d92110">medium.com/javascript-scene/every-developer-needs-a-code-portfolio</a>
:link: <a target="_blank" href="https://medium.com/@jayshah_84248/how-to-do-well-in-a-coding-interview-2bcd67e93cb5">Collection of Resources for Interview preparations and practices</a>
:link: <a target="_blank" href="https://medium.com/@rachit138/how-i-cleared-the-amazon-sde-2-interview-f82a33706ff4">How I cleared the Amazon SDE 2 interview</a>
:link: <a target="_blank" href="https://blog.usejournal.com/how-i-got-7-job-offers-in-8-weeks-part-1-please-interview-me-21e6f4ded106">How I got 7 Job Offers in 8 Weeks </a></li>
<li>:link: <a target="_blank" href="https://medium.com/javascript-scene/master-the-javascript-interview-soft-skills-a8a5fb02c466">/master-the-javascript-interview-soft-skills</a></li>
<li>:link: <a target="_blank" href="https://medium.com/@jayshah_84248/google-lost-a-chance-to-hire-me-finally-amazon-hired-me-e35076c73fe2">google-lost-a-chance-to-hire-me-finally-amazon-hired-me</a></li>
<li>:link: <a target="_blank" href="https://medium.com/javascript-scene/the-best-way-to-learn-to-code-is-to-code-learn-app-architecture-by-building-apps-7ec029db6e00">the-best-way-to-learn-to-code-is-to-code-learn-app-architecture-by-building-apps</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/7-key-steps-to-getting-your-first-software-engineering-job-6ef80543cad9">7-key-steps-to-getting-your-first-software-engineering-job</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/5-key-learnings-from-the-post-bootcamp-job-search-9a07468d2331">5-key-learnings-from-the-post-bootcamp-job-search</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/https-medium-com-samwcoding-how-to-get-your-first-developer-job-in-4-months-ec86da6e5d9a">how-to-get-your-first-developer-job-in-4-months</a></li>
<li>:link: <a target="_blank" href="https://medium.com/swlh/how-to-land-your-first-dev-job-even-if-you-don-t-have-a-cs-degree-e83d08db4615">how-to-land-your-first-dev-job-even-if-you-don-t-have-a-cs-degree</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/how-to-land-a-top-notch-tech-job-as-a-student-5c97fec82f3d">how-to-land-a-top-notch-tech-job-as-a-student</a></li>
<li>:link: <a target="_blank" href="https://medium.com/appsflyer/unlocking-the-javascript-code-interview-an-interviewer-perspective-f4fe06246b29">unlocking-the-javascript-code-interview-an-interviewer-perspective</a></li>
<li>:link: <a target="_blank" href="https://steve-yegge.blogspot.com/2008/03/get-that-job-at-google.html">get-that-job-at-google.html</a></li>
<li>:link: <a target="_blank" href="https://blog.usejournal.com/i-failed-my-effing-coding-interview">i-failed-my-effing-coding-interview-ab720c339c8a</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/how-i-landed-a-full-stack-developer-job-without-a-tech-degree-or-work-experience-6add97be2051">how-i-landed-a-full-stack-developer-job-without-a-tech-degree-or-work-experience</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/here-are-4-best-ways-to-apply-for-software-engineer-jobs-and-exactly-how-to-use-them-a644a88b2241">here-are-4-best-ways-to-apply-for-software-engineer-jobs-and-exactly-how-to-use-them</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/how-to-get-a-tech-job-with-no-previous-work-experience-6d3d7d25e1">how-to-get-a-tech-job-with-no-previous-work-experience</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/the-hard-thing-about-learning-hard-things-168e655ac7f2">the-hard-thing-about-learning-hard-things</a></li>
<li>:link: <a target="_blank" href="https://medium.com/@traversymedia/70-job-find-websites-for-developers-other-tech-professionals-34cdb45518be">70-job-find-websites-for-developers-other-tech-professionals</a></li>
<li>:link: <a target="_blank" href="https://www.youtube.com/watch?v=xKOPqWWmxEQ">YouTube - 70+ Websites To Find Developer Jobs</a></li>
<li>:link: <a target="_blank" href="https://www.youtube.com/watch?v=EJDZ2L95Sjo">YouTube - I'm 47 And Now I Want to be a Programmer</a></li>
<li>:link: <a target="_blank" href="https://www.youtube.com/watch?v=V71Cv7mjgfI">YouTube - How To Be A Well-Paid Programmer In 1 Year?</a></li>
<li>:link: <a target="_blank" href="https://medium.freecodecamp.org/the-secret-to-being-a-top-developer-is-building-things-heres-a-list-of-fun-apps-to-build-aac61ac0736c">the-secret-to-being-a-top-developer-is-building-things-heres-a-list-of-fun-apps-to-build</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h3 id="heading-other-important-resources">Other important resources</h3>
<ul>
<li>:link: <a target="_blank" href="http://overapi.com/javascript">javascript cheatsheet</a></li>
<li>:link: <a target="_blank" href="https://www.interviewbit.com/javascript-cheat-sheet/">Javascript cheat sheet - InterviewBit</a></li>
<li>:link: <a target="_blank" href="https://github.com/DrkSephy/es6-cheatsheet">Super useful es6-cheatsheet</a></li>
<li>:link: <a target="_blank" href="https://guide.freecodecamp.org/">freeCodeCamp Guide</a></li>
<li>:link: <a target="_blank" href="https://hackernoon.com/functional-programming-in-js-map-filter-reduce-pt-5-308a205fdd5f">functional-programming-in-js-map-filter-reduce</a></li>
<li>:link: <a target="_blank" href="https://medium.com/javascript-in-plain-english/you-must-understand-these-14-javasript-functions-1f4fa1c620e2">you-must-understand-these-14-javasript-functions</a></li>
<li>:link: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">developer.mozilla.org/JavaScript/A_re-introduction_to_JavaScript</a></li>
<li>:link: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide">developer.mozilla.org/docs/JavaScript/Guide</a></li>
<li>:book: <a target="_blank" href="https://github.com/getify/You-Dont-Know-JS">You-Dont-Know-JS</a></li>
<li>:link: <a target="_blank" href="https://www.geeksforgeeks.org/">GeeksForGeeks</a></li>
<li>:link: <a target="_blank" href="https://dev.to/">Dev.To</a></li>
<li>:link: <a target="_blank" href="https://stackoverflow.com/">Stack Overflow</a></li>
<li>:link: <a target="_blank" href="https://dzone.com/">Dzone</a></li>
<li>:link: <a target="_blank" href="https://scotch.io/">https://scotch.io/</a></li>
<li>:link: <a target="_blank" href="https://30secondsofcode.org/">https://30secondsofcode.org/</a></li>
<li>:link: <a target="_blank" href="https://blog.webf.zone/front-end-javascript-interviews-in-2018-19-e17b0b10514">Front-end JavaScript Interviews in 2018–19</a></li>
<li>:link: <a target="_blank" href="https://www.scaler.com/topics/">Scaler Topics</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-coding-challenge-practice-platforms">Coding Challenge Practice Platforms</h2>
<ul>
<li>:link: <a target="_blank" href="https://interviewing.io/">interviewing.io</a></li>
<li>:link: <a target="_blank" href="https://leetcode.com/">Leetcode</a></li>
<li>:link: <a target="_blank" href="https://www.hackerrank.com/">HackerRank</a></li>
<li>:link: <a target="_blank" href="http://codeforces.com/">CodeForces</a></li>
<li>:link: <a target="_blank" href="https://www.codechef.com">CodeChef</a></li>
<li>:link: <a target="_blank" href="https://coderbyte.com/">Coderbyte</a></li>
<li>:link: <a target="_blank" href="https://www.codingame.com/">CodinGame</a></li>
<li>:link: <a target="_blank" href="https://csacademy.com/">Cs Academy</a></li>
<li>:link: <a target="_blank" href="https://www.dailycodingproblem.com/">Daily Coding Problem</a></li>
<li>:link: <a target="_blank" href="https://spoj.com/">Spoj</a></li>
<li>:link: <a target="_blank" href="https://hackerearth.com/">HackerEarth</a></li>
<li>:link: <a target="_blank" href="https://www.topcoder.com/">TopCoder</a></li>
<li>:link: <a target="_blank" href="https://codewars.com/">Codewars</a></li>
<li>:link: <a target="_blank" href="http://www.exercism.io/">Exercism</a></li>
<li>:link: <a target="_blank" href="https://codefights.com/">CodeFights</a></li>
<li>:link: <a target="_blank" href="https://projecteuler.net/">Project Euler</a></li>
<li>:link: <a target="_blank" href="https://www.interviewcake.com/">Interviewcake</a></li>
<li>:link: <a target="_blank" href="https://www.interviewbit.com/">InterviewBit</a></li>
<li>:link: <a target="_blank" href="ucoder.com.br">uCoder</a></li>
<li>:link: <a target="_blank" href="https://www.lintcode.com/">LintCode</a></li>
<li>:link: <a target="_blank" href="https://codecombat.com/">CodeCombat</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-more-curated-list-of-general-resources-for-javascript-interviews">More curated list of general resources for JavaScript Interviews</h2>
<ul>
<li><p>:link: <a target="_blank" href="https://twitter.com/i/lists/1273224332521717761">Follow this list in Twitter - These are some great developers who regularly gives a lot of useful advice for a wannabe dev regularly</a></p>
</li>
<li><p>:link: <a target="_blank" href="https://www.thatjsdude.com/interview/js1.html">https://www.thatjsdude.com/interview/js1.html</a> - JS: Interview Algorithm Part-1</p>
</li>
<li><p>:link: <a target="_blank" href="https://www.thatjsdude.com/interview/js2.html">https://www.thatjsdude.com/interview/js2.html</a> - JS: Basics and Tricky Questions Part-2: intermediate</p>
</li>
<li><p>:link: <a target="_blank" href="https://www.thatjsdude.com/interview/dom.html">https://www.thatjsdude.com/interview/dom.html</a> - JS: Interview Questions Part-3</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb">https://medium.freecodecamp.org/3-questions-to-watch-out-for-in-a-javascript-interview-725012834ccb</a> - 3 JavaScript questions to watch out for during coding interviews</p>
</li>
<li><p>:link: <a target="_blank" href="https://github.com/ggomaeng/awesome-js">https://github.com/ggomaeng/awesome-js</a> - A curated list of javascript fundamentals and algorithms</p>
</li>
<li><p>:link: <a target="_blank" href="https://github.com/Chalarangelo/30-seconds-of-code">https://github.com/Chalarangelo/30-seconds-of-code</a> - Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/dev-bits/a-perfect-guide-for-cracking-a-javascript-interview-a-developers-perspective-23a5c0fa4d0d">https://medium.com/dev-bits/a-perfect-guide-for-cracking-a-javascript-interview-a-developers-perspective-23a5c0fa4d0d</a> - A perfect guide for cracking a JavaScript interview - A developer’s perspective</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/javascript-scene/master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9">master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9</a> - Master the JavaScript Interview: What’s the Difference Between Class &amp; Prototypal Inheritance?</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36">https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36</a> - Master the JavaScript Interview: What is a Closure?</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-function-composition-20dfb109a1a0">https://medium.com/javascript-scene/master-the-javascript-interview-what-is-function-composition-20dfb109a1a0</a> - Master the JavaScript Interview: What is Function Composition?</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a">https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a</a> - Common Misconceptions About Inheritance in JavaScript</p>
</li>
<li><p>:link: <a target="_blank" href="https://dev.to/arnavaggarwal/10-javascript-concepts-you-need-to-know-for-interviews?utm_source=hashnode.com">https://dev.to/arnavaggarwal/10-javascript-concepts-you-need-to-know-for-interviews?utm_source=hashnode.com</a> - 10 JavaScript concepts you need to know for interviews</p>
</li>
<li><p>:link: <a target="_blank" href="https://hackernoon.com/a-quick-introduction-to-functional-javascript-7e6fe520e7fa">https://hackernoon.com/a-quick-introduction-to-functional-javascript-7e6fe520e7fa</a> - A Quick Introduction to Functional Javascript</p>
</li>
<li><p>:link: <a target="_blank" href="https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions">https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Question</a> - 123-Essential-JavaScript-Interview-Question</p>
</li>
<li><p>:link: <a target="_blank" href="https://www.toptal.com/javascript/interview-questions">https://www.toptal.com/javascript/interview-questions</a> - 37 Essential JavaScript Interview Questions</p>
</li>
<li><p>:link: <a target="_blank" href="https://medium.com/coderbyte/a-tricky-javascript-interview-question-asked-by-google-and-amazon-48d212890703">https://medium.com/coderbyte/a-tricky-javascript-interview-question-asked-by-google-and-amazon-48d212890703</a> - A Tricky JavaScript Interview Question Asked by Google and Amazon</p>
</li>
<li><p>:link: <a target="_blank" href="https://github.com/lydiahallie/javascript-questions">Many tricky and common javascript-questions</a></p>
</li>
<li><p>:link: [Javascript Interview Questions](<a target="_blank" href="https://www.interviewbit.com/javascript-interview-questions/">https://github.com/lydiahallie/javascript-questions</a> - Prepare from this comprehensive list of the latest Javascript Interview Questions and ace your interview.</p>
</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-most-frequently-asked-concepts-for-front-end-engineering-interview">Most frequently asked concepts for Front End Engineering Interview</h2>
<ol>
<li>call, apply and bind method</li>
<li>Polyfill for bind method</li>
<li>Currying</li>
<li>Debouncing</li>
<li>async vs defer</li>
<li>Event Bubbling &amp; Capturing</li>
<li>Prototype &amp; Prototypal Inheritance</li>
<li>Throttling</li>
<li>Thinking Recursively</li>
<li>Local Storage and Session Storage</li>
<li>CORS</li>
<li>sum(a)(b)(c)...(n)</li>
<li>Web Storage APIs</li>
<li>Event Loop</li>
<li>Web Sockets</li>
<li>Closures</li>
<li>Callbacks &amp; Promises</li>
<li>Revise everything again</li>
<li>Difference between deep clone and shallow clone and how to write your own deep clone fucntion/polyfill for deepclone</li>
<li>ES6 data structures such as Map and Set. In certain cases, Map is much better suited than an Object. Probably even Server Sent Events would be a good thing to know.</li>
<li>Observable and subscribers, subject, behaviour subject and repeatable subject</li>
</ol>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-list-of-sites-where-you-can-hunt-for-a-developer-job">List of sites where you can hunt for a developer job</h2>
<ul>
<li>:link: AngelList - https://angel.co</li>
<li>:link: DevITjobs.us: https://devitjobs.us</li>
<li>:link: DevITjobs.uk: https://devitjobs.uk</li>
<li>:link: Mashable: http://jobs.mashable.com/jobs</li>
<li>:link: Indeed: http://indeed.com</li>
<li>:link: StackOverflow: http://stackoverflow.com/jobs</li>
<li>:link: LinkedIn: http://linkedIn.com</li>
<li>:link: Glassdoor: http://glassdoor.com</li>
<li>:link: Dice: http://dice.com</li>
<li>:link: Monster: http://monster.com</li>
<li>:link: Simply Hired: http://simplyhired.com</li>
<li>:link: Toptal: https://toptal.com</li>
<li>:link: Hired - https://hired.com</li>
<li>:link: Muse: http://themuse.com/jobs</li>
<li>:link: Tuts+: http://jobs.tutsplus.com</li>
<li>:link: Krop: http://krop.com</li>
<li>:link: PowerToFly: http://powertofly.com/jobs</li>
<li>:link: Developers for Hire: http://developersforhire.com</li>
<li>:link: http://Joblist.app: http://joblist.app</li>
<li>:link: Fullstack Job: http://fullstackjob.com</li>
<li>:link: Authentic jobs: http://authenticjobs.com</li>
<li>:link: Jobspresso: http://jobspresso.co</li>
<li>:link: Jobs in Europe: http://landing.jobs</li>
<li>:link: TripleByte: https://triplebyte.com</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-want-a-startup-job">Want a startup job?</h2>
<ul>
<li>:link: AngelList: http://angel.co/jobs</li>
<li>:link: Product Hunt: http://producthunt.com/jobs</li>
<li>:link: Startup Hire: http://startuphire.com</li>
<li>:link: Startupers: http://startupers.com</li>
<li>:link: YCombinator: http://news.ycombinator.com/jobs</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-best-places-to-job-hunt-for-remote-jobs">Best places to job hunt for remote jobs:</h2>
<ul>
<li>:link: FlexJobs: http://flexjobs.com</li>
<li>:link: WeWorkRemotely: http://weworkremotely.com</li>
<li>:link: RemoteOk: http://remoteok.io/remote-dev-jobs</li>
<li>:link: Stackoverflow: http://stackoverflow.com/jobs/remote-developer-jobs</li>
<li>:link: Working Nomads: http://workingnomads.co/remote-development-jobs</li>
<li>:link: Remote . co - https://remote.co/remote-jobs/developer/</li>
<li>:link: Remoters: http://remoters.net/jobs/software-development</li>
<li>:link: JS Remotely: http://jsremotely.com</li>
<li>:link: Front-end remote: http://frontendremotejobs.com</li>
<li>:link: IWantRemote: http://iwantremote.com</li>
<li>:link: DailyRemote - https://dailyremote.com</li>
<li>:link: Remotive: https://remotive.io/remote-jobs/software-dev</li>
<li>:link: Outsourcely: http://outsourcely.com/remote-web-development-jobs</li>
<li>:link: Pangian: https://pangian.com/job-travel-remote/</li>
<li>:link: RemoteLeads: http://remoteleads.io</li>
<li>:link: Remote Talent: http://remotetalent.co/jobs</li>
<li>:link: JustRemote: https://justremote.co/remote-developer-jobs</li>
<li>:link: RemoteLeaf - https://remoteleaf.com</li>
<li>:link: Sitepoint - https://sitepoint.com/jobs/</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-here-are-a-few-places-to-hunt-for-ios-react-vue-and-more">Here are a few places to hunt for ios, react, vue and more</h2>
<ul>
<li>:link: iOS: http://iosdevjobs.com</li>
<li>:link: React: http://reactjobboard.com</li>
<li>:link: Vue jobs: http://vuejobs.com</li>
<li>:link: Ember: http://jobs.emberjs.com</li>
<li>:link: Python Jobs - http://python.org/jobs</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-want-a-list-of-just-javascript-jobs">Want a list of just JavaScript jobs?</h2>
<ul>
<li>:link: JavaScript job XYZ: http://javascriptjob.xyz</li>
<li>:link: Javascript remotely: http://jsremotely.com</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-are-you-looking-for-a-junior-dev-job">Are you looking for a junior dev job?</h2>
<ul>
<li>:link: JrDevJobs: http://jrdevjobs.com</li>
<li>:link: Stackoverflow Junior jobs: https://stackoverflow.com/jobs/junior-developer-jobs</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-women-focused-job-boards">Women focused job boards!</h2>
<ul>
<li>:link: Women Who Code: http://womenwhocode.com/jobs</li>
<li>:link: Tech Ladies - https://hiretechladies.com</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-want-a-job-as-a-freelance-dev-heres-a-list">Want a job as a freelance dev? Here's a list</h2>
<ul>
<li>:link: Freelancer: http://freelancer.com/jobs</li>
<li>:link: Upwork: http://upwork.com</li>
<li>:link: FlexJobs: http://flexjobs.com/jobs</li>
<li>:link: FreelancerMap: http://freelancermap.com</li>
<li>:link: http://Gun.io: http://gun.io</li>
<li>:link: Guru: http://guru.com/d/jobs</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-some-useful-websites-for-programmers">Some useful websites for programmers</h2>
<li><a href="#when-you-get-stuck">When you get stuck</a></li>
<li><a href="#for-small-project-ideas">For small project ideas</a></li>
<li><a href="#general-coding-advice">General Coding advice</a></li>
<li><a href="#coding-style">Coding Style</a></li>
<li><a href="#general-good-articles">General Good Articles</a></li>

<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-when-you-get-stuck">When you get stuck</h2>
<ul>
<li><a target="_blank" href="https://www.codementor.io">Codementor</a> : A mentorship community to learn from fellow developers via live 1:1 help and more.</li>
<li><a target="_blank" href="https://www.devrant.io">devRant</a> : Community where you can rant and release your stress</li>
<li><a target="_blank" href="https://learn-anything.xyz">Learn Anything</a> : Community curated knowledge graph of best paths for learning anything</li>
<li><a target="_blank" href="https://www.quora.com">Quora</a> : A place to share knowledge and better understand the world</li>
<li><a target="_blank" href="https://stackoverflow.com">Stack Overflow</a> : subscribe to their weekly newsletter and any other topic which you find interesting</li>
<li><a target="_blank" href="https://dashboard.nbshare.io/apps/stackoverflow/top-javascript-questions/">Stackoverflow High Scored JS Questions</a> : Dashboard to track top Javascript questions asked on Stackoverflow</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-ideas-for-small-project-ideas">Ideas For small project ideas</h2>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/every-time-you-build-a-to-do-list-app-a-puppy-dies-505b54637a5d?gi=c786640fbd11">freeCodeCamp | React project ideas</a> : 27 fun app ideas you can build while learning React.</li>
<li><a target="_blank" href="http://www.dreamincode.net/forums/topic/78802-martyr2s-mega-project-ideas-list/">martyr2s-mega-project-ideas-list</a> : contains about 125 project ideas from beginner to intermediate level.</li>
<li><a target="_blank" href="https://github.com/karan/Projects">karan/Projects</a> : a large collection of small projects for beginners with</li>
<li><a target="_blank" href="http://rodiongork.tumblr.com/post/108155476418/wrong-big-projects-for-beginners">Wrong "big projects" for beginners</a> : How to choose where to start</li>
<li><a target="_blank" href="https://github.com/vicky002/1000_Projects">vicky002/1000-Projects</a> : Mega List of practical projects that one can solve in any programming language!</li>
<li><a target="_blank" href="https://www.reddit.com/r/AppIdeas/">reddit.com/r/AppIdeas</a> : A place to discuss ideas for applications, for bored developers.</li>
<li><a target="_blank" href="https://www.reddit.com/r/SomebodyMakeThis/">reddit.com/r/SomebodyMakeThis</a> : A home for ideas by people who lack time, money, or skills.</li>
<li><a target="_blank" href="https://www.interviewbit.com/blog/javascript-projects/">InterviewBit | JavaScript Projects Ideas</a> : Top 15+ JavaScript Projects Ideas.</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-general-coding-advice">General Coding advice</h2>
<ul>
<li><a target="_blank" href="https://stephenhaunts.files.wordpress.com/2014/04/10-ways-to-be-a-better-developer.png">10-ways-to-be-a-better-developer</a> : Ways to become a better dev!</li>
<li><a target="_blank" href="https://www.kevinlondon.com/2015/05/05/code-review-best-practices.html">Code Review Best Practices</a> : Kevin London's blog</li>
<li><a target="_blank" href="https://sourcemaking.com/design_patterns">Design Patterns</a> : Design Patterns explained in detail with examples.</li>
<li><a target="_blank" href="http://developforperformance.com">Develop for Performance</a> : High-performance computing techniques for software architects and developers</li>
<li><a target="_blank" href="https://okepi.wordpress.com/2014/08/21/how-to-become-a-programmer-or-the-art-of-googling-well/">How to become a programmer or the art of Googling well</a> : How to become a programmer or the art of Googling well</li>
<li><a target="_blank" href="https://medium.freecodecamp.org/how-to-escape-tutorial-purgatory-as-a-new-developer-or-at-any-time-in-your-career-e3a4b2384a40">How to escape tutorial purgatory as a new developer — or at any time in your career</a> : How to escape tutorial purgatory</li>
<li><a target="_blank" href="https://github.com/wearehive/project-guidelines">JS Project Guidelines</a> : A set of best practices for JavaScript projects.</li>
<li><a target="_blank" href="https://learntocodewith.me">Learn to Code With Me</a> : A comprehensive site resource by Laurence Bradford for developers who aims to build a career in the tech world</li>
<li><a target="_blank" href="http://thecodist.com/article/lessons_from_a_lifetime_of_being_a_programmer">Lessons From A Lifetime Of Being A Programmer</a> : The Codist Header Lessons From A Lifetime Of Being A Programmer</li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Software_design_pattern">Software design pattern</a> : The entire collection of Design Patterns.</li>
<li><a target="_blank" href="https://medium.freecodecamp.com/things-i-wish-someone-had-told-me-when-i-was-learning-how-to-code-565fc9dcb329?gi=fc6d0a309be">Things I Wish Someone Had Told Me When I Was Learning How to Code — Free Code Camp</a> : What I’ve learned from teaching others</li>
<li><a target="_blank" href="http://matt.might.net/articles/what-cs-majors-should-know/">What every computer science major should know</a> : The Principles of Good Programming</li>
<li><a target="_blank" href="https://henrikwarne.com/2012/12/12/working-as-a-software-developer/">Working as a Software Developer</a> : Henrik Warne's blog</li>
<li><a target="_blank" href="https://www.owasp.org">The Open Web Application Security Project (OWASP)</a> : OWASP is an open community dedicated to enabling organizations to conceive, develop, acquire, operate, and maintain applications that can be trusted.</li>
<li><a target="_blank" href="https://www.infoq.com/articles/Starting-With-MongoDB/">14 Things I Wish I’d Known When Starting with MongoDB</a></li>
<li><a target="_blank" href="http://carlcheo.com/compsci">40 Keys Computer Science Concepts Explained In Layman’s Terms</a></li>
<li><a target="_blank" href="https://dev.to/vaidehijoshi/a-gentle-introduction-to-graph-theory">A Gentle Introduction To Graph Theory</a></li>
<li><a target="_blank" href="http://moonscript.org">A programmer-friendly language that compiles to Lua.</a></li>
<li><a target="_blank" href="https://stevewedig.com/2014/02/03/software-developers-reading-list/">A Software Developer’s Reading List</a> : Some good books and links in there.</li>
<li><a target="_blank" href="http://www.saminiir.com/lets-code-tcp-ip-stack-5-tcp-retransmission/">Code a TCP/IP stack</a> : Let's code a TCP/IP stack, 5: TCP Retransmission</li>
<li><a target="_blank" href="https://codewords.recurse.com/issues/four/the-language-of-choice">Codewords.recurse</a> : The language of choice</li>
<li><a target="_blank" href="https://www.wikiwand.com/en/Java_bytecode">Dive into the byte code</a></li>
<li><a target="_blank" href="http://blog.thefirehoseproject.com/posts/expectations-of-a-junior-developer/">Expectations of a Junior Developer</a></li>
<li><a target="_blank" href="https://studio3t.com/knowledge-base/articles/mongodb-getting-started/">Getting Started with MongoDB – An Introduction</a></li>
<li><a target="_blank" href="https://logit.io/blog/post/elk-stack-guide">How to install ELK</a></li>
<li><a target="_blank" href="https://0xax.gitbooks.io/linux-insides/content/Booting/linux-bootstrap-1.html">Linux Inside</a></li>
<li><a target="_blank" href="https://www.wikiwand.com/en/List_of_algorithms">List of algorithms</a></li>
<li><a target="_blank" href="https://www.databasestar.com/normalization-in-dbms/">Step by Step Guide to Database Normalization</a>: A guide to database normalization.</li>
<li><a target="_blank" href="http://blog.thefirehoseproject.com/posts/learn-to-code-and-be-self-reliant/">The Key To Accelerating Your Coding Skills</a></li>
<li><a target="_blank" href="https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/">Unicode</a></li>
<li><a target="_blank" href="http://multithreaded.stitchfix.com">We are reinventing the retail industry through innovative technology</a></li>
<li><a target="_blank" href="http://kunststube.net/encoding/">What every programmer absolutely, positively needs to know about encodings and character sets to work with text</a></li>
<li><a target="_blank" href="http://futuretech.blinkenlights.nl/misc/cpumemory.pdf">What every programmer should know about memory - PDF</a></li>
<li><a target="_blank" href="https://qotoqot.com/blog/improving-focus/">qotoqot - improving-focus</a> : How I got to 200 productive hours a month</li>
<li><a target="_blank" href="http://www.pixelbeat.org/docs/unix-parallel-tools.html">Pixel Beat - Unix</a> : Parallel processing with Unix tools</li>
<li><a target="_blank" href="https://hackernoon.com/learning-vim-what-i-wish-i-knew-b5dca186bef7">Learning Vim</a> : What I Wish I Knew</li>
<li><a target="_blank" href="http://arjunsreedharan.org/post/82710718100/kernel-101-lets-write-a-kernel">Write a Kernel</a> : Kernel 101 – Let’s write a Kernel</li>
<li><a target="_blank" href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/">Learning JavaScript Design Patterns</a> : the online version of the Learning JavaScript Design Patterns published by O'Reilly, released by the author Addy Osmani under CC BY-NC-ND 3.0</li>
<li><a target="_blank" href="https://requestbin.com/blog/working-with-webhooks/">Working with Webhooks</a> : a comprehensive guide on webhooks</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-coding-style">Coding Style</h2>
<ul>
<li><a target="_blank" href="https://github.com/airbnb/javascript">Airbnb JS Style Guide</a> : A mostly reasonable approach to JavaScript</li>
<li><a target="_blank" href="https://github.com/airbnb/ruby">Airbnb Ruby Style Guide</a> : A ruby style guide by Airbnb</li>
<li><a target="_blank" href="https://github.com/bbatsov/ruby-style-guide">Ruby coding style guide</a> : A community-driven Ruby coding style guide</li>
<li><a target="_blank" href="https://github.com/johnpapa/angular-styleguide/tree/master/a1">Angular Style Guide</a> : Officially endorsed style guide by John Pappa</li>
<li><a target="_blank" href="http://stanford.edu/class/archive/cs/cs106b/cs106b.1158/styleguide.shtml">CS 106B Coding Style Guide</a> : must see for those who create spaghetti</li>
<li><a target="_blank" href="http://www.umich.edu/~eecs381/generalFAQ/Debugging.html">Debugging Faqs</a> : Check out how to debug your program</li>
<li><a target="_blank" href="https://github.com/prakhar1989/awesome-courses">Directory of CS Courses (many with online lectures)</a> : Another online CS courses</li>
<li><a target="_blank" href="https://github.com/ossu/computer-science">Directory of Online CS Courses</a> : Free online CS courses</li>
<li><a target="_blank" href="https://www.reddit.com/r/C_Programming/comments/1vuubw/good_c_programming_habits/">Good C programming habits. • /r/C_Programming</a> : C programming habits to adopt</li>
<li><a target="_blank" href="https://google.github.io/styleguide/cppguide.html">Google C++ Style Guide</a></li>
<li><a target="_blank" href="https://www.chiark.greenend.org.uk/~sgtatham/bugs.html">How to Report Bugs Effectively</a> : Want to report a bug but you don't how? Check out this post</li>
<li><a target="_blank" href="https://www.reddit.com/r/learnprogramming/comments/1i4ds4/what_are_some_bad_coding_habits_you_would/">What are some bad coding habits you would recommend a beginner avoid getting into?</a> : Bad habits to avoid when you get start</li>
<li><a target="_blank" href="https://www.python.org/dev/peps/pep-0008/">PEP8 - Style Guide for Python Code</a> : Style Guide for Python Code</li>
<li><a target="_blank" href="https://standardjs.com">Standard JS Style Guide</a> : JavaScript style guide, with linter &amp; automatic code fixer</li>
<li><a target="_blank" href="https://google.github.io/styleguide/pyguide.html">Google Python Style Guide</a> : Google Python Style Guide</li>
<li><a target="_blank" href="https://github.com/behzad888/Aurelia-styleguide">Aurelia Style Guide</a> : An Aurelia style guide by Behzad Abbasi(Behzad888)</li>
<li><a target="_blank" href="https://sourcemaking.com/">Source Making </a>: Design Patterns &amp; Refactoring</li>
<li><a target="_blank" href="https://refactoring.guru/">Refactoring Guru</a>: Refactoring And Design Patterns</li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-collection-of-leetcode-problem-solution">Collection of Leetcode Problem solution</h2>
<ul>
<li><a target="_blank" href="https://github.com/AlanWei/LeetCode">github.com/AlanWei/LeetCode</a></li>
<li><a target="_blank" href="https://github.com/LiuL0703/algorithm/tree/master/LeetCode/JavaScript">github.com/LiuL0703/algorithm/tree/master/LeetCode/JavaScript</a></li>
<li><a target="_blank" href="https://github.com/ecmadao/algorithms/tree/master/leetcode">github.com/ecmadao/algorithms/tree/master/leetcode</a></li>
<li><a target="_blank" href="https://github.com/paopao2/leetcode-js">github.com/paopao2/leetcode-js</a></li>
<li><a target="_blank" href="https://github.com/cs1707/leetcode">github.com/cs1707/leetcode</a></li>
<li><a target="_blank" href="https://github.com/EasyHard/leetcodejs">github.com/EasyHard/leetcodejs</a></li>
<li><a target="_blank" href="https://github.com/fa-ge/leetcode">github.com/fa-ge/leetcode</a></li>
<li><a target="_blank" href="https://github.com/ktorng/AlgoInterviewPrep/tree/master/misc/LeetCode">github.com/ktorng/AlgoInterviewPrep/tree/master/misc/LeetCode</a></li>
<li><a target="_blank" href="https://github.com/bluesh/LeetCode">github.com/bluesh/LeetCode</a></li>
<li><a target="_blank" href="https://github.com/chihungyu1116/leetcode-javascript">github.com/chihungyu1116/leetcode-javascript</a></li>
<li><a target="_blank" href="https://github.com/didi0613/leetcode-javascript">github.com/didi0613/leetcode-javascript</a></li>
<li><a target="_blank" href="https://github.com/dnshi/Leetcode/tree/master/algorithms">github.com/dnshi/Leetcode/tree/master/algorithms</a></li>
<li><a target="_blank" href="https://github.com/xiaoyu2er/leetcode-js">github.com/xiaoyu2er/leetcode-js</a></li>
<li><a target="_blank" href="http://blog.sodhanalibrary.com/search/label/JavaScript">blog.sodhanalibrary.com/search/label/JavaScript</a></li>
<li><a target="_blank" href="https://github.com/imcoddy/leetcode">github.com/imcoddy/leetcode</a></li>
<li><a target="_blank" href="https://github.com/iwantooxxoox/leetcode">github.com/iwantooxxoox/leetcode</a></li>
<li><a target="_blank" href="https://github.com/karenpeng/leetCode">github.com/karenpeng/leetCode</a></li>
<li><a target="_blank" href="https://github.com/KMBaby-zyl/leetcode/tree/master/Algorithms">github.com/KMBaby-zyl/leetcode/tree/master/Algorithms</a></li>
<li><a target="_blank" href="https://github.com/MrErHu/Leetcode/tree/master/algorithms">github.com/MrErHu/Leetcode/tree/master/algorithms</a></li>
<li><a target="_blank" href="https://github.com/zzxboy1/leetcode/tree/master/algorithms">github.com/zzxboy1/leetcode/tree/master/algorithms</a></li>
<li><a target="_blank" href="https://github.com/loatheb/leetcode-javascript">github.com/loatheb/leetcode-javascript</a></li>
<li><a target="_blank" href="https://github.com/paopao2/leetcode-js">github.com/paopao2/leetcode-js</a></li>
<li><a target="_blank" href="https://github.com/theFool32/LeetCode">github.com/theFool32/LeetCode</a></li>
<li><a target="_blank" href="https://github.com/whwei/LeetCode">github.com/whwei/LeetCode</a></li>
<li><a target="_blank" href="https://github.com/jiangxiaoli/leetcode-javascript">github.com/jiangxiaoli/leetcode-javascript</a></li>
<li><a target="_blank" href="https://skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/299md.html">skyyen999.gitbooks.io/-leetcode-with-javascript/content/questions/299md.html</a></li>
<li><a target="_blank" href="https://github.com/HandsomeOne/LeetCode/tree/master/Algorithms">github.com/HandsomeOne/LeetCode/tree/master/Algorithms</a></li>
<li><a target="_blank" href="https://github.com/zj972/leetcode/tree/master/code">github.com/zj972/leetcode/tree/master/code</a></li>
<li><a target="_blank" href="https://github.com/xiaoliwang/leetcode/tree/master/iojs">github.com/xiaoliwang/leetcode/tree/master/iojs</a></li>
<li><a target="_blank" href="https://github.com/dieface/leetcode/tree/master/javascript">github.com/dieface/leetcode/tree/master/javascript</a></li>
<li><a target="_blank" href="https://github.com/magicly/leetcode/tree/master/js">github.com/magicly/leetcode/tree/master/js</a></li>
<li><a target="_blank" href="https://github.com/LuciferChiu/leetcode/tree/master/solutions">github.com/LuciferChiu/leetcode/tree/master/solutions</a></li>
<li><a target="_blank" href="https://github.com/alenny/leetcode/tree/master/src">github.com/alenny/leetcode/tree/master/src</a></li>
<li><a target="_blank" href="https://github.com/kpman/leetcode/tree/master/src">github.com/kpman/leetcode/tree/master/src</a></li>
<li><a target="_blank" href="https://github.com/hijiangtao/LeetCode-with-JavaScript/tree/master/src">github.com/hijiangtao/LeetCode-with-JavaScript/tree/master/src</a></li>
<li><a target="_blank" href="https://www.cnblogs.com/Liok3187/default.html?page=1">www.cnblogs.com/Liok3187/default.html?page=1</a></li>
<li><a target="_blank" href="https://github.com/yuguo/LeetCode">github.com/yuguo/LeetCode</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-collection-of-cracking-the-coding-interview-book-problem-solution">Collection of Cracking the Coding Interview Book Problem solution</h2>
<ul>
<li><a target="_blank" href="https://github.com/sharlatta/cracking">github.com/sharlatta/cracking</a></li>
<li><a target="_blank" href="https://github.com/ammiranda/CrackingTheCodingInterview">github.com/ammiranda/CrackingTheCodingInterview</a></li>
<li><a target="_blank" href="https://github.com/bryclee/ctci">github.com/bryclee/ctci</a></li>
<li><a target="_blank" href="https://github.com/macalinao/node-ctci">github.com/macalinao/node-ctci</a></li>
<li><a target="_blank" href="https://github.com/seemaullal/CrackingTheCodingInterview-JS">github.com/seemaullal/CrackingTheCodingInterview-JS</a></li>
<li><a target="_blank" href="https://github.com/rcerf/MyCtci">github.com/rcerf/MyCtci</a></li>
<li><a target="_blank" href="https://github.com/SashaBayan/CCI">github.com/SashaBayan/CCI</a></li>
<li><a target="_blank" href="https://github.com/careercup/CtCI-6th-Edition-JavaScript-ES2015">github.com/careercup/CtCI-6th-Edition-JavaScript-ES2015</a></li>
<li><a target="_blank" href="https://github.com/ktorng/AlgoInterviewPrep/tree/master/CrackingTheCodingInterview">github.com/ktorng/AlgoInterviewPrep/tree/master/CrackingTheCodingInterview</a></li>
<li><a target="_blank" href="https://github.com/muddybarefeet/Cracking-the-Coding-Interview-Problems/tree/master/toyProblems">github.com/muddybarefeet/Cracking-the-Coding-Interview-Problems/tree/master/toyProblems</a></li>
<li><a target="_blank" href="https://github.com/randy909/coding-interview/tree/master/cracking">github.com/randy909/coding-interview/tree/master/cracking</a></li>
<li><a target="_blank" href="https://github.com/rohan-paul/Awesome-JavaScript-Interviews#collection-of-cracking-the-coding-interview-book-problem-solution">github.com/rohan-paul/Awesome-JavaScript-Interviews#collection-of-cracking-the-coding-interview-book-problem-solution</a></li>
<li><a target="_blank" href="https://github.com/careercup/ctci/tree/master/javascript/lib/data-structures">github.com/careercup/ctci/tree/master/javascript/lib/data-structures</a></li>
<li><a target="_blank" href="https://github.com/miguelmota/ctci-js">github.com/miguelmota/ctci-js</a></li>
<li><a target="_blank" href="https://github.com/ChirpingMermaid/CTCI">github.com/ChirpingMermaid/CTCI</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-ux-css-design-sense-related">UX-CSS-Design Sense Related</h2>
<ul>
<li><a target="_blank" href="https://scottaohara.github.io/accessibility_interview_questions/">Accessibility Interview Questions</a></li>
</ul>
<h2 id="heading-most-common-system-design-interview-topics-amp-questions">Most common System-Design Interview Topics &amp; Questions</h2>
<p>(Below Links are all within this Repository)</p>
<ul>
<li><a target="_blank" href="system-design/design-url-shortner.md">design-url-shortner</a></li>
<li><a target="_blank" href="system-design/e-Commerce-site.md">e-Commerce-site</a></li>
<li><a target="_blank" href="system-design/Whatsapp-Basic-Features-of-a-chat-app.md">Whatsapp-Basic-Features-of-a-chat-app</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-system-design-related-topics-some-very-useful-articles">System-Design related topics-Some very useful articles</h2>
<ul>
<li><a target="_blank" href="http://www.hiredintech.com/app#system-design">System Interview</a></li>
<li><a target="_blank" href="http://www.lecloud.net/tagged/scalability">Scalability for Dummies</a></li>
<li><a target="_blank" href="http://www.aosabook.org/en/distsys.html">Scalable Web Architecture and Distributed Systems</a></li>
<li><a target="_blank" href="http://everythingisdata.wordpress.com/2009/10/17/numbers-everyone-should-know/">Numbers Everyone Should Know</a></li>
<li><a target="_blank" href="https://pages.cs.wisc.edu/~zuyu/files/fallacies.pdf">Fallacies of distributed systems</a></li>
<li><a target="_blank" href="http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html">Scalable System Design Patterns</a></li>
<li><a target="_blank" href="http://lethain.com/introduction-to-architecting-systems-for-scale/">Introduction to Architecting Systems for Scale</a></li>
<li><a target="_blank" href="http://snarfed.org/transactions_across_datacenters_io.html">Transactions Across Datacenters</a></li>
<li><a target="_blank" href="https://github.com/henryr/cap-faq">The CAP FAQ</a></li>
<li><a target="_blank" href="http://research.microsoft.com/en-us/um/people/lamport/pubs/paxos-simple.pdf">Paxos Made Simple</a></li>
<li><a target="_blank" href="http://www.tom-e-white.com/2007/11/consistent-hashing.html">Consistent Hashing</a></li>
<li><a target="_blank" href="http://horicky.blogspot.com/2009/11/nosql-patterns.html">NOSQL Patterns</a></li>
<li><a target="_blank" href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns">Scalability, Availability &amp; Stability Patterns</a></li>
<li><a target="_blank" href="http://repository.cmu.edu/cgi/viewcontent.cgi?article=2112&amp;context=compsci">Design a CDN network-Globally Distributed Content Delivery</a></li>
<li><a target="_blank" href="https://www.interviewbit.com/system-design-interview-questions/">System Design Interview Questions</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a Google document system</strong></p>
<ul>
<li><a target="_blank" href="https://code.google.com/p/google-mobwrite/">google-mobwrite</a></li>
<li><a target="_blank" href="https://neil.fraser.name/writing/sync/">Differential Synchronization</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a random ID generation system</strong></p>
<ul>
<li><a target="_blank" href="https://blog.twitter.com/2010/announcing-snowflake">Announcing Snowflake</a></li>
<li><a target="_blank" href="https://github.com/twitter/snowflake/">snowflake</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a key-value database</strong></p>
<ul>
<li><a target="_blank" href="http://www.slideshare.net/dvirsky/introduction-to-redis">Introduction to Redis</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design the Facebook news feed function</strong></p>
<ul>
<li><a target="_blank" href="http://www.quora.com/What-are-best-practices-for-building-something-like-a-News-Feed">What are best practices for building something like a News Feed?</a></li>
<li><a target="_blank" href="http://www.quora.com/Activity-Streams/What-are-the-scaling-issues-to-keep-in-mind-while-developing-a-social-network-feed">What are the scaling issues to keep in mind while developing a social network feed?</a></li>
<li><a target="_blank" href="http://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture">Activity Feeds Architecture</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design the Facebook timeline function</strong></p>
<ul>
<li><a target="_blank" href="https://www.facebook.com/note.php?note_id=10150468255628920">Building Timeline</a></li>
<li><a target="_blank" href="http://highscalability.com/blog/2012/1/23/facebook-timeline-brought-to-you-by-the-power-of-denormaliza.html">Facebook Timeline</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a function to return the top k requests during past time interval</strong></p>
<ul>
<li><a target="_blank" href="http://www.cse.ust.hk/~raywong/comp5331/References/EfficientComputationOfFrequentAndTop-kElementsInDataStreams.pdf">Efficient Computation of Frequent and Top-k Elements in Data Streams</a></li>
<li><a target="_blank" href="http://davis.wpi.edu/xmdv/docs/EDBT11-diyang.pdf">An Optimal Strategy for Monitoring Top-k Queries in Streaming Windows</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design an online multiplayer card game</strong></p>
<ul>
<li><a target="_blank" href="http://www.indieflashblog.com/how-to-create-an-asynchronous-multiplayer-game.html">How to Create an Asynchronous Multiplayer Game</a></li>
<li><a target="_blank" href="http://www.indieflashblog.com/how-to-create-async-part2.html">How to Create an Asynchronous Multiplayer Game Part 2: Saving the Game State to Online Database</a></li>
<li><a target="_blank" href="http://www.indieflashblog.com/how-to-create-async-part3.html">How to Create an Asynchronous Multiplayer Game Part 3: Loading Games from the Database</a></li>
<li><a target="_blank" href="http://buildnewgames.com/real-time-multiplayer/">Real Time Multiplayer in HTML5</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a graph search function</strong></p>
<ul>
<li><a target="_blank" href="https://www.facebook.com/notes/facebook-engineering/under-the-hood-building-out-the-infrastructure-for-graph-search/10151347573598920">Building out the infrastructure for Graph Search</a></li>
<li><a target="_blank" href="https://www.facebook.com/notes/facebook-engineering/under-the-hood-indexing-and-ranking-in-graph-search/10151361720763920">Indexing and ranking in Graph Search</a></li>
<li><a target="_blank" href="https://www.facebook.com/notes/facebook-engineering/under-the-hood-the-natural-language-interface-of-graph-search/10151432733048920">The natural language interface of Graph Search</a> and <a target="_blank" href="http://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf">Erlang at Facebook</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a picture sharing system</strong></p>
<ul>
<li><a target="_blank" href="http://highscalability.com/flickr-architecture">Flickr Architecture</a></li>
<li><a target="_blank" href="http://highscalability.com/blog/2011/12/6/instagram-architecture-14-million-users-terabytes-of-photos.html">Instagram Architecture</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a search engine</strong></p>
<ul>
<li><a target="_blank" href="http://programmers.stackexchange.com/questions/38324/interview-question-how-would-you-implement-google-search">How would you implement Google Search?</a></li>
<li><a target="_blank" href="http://www.ardendertat.com/2012/01/11/implementing-search-engines/">Implementing Search Engines</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a recommendation system</strong></p>
<ul>
<li><a target="_blank" href="http://tech.hulu.com/blog/2011/09/19/recommendation-system.html">Hulu’s Recommendation System</a></li>
<li><a target="_blank" href="http://ijcai13.org/files/tutorial_slides/td3.pdf">Recommender Systems</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a tinyurl system</strong></p>
<ul>
<li><a target="_blank" href="http://n00tc0d3r.blogspot.com/">System Design for Big Data-tinyurl</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a garbage collection system</strong></p>
<ul>
<li><a target="_blank" href="http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/">Baby's First Garbage Collector</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a scalable web crawling system</strong></p>
<ul>
<li><a target="_blank" href="https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch">How can I build a web crawler from scratch?</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design the Facebook chat function</strong></p>
<ul>
<li><a target="_blank" href="http://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf">Erlang at Facebook</a></li>
<li><a target="_blank" href="https://www.facebook.com/note.php?note_id=14218138919&amp;id=9445547199&amp;index=0">Facebook Chat</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a trending topic system</strong></p>
<ul>
<li><a target="_blank" href="http://www.michael-noll.com/blog/2013/01/18/implementing-real-time-trending-topics-in-storm/">Implementing Real-Time Trending Topics With a Distributed Rolling Count Algorithm in Storm</a></li>
<li><a target="_blank" href="http://snikolov.wordpress.com/2012/11/14/early-detection-of-twitter-trends/">Early detection of Twitter trends explained</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<p><strong>Design a cache system</strong></p>
<ul>
<li><a target="_blank" href="http://www.slideshare.net/oemebamo/introduction-to-memcached">Introduction to Memcached</a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
<h2 id="heading-system-design-company-engineering-blog">System-Design-Company engineering blog</h2>
<ul>
<li><a target="_blank" href="http://highscalability.com/">High Scalability</a></li>
<li><a target="_blank" href="https://github.com/blog/category/engineering">The GitHub Blog</a></li>
<li><a target="_blank" href="http://engineering.quora.com/">Engineering at Quora</a></li>
<li><a target="_blank" href="http://engineeringblog.yelp.com/">Yelp Engineering Blog</a></li>
<li><a target="_blank" href="https://engineering.twitter.com/">Twitter Engineering</a></li>
<li><a target="_blank" href="https://www.facebook.com/Engineering">Facebook Engineering</a></li>
<li><a target="_blank" href="http://eng.yammer.com/blog/">Yammer Engineering</a></li>
<li><a target="_blank" href="http://codeascraft.com/">Etsy Code as Craft</a></li>
<li><a target="_blank" href="http://engineering.foursquare.com/">Foursquare Engineering Blog</a></li>
<li><a target="_blank" href="http://nerds.airbnb.com/">Airbnb Engineering</a></li>
<li><a target="_blank" href="http://engineering.webengage.com/">WebEngage Engineering Blog</a></li>
<li><a target="_blank" href="http://engineering.linkedin.com/blog">LinkedIn Engineering</a></li>
<li><a target="_blank" href="http://techblog.netflix.com/">The Netflix Tech Blog</a></li>
<li><a target="_blank" href="https://www.simple.com/engineering/">BankSimple Simple Blog</a></li>
<li><a target="_blank" href="http://corner.squareup.com/">Square The Corner</a></li>
<li><a target="_blank" href="https://developers.soundcloud.com/blog/">SoundCloud Backstage Blog</a></li>
<li><a target="_blank" href="http://code.flickr.net/">Flickr Code</a></li>
<li><a target="_blank" href="http://instagram-engineering.tumblr.com/">Instagram Engineering</a></li>
<li><a target="_blank" href="https://tech.dropbox.com/">Dropbox Tech Blog</a></li>
<li><a target="_blank" href="http://blog.cloudera.com/">Cloudera Developer Blog</a></li>
<li><a target="_blank" href="http://bandcamptech.wordpress.com/">Bandcamp Tech</a></li>
<li><a target="_blank" href="http://tech.oyster.com/">Oyster Tech Blog</a></li>
<li><a target="_blank" href="http://www.redditblog.com/">THE REDDIT BLOG</a></li>
<li><a target="_blank" href="https://engineering.groupon.com/">Groupon Engineering Blog</a></li>
<li><a target="_blank" href="http://devblog.songkick.com/">Songkick Technology Blog</a></li>
<li><a target="_blank" href="http://googleresearch.blogspot.com/">Google Research Blog</a></li>
<li><a target="_blank" href="http://engineering.pinterest.com/">Pinterest Engineering Blog</a></li>
<li><a target="_blank" href="http://www.twilio.com/engineering">Twilio Engineering Blog</a></li>
<li><a target="_blank" href="http://word.bitly.com/">Bitly Engineering Blog</a></li>
<li><a target="_blank" href="https://eng.uber.com/">Uber Engineering Blog </a></li>
<li><a target="_blank" href="http://engineering.godaddy.com/">Godaddy Engineering</a></li>
<li><a target="_blank" href="http://blogs.splunk.com/">Splunk Blog</a></li>
<li><a target="_blank" href="https://building.coursera.org/">Coursera Engineering Blog</a></li>
<li><a target="_blank" href="https://www.paypal-engineering.com/">PayPal Engineering Blog</a></li>
<li><a target="_blank" href="https://engblog.nextdoor.com/">Nextdoor Engineering Blog</a></li>
<li><a target="_blank" href="https://blog.booking.com/">Booking.com Development Blog</a></li>
<li><a target="_blank" href="https://blog.scalyr.com/">Scalyr Engineering Blog </a></li>
</ul>
<p><a class="post-section-overview" href="#table-of-contents-of-this-readme-file">[↑] Back to top</a></p>
]]></content:encoded></item><item><title><![CDATA[Front End Engineer interviews Questions]]></title><description><![CDATA[This list contains the top essential questions that are frequently-asked during Front End Engineer interviews. Concise versions of the answers are…]]></description><link>https://articles.tkssharma.com/front-end-engineer-interviews-questions</link><guid isPermaLink="true">https://articles.tkssharma.com/front-end-engineer-interviews-questions</guid><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sat, 19 Oct 2024 17:38:09 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-table-of-contents-top-questions">Table of Contents (Top Questions)</h2>
<p>This list contains the top essential questions that are frequently-asked during Front End Engineer interviews. Concise versions of the answers are presented here with links to elaborate versions for further reading. This section is great if you need a quick refresher of the most important concepts.</p>

<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td><td>Level</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td><a class="post-section-overview" href="#explain-the-concept-of-hoisting-in-javascript">Explain the concept of "hoisting" in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const">What are the differences between JavaScript variables created using <code>let</code>, <code>var</code> or <code>const</code>?</a></td><td>Basic</td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#what-is-the-difference-between--and--in-javascript">What is the difference between <code>==</code> and <code>===</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#what-is-the-event-loop-in-javascript-runtimes">What is the event loop in JavaScript runtimes?</a></td><td>Basic</td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#explain-event-delegation-in-javascript">Explain event delegation in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#explain-how-this-works-in-javascript">Explain how <code>this</code> works in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers">Describe the difference between a cookie, <code>sessionStorage</code> and <code>localStorage</code> in browsers</a></td><td>Basic</td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#describe-the-difference-between-script-script-async-and-script-defer">Describe the difference between <code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code> and <code>&lt;script defer&gt;</code></a></td><td>Basic</td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared">What's the difference between a JavaScript variable that is: <code>null</code>, <code>undefined</code> or undeclared?</a></td><td>Basic</td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#whats-the-difference-between-call-and-apply-in-javascript">What's the difference between <code>.call</code> and <code>.apply</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#explain-functionprototypebind-in-javascript">Explain <code>Function.prototype.bind</code> in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor">What advantage is there for using the JavaScript arrow syntax for a method in a constructor?</a></td><td>Basic</td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#explain-how-prototypal-inheritance-works-in-javascript">Explain how prototypal inheritance works in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript">Difference between: <code>function Person(){}</code>, <code>const person = Person()</code>, and <code>const person = new Person()</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript">Explain the differences on the usage of <code>foo</code> between <code>function foo() {}</code> and <code>var foo = function() {}</code> in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#whats-a-typical-use-case-for-anonymous-functions-in-javascript">What's a typical use case for anonymous functions in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#what-are-the-various-ways-to-create-objects-in-javascript">What are the various ways to create objects in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one">What is a closure in JavaScript, and how/why would you use one?</a></td><td>Intermediate</td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#what-is-the-definition-of-a-higher-order-function-in-javascript">What is the definition of a higher-order function in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors">What are the differences between JavaScript ES2015 classes and ES5 function constructors?</a></td><td>Basic</td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#describe-event-bubbling-in-javascript-and-browsers">Describe event bubbling in JavaScript and browsers</a></td><td>Basic</td></tr>
<tr>
<td>22</td><td><a class="post-section-overview" href="#describe-event-capturing-in-javascript-and-browsers">Describe event capturing in JavaScript and browsers</a></td><td>Basic</td></tr>
<tr>
<td>23</td><td><a class="post-section-overview" href="#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers">What is the difference between <code>mouseenter</code> and <code>mouseover</code> event in JavaScript and browsers?</a></td><td>Basic</td></tr>
<tr>
<td>24</td><td><a class="post-section-overview" href="#what-is-use-strict-in-javascript-for">What is <code>'use strict';</code> in JavaScript for?</a></td><td>Advanced</td></tr>
<tr>
<td>25</td><td><a class="post-section-overview" href="#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript">Explain the difference between synchronous and asynchronous functions in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>26</td><td><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript">What are the pros and cons of using Promises instead of callbacks in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>27</td><td><a class="post-section-overview" href="#explain-ajax-in-as-much-detail-as-possible">Explain AJAX in as much detail as possible</a></td><td>Basic</td></tr>
<tr>
<td>28</td><td><a class="post-section-overview" href="#what-are-the-advantages-and-disadvantages-of-using-ajax">What are the advantages and disadvantages of using AJAX?</a></td><td>Basic</td></tr>
<tr>
<td>29</td><td><a class="post-section-overview" href="#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers">What are the differences between <code>XMLHttpRequest</code> and <code>fetch()</code> in JavaScript and browsers?</a></td><td>Basic</td></tr>
<tr>
<td>30</td><td><a class="post-section-overview" href="#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript">How do you abort a web request using <code>AbortController</code> in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>31</td><td><a class="post-section-overview" href="#what-are-javascript-polyfills-for">What are JavaScript polyfills for?</a></td><td>Advanced</td></tr>
<tr>
<td>32</td><td><a class="post-section-overview" href="#why-is-extending-built-in-javascript-objects-not-a-good-idea">Why is extending built-in JavaScript objects not a good idea?</a></td><td>Intermediate</td></tr>
<tr>
<td>33</td><td><a class="post-section-overview" href="#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it">Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?</a></td><td>Intermediate</td></tr>
<tr>
<td>34</td><td><a class="post-section-overview" href="#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript">Explain the differences between CommonJS modules and ES modules in JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>35</td><td><a class="post-section-overview" href="#what-are-the-various-data-types-in-javascript">What are the various data types in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>36</td><td><a class="post-section-overview" href="#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript">What language constructs do you use for iterating over object properties and array items in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>37</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax">What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?</a></td><td>Basic</td></tr>
<tr>
<td>38</td><td><a class="post-section-overview" href="#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for">What are iterators and generators in JavaScript and what are they used for?</a></td><td>Advanced</td></tr>
<tr>
<td>39</td><td><a class="post-section-overview" href="#explain-the-difference-between-mutable-and-immutable-objects-in-javascript">Explain the difference between mutable and immutable objects in JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>40</td><td><a class="post-section-overview" href="#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript">What is the difference between a <code>Map</code> object and a plain object in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>41</td><td><a class="post-section-overview" href="#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript">What are the differences between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>42</td><td><a class="post-section-overview" href="#why-might-you-want-to-create-static-class-members-in-javascript">Why might you want to create static class members in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>43</td><td><a class="post-section-overview" href="#what-are-symbols-used-for-in-javascript">What are <code>Symbol</code>s used for in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>44</td><td><a class="post-section-overview" href="#what-are-server-sent-events">What are server-sent events?</a></td><td>Advanced</td></tr>
<tr>
<td>45</td><td><a class="post-section-overview" href="#what-are-javascript-object-property-flags-and-descriptors">What are JavaScript object property flags and descriptors?</a></td><td>Advanced</td></tr>
<tr>
<td>46</td><td><a class="post-section-overview" href="#what-are-javascript-object-getters-and-setters-for">What are JavaScript object getters and setters for?</a></td><td>Intermediate</td></tr>
<tr>
<td>47</td><td><a class="post-section-overview" href="#what-are-proxies-in-javascript-used-for">What are proxies in JavaScript used for?</a></td><td>Advanced</td></tr>
<tr>
<td>48</td><td><a class="post-section-overview" href="#what-tools-and-techniques-do-you-use-for-debugging-javascript-code">What tools and techniques do you use for debugging JavaScript code?</a></td><td>Intermediate</td></tr>
<tr>
<td>49</td><td><a class="post-section-overview" href="#what-are-workers-in-javascript-used-for">What are workers in JavaScript used for?</a></td><td>Advanced</td></tr>
<tr>
<td>50</td><td><a class="post-section-overview" href="#how-does-javascript-garbage-collection-work">How does JavaScript garbage collection work?</a></td><td>Advanced</td></tr>
</tbody>
</table>
</div>
<h2 id="heading-table-of-contents-all-questions">Table of Contents (All Questions)</h2>
<p>This list contains a longer list of important JavaScript questions. Not all of them will be asked during Front End Engineer interviews but they provide a well-rounded review of JavaScript concepts ranging from beginner to advanced topics.</p>

<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td><td>Level</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-are-the-various-data-types-in-javascript">What are the various data types in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#how-do-you-check-the-data-type-of-a-variable">How do you check the data type of a variable?</a></td><td>Basic</td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared">What's the difference between a JavaScript variable that is: <code>null</code>, <code>undefined</code> or undeclared?</a></td><td>Basic</td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const">What are the differences between JavaScript variables created using <code>let</code>, <code>var</code> or <code>const</code>?</a></td><td>Basic</td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it">Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?</a></td><td>Intermediate</td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#how-do-you-convert-a-string-to-a-number-in-javascript">How do you convert a string to a number in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-are-template-literals-and-how-are-they-used">What are template literals and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#explain-the-concept-of-tagged-templates">Explain the concept of tagged templates</a></td><td>Intermediate</td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#what-is-the-spread-operator-and-how-is-it-used">What is the spread operator and how is it used?</a></td><td>Basic</td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#what-are-symbols-used-for-in-javascript">What are <code>Symbol</code>s used for in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#what-are-proxies-in-javascript-used-for">What are proxies in JavaScript used for?</a></td><td>Advanced</td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#explain-the-concept-of-hoisting-in-javascript">Explain the concept of "hoisting" in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#explain-the-difference-in-hoisting-between-var-let-and-const">Explain the difference in hoisting between <code>var</code>, <code>let</code>, and <code>const</code></a></td><td>Basic</td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#how-does-hoisting-affect-function-declarations-and-expressions">How does hoisting affect function declarations and expressions?</a></td><td>Advanced</td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#what-are-the-potential-issues-caused-by-hoisting">What are the potential issues caused by hoisting?</a></td><td>Intermediate</td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#how-can-you-avoid-problems-related-to-hoisting">How can you avoid problems related to hoisting?</a></td><td>Basic</td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#what-is-the-difference-between--and--in-javascript">What is the difference between <code>==</code> and <code>===</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript">What language constructs do you use for iterating over object properties and array items in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-break-and-continue-statements">What is the purpose of the <code>break</code> and <code>continue</code> statements?</a></td><td>Basic</td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#what-is-the-ternary-operator-and-how-is-it-used">What is the ternary operator and how is it used?</a></td><td>Basic</td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#how-do-you-access-the-index-of-an-element-in-an-array-during-iteration">How do you access the index of an element in an array during iteration?</a></td><td>Basic</td></tr>
<tr>
<td>22</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-switch-statement">What is the purpose of the <code>switch</code> statement?</a></td><td>Basic</td></tr>
<tr>
<td>23</td><td><a class="post-section-overview" href="#what-are-rest-parameters-and-how-are-they-used">What are rest parameters and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>24</td><td><a class="post-section-overview" href="#explain-the-concept-of-the-spread-operator-and-its-uses">Explain the concept of the spread operator and its uses</a></td><td>Basic</td></tr>
<tr>
<td>25</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax">What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?</a></td><td>Basic</td></tr>
<tr>
<td>26</td><td><a class="post-section-overview" href="#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for">What are iterators and generators in JavaScript and what are they used for?</a></td><td>Advanced</td></tr>
<tr>
<td>27</td><td><a class="post-section-overview" href="#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript">Explain the differences on the usage of <code>foo</code> between <code>function foo() {}</code> and <code>var foo = function() {}</code> in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>28</td><td><a class="post-section-overview" href="#what-is-the-difference-between-a-parameter-and-an-argument">What is the difference between a parameter and an argument?</a></td><td>Basic</td></tr>
<tr>
<td>29</td><td><a class="post-section-overview" href="#explain-the-concept-of-hoisting-with-regards-to-functions">Explain the concept of hoisting with regards to functions</a></td><td>Basic</td></tr>
<tr>
<td>30</td><td><a class="post-section-overview" href="#whats-the-difference-between-call-and-apply-in-javascript">What's the difference between <code>.call</code> and <code>.apply</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>31</td><td><a class="post-section-overview" href="#can-you-offer-a-use-case-for-the-new-arrow--function-syntax">Can you offer a use case for the new arrow =&gt; function syntax?</a></td><td>Basic</td></tr>
<tr>
<td>32</td><td><a class="post-section-overview" href="#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript">Difference between: <code>function Person(){}</code>, <code>const person = Person()</code>, and <code>const person = new Person()</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>33</td><td><a class="post-section-overview" href="#what-is-the-definition-of-a-higher-order-function-in-javascript">What is the definition of a higher-order function in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>34</td><td><a class="post-section-overview" href="#what-are-callback-functions-and-how-are-they-used">What are callback functions and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>35</td><td><a class="post-section-overview" href="#whats-a-typical-use-case-for-anonymous-functions-in-javascript">What's a typical use case for anonymous functions in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>36</td><td><a class="post-section-overview" href="#what-is-recursion-and-how-is-it-used-in-javascript">What is recursion and how is it used in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>37</td><td><a class="post-section-overview" href="#what-are-default-parameters-and-how-are-they-used">What are default parameters and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>38</td><td><a class="post-section-overview" href="#explain-why-the-following-doesnt-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife">Explain why the following doesn't work as an IIFE: <code>function foo(){}();</code>. What needs to be changed to properly make it an IIFE?</a></td><td>Advanced</td></tr>
<tr>
<td>39</td><td><a class="post-section-overview" href="#what-are-the-various-ways-to-create-objects-in-javascript">What are the various ways to create objects in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>40</td><td><a class="post-section-overview" href="#explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties">Explain the difference between dot notation and bracket notation for accessing object properties</a></td><td>Basic</td></tr>
<tr>
<td>41</td><td><a class="post-section-overview" href="#what-are-the-different-methods-for-iterating-over-an-array">What are the different methods for iterating over an array?</a></td><td>Basic</td></tr>
<tr>
<td>42</td><td><a class="post-section-overview" href="#how-do-you-add-remove-and-update-elements-in-an-array">How do you add, remove, and update elements in an array?</a></td><td>Basic</td></tr>
<tr>
<td>43</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-copy-an-object-or-an-array">What are the different ways to copy an object or an array?</a></td><td>Basic</td></tr>
<tr>
<td>44</td><td><a class="post-section-overview" href="#explain-the-difference-between-shallow-copy-and-deep-copy">Explain the difference between shallow copy and deep copy</a></td><td>Basic</td></tr>
<tr>
<td>45</td><td><a class="post-section-overview" href="#what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects">What are the advantages of using the spread operator with arrays and objects?</a></td><td>Basic</td></tr>
<tr>
<td>46</td><td><a class="post-section-overview" href="#how-do-you-check-if-an-object-has-a-specific-property">How do you check if an object has a specific property?</a></td><td>Basic</td></tr>
<tr>
<td>47</td><td><a class="post-section-overview" href="#explain-the-difference-between-mutable-and-immutable-objects-in-javascript">Explain the difference between mutable and immutable objects in JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>48</td><td><a class="post-section-overview" href="#explain-the-concept-of-destructuring-assignment-for-objects-and-arrays">Explain the concept of destructuring assignment for objects and arrays</a></td><td>Basic</td></tr>
<tr>
<td>49</td><td><a class="post-section-overview" href="#what-is-objectfreeze-for">What is <code>Object.freeze()</code> for?</a></td><td>Intermediate</td></tr>
<tr>
<td>50</td><td><a class="post-section-overview" href="#what-is-objectseal-for">What is <code>Object.seal()</code> for?</a></td><td>Intermediate</td></tr>
<tr>
<td>51</td><td><a class="post-section-overview" href="#what-is-objectpreventextensions-for">What is <code>Object.preventExtensions()</code> for?</a></td><td>Intermediate</td></tr>
<tr>
<td>52</td><td><a class="post-section-overview" href="#what-are-javascript-object-getters-and-setters-for">What are JavaScript object getters and setters for?</a></td><td>Intermediate</td></tr>
<tr>
<td>53</td><td><a class="post-section-overview" href="#what-are-javascript-object-property-flags-and-descriptors">What are JavaScript object property flags and descriptors?</a></td><td>Advanced</td></tr>
<tr>
<td>54</td><td><a class="post-section-overview" href="#how-do-you-reliably-determine-whether-an-object-is-empty">How do you reliably determine whether an object is empty?</a></td><td>Basic</td></tr>
<tr>
<td>55</td><td><a class="post-section-overview" href="#what-is-the-event-loop-in-javascript-runtimes">What is the event loop in JavaScript runtimes?</a></td><td>Basic</td></tr>
<tr>
<td>56</td><td><a class="post-section-overview" href="#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript">Explain the difference between synchronous and asynchronous functions in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>57</td><td><a class="post-section-overview" href="#explain-the-concept-of-a-callback-function-in-asynchronous-operations">Explain the concept of a callback function in asynchronous operations</a></td><td>Basic</td></tr>
<tr>
<td>58</td><td><a class="post-section-overview" href="#what-are-promises-and-how-do-they-work">What are Promises and how do they work?</a></td><td>Basic</td></tr>
<tr>
<td>59</td><td><a class="post-section-overview" href="#explain-the-different-states-of-a-promise">Explain the different states of a Promise</a></td><td>Intermediate</td></tr>
<tr>
<td>60</td><td><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript">What are the pros and cons of using Promises instead of callbacks in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>61</td><td><a class="post-section-overview" href="#what-is-the-use-of-promiseall">What is the use of <code>Promise.all()</code></a></td><td>Basic</td></tr>
<tr>
<td>62</td><td><a class="post-section-overview" href="#how-is-promiseall-different-from-promiseallsettled">How is <code>Promise.all()</code> different from <code>Promise.allSettled()</code>?</a></td><td>Intermediate</td></tr>
<tr>
<td>63</td><td><a class="post-section-overview" href="#what-is-asyncawait-and-how-does-it-simplify-asynchronous-code">What is async/await and how does it simplify asynchronous code?</a></td><td>Intermediate</td></tr>
<tr>
<td>64</td><td><a class="post-section-overview" href="#how-do-you-handle-errors-in-asynchronous-operations">How do you handle errors in asynchronous operations?</a></td><td>Basic</td></tr>
<tr>
<td>65</td><td><a class="post-section-overview" href="#explain-the-concept-of-a-microtask-queue">Explain the concept of a microtask queue</a></td><td>Intermediate</td></tr>
<tr>
<td>66</td><td><a class="post-section-overview" href="#what-is-the-difference-between-settimeout-setimmediate-and-processnexttick">What is the difference between <code>setTimeout()</code>, <code>setImmediate()</code>, and <code>process.nextTick()</code>?</a></td><td>Intermediate</td></tr>
<tr>
<td>67</td><td><a class="post-section-overview" href="#explain-how-prototypal-inheritance-works-in-javascript">Explain how prototypal inheritance works in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>68</td><td><a class="post-section-overview" href="#what-is-the-prototype-chain-and-how-does-it-work">What is the prototype chain and how does it work?</a></td><td>Intermediate</td></tr>
<tr>
<td>69</td><td><a class="post-section-overview" href="#explain-the-difference-between-classical-inheritance-and-prototypal-inheritance">Explain the difference between classical inheritance and prototypal inheritance</a></td><td>Basic</td></tr>
<tr>
<td>70</td><td><a class="post-section-overview" href="#explain-the-concept-of-inheritance-in-es2015-classes">Explain the concept of inheritance in ES2015 classes</a></td><td>Basic</td></tr>
<tr>
<td>71</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-new-keyword">What is the purpose of the <code>new</code> keyword?</a></td><td>Basic</td></tr>
<tr>
<td>72</td><td><a class="post-section-overview" href="#how-do-you-create-a-constructor-function">How do you create a constructor function?</a></td><td>Basic</td></tr>
<tr>
<td>73</td><td><a class="post-section-overview" href="#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors">What are the differences between JavaScript ES2015 classes and ES5 function constructors?</a></td><td>Basic</td></tr>
<tr>
<td>74</td><td><a class="post-section-overview" href="#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor">What advantage is there for using the JavaScript arrow syntax for a method in a constructor?</a></td><td>Basic</td></tr>
<tr>
<td>75</td><td><a class="post-section-overview" href="#why-might-you-want-to-create-static-class-members-in-javascript">Why might you want to create static class members in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>76</td><td><a class="post-section-overview" href="#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one">What is a closure in JavaScript, and how/why would you use one?</a></td><td>Intermediate</td></tr>
<tr>
<td>77</td><td><a class="post-section-overview" href="#explain-the-concept-of-lexical-scoping">Explain the concept of lexical scoping</a></td><td>Basic</td></tr>
<tr>
<td>78</td><td><a class="post-section-overview" href="#explain-the-concept-of-scope-in-javascript">Explain the concept of scope in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>79</td><td><a class="post-section-overview" href="#how-can-closures-be-used-to-create-private-variables">How can closures be used to create private variables?</a></td><td>Basic</td></tr>
<tr>
<td>80</td><td><a class="post-section-overview" href="#what-are-the-potential-pitfalls-of-using-closures">What are the potential pitfalls of using closures?</a></td><td>Intermediate</td></tr>
<tr>
<td>81</td><td><a class="post-section-overview" href="#explain-the-difference-between-global-scope-function-scope-and-block-scope">Explain the difference between global scope, function scope, and block scope</a></td><td>Basic</td></tr>
<tr>
<td>82</td><td><a class="post-section-overview" href="#explain-how-this-works-in-javascript">Explain how <code>this</code> works in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>83</td><td><a class="post-section-overview" href="#explain-functionprototypebind-in-javascript">Explain <code>Function.prototype.bind</code> in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>84</td><td><a class="post-section-overview" href="#explain-the-different-ways-the-this-keyword-can-be-bound">Explain the different ways the <code>this</code> keyword can be bound</a></td><td>Intermediate</td></tr>
<tr>
<td>85</td><td><a class="post-section-overview" href="#what-are-the-common-pitfalls-of-using-the-this-keyword">What are the common pitfalls of using the <code>this</code> keyword?</a></td><td>Basic</td></tr>
<tr>
<td>86</td><td><a class="post-section-overview" href="#explain-the-concept-of-this-binding-in-event-handlers">Explain the concept of <code>this</code> binding in event handlers</a></td><td>Basic</td></tr>
<tr>
<td>87</td><td><a class="post-section-overview" href="#what-is-the-dom-and-how-is-it-structured">What is the DOM and how is it structured?</a></td><td>Basic</td></tr>
<tr>
<td>88</td><td><a class="post-section-overview" href="#whats-the-difference-between-an-attribute-and-a-property-in-the-dom">What's the difference between an "attribute" and a "property" in the DOM?</a></td><td>Intermediate</td></tr>
<tr>
<td>89</td><td><a class="post-section-overview" href="#explain-the-difference-between-documentqueryselector-and-documentgetelementbyid">Explain the difference between <code>document.querySelector()</code> and <code>document.getElementById()</code></a></td><td>Basic</td></tr>
<tr>
<td>90</td><td><a class="post-section-overview" href="#how-do-you-add-remove-and-modify-html-elements-using-javascript">How do you add, remove, and modify HTML elements using JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>91</td><td><a class="post-section-overview" href="#what-are-event-listeners-and-how-are-they-used">What are event listeners and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>92</td><td><a class="post-section-overview" href="#explain-the-event-phases-in-a-browser">Explain the event phases in a browser</a></td><td>Intermediate</td></tr>
<tr>
<td>93</td><td><a class="post-section-overview" href="#describe-event-bubbling-in-javascript-and-browsers">Describe event bubbling in JavaScript and browsers</a></td><td>Basic</td></tr>
<tr>
<td>94</td><td><a class="post-section-overview" href="#describe-event-capturing-in-javascript-and-browsers">Describe event capturing in JavaScript and browsers</a></td><td>Basic</td></tr>
<tr>
<td>95</td><td><a class="post-section-overview" href="#explain-event-delegation-in-javascript">Explain event delegation in JavaScript</a></td><td>Basic</td></tr>
<tr>
<td>96</td><td><a class="post-section-overview" href="#how-do-you-prevent-the-default-behavior-of-an-event">How do you prevent the default behavior of an event?</a></td><td>Basic</td></tr>
<tr>
<td>97</td><td><a class="post-section-overview" href="#what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation">What is the difference between <code>event.preventDefault()</code> and <code>event.stopPropagation()</code>?</a></td><td>Intermediate</td></tr>
<tr>
<td>98</td><td><a class="post-section-overview" href="#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers">What is the difference between <code>mouseenter</code> and <code>mouseover</code> event in JavaScript and browsers?</a></td><td>Basic</td></tr>
<tr>
<td>99</td><td><a class="post-section-overview" href="#what-is-the-difference-between-innerhtml-and-textcontent">What is the difference between <code>innerHTML</code> and <code>textContent</code>?</a></td><td>Intermediate</td></tr>
<tr>
<td>100</td><td><a class="post-section-overview" href="#how-do-you-manipulate-css-styles-using-javascript">How do you manipulate CSS styles using JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>101</td><td><a class="post-section-overview" href="#describe-the-difference-between-script-script-async-and-script-defer">Describe the difference between <code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code> and <code>&lt;script defer&gt;</code></a></td><td>Basic</td></tr>
<tr>
<td>102</td><td><a class="post-section-overview" href="#what-is-the-difference-between-the-window-object-and-the-document-object">What is the difference between the Window object and the Document object?</a></td><td>Intermediate</td></tr>
<tr>
<td>103</td><td><a class="post-section-overview" href="#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers">Describe the difference between a cookie, <code>sessionStorage</code> and <code>localStorage</code> in browsers</a></td><td>Basic</td></tr>
<tr>
<td>104</td><td><a class="post-section-overview" href="#how-do-you-make-an-http-request-using-the-fetch-api">How do you make an HTTP request using the Fetch API?</a></td><td>Basic</td></tr>
<tr>
<td>105</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-make-an-api-call-in-javascript">What are the different ways to make an API call in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>106</td><td><a class="post-section-overview" href="#explain-ajax-in-as-much-detail-as-possible">Explain AJAX in as much detail as possible</a></td><td>Basic</td></tr>
<tr>
<td>107</td><td><a class="post-section-overview" href="#what-are-the-advantages-and-disadvantages-of-using-ajax">What are the advantages and disadvantages of using AJAX?</a></td><td>Basic</td></tr>
<tr>
<td>108</td><td><a class="post-section-overview" href="#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers">What are the differences between <code>XMLHttpRequest</code> and <code>fetch()</code> in JavaScript and browsers?</a></td><td>Basic</td></tr>
<tr>
<td>109</td><td><a class="post-section-overview" href="#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript">How do you abort a web request using <code>AbortController</code> in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>110</td><td><a class="post-section-overview" href="#explain-how-jsonp-works-and-how-its-not-really-ajax">Explain how JSONP works (and how it's not really Ajax)</a></td><td>Intermediate</td></tr>
<tr>
<td>111</td><td><a class="post-section-overview" href="#what-are-workers-in-javascript-used-for">What are workers in JavaScript used for?</a></td><td>Advanced</td></tr>
<tr>
<td>112</td><td><a class="post-section-overview" href="#explain-the-concept-of-the-web-socket-api">Explain the concept of the Web Socket API</a></td><td>Intermediate</td></tr>
<tr>
<td>113</td><td><a class="post-section-overview" href="#what-are-javascript-polyfills-for">What are JavaScript polyfills for?</a></td><td>Advanced</td></tr>
<tr>
<td>114</td><td><a class="post-section-overview" href="#how-do-you-detect-if-javascript-is-disabled-on-a-page">How do you detect if JavaScript is disabled on a page?</a></td><td>Intermediate</td></tr>
<tr>
<td>115</td><td><a class="post-section-overview" href="#what-is-the-intl-namespace-object-for">What is the <code>Intl</code> namespace object for?</a></td><td>Intermediate</td></tr>
<tr>
<td>116</td><td><a class="post-section-overview" href="#how-do-you-validate-form-elements-using-the-constraint-validation-api">How do you validate form elements using the Constraint Validation API?</a></td><td>Advanced</td></tr>
<tr>
<td>117</td><td><a class="post-section-overview" href="#how-do-you-use-windowhistory-api">How do you use <code>window.history</code> API?</a></td><td>Basic</td></tr>
<tr>
<td>118</td><td><a class="post-section-overview" href="#how-do-iframe-on-a-page-communicate">How do <code>&lt;iframe&gt;</code> on a page communicate?</a></td><td>Intermediate</td></tr>
<tr>
<td>119</td><td><a class="post-section-overview" href="#difference-between-document-load-event-and-document-domcontentloaded-event">Difference between document <code>load</code> event and document <code>DOMContentLoaded</code> event?</a></td><td>Intermediate</td></tr>
<tr>
<td>120</td><td><a class="post-section-overview" href="#how-do-you-redirect-to-a-new-page-in-javascript">How do you redirect to a new page in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>121</td><td><a class="post-section-overview" href="#how-do-you-get-the-query-string-values-of-the-current-page-in-javascript">How do you get the query string values of the current page in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>122</td><td><a class="post-section-overview" href="#what-are-server-sent-events">What are server-sent events?</a></td><td>Advanced</td></tr>
<tr>
<td>123</td><td><a class="post-section-overview" href="#what-are-progressive-web-applications-pwas">What are Progressive Web Applications (PWAs)?</a></td><td>Intermediate</td></tr>
<tr>
<td>124</td><td><a class="post-section-overview" href="#what-are-modules-and-why-are-they-useful">What are modules and why are they useful?</a></td><td>Basic</td></tr>
<tr>
<td>125</td><td><a class="post-section-overview" href="#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript">Explain the differences between CommonJS modules and ES modules in JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>126</td><td><a class="post-section-overview" href="#how-do-you-import-and-export-modules-in-javascript">How do you import and export modules in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>127</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-using-a-module-bundler">What are the benefits of using a module bundler?</a></td><td>Intermediate</td></tr>
<tr>
<td>128</td><td><a class="post-section-overview" href="#explain-the-concept-of-tree-shaking-in-module-bundling">Explain the concept of tree shaking in module bundling</a></td><td>Intermediate</td></tr>
<tr>
<td>129</td><td><a class="post-section-overview" href="#what-are-the-metadata-fields-of-a-module">What are the metadata fields of a module?</a></td><td>Intermediate</td></tr>
<tr>
<td>130</td><td><a class="post-section-overview" href="#what-do-you-think-of-amd-vs-commonjs">What do you think of AMD vs CommonJS?</a></td><td>Basic</td></tr>
<tr>
<td>131</td><td><a class="post-section-overview" href="#what-are-the-different-types-of-errors-in-javascript">What are the different types of errors in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>132</td><td><a class="post-section-overview" href="#how-do-you-handle-errors-using-trycatch-blocks">How do you handle errors using <code>try...catch</code> blocks?</a></td><td>Basic</td></tr>
<tr>
<td>133</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-finally-block">What is the purpose of the <code>finally</code> block?</a></td><td>Basic</td></tr>
<tr>
<td>134</td><td><a class="post-section-overview" href="#how-can-you-create-custom-error-objects">How can you create custom error objects?</a></td><td>Intermediate</td></tr>
<tr>
<td>135</td><td><a class="post-section-overview" href="#explain-the-concept-of-error-propagation-in-javascript">Explain the concept of error propagation in JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>136</td><td><a class="post-section-overview" href="#what-is-currying-and-how-does-it-work">What is currying and how does it work?</a></td><td>Intermediate</td></tr>
<tr>
<td>137</td><td><a class="post-section-overview" href="#explain-the-concept-of-partial-application">Explain the concept of partial application</a></td><td>Intermediate</td></tr>
<tr>
<td>138</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-using-currying-and-partial-application">What are the benefits of using currying and partial application?</a></td><td>Intermediate</td></tr>
<tr>
<td>139</td><td><a class="post-section-overview" href="#provide-some-examples-of-how-currying-and-partial-application-can-be-used">Provide some examples of how currying and partial application can be used</a></td><td>Basic</td></tr>
<tr>
<td>140</td><td><a class="post-section-overview" href="#how-do-currying-and-partial-application-differ-from-each-other">How do currying and partial application differ from each other?</a></td><td>Intermediate</td></tr>
<tr>
<td>141</td><td><a class="post-section-overview" href="#what-are-sets-and-maps-and-how-are-they-used">What are <code>Set</code>s and <code>Map</code>s and how are they used?</a></td><td>Basic</td></tr>
<tr>
<td>142</td><td><a class="post-section-overview" href="#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript">What are the differences between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>143</td><td><a class="post-section-overview" href="#how-do-you-convert-a-set-to-an-array-in-javascript">How do you convert a <code>Set</code> to an array in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>144</td><td><a class="post-section-overview" href="#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript">What is the difference between a <code>Map</code> object and a plain object in JavaScript?</a></td><td>Basic</td></tr>
<tr>
<td>145</td><td><a class="post-section-overview" href="#how-do-sets-and-maps-handle-equality-checks-for-objects">How do <code>Set</code>s and <code>Map</code>s handle equality checks for objects?</a></td><td>Basic</td></tr>
<tr>
<td>146</td><td><a class="post-section-overview" href="#what-are-some-common-performance-bottlenecks-in-javascript-applications">What are some common performance bottlenecks in JavaScript applications?</a></td><td>Intermediate</td></tr>
<tr>
<td>147</td><td><a class="post-section-overview" href="#explain-the-concept-of-debouncing-and-throttling">Explain the concept of debouncing and throttling</a></td><td>Basic</td></tr>
<tr>
<td>148</td><td><a class="post-section-overview" href="#how-can-you-optimize-dom-manipulation-for-better-performance">How can you optimize DOM manipulation for better performance?</a></td><td>Advanced</td></tr>
<tr>
<td>149</td><td><a class="post-section-overview" href="#what-are-some-techniques-for-reducing-reflows-and-repaints">What are some techniques for reducing reflows and repaints?</a></td><td>Advanced</td></tr>
<tr>
<td>150</td><td><a class="post-section-overview" href="#explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance">Explain the concept of lazy loading and how it can improve performance</a></td><td>Basic</td></tr>
<tr>
<td>151</td><td><a class="post-section-overview" href="#what-are-web-workers-and-how-can-they-be-used-to-improve-performance">What are Web Workers and how can they be used to improve performance?</a></td><td>Advanced</td></tr>
<tr>
<td>152</td><td><a class="post-section-overview" href="#explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance">Explain the concept of caching and how it can be used to improve performance</a></td><td>Basic</td></tr>
<tr>
<td>153</td><td><a class="post-section-overview" href="#what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance">What are some tools that can be used to measure and analyze JavaScript performance?</a></td><td>Advanced</td></tr>
<tr>
<td>154</td><td><a class="post-section-overview" href="#how-can-you-optimize-network-requests-for-better-performance">How can you optimize network requests for better performance?</a></td><td>Advanced</td></tr>
<tr>
<td>155</td><td><a class="post-section-overview" href="#what-are-the-different-types-of-testing-in-software-development">What are the different types of testing in software development?</a></td><td>Intermediate</td></tr>
<tr>
<td>156</td><td><a class="post-section-overview" href="#explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing">Explain the difference between unit testing, integration testing, and end-to-end testing</a></td><td>Intermediate</td></tr>
<tr>
<td>157</td><td><a class="post-section-overview" href="#what-are-some-popular-javascript-testing-frameworks">What are some popular JavaScript testing frameworks?</a></td><td>Basic</td></tr>
<tr>
<td>158</td><td><a class="post-section-overview" href="#how-do-you-write-unit-tests-for-javascript-code">How do you write unit tests for JavaScript code?</a></td><td>Intermediate</td></tr>
<tr>
<td>159</td><td><a class="post-section-overview" href="#explain-the-concept-of-test-driven-development-tdd">Explain the concept of test-driven development (TDD)</a></td><td>Intermediate</td></tr>
<tr>
<td>160</td><td><a class="post-section-overview" href="#what-are-mocks-and-stubs-and-how-are-they-used-in-testing">What are mocks and stubs and how are they used in testing?</a></td><td>Advanced</td></tr>
<tr>
<td>161</td><td><a class="post-section-overview" href="#how-can-you-test-asynchronous-code-in-javascript">How can you test asynchronous code in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>162</td><td><a class="post-section-overview" href="#what-are-some-best-practices-for-writing-maintainable-and-effective-tests-in-javascript">What are some best practices for writing maintainable and effective tests in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>163</td><td><a class="post-section-overview" href="#explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality">Explain the concept of code coverage and how it can be used to assess test quality</a></td><td>Intermediate</td></tr>
<tr>
<td>164</td><td><a class="post-section-overview" href="#what-are-some-tools-that-can-be-used-for-javascript-testing">What are some tools that can be used for JavaScript testing?</a></td><td>Basic</td></tr>
<tr>
<td>165</td><td><a class="post-section-overview" href="#what-are-design-patterns-and-why-are-they-useful">What are design patterns and why are they useful?</a></td><td>Basic</td></tr>
<tr>
<td>166</td><td><a class="post-section-overview" href="#explain-the-concept-of-the-singleton-pattern">Explain the concept of the Singleton pattern</a></td><td>Basic</td></tr>
<tr>
<td>167</td><td><a class="post-section-overview" href="#what-is-the-factory-pattern-and-how-is-it-used">What is the Factory pattern and how is it used?</a></td><td>Intermediate</td></tr>
<tr>
<td>168</td><td><a class="post-section-overview" href="#explain-the-observer-pattern-and-its-use-cases">Explain the Observer pattern and its use cases</a></td><td>Intermediate</td></tr>
<tr>
<td>169</td><td><a class="post-section-overview" href="#what-is-the-module-pattern-and-how-does-it-help-with-encapsulation">What is the Module pattern and how does it help with encapsulation?</a></td><td>Intermediate</td></tr>
<tr>
<td>170</td><td><a class="post-section-overview" href="#explain-the-concept-of-the-prototype-pattern">Explain the concept of the Prototype pattern</a></td><td>Basic</td></tr>
<tr>
<td>171</td><td><a class="post-section-overview" href="#what-is-the-decorator-pattern-and-how-is-it-used">What is the Decorator pattern and how is it used?</a></td><td>Intermediate</td></tr>
<tr>
<td>172</td><td><a class="post-section-overview" href="#explain-the-concept-of-the-strategy-pattern">Explain the concept of the Strategy pattern</a></td><td>Intermediate</td></tr>
<tr>
<td>173</td><td><a class="post-section-overview" href="#what-is-the-command-pattern-and-how-is-it-used">What is the Command pattern and how is it used?</a></td><td>Intermediate</td></tr>
<tr>
<td>174</td><td><a class="post-section-overview" href="#why-is-extending-built-in-javascript-objects-not-a-good-idea">Why is extending built-in JavaScript objects not a good idea?</a></td><td>Intermediate</td></tr>
<tr>
<td>175</td><td><a class="post-section-overview" href="#what-is-cross-site-scripting-xss-and-how-can-you-prevent-it">What is Cross-Site Scripting (XSS) and how can you prevent it?</a></td><td>Intermediate</td></tr>
<tr>
<td>176</td><td><a class="post-section-overview" href="#explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques">Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques</a></td><td>Intermediate</td></tr>
<tr>
<td>177</td><td><a class="post-section-overview" href="#how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications">How can you prevent SQL injection vulnerabilities in JavaScript applications?</a></td><td>Intermediate</td></tr>
<tr>
<td>178</td><td><a class="post-section-overview" href="#what-are-some-best-practices-for-handling-sensitive-data-in-javascript">What are some best practices for handling sensitive data in JavaScript?</a></td><td>Intermediate</td></tr>
<tr>
<td>179</td><td><a class="post-section-overview" href="#explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security">Explain the concept of Content Security Policy (CSP) and how it enhances security</a></td><td>Intermediate</td></tr>
<tr>
<td>180</td><td><a class="post-section-overview" href="#what-are-some-common-security-headers-and-their-purpose">What are some common security headers and their purpose?</a></td><td>Intermediate</td></tr>
<tr>
<td>181</td><td><a class="post-section-overview" href="#how-can-you-prevent-clickjacking-attacks">How can you prevent clickjacking attacks?</a></td><td>Advanced</td></tr>
<tr>
<td>182</td><td><a class="post-section-overview" href="#explain-the-concept-of-input-validation-and-its-importance-in-security">Explain the concept of input validation and its importance in security</a></td><td>Intermediate</td></tr>
<tr>
<td>183</td><td><a class="post-section-overview" href="#what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code">What are some tools and techniques for identifying security vulnerabilities in JavaScript code?</a></td><td>Intermediate</td></tr>
<tr>
<td>184</td><td><a class="post-section-overview" href="#how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications">How can you implement secure authentication and authorization in JavaScript applications?</a></td><td>Advanced</td></tr>
<tr>
<td>185</td><td><a class="post-section-overview" href="#explain-the-same-origin-policy-with-regards-to-javascript">Explain the same-origin policy with regards to JavaScript</a></td><td>Intermediate</td></tr>
<tr>
<td>186</td><td><a class="post-section-overview" href="#what-is-use-strict-in-javascript-for">What is <code>'use strict';</code> in JavaScript for?</a></td><td>Advanced</td></tr>
<tr>
<td>187</td><td><a class="post-section-overview" href="#what-tools-and-techniques-do-you-use-for-debugging-javascript-code">What tools and techniques do you use for debugging JavaScript code?</a></td><td>Intermediate</td></tr>
<tr>
<td>188</td><td><a class="post-section-overview" href="#how-does-javascript-garbage-collection-work">How does JavaScript garbage collection work?</a></td><td>Advanced</td></tr>
<tr>
<td>189</td><td><a class="post-section-overview" href="#explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly">Explain what a single page app is and how to make one SEO-friendly</a></td><td>Intermediate</td></tr>
<tr>
<td>190</td><td><a class="post-section-overview" href="#how-can-you-share-code-between-javascript-files">How can you share code between JavaScript files?</a></td><td>Basic</td></tr>
<tr>
<td>191</td><td><a class="post-section-overview" href="#how-do-you-organize-your-code">How do you organize your code?</a></td><td>Intermediate</td></tr>
<tr>
<td>192</td><td><a class="post-section-overview" href="#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript">What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?</a></td><td>Advanced</td></tr>
<tr>
<td>193</td><td><a class="post-section-overview" href="#when-would-you-use-documentwrite">When would you use <code>document.write()</code>?</a></td><td>Advanced</td></tr>
</tbody>
</table>
</div>
<h2 id="heading-top-questions-with-answers">Top Questions with Answers</h2>

<h3 id="heading-explain-the-concept-of-hoisting-in-javascript">Explain the concept of "hoisting" in JavaScript</h3>

<ul>
<li><strong>Variable declarations (<code>var</code>)</strong>: Declarations are hoisted, but not initializations. The value of the variable is <code>undefined</code> if accessed before initialization.</li>
<li><strong>Variable declarations (<code>let</code> and <code>const</code>)</strong>: Declarations are hoisted, but not initialized. Accessing them results in <code>ReferenceError</code> until the actual declaration is encountered.</li>
<li><strong>Function expressions (<code>var</code>)</strong>: Declarations are hoisted, but not initializations. The value of the variable is <code>undefined</code> if accessed before initialization.</li>
<li><strong>Function declarations (<code>function</code>)</strong>: Both declaration and definition are fully hoisted.</li>
<li><strong>Class declarations (<code>class</code>)</strong>: Declarations are hoisted, but not initialized. Accessing them results in <code>ReferenceError</code> until the actual declaration is encountered.</li>
<li><strong>Import declarations (<code>import</code>)</strong>: Declarations are hoisted, and side effects of importing the module are executed before the rest of the code.</li>
</ul>
<p>The following behavior summarizes the result of accessing the variables before they are declared.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Declaration</td><td>Accessing before declaration</td></tr>
</thead>
<tbody>
<tr>
<td><code>var foo</code></td><td><code>undefined</code></td></tr>
<tr>
<td><code>let foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>const foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>class Foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>var foo = function() { ... }</code></td><td><code>undefined</code></td></tr>
<tr>
<td><code>function foo() { ... }</code></td><td>Normal</td></tr>
<tr>
<td><code>import</code></td><td>Normal</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-hoisting">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-hoisting/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-javascript-variables-created-using-let-var-or-const">What are the differences between JavaScript variables created using <code>let</code>, <code>var</code> or <code>const</code>?</h3>

<p>In JavaScript, <code>let</code>, <code>var</code>, and <code>const</code> are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Behavior</td><td><code>var</code></td><td><code>let</code></td><td><code>const</code></td></tr>
</thead>
<tbody>
<tr>
<td>Scope</td><td>Function or Global</td><td>Block</td><td>Block</td></tr>
<tr>
<td>Initialization</td><td>Optional</td><td>Optional</td><td>Required</td></tr>
<tr>
<td>Redeclaration</td><td>Yes</td><td>No</td><td>No</td></tr>
<tr>
<td>Reassignment</td><td>Yes</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Accessing before declaration</td><td><code>undefined</code></td><td><code>ReferenceError</code></td><td><code>ReferenceError</code></td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-differences-between-variables-created-using-let-var-or-const">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-and-in-javascript">What is the difference between <code>==</code> and <code>===</code> in JavaScript?</h3>

<p><code>==</code> is the abstract equality operator while <code>===</code> is the strict equality operator. The <code>==</code> operator will compare for equality after doing any necessary type conversions. The <code>===</code> operator will not do type conversion, so if two values are not the same type <code>===</code> will simply return <code>false</code>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td><code>==</code></td><td><code>===</code></td></tr>
</thead>
<tbody>
<tr>
<td>Name</td><td>(Loose) Equality operator</td><td>Strict equality operator</td></tr>
<tr>
<td>Type coercion</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Compares value and type</td><td>No</td><td>Yes</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-the-difference-between-double-equal-and-triple-equal">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-event-loop-in-javascript-runtimes">What is the event loop in JavaScript runtimes?</h3>

<p>The event loop is concept within the browser runtime environment regarding how asynchronous operations are executed within JavaScript engines. It works as such:</p>
<ol>
<li>The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.</li>
<li>When an asynchronous operation is encountered (e.g., <code>setTimeout()</code>, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.</li>
<li>Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to "task queue" as "macrotask queue" from here on to better differentiate from the microtask queue.</li>
<li>The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:<ol>
<li>Microtask queue is processed. Microtasks include promise callbacks (<code>then</code>, <code>catch</code>, <code>finally</code>), <code>MutationObserver</code> callbacks, and calls to <code>queueMicrotask()</code>. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.</li>
<li>Macrotask queue is processed. Macrotasks include web APIs like <code>setTimeout()</code>, HTTP requests, user interface event handlers like clicks, scrolls, etc. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!<ol>
<li>If the microtask queue is non-empty, process them as per the previous step.</li>
<li>If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.</li>
</ol>
</li>
</ol>
</li>
<li>This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.</li>
</ol>
<p>The unfortunate truth is that it is extremely hard to explain the event loop well using only text. We recommend checking out one of the following excellent videos explaining the event loop:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=eiC58R16hb8">JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue</a> (2024): Lydia Hallie is a popular educator on JavaScript and this is the best recent videos explaining the event loop. There's also an <a target="_blank" href="https://www.lydiahallie.com/blog/event-loop">accompanying blog post</a> for those who prefer detailed text-based explanations.</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=cCOL7MC4Pl0">In the Loop</a> (2018): Jake Archibald previously from the Chrome team provides a visual demonstration of the event loop during JSConf 2018, accounting for different types of tasks.</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">What the heck is the event loop anyway?</a> (2014): Philip Robert's gave this epic talk at JSConf 2014 and it is one of the most viewed JavaScript videos on YouTube.</li>
</ul>
<p>We recommend watching <a target="_blank" href="https://www.youtube.com/watch?v=eiC58R16hb8">Lydia's video</a> as it is the most modern and concise explanation standing at only 13 minutes long whereas the other videos are at least 30 minutes long. Her video is sufficient for the purpose of interviews.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-event-delegation-in-javascript">Explain event delegation in JavaScript</h3>

<p>Event delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element's event listener handles the event based on the target element.</p>
<p>Event delegation provides the following benefits:</p>
<ul>
<li><strong>Improved performance</strong>: Attaching a single event listener is more efficient than attaching multiple event listeners to individual elements, especially for large or dynamic lists. This reduces memory usage and improves overall performance.</li>
<li><strong>Simplified event handling</strong>: With event delegation, you only need to write the event handling logic once in the parent element's event listener. This makes the code more maintainable and easier to update.</li>
<li><strong>Dynamic element support</strong>: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There's no need to manually attach or remove event listeners when the DOM structure changes</li>
</ul>
<p>However, do note that:</p>
<ul>
<li>It is important to identify the target element that triggered the event.</li>
<li>Not all events can be delegated because they are not bubbled. Non-bubbling events include: <code>focus</code>, <code>blur</code>, <code>scroll</code>, <code>mouseenter</code>, <code>mouseleave</code>, <code>resize</code>, etc.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-event-delegation">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-event-delegation/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-how-this-works-in-javascript">Explain how <code>this</code> works in JavaScript</h3>

<p>There's no simple explanation for <code>this</code>; it is one of the most confusing concepts in JavaScript because it's behavior differs from many other programming languages. The one-liner explanation of the <code>this</code> keyword is that it is a dynamic reference to the context in which a function is executed.</p>
<p>A longer explanation follows is that <code>this</code> follows these rules:</p>
<ol>
<li>If the <code>new</code> keyword is used when calling the function, meaning the function was used as a function constructor, the <code>this</code> inside the function is the newly-created object instance.</li>
<li>If <code>this</code> is used in a <code>class</code> <code>constructor</code>, the <code>this</code> inside the <code>constructor</code> is the newly-created object instance.</li>
<li>If <code>apply()</code>, <code>call()</code>, or <code>bind()</code> is used to call/create a function, <code>this</code> inside the function is the object that is passed in as the argument.</li>
<li>If a function is called as a method (e.g. <code>obj.method()</code>) — <code>this</code> is the object that the function is a property of.</li>
<li>If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, <code>this</code> is the global object. In the browser, the global object is the <code>window</code> object. If in strict mode (<code>'use strict';</code>), <code>this</code> will be <code>undefined</code> instead of the global object.</li>
<li>If multiple of the above rules apply, the rule that is higher wins and will set the <code>this</code> value.</li>
<li>If the function is an ES2015 arrow function, it ignores all the rules above and receives the <code>this</code> value of its surrounding scope at the time it is created.</li>
</ol>
<p>For an in-depth explanation, do check out <a target="_blank" href="https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3">Arnav Aggrawal's article on Medium</a>.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-how-this-works-in-javascript">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-this-works-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers">Describe the difference between a cookie, <code>sessionStorage</code> and <code>localStorage</code> in browsers</h3>

<p>All of the following are mechanisms of storing data on the client, the user's browser in this case. <code>localStorage</code> and <code>sessionStorage</code> both implement the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API">Web Storage API interface</a>.</p>
<ul>
<li><strong>Cookies</strong>: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.</li>
<li><strong><code>localStorage</code></strong>: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.</li>
<li><strong><code>sessionStorage</code></strong>: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.</li>
</ul>
<p>Here's a table summarizing the 3 client storage mechanisms.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td>Cookie</td><td><code>localStorage</code></td><td><code>sessionStorage</code></td></tr>
</thead>
<tbody>
<tr>
<td>Initiator</td><td>Client or server. Server can use <code>Set-Cookie</code> header</td><td>Client</td><td>Client</td></tr>
<tr>
<td>Lifespan</td><td>As specified</td><td>Until deleted</td><td>Until tab is closed</td></tr>
<tr>
<td>Persistent across browser sessions</td><td>If a future expiry date is set</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Sent to server with every HTTP request</td><td>Yes, sent via <code>Cookie</code> header</td><td>No</td><td>No</td></tr>
<tr>
<td>Total capacity (per domain)</td><td>4kb</td><td>5MB</td><td>5MB</td></tr>
<tr>
<td>Access</td><td>Across windows/tabs</td><td>Across windows/tabs</td><td>Same tab</td></tr>
<tr>
<td>Security</td><td>JavaScript cannot access <code>HttpOnly</code> cookies</td><td>None</td><td>None</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-the-difference-between">Describe the difference between <code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code> and <code>&lt;script defer&gt;</code></h3>

<p>All of these ways (<code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code>, and <code>&lt;script defer&gt;</code>) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:</p>
<ul>
<li><code>&lt;script&gt;</code> is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.</li>
<li><code>&lt;script async&gt;</code> downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. <code>&lt;script async&gt;</code> do not wait for each other and execute in no particular order.</li>
<li><code>&lt;script defer&gt;</code> downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.</li>
</ul>
<p>Here's a table summarizing the 3 ways of loading <code>&lt;script&gt;</code>s in a HTML document.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><code>&lt;script&gt;</code></td><td><code>&lt;script async&gt;</code></td><td><code>&lt;script defer&gt;</code></td></tr>
</thead>
<tbody>
<tr>
<td>Parsing behavior</td><td>Blocks HTML parsing</td><td>Runs parallel to parsing</td><td>Runs parallel to parsing</td></tr>
<tr>
<td>Execution order</td><td>In order of appearance</td><td>Not guaranteed</td><td>In order of appearance</td></tr>
<tr>
<td>DOM dependency</td><td>No</td><td>No</td><td>Yes (waits for DOM)</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-the-difference-between-script-async-and-script-defer">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared">What's the difference between a JavaScript variable that is: <code>null</code>, <code>undefined</code> or undeclared?</h3>

<div class="hn-table">
<table>
<thead>
<tr>
<td>Trait</td><td><code>null</code></td><td><code>undefined</code></td><td>Undeclared</td></tr>
</thead>
<tbody>
<tr>
<td>Meaning</td><td>Explicitly set by the developer to indicate that a variable has no value</td><td>Variable has been declared but not assigned a value</td><td>Variable has not been declared at all</td></tr>
<tr>
<td>Type</td><td><code>object</code></td><td><code>undefined</code></td><td>Throws a <code>ReferenceError</code></td></tr>
<tr>
<td>Equality Comparison</td><td><code>null == undefined</code> is <code>true</code></td><td><code>undefined == null</code> is <code>true</code></td><td>Throws a <code>ReferenceError</code></td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-the-difference-between-call-and-apply-in-javascript">What's the difference between <code>.call</code> and <code>.apply</code> in JavaScript?</h3>

<p><code>.call</code> and <code>.apply</code> are both used to invoke functions with a specific <code>this</code> context and arguments. The primary difference lies in how they accept arguments:</p>
<ul>
<li><code>.call(thisArg, arg1, arg2, ...)</code>: Takes arguments individually.</li>
<li><code>.apply(thisArg, [argsArray])</code>: Takes arguments as an array.</li>
</ul>
<p>Assuming we have a function <code>add</code>, the function can be invoked using <code>.call</code> and <code>.apply</code> in the following manner:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-built_in">console</span>.log(add.call(<span class="hljs-literal">null</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); <span class="hljs-comment">// 3</span>
<span class="hljs-built_in">console</span>.log(add.apply(<span class="hljs-literal">null</span>, [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>])); <span class="hljs-comment">// 3</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/whats-the-difference-between-call-and-apply">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-call-and-apply/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-functionprototypebind-in-javascript">Explain <code>Function.prototype.bind</code> in JavaScript</h3>

<p><code>Function.prototype.bind</code> is a method in JavaScript that allows you to create a new function with a specific <code>this</code> value and optional initial arguments. It's primary purpose is to:</p>
<ul>
<li><strong>Binding <code>this</code> value to preserve context</strong>: The primary purpose of <code>bind</code> is to bind the <code>this</code> value of a function to a specific object. When you call <code>func.bind(thisArg)</code>, it creates a new function with the same body as <code>func</code>, but with <code>this</code> permanently bound to <code>thisArg</code>.</li>
<li><strong>Partial application of arguments</strong>: <code>bind</code> also allows you to pre-specify arguments for the new function. Any arguments passed to <code>bind</code> after <code>thisArg</code> will be prepended to the arguments list when the new function is called.</li>
<li><strong>Method borrowing</strong>: <code>bind</code> allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.</li>
</ul>
<p>The <code>bind</code> method is particularly useful in scenarios where you need to ensure that a function is called with a specific <code>this</code> context, such as in event handlers, callbacks, or method borrowing.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-function-prototype-bind">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-function-prototype-bind/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor">What advantage is there for using the JavaScript arrow syntax for a method in a constructor?</h3>

<p>The main advantage of using an arrow function as a method inside a constructor is that the value of <code>this</code> gets set at the time of the function creation and can't change after that. When the constructor is used to create a new object, <code>this</code> will always refer to that object.</p>
<p>For example, let's say we have a <code>Person</code> constructor that takes a first name as an argument has two methods to <code>console.log()</code> that name, one as a regular function and one as an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Person = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.sayName1 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  };
  <span class="hljs-built_in">this</span>.sayName2 = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  };
};

<span class="hljs-keyword">const</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>);
<span class="hljs-keyword">const</span> dave = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Dave'</span>);

john.sayName1(); <span class="hljs-comment">// John</span>
john.sayName2(); <span class="hljs-comment">// John</span>

<span class="hljs-comment">// The regular function can have its `this` value changed, but the arrow function cannot</span>
john.sayName1.call(dave); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.call(dave); <span class="hljs-comment">// John</span>

john.sayName1.apply(dave); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.apply(dave); <span class="hljs-comment">// John</span>

john.sayName1.bind(dave)(); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.bind(dave)(); <span class="hljs-comment">// John</span>

<span class="hljs-keyword">const</span> sayNameFromWindow1 = john.sayName1;
sayNameFromWindow1(); <span class="hljs-comment">// undefined (because `this` is now the window object)</span>

<span class="hljs-keyword">const</span> sayNameFromWindow2 = john.sayName2;
sayNameFromWindow2(); <span class="hljs-comment">// John</span>
</code></pre>
<p>The main takeaway here is that <code>this</code> can be changed for a normal function, but <code>this</code> always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the value of <code>this</code> changing.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-how-prototypal-inheritance-works-in-javascript">Explain how prototypal inheritance works in JavaScript</h3>

<p>Prototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called <code>[[Prototype]]</code> (commonly accessed via <code>__proto__</code> or using <code>Object.getPrototypeOf()</code>) that is a reference to another object, which is called the object's "prototype".</p>
<p>When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's <code>__proto__</code>, and the <code>__proto__</code>'s <code>__proto__</code> and so on, until it finds the property defined on one of the <code>__proto__</code>s or until it reaches the end of the prototype chain.</p>
<p>This behavior simulates classical inheritance, but it is really more of <a target="_blank" href="https://davidwalsh.name/javascript-objects">delegation than inheritance</a>.</p>
<p>Here's an example of prototypal inheritance:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Parent object constructor.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-comment">// Add a method to the parent object's prototype.</span>
Animal.prototype.makeSound = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The '</span> + <span class="hljs-built_in">this</span>.constructor.name + <span class="hljs-string">' makes a sound.'</span>);
};

<span class="hljs-comment">// Child object constructor.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">name</span>) </span>{
  Animal.call(<span class="hljs-built_in">this</span>, name); <span class="hljs-comment">// Call the parent constructor.</span>
}

<span class="hljs-comment">// Set the child object's prototype to be the parent's prototype.</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(Dog.prototype, Animal.prototype);

<span class="hljs-comment">// Add a method to the child object's prototype.</span>
Dog.prototype.bark = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Woof!'</span>);
};

<span class="hljs-comment">// Create a new instance of Dog.</span>
<span class="hljs-keyword">const</span> bolt = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Bolt'</span>);

<span class="hljs-comment">// Call methods on the child object.</span>
<span class="hljs-built_in">console</span>.log(bolt.name); <span class="hljs-comment">// "Bolt"</span>
bolt.makeSound(); <span class="hljs-comment">// "The Dog makes a sound."</span>
bolt.bark(); <span class="hljs-comment">// "Woof!"</span>
</code></pre>
<p>Things to note are:</p>
<ul>
<li><code>.makeSound</code> is not defined on <code>Dog</code>, so the JavaScript engine goes up the prototype chain and finds <code>.makeSound</code> on the inherited <code>Animal</code>.</li>
<li>Using <code>Object.create()</code> to build the inheritance chain is no longer recommended. Use <code>Object.setPrototypeOf()</code> instead.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-how-prototypal-inheritance-works">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-prototypal-inheritance-works/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-difference-between-function-person-const-person-person-and-const-person-new-person-in-javascript">Difference between: <code>function Person(){}</code>, <code>const person = Person()</code>, and <code>const person = new Person()</code> in JavaScript?</h3>

<ul>
<li><code>function Person(){}</code>: A function declaration in JavaScript. It can be used as a regular function or as a constructor.</li>
<li><code>const person = Person()</code>: Calls <code>Person</code> as a regular function, not a constructor. If <code>Person</code> is intended to be a constructor, this will lead to unexpected behavior.</li>
<li><code>const person = new Person()</code>: Creates a new instance of <code>Person</code>, correctly utilizing the constructor function to initialize the new object.</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td><code>function Person(){}</code></td><td><code>const person = Person()</code></td><td><code>const person = new Person()</code></td></tr>
</thead>
<tbody>
<tr>
<td>Type</td><td>Function declaration</td><td>Function call</td><td>Constructor call</td></tr>
<tr>
<td>Usage</td><td>Defines a function</td><td>Invokes <code>Person</code> as a regular function</td><td>Creates a new instance of <code>Person</code></td></tr>
<tr>
<td>Instance Creation</td><td>No instance created</td><td>No instance created</td><td>New instance created</td></tr>
<tr>
<td>Common Mistake</td><td>N/A</td><td>Misusing as constructor leading to <code>undefined</code></td><td>None (when used correctly)</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/difference-between-function-person-var-person-person-and-var-person-new-person">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function-in-javascript">Explain the differences on the usage of <code>foo</code> between <code>function foo() {}</code> and <code>var foo = function() {}</code> in JavaScript</h3>

<p><code>function foo() {}</code> a function declaration while the <code>var foo = function() {}</code> is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as <code>var</code>-declared variables).</p>
<p>If you try to invoke a function expression before it is declared, you will get an <code>Uncaught TypeError: XXX is not a function</code> error.</p>
<p>Function declarations can be called in the enclosing scope even before they are declared.</p>
<pre><code class="lang-js">foo(); <span class="hljs-comment">// 'FOOOOO'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'FOOOOO'</span>);
}
</code></pre>
<p>Function expressions if called before they are declared will result in an error.</p>
<pre><code class="lang-js">foo(); <span class="hljs-comment">// Uncaught TypeError: foo is not a function</span>
<span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'FOOOOO'</span>);
};
</code></pre>
<p>Another key difference is in the scope of the function name. Function expressions can be named by defining it after the <code>function</code> and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or <code>undefined</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunc = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">namedFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(namedFunc); <span class="hljs-comment">// Works</span>
};
<span class="hljs-built_in">console</span>.log(namedFunc); <span class="hljs-comment">// undefined</span>
</code></pre>
<p><strong>Note</strong>: The examples uses <code>var</code> due to legacy reasons. Function expressions can be defined using <code>let</code> and <code>const</code> and the key difference is in the hoisting behavior of those keywords.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-a-typical-use-case-for-anonymous-functions-in-javascript">What's a typical use case for anonymous functions in JavaScript?</h3>

<p>Anonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.</p>
<pre><code class="lang-js"><span class="hljs-comment">// The filter method is passed an anonymous function.</span>
arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">1</span>);
</code></pre>
<p>They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to "close over" and remember the environment in which they were created.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Encapsulating Code</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Some code here.</span>
})();

<span class="hljs-comment">// Callbacks</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello world!'</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Functional programming constructs</span>
<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> double = arr.map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el</span>) </span>{
  <span class="hljs-keyword">return</span> el * <span class="hljs-number">2</span>;
});
<span class="hljs-built_in">console</span>.log(double); <span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/whats-a-typical-use-case-for-anonymous-functions">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-various-ways-to-create-objects-in-javascript">What are the various ways to create objects in JavaScript?</h3>

<p>Creating objects in JavaScript offers several methods:</p>
<ul>
<li><strong>Object literals (<code>{}</code>)</strong>: Simplest and most popular approach. Define key-value pairs within curly braces.</li>
<li><strong><code>Object()</code> constructor</strong>: Use <code>new Object()</code> with dot notation to add properties.</li>
<li><strong><code>Object.create()</code></strong>: Create new objects using existing objects as prototypes, inheriting properties and methods.</li>
<li><strong>Constructor functions</strong>: Define blueprints for objects using functions, creating instances with <code>new</code>.</li>
<li><strong>ES2015 classes</strong>: Structured syntax similar to other languages, using <code>class</code> and <code>constructor</code> keywords.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-various-ways-to-create-objects-in-javascript">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-a-closure-in-javascript-and-howwhy-would-you-use-one">What is a closure in JavaScript, and how/why would you use one?</h3>

<p>In the book <a target="_blank" href="https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures">"You Don't Know JS"</a> (YDKJS) by Kyle Simpson, a closure is defined as follows:</p>
<blockquote>
<p>Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope</p>
</blockquote>
<p>In simple terms, functions have access to variables that were in their scope at the time of their creation. This is what we call the function's lexical scope. A closure is a function that retains access to these variables even after the outer function has finished executing. This is like the function has a memory of its original environment.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> outerVar = <span class="hljs-string">'I am outside of innerFunction'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(outerVar); <span class="hljs-comment">// `innerFunction` can still access `outerVar`.</span>
  }

  <span class="hljs-keyword">return</span> innerFunction;
}

<span class="hljs-keyword">const</span> inner = outerFunction(); <span class="hljs-comment">// `inner` now holds a reference to `innerFunction`.</span>

inner(); <span class="hljs-comment">// "I am outside of innerFunction"</span>
<span class="hljs-comment">// Even though `outerFunction` has completed execution, `inner` still has access to variables defined inside `outerFunction`.</span>
</code></pre>
<p>Key points to remember:</p>
<ul>
<li>Closure occurs when an inner function has access to variables in its outer (lexical) scope, even when the outer function has finished executing.</li>
<li>Closure allows a function to <strong>remember</strong> the environment in which it was created, even if that environment is no longer present.</li>
<li>Closures are used extensively in JavaScript, such as in callbacks, event handlers, and asynchronous functions.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-a-closure-and-how-why-would-you-use-one">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-definition-of-a-higher-order-function-in-javascript">What is the definition of a higher-order function in JavaScript?</h3>

<p>A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.</p>
<p>Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is <code>Array.prototype.map()</code>, which takes an array and a function as arguments. <code>Array.prototype.map()</code> then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are <code>Array.prototype.forEach()</code>, <code>Array.prototype.filter()</code>, and <code>Array.prototype.reduce()</code>. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. <code>Function.prototype.bind()</code> is an example that returns another function.</p>
<p>Imagine a scenario where we have an array of names that we need to transform to uppercase.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> names = [<span class="hljs-string">'irish'</span>, <span class="hljs-string">'daisy'</span>, <span class="hljs-string">'anna'</span>];
</code></pre>
<p>The imperative way will be as such:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformNamesToUppercase</span>(<span class="hljs-params">names</span>) </span>{
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; names.length; i++) {
    results.push(names[i].toUpperCase());
  }
  <span class="hljs-keyword">return</span> results;
}

transformNamesToUppercase(names); <span class="hljs-comment">// ['IRISH', 'DAISY', 'ANNA']</span>
</code></pre>
<p>Using <code>Array.prototype.map(transformerFn)</code> makes the code shorter and more declarative.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformNamesToUppercase</span>(<span class="hljs-params">names</span>) </span>{
  <span class="hljs-keyword">return</span> names.map(<span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> name.toUpperCase());
}

transformNamesToUppercase(names); <span class="hljs-comment">// ['IRISH', 'DAISY', 'ANNA']</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-the-definition-of-a-higher-order-function">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors">What are the differences between JavaScript ES2015 classes and ES5 function constructors?</h3>

<p>ES2015 introduces a new way of creating classes, which provides a more intuitive and concise way to define and work with objects and inheritance compared to the ES5 function constructor syntax. Here's an example of each:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 function constructor</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-comment">// ES2015 Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}
</code></pre>
<p>For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a <code>Student</code> class that subclasses <code>Person</code> and add a <code>studentId</code> field, this is what we have to do in addition to the above.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 function constructor</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Student</span>(<span class="hljs-params">name, studentId</span>) </span>{
  <span class="hljs-comment">// Call constructor of superclass to initialize superclass-derived members.</span>
  Person.call(<span class="hljs-built_in">this</span>, name);

  <span class="hljs-comment">// Initialize subclass's own members.</span>
  <span class="hljs-built_in">this</span>.studentId = studentId;
}

Student.prototype = <span class="hljs-built_in">Object</span>.create(Person.prototype);
Student.prototype.constructor = Student;

<span class="hljs-comment">// ES2015 Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, studentId) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.studentId = studentId;
  }
}
</code></pre>
<p>It's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember.</p>
<p><strong>Comparison of ES5 function constructors vs ES2015 classes</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>ES5 Function Constructor</td><td>ES2015 Class</td></tr>
</thead>
<tbody>
<tr>
<td>Syntax</td><td>Uses function constructors and prototypes</td><td>Uses <code>class</code> keyword</td></tr>
<tr>
<td>Constructor</td><td>Function with properties assigned using <code>this</code></td><td><code>constructor</code> method inside the class</td></tr>
<tr>
<td>Method Definition</td><td>Defined on the prototype</td><td>Defined inside the class body</td></tr>
<tr>
<td>Static Methods</td><td>Added directly to the constructor function</td><td>Defined using the <code>static</code> keyword</td></tr>
<tr>
<td>Inheritance</td><td>Uses <code>Object.create()</code> and manually sets prototype chain</td><td>Uses <code>extends</code> keyword and <code>super</code> function</td></tr>
<tr>
<td>Readability</td><td>Less intuitive and more verbose</td><td>More concise and intuitive</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-differences-between-es6-class-and-es5-function-constructors">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-event-bubbling-in-javascript-and-browsers">Describe event bubbling in JavaScript and browsers</h3>

<p>Event bubbling is a DOM event propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event.</p>
<p>Event bubbling is essential for event delegation, where a single event handler manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-event-bubbling">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-bubbling/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-event-capturing-in-javascript-and-browsers">Describe event capturing in JavaScript and browsers</h3>

<p>Event capturing is a lesser-used counterpart to <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-event-bubbling">event bubbling</a> in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.</p>
<p>Event capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on <code>addEventListener()</code>.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-event-capturing">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-capturing/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers">What is the difference between <code>mouseenter</code> and <code>mouseover</code> event in JavaScript and browsers?</h3>

<p>The main difference lies in the bubbling behavior of <code>mouseenter</code> and <code>mouseover</code> events. <code>mouseenter</code> does not bubble while <code>mouseover</code> bubbles.</p>
<p><code>mouseenter</code> events do not bubble. The <code>mouseenter</code> event is triggered only when the mouse pointer enters the element itself, not its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the <code>mouseenter</code> event will not be triggered on the parent element again, it's only triggered once upon entry of parent element without regard for its contents. If both parent and child have <code>mouseenter</code> listeners attached and the mouse pointer moves from the parent element to the child element, <code>mouseenter</code> will only fire for the child.</p>
<p><code>mouseover</code> events bubble up the DOM tree. The <code>mouseover</code> event is triggered when the mouse pointer enters the element or one of its descendants. If have a parent element has child elements, and the mouse pointer enters child elements, the <code>mouseover</code> event will be triggered on the parent element again as well. If the parent element has multiple child elements, this can result in multiple event callbacks fired. If there are child elements, and the mouse pointer moves from the parent element to the child element, <code>mouseover</code> will fire for both the parent and the child.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td><code>mouseenter</code></td><td><code>mouseover</code></td></tr>
</thead>
<tbody>
<tr>
<td>Bubbling</td><td>No</td><td>Yes</td></tr>
<tr>
<td>Trigger</td><td>Only when entering itself</td><td>When entering itself and when entering descendants</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-the-difference-between-mouseenter-and-mouseover-event">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-use-strict-in-javascript-for">What is <code>'use strict';</code> in JavaScript for?</h3>

<p><code>'use strict'</code> is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.</p>
<p><strong>Advantages</strong></p>
<ul>
<li>Makes it impossible to accidentally create global variables.</li>
<li>Makes assignments which would otherwise silently fail to throw an exception.</li>
<li>Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).</li>
<li>Requires that function parameter names be unique.</li>
<li><code>this</code> is <code>undefined</code> in the global context.</li>
<li>It catches some common coding bloopers, throwing exceptions.</li>
<li>It disables features that are confusing or poorly thought out.</li>
</ul>
<p><strong>Disadvantages</strong></p>
<ul>
<li>Many missing features that some developers might be used to.</li>
<li>No more access to <code>function.caller</code> and <code>function.arguments</code>.</li>
<li>Concatenation of scripts written in different strict modes might cause issues.</li>
</ul>
<p>Overall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript">Explain the difference between synchronous and asynchronous functions in JavaScript</h3>

<p>Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Inside sum function'</span>);
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">const</span> result = sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// The program waits for sum() to complete before assigning the result</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result: '</span>, result); <span class="hljs-comment">// Output: 5</span>

<span class="hljs-comment">// Console output:</span>
<span class="hljs-comment">// Inside sum function</span>
<span class="hljs-comment">// Result: 5</span>
</code></pre>
<p>Asynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
    callback(data); <span class="hljs-comment">// Calling the callback function with data</span>
  }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulating a 2-second delay</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Fetching data...'</span>);
fetchData(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data); <span class="hljs-comment">// Output: { name: 'John', age: 30 } (after 2 seconds)</span>
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Call made to fetch data'</span>); <span class="hljs-comment">// Output: This will be printed first</span>

<span class="hljs-comment">// Console output:</span>
<span class="hljs-comment">// Fetching data...</span>
<span class="hljs-comment">// Call made to fetch data</span>
<span class="hljs-comment">// { name: 'John', age: 30 }</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-the-difference-between-synchronous-and-asynchronous-functions">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript">What are the pros and cons of using Promises instead of callbacks in JavaScript?</h3>

<p>Promises offer a cleaner alternative to callbacks, helping to avoid callback hell and making asynchronous code more readable. They facilitate writing sequential and parallel asynchronous operations with ease. However, using promises may introduce slightly more complex code.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-ajax-in-as-much-detail-as-possible">Explain AJAX in as much detail as possible</h3>

<p>AJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like <code>XMLHttpRequest</code> or the <code>fetch()</code> API to send and receive data in the background. In modern web applications, the <code>fetch()</code> API is more commonly used to implement AJAX.</p>
<p><strong>Using <code>XMLHttpRequest</code></strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (xhr.readyState === XMLHttpRequest.DONE) {
    <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
      <span class="hljs-built_in">console</span>.log(xhr.responseText);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Request failed: '</span> + xhr.status);
    }
  }
};
xhr.open(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>, <span class="hljs-literal">true</span>);
xhr.send();
</code></pre>
<p><strong>Using <code>fetch()</code></strong></p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
    }
    <span class="hljs-keyword">return</span> response.json();
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Fetch error:'</span>, error));
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-ajax-in-as-much-detail-as-possible">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-advantages-and-disadvantages-of-using-ajax">What are the advantages and disadvantages of using AJAX?</h3>

<p>AJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page.</p>
<p><strong>Advantages</strong></p>
<ul>
<li><strong>Smoother user experience</strong>: Updates happen without full page reloads, like in mail and chat applications.</li>
<li><strong>Lighter server Load</strong>: Only necessary data is fetched via AJAX, reducing server load and improving perceived performance of webpages.</li>
<li><strong>Maintains client state</strong>: User interactions and any client states are persisted within the page.</li>
</ul>
<p><strong>Disadvantages</strong></p>
<ul>
<li><strong>Reliance on JavaScript</strong>: If disabled, Ajax functionality breaks.</li>
<li><strong>Bookmarking issues</strong>: Dynamic content makes bookmarking specific page states difficult.</li>
<li><strong>SEO Challenges</strong>: Search engines may struggle to index dynamic content.</li>
<li><strong>Performance Concerns</strong>: Processing Ajax data on low-end devices can be slow.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-advantages-and-disadvantages-of-using-ajax">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers">What are the differences between <code>XMLHttpRequest</code> and <code>fetch()</code> in JavaScript and browsers?</h3>

<p><code>XMLHttpRequest</code> (XHR) and <code>fetch()</code> API are both used for asynchronous HTTP requests in JavaScript (AJAX). <code>fetch()</code> offers a cleaner syntax, promise-based approach, and more modern feature set compared to XHR. However, there are some differences:</p>
<ul>
<li><code>XMLHttpRequest</code> event callbacks, while <code>fetch()</code> utilizes promise chaining.</li>
<li><code>fetch()</code> provides more flexibility in headers and request bodies.</li>
<li><code>fetch()</code> support cleaner error handling with <code>catch()</code>.</li>
<li>Handling caching with <code>XMLHttpRequest</code> is difficult but caching is supported by <code>fetch()</code> by default in the <code>options.cache</code> object (<code>cache</code> value of second parameter) to <code>fetch()</code> or <code>Request()</code>.</li>
<li><code>fetch()</code> requires an <code>AbortController</code> for cancelation, while for <code>XMLHttpRequest</code>, it provides <code>abort()</code> property.</li>
<li><code>XMLHttpRequest</code> has good support for progress tracking, which <code>fetch()</code> lacks.</li>
<li><code>XMLHttpRequest</code> is only available in the browser and not natively supported in Node.js environments. On the other hand <code>fetch()</code> is part of the JavaScript language and is supported on all modern JavaScript runtimes.</li>
</ul>
<p>These days <code>fetch()</code> is preferred for its cleaner syntax and modern features.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-differences-between-xmlhttprequest-and-fetch">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-abort-a-web-request-using-abortcontroller-in-javascript">How do you abort a web request using <code>AbortController</code> in JavaScript?</h3>

<p><code>AbortController</code> is used to cancel ongoing asynchronous operations like fetch requests.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> AbortController();
<span class="hljs-keyword">const</span> signal = controller.signal;

fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>, { signal })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-comment">// Handle response</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request aborted'</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    }
  });

<span class="hljs-comment">// Call abort() to abort the request</span>
controller.abort();
</code></pre>
<p>Aborting web requests is useful for:</p>
<ul>
<li>Canceling requests based on user actions.</li>
<li>Prioritizing the latest requests in scenarios with multiple simultaneous requests.</li>
<li>Canceling requests that are no longer needed, e.g. after the user has navigated away from the page.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/how-do-you-abort-a-web-request-using-abortcontrollers">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-polyfills-for">What are JavaScript polyfills for?</h3>

<p>Polyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.</p>
<p>They can be implemented manually or included through libraries and are often used in conjunction with feature detection.</p>
<p>Common use cases include:</p>
<ul>
<li><strong>New JavaScript Methods</strong>: For example, <code>Array.prototype.includes()</code>, <code>Object.assign()</code>, etc.</li>
<li><strong>New APIs</strong>: Such as <code>fetch()</code>, <code>Promise</code>, <code>IntersectionObserver</code>, etc. Modern browsers support these now but for a long time they have to be polyfilled.</li>
</ul>
<p>Libraries and services for polyfills:</p>
<ul>
<li><p><strong><code>core-js</code></strong>: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/actual/array/flat-map'</span>; <span class="hljs-comment">// With this, Array.prototype.flatMap is available to be used.</span>

[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>].flatMap(<span class="hljs-function">(<span class="hljs-params">it</span>) =&gt;</span> [it, it]); <span class="hljs-comment">// =&gt; [1, 1, 2, 2]</span>
</code></pre>
</li>
<li><p><strong>Polyfill.io</strong>: A service that provides polyfills based on the features and user agents specified in the request.</p>
<pre><code class="lang-js">&lt;script src=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js"</span>&gt;&lt;/script&gt;
</code></pre>
</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-javascript-polyfills-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-polyfills-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-is-extending-built-in-javascript-objects-not-a-good-idea">Why is extending built-in JavaScript objects not a good idea?</h3>

<p>Extending a built-in/native JavaScript object means adding properties/functions to its <code>prototype</code>. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the <code>Array.prototype</code> by adding the same <code>contains</code> method, the implementations will overwrite each other and your code will have unpredictable behavior if these two methods do not work the same way.</p>
<p>The only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/why-is-extending-built-in-javascript-objects-not-a-good-idea">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it">Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?</h3>

<p>JavaScript that is executed in the browser has access to the global scope (the <code>window</code> object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. Several reasons to avoid touching the global scope:</p>
<ul>
<li><strong>Naming conflicts</strong>: Sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced.</li>
<li><strong>Cluttered global namespace</strong>: Keeping the global namespace minimal avoids making the codebase hard to manage and maintain.</li>
<li><strong>Scope leaks</strong>: Unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues.</li>
<li><strong>Modularity and encapsulation</strong>: Good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability.</li>
<li><strong>Security concerns</strong>: Global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there.</li>
<li><strong>Compatibility and portability</strong>: Heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks.</li>
</ul>
<p>Follow these best practices to avoid global scope pollution:</p>
<ul>
<li><strong>Use local variables</strong>: Declare variables within functions or blocks using <code>var</code>, <code>let</code>, or <code>const</code> to limit their scope.</li>
<li><strong>Pass variables as function parameters</strong>: Maintain encapsulation by passing variables as parameters instead of accessing them globally.</li>
<li><strong>Use immediately invoked function expressions (IIFE)</strong>: Create new scopes with IIFEs to prevent adding variables to the global scope.</li>
<li><strong>Use modules</strong>: Encapsulate code with module systems to maintain separate scopes and manageability.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript">Explain the differences between CommonJS modules and ES modules in JavaScript</h3>

<p>In JavaScript, modules are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.</p>
<p><strong>CommonJS</strong> is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the <code>require()</code> function to load modules and the <code>module.exports</code> or <code>exports</code> object to define the exports of a module.</p>
<pre><code class="lang-js"><span class="hljs-comment">// my-module.js</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-number">42</span>;
<span class="hljs-built_in">module</span>.exports = { value };

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./my-module.js'</span>);
<span class="hljs-built_in">console</span>.log(myModule.value); <span class="hljs-comment">// 42</span>
</code></pre>
<p><strong>ES Modules</strong> (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the <code>import</code> and <code>export</code> statements to handle module dependencies.</p>
<pre><code class="lang-js"><span class="hljs-comment">// my-module.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> value = <span class="hljs-number">42</span>;

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> { value } <span class="hljs-keyword">from</span> <span class="hljs-string">'./my-module.js'</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 42</span>
</code></pre>
<p><strong>CommonJS vs ES modules</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>CommonJS</td><td>ES modules</td></tr>
</thead>
<tbody>
<tr>
<td>Module Syntax</td><td><code>require()</code> for importing <code>module.exports</code> for exporting</td><td><code>import</code> for importing <code>export</code> for exporting</td></tr>
<tr>
<td>Environment</td><td>Primarily used in Node.js for server-side development</td><td>Designed for both browser and server-side JavaScript (Node.js)</td></tr>
<tr>
<td>Loading</td><td>Synchronous loading of modules</td><td>Asynchronous loading of modules</td></tr>
<tr>
<td>Structure</td><td>Dynamic imports, can be conditionally called</td><td>Static imports/exports at the top level</td></tr>
<tr>
<td>File extensions</td><td><code>.js</code> (default)</td><td><code>.mjs</code> or <code>.js</code> (with <code>type: "module"</code> in <code>package.json</code>)</td></tr>
<tr>
<td>Browser support</td><td>Not natively supported in browsers</td><td>Natively supported in modern browsers</td></tr>
<tr>
<td>Optimization</td><td>Limited optimization due to dynamic nature</td><td>Allows for optimizations like tree-shaking due to static structure</td></tr>
<tr>
<td>Compatibility</td><td>Widely used in existing Node.js codebases and libraries</td><td>Newer standard, but gaining adoption in modern projects</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-the-differences-between-commonjs-modules-and-es-modules">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-various-data-types-in-javascript">What are the various data types in JavaScript?</h3>

<p>In JavaScript, data types can be categorized into <code>primitive</code> and <code>non-primitive</code> types:</p>
<p><strong>Primitive data types</strong></p>
<ul>
<li><strong>Number</strong>: Represents both integers and floating-point numbers.</li>
<li><strong>String</strong>: Represents sequences of characters.</li>
<li><strong>Boolean</strong>: Represents <code>true</code> or <code>false</code> values.</li>
<li><strong>Undefined</strong>: A variable that has been declared but not assigned a value.</li>
<li><strong>Null</strong>: Represents the intentional absence of any object value.</li>
<li><strong>Symbol</strong>: A unique and immutable value used as object property keys. Read more in our <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-symbols-used-for">deep dive on <code>Symbol</code>s</a></li>
<li><strong>BigInt</strong>: Represents integers with arbitrary precision.</li>
</ul>
<p><strong>Non-primitive (Reference) data types</strong></p>
<ul>
<li><strong>Object</strong>: Used to store collections of data.</li>
<li><strong>Array</strong>: An ordered collection of data.</li>
<li><strong>Function</strong>: A callable object.</li>
<li><strong>Date</strong>: Represents dates and times.</li>
<li><strong>RegExp</strong>: Represents regular expressions.</li>
<li><strong>Map</strong>: A collection of keyed data items.</li>
<li><strong>Set</strong>: A collection of unique values.</li>
</ul>
<p>The primitive types store a single value, while non-primitive types can store collections of data or complex entities.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-various-data-types-in-javascript">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-data-types-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript">What language constructs do you use for iterating over object properties and array items in JavaScript?</h3>

<p>There are multiple ways to iterate over object properties as well as arrays in JavaScript:</p>
<p><strong><code>for...in</code> loop</strong></p>
<p>The <code>for...in</code> loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
  <span class="hljs-comment">// To avoid iterating over inherited properties</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.hasOwn(obj, key)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${obj[key]}</span>`</span>);
  }
}
</code></pre>
<p><strong><code>Object.keys()</code></strong></p>
<p><code>Object.keys()</code> returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};

<span class="hljs-built_in">Object</span>.keys(obj).forEach(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${obj[key]}</span>`</span>);
});
</code></pre>
<p>Most common ways to iterate over array are using <code>for</code> loop and <code>Array.prototype.forEach</code> method.</p>
<p><strong>Using <code>for</code> loop</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = <span class="hljs-number">0</span>; index &lt; array.length; index++) {
  <span class="hljs-built_in">console</span>.log(array[index]);
}
</code></pre>
<p><strong>Using <code>Array.prototype.forEach</code> method</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
array.forEach(<span class="hljs-function">(<span class="hljs-params">number, index</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${number}</span> at index <span class="hljs-subst">${index}</span>`</span>);
});
</code></pre>
<p><strong>Using <code>for...of</code></strong></p>
<p>This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> number <span class="hljs-keyword">of</span> numbers) {
  <span class="hljs-built_in">console</span>.log(number);
}
</code></pre>
<p>There are also other inbuilt methods available which are suitable for specific scenarios for example:</p>
<ul>
<li><code>Array.prototype.filter</code>: You can use the <code>filter</code> method to create a new array containing only the elements that satisfy a certain condition.</li>
<li><code>Array.prototype.map</code>: You can use the <code>map</code> method to create a new array based on the existing one, transforming each element with a provided function.</li>
<li><code>Array.prototype.reduce</code>: You can use the <code>reduce</code> method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax">What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?</h3>

<p><strong>Spread syntax</strong> (<code>...</code>) allows an iterable (like an array or string) to be expanded into individual elements. This is often used as a convenient and modern way to create new arrays or objects by combining existing ones.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Traditional</td><td>Spread</td></tr>
</thead>
<tbody>
<tr>
<td>Array cloning</td><td><code>arr.slice()</code></td><td><code>[...arr]</code></td></tr>
<tr>
<td>Array merging</td><td><code>arr1.concat(arr2)</code></td><td><code>[...arr1, ...arr2]</code></td></tr>
<tr>
<td>Object cloning</td><td><code>Object.assign({}, obj)</code></td><td><code>{ ...obj }</code></td></tr>
<tr>
<td>Object merging</td><td><code>Object.assign({}, obj1, obj2)</code></td><td><code>{ ...obj1, ...obj2 }</code></td></tr>
</tbody>
</table>
</div><p><strong>Rest syntax</strong> is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using rest syntax in a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...numbers</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.reduce(<span class="hljs-function">(<span class="hljs-params">total, num</span>) =&gt;</span> total + num, <span class="hljs-number">0</span>);
}

<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 6</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for">What are iterators and generators in JavaScript and what are they used for?</h3>

<p>In JavaScript, iterators and generators are powerful tools for managing sequences of data and controlling the flow of execution in a more flexible way.</p>
<p><strong>Iterators</strong> are objects that define a sequence and potentially a return value upon its termination. It adheres to a specific interface:</p>
<ul>
<li>An iterator object must implement a <code>next()</code> method.</li>
<li>The <code>next()</code> method returns an object with two properties:<ul>
<li><code>value</code>: The next value in the sequence.</li>
<li><code>done</code>: A boolean that is <code>true</code> if the iterator has finished its sequence, otherwise <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Here's an example of an object implementing the iterator interface.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> iterator = {
  <span class="hljs-attr">current</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">last</span>: <span class="hljs-number">5</span>,
  next() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.current &lt;= <span class="hljs-built_in">this</span>.last) {
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">value</span>: <span class="hljs-built_in">this</span>.current++, done: <span class="hljs-literal">false</span> };
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">value</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">done</span>: <span class="hljs-literal">true</span> };
    }
  },
};

<span class="hljs-keyword">let</span> result = iterator.next();
<span class="hljs-keyword">while</span> (!result.done) {
  <span class="hljs-built_in">console</span>.log(result.value); <span class="hljs-comment">// Logs 0, 1, 2, 3, 4, 5</span>
  result = iterator.next();
}
</code></pre>
<p><strong>Generators</strong> are a special functions that <strong>can pause execution and resume at a later point</strong>. It uses the <code>function*</code> syntax and the <code>yield</code> keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the <code>next()</code> method on the returned iterator advances the generator to the next <code>yield</code> statement, and the value after <code>yield</code> becomes the return value of <code>next()</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">numberGenerator</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> num = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">while</span> (num &lt;= <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">yield</span> num++;
  }
}

<span class="hljs-keyword">const</span> gen = numberGenerator();
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 0, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 1, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 2, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 3, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 4, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 5, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: undefined, done: true }</span>
</code></pre>
<p>Generators are powerful for creating iterators on-demand, especially for infinite sequences or complex iteration logic. They can be used for:</p>
<ul>
<li>Lazy evaluation – processing elements only when needed, improving memory efficiency for large datasets.</li>
<li>Implementing iterators for custom data structures.</li>
<li>Creating asynchronous iterators for handling data streams.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-iterators-and-generators-and-what-are-they-used-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-mutable-and-immutable-objects-in-javascript">Explain the difference between mutable and immutable objects in JavaScript</h3>

<p><strong>Mutable objects</strong> allow for modification of properties and values after creation, which is the default behavior for most objects.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mutableObject = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
};

<span class="hljs-comment">// Modify the object</span>
mutableObject.name = <span class="hljs-string">'Jane'</span>;

<span class="hljs-comment">// The object has been modified</span>
<span class="hljs-built_in">console</span>.log(mutableObject); <span class="hljs-comment">// Output: { name: 'Jane', age: 30 }</span>
</code></pre>
<p><strong>Immutable objects</strong> cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> immutableObject = <span class="hljs-built_in">Object</span>.freeze({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
});

<span class="hljs-comment">// Attempt to modify the object</span>
immutableObject.name = <span class="hljs-string">'Jane'</span>;

<span class="hljs-comment">// The object remains unchanged</span>
<span class="hljs-built_in">console</span>.log(immutableObject); <span class="hljs-comment">// Output: { name: 'John', age: 30 }</span>
</code></pre>
<p>The key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/explain-the-difference-between-mutable-and-immutable-objects">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript">What is the difference between a <code>Map</code> object and a plain object in JavaScript?</h3>

<p>Both <code>Map</code> objects and plain objects in JavaScript can store key-value pairs, but they have several key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><code>Map</code></td><td>Plain object</td></tr>
</thead>
<tbody>
<tr>
<td>Key type</td><td>Any data type</td><td>String (or Symbol)</td></tr>
<tr>
<td>Key order</td><td>Maintained</td><td>Not guaranteed</td></tr>
<tr>
<td>Size property</td><td>Yes (<code>size</code>)</td><td>None</td></tr>
<tr>
<td>Iteration</td><td><code>forEach</code>, <code>keys()</code>, <code>values()</code>, <code>entries()</code></td><td><code>for...in</code>, <code>Object.keys()</code>, etc.</td></tr>
<tr>
<td>Inheritance</td><td>No</td><td>Yes</td></tr>
<tr>
<td>Performance</td><td>Generally better for larger datasets and frequent additions/deletions</td><td>Faster for small datasets and simple operations</td></tr>
<tr>
<td>Serializable</td><td>No</td><td>Yes</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript">What are the differences between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript?</h3>

<p>The primary difference between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript lies in how they handle keys. Here's a breakdown:</p>
<p><strong><code>Map</code> vs. <code>WeakMap</code></strong></p>
<p><code>Map</code>s allows any data type (strings, numbers, objects) as keys. The key-value pairs remain in memory as long as the <code>Map</code> object itself is referenced. Thus they are suitable for general-purpose key-value storage where you want to maintain references to both keys and values. Common use cases include storing user data, configuration settings, or relationships between objects.</p>
<p><code>WeakMap</code>s only allows objects as keys. However, these object keys are held weakly. This means the garbage collector can remove them from memory even if the <code>WeakMap</code> itself still exists, as long as there are no other references to those objects. <code>WeakMap</code>s are ideal for scenarios where you want to associate data with objects without preventing those objects from being garbage collected. This can be useful for things like:</p>
<ul>
<li>Caching data based on objects without preventing garbage collection of the objects themselves.</li>
<li>Storing private data associated with DOM nodes without affecting their lifecycle.</li>
</ul>
<p><strong><code>Set</code> vs. <code>WeakSet</code></strong></p>
<p>Similar to <code>Map</code>, <code>Set</code>s allow any data type as keys. The elements within a <code>Set</code> must be unique. <code>Set</code>s are useful for storing unique values and checking for membership efficiently. Common use cases include removing duplicates from arrays or keeping track of completed tasks.</p>
<p>On the other hand, <code>WeakSet</code> only allows objects as elements, and these object elements are held weakly, similar to <code>WeakMap</code> keys. <code>WeakSet</code>s are less commonly used, but applicable when you want a collection of unique objects without affecting their garbage collection. This might be necessary for:</p>
<ul>
<li>Tracking DOM nodes that have been interacted with without affecting their memory management.</li>
<li>Implementing custom object weak references for specific use cases.</li>
</ul>
<p><strong>Here's a table summarizing the key differences:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Map</td><td>WeakMap</td><td>Set</td><td>WeakSet</td></tr>
</thead>
<tbody>
<tr>
<td>Key Types</td><td>Any data type</td><td>Objects (weak references)</td><td>Any data type (unique)</td><td>Objects (weak references, unique)</td></tr>
<tr>
<td>Garbage Collection</td><td>Keys and values are not garbage collected</td><td>Keys can be garbage collected if not referenced elsewhere</td><td>Elements are not garbage collected</td><td>Elements can be garbage collected if not referenced elsewhere</td></tr>
<tr>
<td>Use Cases</td><td>General-purpose key-value storage</td><td>Caching, private DOM node data</td><td>Removing duplicates, membership checks</td><td>Object weak references, custom use cases</td></tr>
</tbody>
</table>
</div><p><strong>Choosing between them</strong></p>
<ul>
<li>Use <code>Map</code> and <code>Set</code> for most scenarios where you need to store key-value pairs or unique elements and want to maintain references to both the keys/elements and the values.</li>
<li>Use <code>WeakMap</code> and <code>WeakSet</code> cautiously in specific situations where you want to associate data with objects without affecting their garbage collection. Be aware of the implications of weak references and potential memory leaks if not used correctly.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-the-differences-between-map-set-and-weakmap-weakset">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-might-you-want-to-create-static-class-members-in-javascript">Why might you want to create static class members in JavaScript?</h3>

<p>Static class members (properties/methods) has a <code>static</code> keyword prepended. Such members cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
  <span class="hljs-keyword">static</span> noOfWheels = <span class="hljs-number">4</span>;
  <span class="hljs-keyword">static</span> compare() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Static method has been called.'</span>;
  }
}

<span class="hljs-built_in">console</span>.log(Car.noOfWheels); <span class="hljs-comment">// 4</span>
</code></pre>
<p>Static members are useful under the following scenarios:</p>
<ul>
<li><strong>Namespace organization</strong>: Static properties can be used to define constants or configuration values that are specific to a class. This helps organize related data within the class namespace and prevents naming conflicts with other variables. Examples include <code>Math.PI</code>, <code>Math.SQRT2</code>.</li>
<li><strong>Helper functions</strong>: Static methods can be used as helper functions that operate on the class itself or its instances. This can improve code readability and maintainability by separating utility logic from the core functionality of the class. Examples of frequently used static methods include <code>Object.assign()</code>, <code>Math.max()</code>.</li>
<li><strong>Singleton pattern</strong>: In some rare cases, static properties and methods can be used to implement a singleton pattern, where only one instance of a class ever exists. However, this pattern can be tricky to manage and is generally discouraged in favor of more modern dependency injection techniques.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/why-you-might-want-to-create-static-class-members">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-you-might-want-to-create-static-class-members/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-symbols-used-for-in-javascript">What are <code>Symbol</code>s used for in JavaScript?</h3>

<p><code>Symbol</code>s in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using <code>Symbol(...)</code> function, and each <code>Symbol</code> value is guaranteed to be unique, even if they have the same key/description. <code>Symbol</code> properties are not enumerable in <code>for...in</code> loops or <code>Object.keys()</code>, making them suitable for creating private/internal object state.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sym1 = <span class="hljs-built_in">Symbol</span>();
<span class="hljs-keyword">let</span> sym2 = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'myKey'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> sym1); <span class="hljs-comment">// "symbol"</span>
<span class="hljs-built_in">console</span>.log(sym1 === sym2); <span class="hljs-comment">// false, because each symbol is unique</span>

<span class="hljs-keyword">let</span> obj = {};
<span class="hljs-keyword">let</span> sym = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'uniqueKey'</span>);

obj[sym] = <span class="hljs-string">'value'</span>;
<span class="hljs-built_in">console</span>.log(obj[sym]); <span class="hljs-comment">// "value"</span>
</code></pre>
<p><strong>Note</strong>: The <code>Symbol()</code> function must be called without the <code>new</code> keyword. It is not exactly a constructor because it can only be called as a function instead of with <code>new Symbol()</code>.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-symbols-used-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-symbols-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-server-sent-events">What are server-sent events?</h3>

<p><a target="_blank" href="https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface">Server-sent events (SSE)</a> is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with <code>EventSource</code> instances that opens a connection with a server and allows client to receive events from the server. Connections created by server-sent events are persistent (similar to the <code>WebSocket</code>s), however there are a few differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td><code>WebSocket</code></td><td><code>EventSource</code></td></tr>
</thead>
<tbody>
<tr>
<td>Direction</td><td>Bi-directional – both client and server can exchange messages</td><td>Unidirectional – only server sends data</td></tr>
<tr>
<td>Data type</td><td>Binary and text data</td><td>Only text</td></tr>
<tr>
<td>Protocol</td><td>WebSocket protocol (<code>ws://</code>)</td><td>Regular HTTP (<code>http://</code>)</td></tr>
</tbody>
</table>
</div><p><strong>Creating an event source</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> eventSource = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'/sse-stream'</span>);
</code></pre>
<p><strong>Listening for events</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Fired when the connection is established.</span>
eventSource.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connection opened'</span>);
});

<span class="hljs-comment">// Fired when a message is received from the server.</span>
eventSource.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received message:'</span>, event.data);
});

<span class="hljs-comment">// Fired when an error occurs.</span>
eventSource.addEventListener(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error occurred:'</span>, error);
});
</code></pre>
<p><strong>Sending events from server</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/sse-stream'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// `Content-Type` need to be set to `text/event-stream`.</span>
  res.setHeader(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/event-stream'</span>);
  res.setHeader(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'no-cache'</span>);
  res.setHeader(<span class="hljs-string">'Connection'</span>, <span class="hljs-string">'keep-alive'</span>);

  <span class="hljs-comment">// Each message should be prefixed with data.</span>
  <span class="hljs-keyword">const</span> sendEvent = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> res.write(<span class="hljs-string">`data: <span class="hljs-subst">${data}</span>\n\n`</span>);

  sendEvent(<span class="hljs-string">'Hello from server'</span>);

  <span class="hljs-keyword">const</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> sendEvent(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toString()), <span class="hljs-number">1000</span>);

  res.on(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Client closed connection'</span>);
    <span class="hljs-built_in">clearInterval</span>(intervalId);
  });
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server started on port 3000'</span>));
</code></pre>
<p>In this example, the server sends a "Hello from server" message initially, and then sends the current date every second. The connection is kept alive until the client closes it</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-server-sent-events">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-server-sent-events/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-object-property-flags-and-descriptors">What are JavaScript object property flags and descriptors?</h3>

<p>In JavaScript, property flags and descriptors manage the behavior and attributes of object properties.</p>
<p><strong>Property flags</strong></p>
<p>Property flags are used to specify the behavior of a property on an object. Here are the available flags:</p>
<ul>
<li><code>writable</code>: Specifies whether the property can be written to. Defaults to <code>true</code>.</li>
<li><code>enumerable</code>: Specifies whether the property is enumerable. Defaults to <code>true</code>.</li>
<li><code>configurable</code>: Specifies whether the property can be deleted or its attributes changed. Default is <code>true</code>.</li>
</ul>
<p><strong>Property descriptors</strong></p>
<p>These provide detailed information about an object's property, including its value and flags. They are retrieved using <code>Object.getOwnPropertyDescriptor()</code> and set using <code>Object.defineProperty()</code>.</p>
<p>The use cases of property descriptors are as follows:</p>
<ul>
<li>Making a property non-writable by setting <code>writable: false</code> to ensure data consistency.</li>
<li>Hiding a property from enumeration by setting <code>enumerable: false</code>.</li>
<li>Preventing property deletion and modification by setting <code>configurable: false</code>.</li>
<li>Freezing or sealing objects to prevent modifications globally.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-javascript-object-property-flags-and-descriptors">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-object-getters-and-setters-for">What are JavaScript object getters and setters for?</h3>

<p>JavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.</p>
<p>Getters and setters are defined using the <code>get</code> and <code>set</code> keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.</p>
<p>Here's a code example demonstrating the use of getters and setters:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">_name</span>: <span class="hljs-string">'John Doe'</span>, <span class="hljs-comment">// Private property</span>

  <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
    <span class="hljs-comment">// Getter</span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._name;
  },
  <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">newName</span>) {
    <span class="hljs-comment">// Setter</span>
    <span class="hljs-keyword">if</span> (newName.trim().length &gt; <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">this</span>._name = newName;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Invalid name'</span>);
    }
  },
};

<span class="hljs-comment">// Accessing the name property using the getter</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'John Doe'</span>

<span class="hljs-comment">// Setting the name property using the setter</span>
person.name = <span class="hljs-string">'Jane Smith'</span>; <span class="hljs-comment">// Setter is called</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'Jane Smith'</span>

person.name = <span class="hljs-string">''</span>; <span class="hljs-comment">// Setter is called, but the value is not set due to validation</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'Jane Smith'</span>
</code></pre>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-javascript-object-getters-and-setters-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-proxies-in-javascript-used-for">What are proxies in JavaScript used for?</h3>

<p>In JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.</p>
<p>Here's a basic example of using a <code>Proxy</code> to log every property access:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myObject = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">42</span>,
};

<span class="hljs-keyword">const</span> handler = {
  <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">target, prop, receiver</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Someone accessed property "<span class="hljs-subst">${prop}</span>"`</span>);
    <span class="hljs-keyword">return</span> target[prop];
  },
};

<span class="hljs-keyword">const</span> proxiedObject = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(myObject, handler);

<span class="hljs-built_in">console</span>.log(proxiedObject.name); <span class="hljs-comment">// 'John'</span>
<span class="hljs-comment">// Someone accessed property "name"</span>

<span class="hljs-built_in">console</span>.log(proxiedObject.value); <span class="hljs-comment">// 42</span>
<span class="hljs-comment">// Someone accessed property "value"</span>
</code></pre>
<p>Use cases include:</p>
<ul>
<li><strong>Property access interception</strong>: Intercept and customize property access on an object.<ul>
<li><strong>Property assignment validation</strong>: Validate property values before they are set on the target object.</li>
<li><strong>Logging and debugging</strong>: Create wrappers for logging and debugging interactions with an object</li>
<li><strong>Creating reactive systems</strong>: Trigger updates in other parts of your application when object properties change (data binding).</li>
<li><strong>Data transformation</strong>: Transforming data being set or retrieved from an object.</li>
<li><strong>Mocking and stubbing in tests</strong>: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test</li>
</ul>
</li>
<li><strong>Function invocation interception</strong>: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance</li>
<li><strong>Dynamic property creation</strong>: Useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-proxies-in-javascript-used-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-proxies-in-javascript-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-tools-and-techniques-do-you-use-for-debugging-javascript-code">What tools and techniques do you use for debugging JavaScript code?</h3>

<p>Some of the most commonly used tools and techniques for debugging JavaScript:</p>
<ul>
<li>JavaScript language<ul>
<li><code>console</code> methods (e.g. <code>console.log()</code>, <code>console.error()</code>, <code>console.warn()</code>, <code>console.table()</code>)</li>
<li><code>debugger</code> statement</li>
</ul>
</li>
<li>Breakpoints (browser or IDE)</li>
<li>JavaScript frameworks<ul>
<li><a target="_blank" href="https://github.com/facebook/react-devtools">React Devtools</a></li>
<li><a target="_blank" href="https://github.com/gaearon/redux-devtools">Redux Devtools</a></li>
<li><a target="_blank" href="https://github.com/vuejs/vue-devtools">Vue Devtools</a></li>
</ul>
</li>
<li>Browser developer tools<ul>
<li><strong>Chrome DevTools</strong>: The most widely used tool for debugging JavaScript. It provides a rich set of features including the ability to set breakpoints, inspect variables, view the call stack, and more.</li>
<li><strong>Firefox Developer Tools</strong>: Similar to Chrome DevTools with its own set of features for debugging.</li>
<li><strong>Safari Web Inspector</strong>: Provides tools for debugging on Safari.</li>
<li><strong>Edge Developer Tools</strong>: Similar to Chrome DevTools, as Edge is now Chromium-based.</li>
</ul>
</li>
<li>Network requests<ul>
<li><strong>Postman</strong>: Useful for debugging API calls.</li>
<li><strong>Fiddler</strong>: Helps capture and inspect HTTP/HTTPS traffic.</li>
<li><strong>Charles Proxy</strong>: Another tool for intercepting and debugging network calls.</li>
</ul>
</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-tools-and-techniques-do-you-use-for-debugging-javascript-code">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-workers-in-javascript-used-for">What are workers in JavaScript used for?</h3>

<p>Workers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface. Their key features include:</p>
<ul>
<li><strong>Parallel processing</strong>: Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks. It's useful for moving CPU-intensive work off the main thread and be free from JavaScript's single-threaded nature.</li>
<li><strong>Communication</strong>: Uses <code>postMessage()</code> and <code>onmessage</code>/ <code>'message'</code> event for messaging.</li>
<li><strong>Access to web APIs</strong>: Workers have access to various Web APIs, including <code>fetch()</code>, IndexedDB, and Web Storage, allowing them to perform tasks like data fetching and persisting data independently.</li>
<li><strong>No DOM access</strong>: Workers cannot directly manipulate the DOM, thus cannot interact with the UI, ensuring they don't accidentally interfere with the main thread's operation.</li>
</ul>
<p>There are three main types of workers in JavaScript:</p>
<ul>
<li><strong>Web workers / Dedicated workers</strong><ul>
<li>Run scripts in background threads, separate from the main UI thread.</li>
<li>Useful for CPU-intensive tasks like data processing, calculations, etc.</li>
<li>Cannot directly access or manipulate the DOM.</li>
</ul>
</li>
<li><strong>Service workers</strong><ul>
<li>Act as network proxies, handling requests between the app and network.</li>
<li>Enable offline functionality, caching, and push notifications.</li>
<li>Runs independently of the web page, even when it's closed.</li>
</ul>
</li>
<li><strong>Shared workers</strong><ul>
<li>Can be shared by multiple scripts running in different windows or frames, as long as they're in the same domain.</li>
<li>Scripts communicate with the shared worker by sending and receiving messages.</li>
<li>Useful for coordinating tasks across different parts of a web page.</li>
</ul>
</li>
</ul>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-workers-in-javascript-used-for">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-workers-in-javascript-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-does-javascript-garbage-collection-work">How does JavaScript garbage collection work?</h3>

<p>Garbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.</p>
<p><strong>Mark-and-sweep</strong></p>
<p>The most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:</p>
<ul>
<li><strong>Marking phase</strong>: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as "in-use".</li>
<li><strong>Sweeping phase</strong>: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.</li>
</ul>
<p>This algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.</p>
<p><strong>Generational garbage collection</strong></p>
<p>Leveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.</p>
<p>Different JavaScript engines (differs according to browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.</p>

<p><br /></p>
<blockquote>
<p>Read the <a target="_blank" href="https://greatfrontend.com/questions/quiz/how-does-javascript-garbage-collection-work">detailed answer</a> on <a target="_blank" href="https://greatfrontend.com/">GreatFrontEnd</a> which allows progress tracking, contains more code samples, and useful resources.</p>
</blockquote>
<p><a class="post-section-overview" href="#table-of-contents-top-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-javascript-garbage-collection-work/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>

<h2 id="heading-all-questions-with-answers">All Questions with Answers</h2>

<h3 id="heading-what-are-the-various-data-types-in-javascript-1">What are the various data types in JavaScript?</h3>

<p>In JavaScript, data types can be categorized into <code>primitive</code> and <code>non-primitive</code> types:</p>
<p><strong>Primitive data types</strong></p>
<ul>
<li><strong>Number</strong>: Represents both integers and floating-point numbers.</li>
<li><strong>String</strong>: Represents sequences of characters.</li>
<li><strong>Boolean</strong>: Represents <code>true</code> or <code>false</code> values.</li>
<li><strong>Undefined</strong>: A variable that has been declared but not assigned a value.</li>
<li><strong>Null</strong>: Represents the intentional absence of any object value.</li>
<li><strong>Symbol</strong>: A unique and immutable value used as object property keys. Read more in our <a target="_blank" href="https://greatfrontend.com/questions/quiz/what-are-symbols-used-for">deep dive on <code>Symbol</code>s</a></li>
<li><strong>BigInt</strong>: Represents integers with arbitrary precision.</li>
</ul>
<p><strong>Non-primitive (Reference) data types</strong></p>
<ul>
<li><strong>Object</strong>: Used to store collections of data.</li>
<li><strong>Array</strong>: An ordered collection of data.</li>
<li><strong>Function</strong>: A callable object.</li>
<li><strong>Date</strong>: Represents dates and times.</li>
<li><strong>RegExp</strong>: Represents regular expressions.</li>
<li><strong>Map</strong>: A collection of keyed data items.</li>
<li><strong>Set</strong>: A collection of unique values.</li>
</ul>
<p>The primitive types store a single value, while non-primitive types can store collections of data or complex entities.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-data-types-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-check-the-data-type-of-a-variable">How do you check the data type of a variable?</h3>

<p>To check the data type of a variable in JavaScript, you can use the <code>typeof</code> operator. For example, <code>typeof variableName</code> will return a string indicating the type of the variable, such as <code>"string"</code>, <code>"number"</code>, <code>"boolean"</code>, <code>"object"</code>, <code>"function"</code>, <code>"undefined"</code>, or <code>"symbol"</code>. For arrays and <code>null</code>, you can use <code>Array.isArray(variableName)</code> and <code>variableName === null</code>, respectively.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared-1">What's the difference between a JavaScript variable that is: <code>null</code>, <code>undefined</code> or undeclared?</h3>

<div class="hn-table">
<table>
<thead>
<tr>
<td>Trait</td><td><code>null</code></td><td><code>undefined</code></td><td>Undeclared</td></tr>
</thead>
<tbody>
<tr>
<td>Meaning</td><td>Explicitly set by the developer to indicate that a variable has no value</td><td>Variable has been declared but not assigned a value</td><td>Variable has not been declared at all</td></tr>
<tr>
<td>Type</td><td><code>object</code></td><td><code>undefined</code></td><td>Throws a <code>ReferenceError</code></td></tr>
<tr>
<td>Equality Comparison</td><td><code>null == undefined</code> is <code>true</code></td><td><code>undefined == null</code> is <code>true</code></td><td>Throws a <code>ReferenceError</code></td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-javascript-variables-created-using-let-var-or-const-1">What are the differences between JavaScript variables created using <code>let</code>, <code>var</code> or <code>const</code>?</h3>

<p>In JavaScript, <code>let</code>, <code>var</code>, and <code>const</code> are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Behavior</td><td><code>var</code></td><td><code>let</code></td><td><code>const</code></td></tr>
</thead>
<tbody>
<tr>
<td>Scope</td><td>Function or Global</td><td>Block</td><td>Block</td></tr>
<tr>
<td>Initialization</td><td>Optional</td><td>Optional</td><td>Required</td></tr>
<tr>
<td>Redeclaration</td><td>Yes</td><td>No</td><td>No</td></tr>
<tr>
<td>Reassignment</td><td>Yes</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Accessing before declaration</td><td><code>undefined</code></td><td><code>ReferenceError</code></td><td><code>ReferenceError</code></td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it-1">Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?</h3>

<p>JavaScript that is executed in the browser has access to the global scope (the <code>window</code> object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. Several reasons to avoid touching the global scope:</p>
<ul>
<li><strong>Naming conflicts</strong>: Sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced.</li>
<li><strong>Cluttered global namespace</strong>: Keeping the global namespace minimal avoids making the codebase hard to manage and maintain.</li>
<li><strong>Scope leaks</strong>: Unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues.</li>
<li><strong>Modularity and encapsulation</strong>: Good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability.</li>
<li><strong>Security concerns</strong>: Global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there.</li>
<li><strong>Compatibility and portability</strong>: Heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks.</li>
</ul>
<p>Follow these best practices to avoid global scope pollution:</p>
<ul>
<li><strong>Use local variables</strong>: Declare variables within functions or blocks using <code>var</code>, <code>let</code>, or <code>const</code> to limit their scope.</li>
<li><strong>Pass variables as function parameters</strong>: Maintain encapsulation by passing variables as parameters instead of accessing them globally.</li>
<li><strong>Use immediately invoked function expressions (IIFE)</strong>: Create new scopes with IIFEs to prevent adding variables to the global scope.</li>
<li><strong>Use modules</strong>: Encapsulate code with module systems to maintain separate scopes and manageability.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-convert-a-string-to-a-number-in-javascript">How do you convert a string to a number in JavaScript?</h3>

<p>In JavaScript, you can convert a string to a number using several methods. The most common ones are <code>Number()</code>, <code>parseInt()</code>, <code>parseFloat()</code>, and the unary plus operator (<code>+</code>). For example, <code>Number("123")</code> converts the string <code>"123"</code> to the number <code>123</code>, and <code>parseInt("123.45")</code> converts the string <code>"123.45"</code> to the integer <code>123</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-template-literals-and-how-are-they-used">What are template literals and how are they used?</h3>

<p>Template literals are a feature in JavaScript that allow for easier string interpolation and multi-line strings. They are enclosed by backticks (<code>` </code>) instead of single or double quotes. You can embed expressions within template literals using <code>${expression}</code> syntax.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'John'</span>;
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Output: Hello, John!</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-tagged-templates">Explain the concept of tagged templates</h3>

<p>Tagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tag</span>(<span class="hljs-params">strings, ...values</span>) </span>{
  <span class="hljs-keyword">return</span> strings[<span class="hljs-number">0</span>] + values[<span class="hljs-number">0</span>] + strings[<span class="hljs-number">1</span>] + values[<span class="hljs-number">1</span>];
}

<span class="hljs-keyword">const</span> result = tag<span class="hljs-string">`Hello <span class="hljs-subst">${<span class="hljs-string">'world'</span>}</span>! How are <span class="hljs-subst">${<span class="hljs-string">'you'</span>}</span>?`</span>;
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// "Hello world! How are you?"</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-tagged-templates/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-spread-operator-and-how-is-it-used">What is the spread operator and how is it used?</h3>

<p>The spread operator, represented by three dots (<code>...</code>), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> arr2 = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">const</span> combined = [...arr1, ...arr2]; <span class="hljs-comment">// [1, 2, 3, 4, 5, 6]</span>

<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span> };
<span class="hljs-keyword">const</span> combinedObj = { ...obj1, ...obj2 }; <span class="hljs-comment">// { a: 1, b: 2, c: 3, d: 4 }</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-symbols-used-for-in-javascript-1">What are <code>Symbol</code>s used for in JavaScript?</h3>

<p><code>Symbol</code>s in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using <code>Symbol(...)</code> function, and each <code>Symbol</code> value is guaranteed to be unique, even if they have the same key/description. <code>Symbol</code> properties are not enumerable in <code>for...in</code> loops or <code>Object.keys()</code>, making them suitable for creating private/internal object state.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> sym1 = <span class="hljs-built_in">Symbol</span>();
<span class="hljs-keyword">let</span> sym2 = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'myKey'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> sym1); <span class="hljs-comment">// "symbol"</span>
<span class="hljs-built_in">console</span>.log(sym1 === sym2); <span class="hljs-comment">// false, because each symbol is unique</span>

<span class="hljs-keyword">let</span> obj = {};
<span class="hljs-keyword">let</span> sym = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">'uniqueKey'</span>);

obj[sym] = <span class="hljs-string">'value'</span>;
<span class="hljs-built_in">console</span>.log(obj[sym]); <span class="hljs-comment">// "value"</span>
</code></pre>
<p><strong>Note</strong>: The <code>Symbol()</code> function must be called without the <code>new</code> keyword. It is not exactly a constructor because it can only be called as a function instead of with <code>new Symbol()</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-symbols-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-proxies-in-javascript-used-for-1">What are proxies in JavaScript used for?</h3>

<p>In JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.</p>
<p>Here's a basic example of using a <code>Proxy</code> to log every property access:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myObject = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">42</span>,
};

<span class="hljs-keyword">const</span> handler = {
  <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">target, prop, receiver</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Someone accessed property "<span class="hljs-subst">${prop}</span>"`</span>);
    <span class="hljs-keyword">return</span> target[prop];
  },
};

<span class="hljs-keyword">const</span> proxiedObject = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(myObject, handler);

<span class="hljs-built_in">console</span>.log(proxiedObject.name); <span class="hljs-comment">// 'John'</span>
<span class="hljs-comment">// Someone accessed property "name"</span>

<span class="hljs-built_in">console</span>.log(proxiedObject.value); <span class="hljs-comment">// 42</span>
<span class="hljs-comment">// Someone accessed property "value"</span>
</code></pre>
<p>Use cases include:</p>
<ul>
<li><strong>Property access interception</strong>: Intercept and customize property access on an object.<ul>
<li><strong>Property assignment validation</strong>: Validate property values before they are set on the target object.</li>
<li><strong>Logging and debugging</strong>: Create wrappers for logging and debugging interactions with an object</li>
<li><strong>Creating reactive systems</strong>: Trigger updates in other parts of your application when object properties change (data binding).</li>
<li><strong>Data transformation</strong>: Transforming data being set or retrieved from an object.</li>
<li><strong>Mocking and stubbing in tests</strong>: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test</li>
</ul>
</li>
<li><strong>Function invocation interception</strong>: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance</li>
<li><strong>Dynamic property creation</strong>: Useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-proxies-in-javascript-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-hoisting-in-javascript-1">Explain the concept of "hoisting" in JavaScript</h3>

<ul>
<li><strong>Variable declarations (<code>var</code>)</strong>: Declarations are hoisted, but not initializations. The value of the variable is <code>undefined</code> if accessed before initialization.</li>
<li><strong>Variable declarations (<code>let</code> and <code>const</code>)</strong>: Declarations are hoisted, but not initialized. Accessing them results in <code>ReferenceError</code> until the actual declaration is encountered.</li>
<li><strong>Function expressions (<code>var</code>)</strong>: Declarations are hoisted, but not initializations. The value of the variable is <code>undefined</code> if accessed before initialization.</li>
<li><strong>Function declarations (<code>function</code>)</strong>: Both declaration and definition are fully hoisted.</li>
<li><strong>Class declarations (<code>class</code>)</strong>: Declarations are hoisted, but not initialized. Accessing them results in <code>ReferenceError</code> until the actual declaration is encountered.</li>
<li><strong>Import declarations (<code>import</code>)</strong>: Declarations are hoisted, and side effects of importing the module are executed before the rest of the code.</li>
</ul>
<p>The following behavior summarizes the result of accessing the variables before they are declared.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Declaration</td><td>Accessing before declaration</td></tr>
</thead>
<tbody>
<tr>
<td><code>var foo</code></td><td><code>undefined</code></td></tr>
<tr>
<td><code>let foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>const foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>class Foo</code></td><td><code>ReferenceError</code></td></tr>
<tr>
<td><code>var foo = function() { ... }</code></td><td><code>undefined</code></td></tr>
<tr>
<td><code>function foo() { ... }</code></td><td>Normal</td></tr>
<tr>
<td><code>import</code></td><td>Normal</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-hoisting/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-in-hoisting-between-var-let-and-const">Explain the difference in hoisting between <code>var</code>, <code>let</code>, and <code>const</code></h3>

<p><code>var</code> declarations are hoisted to the top of their scope and initialized with <code>undefined</code>, allowing them to be used before their declaration. <code>let</code> and <code>const</code> declarations are also hoisted but are not initialized, resulting in a <code>ReferenceError</code> if accessed before their declaration. <code>const</code> additionally requires an initial value at the time of declaration.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-does-hoisting-affect-function-declarations-and-expressions">How does hoisting affect function declarations and expressions?</h3>

<p>Hoisting in JavaScript means that function declarations are moved to the top of their containing scope during the compile phase, making them available throughout the entire scope. This allows you to call a function before it is defined in the code. However, function expressions are not hoisted in the same way. If you try to call a function expression before it is defined, you will get an error because the variable holding the function is hoisted but not its assignment.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Function declaration</span>
<span class="hljs-built_in">console</span>.log(foo()); <span class="hljs-comment">// Works fine</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello'</span>;
}

<span class="hljs-comment">// Function expression</span>
<span class="hljs-built_in">console</span>.log(bar()); <span class="hljs-comment">// Throws TypeError: bar is not a function</span>
<span class="hljs-keyword">var</span> bar = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello'</span>;
};
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-potential-issues-caused-by-hoisting">What are the potential issues caused by hoisting?</h3>

<p>Hoisting can lead to unexpected behavior in JavaScript because variable and function declarations are moved to the top of their containing scope during the compilation phase. This can result in <code>undefined</code> values for variables if they are used before their declaration and can cause confusion with function declarations and expressions. For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// undefined</span>
<span class="hljs-keyword">var</span> a = <span class="hljs-number">5</span>;

<span class="hljs-built_in">console</span>.log(b); <span class="hljs-comment">// ReferenceError: b is not defined</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">10</span>;
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-potential-issues-caused-by-hoisting/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-avoid-problems-related-to-hoisting">How can you avoid problems related to hoisting?</h3>

<p>To avoid problems related to hoisting, always declare variables at the top of their scope using <code>let</code> or <code>const</code> instead of <code>var</code>. This ensures that variables are block-scoped and not hoisted to the top of their containing function or global scope. Additionally, declare functions before they are called to avoid issues with function hoisting.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Use let or const</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">20</span>;

<span class="hljs-comment">// Declare functions before calling them</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, world!'</span>);
}
myFunction();
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-and-in-javascript-1">What is the difference between <code>==</code> and <code>===</code> in JavaScript?</h3>

<p><code>==</code> is the abstract equality operator while <code>===</code> is the strict equality operator. The <code>==</code> operator will compare for equality after doing any necessary type conversions. The <code>===</code> operator will not do type conversion, so if two values are not the same type <code>===</code> will simply return <code>false</code>.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operator</td><td><code>==</code></td><td><code>===</code></td></tr>
</thead>
<tbody>
<tr>
<td>Name</td><td>(Loose) Equality operator</td><td>Strict equality operator</td></tr>
<tr>
<td>Type coercion</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Compares value and type</td><td>No</td><td>Yes</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript-1">What language constructs do you use for iterating over object properties and array items in JavaScript?</h3>

<p>There are multiple ways to iterate over object properties as well as arrays in JavaScript:</p>
<p><strong><code>for...in</code> loop</strong></p>
<p>The <code>for...in</code> loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
  <span class="hljs-comment">// To avoid iterating over inherited properties</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Object</span>.hasOwn(obj, key)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${obj[key]}</span>`</span>);
  }
}
</code></pre>
<p><strong><code>Object.keys()</code></strong></p>
<p><code>Object.keys()</code> returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};

<span class="hljs-built_in">Object</span>.keys(obj).forEach(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${obj[key]}</span>`</span>);
});
</code></pre>
<p>Most common ways to iterate over array are using <code>for</code> loop and <code>Array.prototype.forEach</code> method.</p>
<p><strong>Using <code>for</code> loop</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> index = <span class="hljs-number">0</span>; index &lt; array.length; index++) {
  <span class="hljs-built_in">console</span>.log(array[index]);
}
</code></pre>
<p><strong>Using <code>Array.prototype.forEach</code> method</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
array.forEach(<span class="hljs-function">(<span class="hljs-params">number, index</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${number}</span> at index <span class="hljs-subst">${index}</span>`</span>);
});
</code></pre>
<p><strong>Using <code>for...of</code></strong></p>
<p>This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> number <span class="hljs-keyword">of</span> numbers) {
  <span class="hljs-built_in">console</span>.log(number);
}
</code></pre>
<p>There are also other inbuilt methods available which are suitable for specific scenarios for example:</p>
<ul>
<li><code>Array.prototype.filter</code>: You can use the <code>filter</code> method to create a new array containing only the elements that satisfy a certain condition.</li>
<li><code>Array.prototype.map</code>: You can use the <code>map</code> method to create a new array based on the existing one, transforming each element with a provided function.</li>
<li><code>Array.prototype.reduce</code>: You can use the <code>reduce</code> method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-purpose-of-the-break-and-continue-statements">What is the purpose of the <code>break</code> and <code>continue</code> statements?</h3>

<p>The <code>break</code> statement is used to exit a loop or switch statement prematurely, while the <code>continue</code> statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a <code>for</code> loop, <code>break</code> will stop the loop entirely, and <code>continue</code> will skip to the next iteration.</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">if</span> (i === <span class="hljs-number">5</span>) <span class="hljs-keyword">break</span>; <span class="hljs-comment">// exits the loop when i is 5</span>
  <span class="hljs-built_in">console</span>.log(i);
}

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">if</span> (i === <span class="hljs-number">5</span>) <span class="hljs-keyword">continue</span>; <span class="hljs-comment">// skips the iteration when i is 5</span>
  <span class="hljs-built_in">console</span>.log(i);
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-ternary-operator-and-how-is-it-used">What is the ternary operator and how is it used?</h3>

<p>The ternary operator is a shorthand for an <code>if-else</code> statement in JavaScript. It takes three operands: a condition, a result for true, and a result for false. The syntax is <code>condition ? expr1 : expr2</code>. For example, <code>let result = (a &gt; b) ? 'a is greater' : 'b is greater';</code> assigns <code>'a is greater'</code> to <code>result</code> if <code>a</code> is greater than <code>b</code>, otherwise it assigns <code>'b is greater'</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-access-the-index-of-an-element-in-an-array-during-iteration">How do you access the index of an element in an array during iteration?</h3>

<p>To access the index of an element in an array during iteration, you can use methods like <code>forEach</code>, <code>map</code>, <code>for...of</code> with <code>entries</code>, or a traditional <code>for</code> loop. For example, using <code>forEach</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> array = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];
array.forEach(<span class="hljs-function">(<span class="hljs-params">element, index</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(index, element);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-purpose-of-the-switch-statement">What is the purpose of the <code>switch</code> statement?</h3>

<p>The <code>switch</code> statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple <code>if...else if</code> statements. The <code>switch</code> statement evaluates an expression, matches the expression's value to a <code>case</code> label, and executes the associated block of code. If no <code>case</code> matches, the <code>default</code> block is executed.</p>
<pre><code class="lang-js"><span class="hljs-keyword">switch</span> (expression) {
  <span class="hljs-keyword">case</span> value1:
    <span class="hljs-comment">// code to be executed if expression === value1</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> value2:
    <span class="hljs-comment">// code to be executed if expression === value2</span>
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
  <span class="hljs-comment">// code to be executed if no case matches</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-rest-parameters-and-how-are-they-used">What are rest parameters and how are they used?</h3>

<p>Rest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (<code>...</code>) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...numbers</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> acc + curr, <span class="hljs-number">0</span>);
}

<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)); <span class="hljs-comment">// Output: 10</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-the-spread-operator-and-its-uses">Explain the concept of the spread operator and its uses</h3>

<p>The spread operator (<code>...</code>) in JavaScript allows you to expand elements of an iterable (like an array or object) into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Copying an array</span>
<span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> arr2 = [...arr1];

<span class="hljs-comment">// Merging arrays</span>
<span class="hljs-keyword">const</span> arr3 = [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">const</span> mergedArray = [...arr1, ...arr3];

<span class="hljs-comment">// Copying an object</span>
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> obj2 = { ...obj1 };

<span class="hljs-comment">// Merging objects</span>
<span class="hljs-keyword">const</span> obj3 = { <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">d</span>: <span class="hljs-number">4</span> };
<span class="hljs-keyword">const</span> mergedObject = { ...obj1, ...obj3 };

<span class="hljs-comment">// Passing array elements as function arguments</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">x, y, z</span>) =&gt;</span> x + y + z;
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-built_in">console</span>.log(sum(...numbers)); <span class="hljs-comment">// Output: 6</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax-1">What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?</h3>

<p><strong>Spread syntax</strong> (<code>...</code>) allows an iterable (like an array or string) to be expanded into individual elements. This is often used as a convenient and modern way to create new arrays or objects by combining existing ones.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Operation</td><td>Traditional</td><td>Spread</td></tr>
</thead>
<tbody>
<tr>
<td>Array cloning</td><td><code>arr.slice()</code></td><td><code>[...arr]</code></td></tr>
<tr>
<td>Array merging</td><td><code>arr1.concat(arr2)</code></td><td><code>[...arr1, ...arr2]</code></td></tr>
<tr>
<td>Object cloning</td><td><code>Object.assign({}, obj)</code></td><td><code>{ ...obj }</code></td></tr>
<tr>
<td>Object merging</td><td><code>Object.assign({}, obj1, obj2)</code></td><td><code>{ ...obj1, ...obj2 }</code></td></tr>
</tbody>
</table>
</div><p><strong>Rest syntax</strong> is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using rest syntax in a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...numbers</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.reduce(<span class="hljs-function">(<span class="hljs-params">total, num</span>) =&gt;</span> total + num, <span class="hljs-number">0</span>);
}

<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 6</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for-1">What are iterators and generators in JavaScript and what are they used for?</h3>

<p>In JavaScript, iterators and generators are powerful tools for managing sequences of data and controlling the flow of execution in a more flexible way.</p>
<p><strong>Iterators</strong> are objects that define a sequence and potentially a return value upon its termination. It adheres to a specific interface:</p>
<ul>
<li>An iterator object must implement a <code>next()</code> method.</li>
<li>The <code>next()</code> method returns an object with two properties:<ul>
<li><code>value</code>: The next value in the sequence.</li>
<li><code>done</code>: A boolean that is <code>true</code> if the iterator has finished its sequence, otherwise <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Here's an example of an object implementing the iterator interface.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> iterator = {
  <span class="hljs-attr">current</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">last</span>: <span class="hljs-number">5</span>,
  next() {
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.current &lt;= <span class="hljs-built_in">this</span>.last) {
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">value</span>: <span class="hljs-built_in">this</span>.current++, done: <span class="hljs-literal">false</span> };
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">value</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">done</span>: <span class="hljs-literal">true</span> };
    }
  },
};

<span class="hljs-keyword">let</span> result = iterator.next();
<span class="hljs-keyword">while</span> (!result.done) {
  <span class="hljs-built_in">console</span>.log(result.value); <span class="hljs-comment">// Logs 0, 1, 2, 3, 4, 5</span>
  result = iterator.next();
}
</code></pre>
<p><strong>Generators</strong> are a special functions that <strong>can pause execution and resume at a later point</strong>. It uses the <code>function*</code> syntax and the <code>yield</code> keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the <code>next()</code> method on the returned iterator advances the generator to the next <code>yield</code> statement, and the value after <code>yield</code> becomes the return value of <code>next()</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">numberGenerator</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> num = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">while</span> (num &lt;= <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">yield</span> num++;
  }
}

<span class="hljs-keyword">const</span> gen = numberGenerator();
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 0, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 1, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 2, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 3, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 4, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: 5, done: false }</span>
<span class="hljs-built_in">console</span>.log(gen.next()); <span class="hljs-comment">// { value: undefined, done: true }</span>
</code></pre>
<p>Generators are powerful for creating iterators on-demand, especially for infinite sequences or complex iteration logic. They can be used for:</p>
<ul>
<li>Lazy evaluation – processing elements only when needed, improving memory efficiency for large datasets.</li>
<li>Implementing iterators for custom data structures.</li>
<li>Creating asynchronous iterators for handling data streams.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function-in-javascript-1">Explain the differences on the usage of <code>foo</code> between <code>function foo() {}</code> and <code>var foo = function() {}</code> in JavaScript</h3>

<p><code>function foo() {}</code> a function declaration while the <code>var foo = function() {}</code> is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as <code>var</code>-declared variables).</p>
<p>If you try to invoke a function expression before it is declared, you will get an <code>Uncaught TypeError: XXX is not a function</code> error.</p>
<p>Function declarations can be called in the enclosing scope even before they are declared.</p>
<pre><code class="lang-js">foo(); <span class="hljs-comment">// 'FOOOOO'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'FOOOOO'</span>);
}
</code></pre>
<p>Function expressions if called before they are declared will result in an error.</p>
<pre><code class="lang-js">foo(); <span class="hljs-comment">// Uncaught TypeError: foo is not a function</span>
<span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'FOOOOO'</span>);
};
</code></pre>
<p>Another key difference is in the scope of the function name. Function expressions can be named by defining it after the <code>function</code> and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or <code>undefined</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunc = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">namedFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(namedFunc); <span class="hljs-comment">// Works</span>
};
<span class="hljs-built_in">console</span>.log(namedFunc); <span class="hljs-comment">// undefined</span>
</code></pre>
<p><strong>Note</strong>: The examples uses <code>var</code> due to legacy reasons. Function expressions can be defined using <code>let</code> and <code>const</code> and the key difference is in the hoisting behavior of those keywords.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-a-parameter-and-an-argument">What is the difference between a parameter and an argument?</h3>

<p>A parameter is a variable in the declaration of a function, while an argument is the actual value passed to the function when it is called. For example, in the function <code>function add(a, b) { return a + b; }</code>, <code>a</code> and <code>b</code> are parameters. When you call <code>add(2, 3)</code>, <code>2</code> and <code>3</code> are arguments.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-hoisting-with-regards-to-functions">Explain the concept of hoisting with regards to functions</h3>

<p>Hoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Function declaration</span>
hoistedFunction(); <span class="hljs-comment">// Works fine</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hoistedFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This function is hoisted'</span>);
}

<span class="hljs-comment">// Function expression</span>
nonHoistedFunction(); <span class="hljs-comment">// Throws an error</span>
<span class="hljs-keyword">var</span> nonHoistedFunction = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This function is not hoisted'</span>);
};
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-the-difference-between-call-and-apply-in-javascript-1">What's the difference between <code>.call</code> and <code>.apply</code> in JavaScript?</h3>

<p><code>.call</code> and <code>.apply</code> are both used to invoke functions with a specific <code>this</code> context and arguments. The primary difference lies in how they accept arguments:</p>
<ul>
<li><code>.call(thisArg, arg1, arg2, ...)</code>: Takes arguments individually.</li>
<li><code>.apply(thisArg, [argsArray])</code>: Takes arguments as an array.</li>
</ul>
<p>Assuming we have a function <code>add</code>, the function can be invoked using <code>.call</code> and <code>.apply</code> in the following manner:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-built_in">console</span>.log(add.call(<span class="hljs-literal">null</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); <span class="hljs-comment">// 3</span>
<span class="hljs-built_in">console</span>.log(add.apply(<span class="hljs-literal">null</span>, [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>])); <span class="hljs-comment">// 3</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-call-and-apply/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-can-you-offer-a-use-case-for-the-new-arrow-gt-function-syntax">Can you offer a use case for the new arrow =&gt; function syntax?</h3>

<p>Arrow functions provide a concise syntax for writing functions in JavaScript. They are particularly useful for maintaining the <code>this</code> context within methods and callbacks. For example, in an event handler or array method like <code>map</code>, arrow functions can simplify the code and avoid issues with <code>this</code> binding.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> doubled = numbers.map(<span class="hljs-function">(<span class="hljs-params">n</span>) =&gt;</span> n * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubled); <span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-difference-between-function-person-const-person-person-and-const-person-new-person-in-javascript-1">Difference between: <code>function Person(){}</code>, <code>const person = Person()</code>, and <code>const person = new Person()</code> in JavaScript?</h3>

<ul>
<li><code>function Person(){}</code>: A function declaration in JavaScript. It can be used as a regular function or as a constructor.</li>
<li><code>const person = Person()</code>: Calls <code>Person</code> as a regular function, not a constructor. If <code>Person</code> is intended to be a constructor, this will lead to unexpected behavior.</li>
<li><code>const person = new Person()</code>: Creates a new instance of <code>Person</code>, correctly utilizing the constructor function to initialize the new object.</li>
</ul>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td><code>function Person(){}</code></td><td><code>const person = Person()</code></td><td><code>const person = new Person()</code></td></tr>
</thead>
<tbody>
<tr>
<td>Type</td><td>Function declaration</td><td>Function call</td><td>Constructor call</td></tr>
<tr>
<td>Usage</td><td>Defines a function</td><td>Invokes <code>Person</code> as a regular function</td><td>Creates a new instance of <code>Person</code></td></tr>
<tr>
<td>Instance Creation</td><td>No instance created</td><td>No instance created</td><td>New instance created</td></tr>
<tr>
<td>Common Mistake</td><td>N/A</td><td>Misusing as constructor leading to <code>undefined</code></td><td>None (when used correctly)</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-definition-of-a-higher-order-function-in-javascript-1">What is the definition of a higher-order function in JavaScript?</h3>

<p>A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.</p>
<p>Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is <code>Array.prototype.map()</code>, which takes an array and a function as arguments. <code>Array.prototype.map()</code> then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are <code>Array.prototype.forEach()</code>, <code>Array.prototype.filter()</code>, and <code>Array.prototype.reduce()</code>. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. <code>Function.prototype.bind()</code> is an example that returns another function.</p>
<p>Imagine a scenario where we have an array of names that we need to transform to uppercase.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> names = [<span class="hljs-string">'irish'</span>, <span class="hljs-string">'daisy'</span>, <span class="hljs-string">'anna'</span>];
</code></pre>
<p>The imperative way will be as such:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformNamesToUppercase</span>(<span class="hljs-params">names</span>) </span>{
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; names.length; i++) {
    results.push(names[i].toUpperCase());
  }
  <span class="hljs-keyword">return</span> results;
}

transformNamesToUppercase(names); <span class="hljs-comment">// ['IRISH', 'DAISY', 'ANNA']</span>
</code></pre>
<p>Using <code>Array.prototype.map(transformerFn)</code> makes the code shorter and more declarative.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transformNamesToUppercase</span>(<span class="hljs-params">names</span>) </span>{
  <span class="hljs-keyword">return</span> names.map(<span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> name.toUpperCase());
}

transformNamesToUppercase(names); <span class="hljs-comment">// ['IRISH', 'DAISY', 'ANNA']</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-callback-functions-and-how-are-they-used">What are callback functions and how are they used?</h3>

<p>A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They are commonly used for asynchronous operations like handling events, making API calls, or reading files. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John Doe'</span> };
    callback(data);
  }, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleData</span>(<span class="hljs-params">data</span>) </span>{
  <span class="hljs-built_in">console</span>.log(data);
}

fetchData(handleData);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-a-typical-use-case-for-anonymous-functions-in-javascript-1">What's a typical use case for anonymous functions in JavaScript?</h3>

<p>Anonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.</p>
<pre><code class="lang-js"><span class="hljs-comment">// The filter method is passed an anonymous function.</span>
arr.filter(<span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x &gt; <span class="hljs-number">1</span>);
</code></pre>
<p>They are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to "close over" and remember the environment in which they were created.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Encapsulating Code</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Some code here.</span>
})();

<span class="hljs-comment">// Callbacks</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello world!'</span>);
}, <span class="hljs-number">1000</span>);

<span class="hljs-comment">// Functional programming constructs</span>
<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> double = arr.map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">el</span>) </span>{
  <span class="hljs-keyword">return</span> el * <span class="hljs-number">2</span>;
});
<span class="hljs-built_in">console</span>.log(double); <span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-recursion-and-how-is-it-used-in-javascript">What is recursion and how is it used in JavaScript?</h3>

<p>Recursion is a programming technique where a function calls itself to solve a problem. In JavaScript, recursion is used to solve problems that can be broken down into smaller, similar sub-problems. A base case is essential to stop the recursive calls and prevent infinite loops. For example, calculating the factorial of a number can be done using recursion:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }
  <span class="hljs-keyword">return</span> n * factorial(n - <span class="hljs-number">1</span>);
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-default-parameters-and-how-are-they-used">What are default parameters and how are they used?</h3>

<p>Default parameters in JavaScript allow you to set default values for function parameters if no value or <code>undefined</code> is passed. This helps avoid <code>undefined</code> values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name = <span class="hljs-string">'Guest'</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greet(); <span class="hljs-comment">// Output: Hello, Guest!</span>
greet(<span class="hljs-string">'Alice'</span>); <span class="hljs-comment">// Output: Hello, Alice!</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-why-the-following-doesnt-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife">Explain why the following doesn't work as an IIFE: <code>function foo(){}();</code>. What needs to be changed to properly make it an IIFE?</h3>

<p>The code <code>function foo(){}();</code> doesn't work as an Immediately Invoked Function Expression (IIFE) because the JavaScript parser treats <code>function foo(){}</code> as a function declaration, not an expression. To make it an IIFE, you need to wrap the function in parentheses to turn it into a function expression: <code>(function foo(){})();</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-various-ways-to-create-objects-in-javascript-1">What are the various ways to create objects in JavaScript?</h3>

<p>Creating objects in JavaScript offers several methods:</p>
<ul>
<li><strong>Object literals (<code>{}</code>)</strong>: Simplest and most popular approach. Define key-value pairs within curly braces.</li>
<li><strong><code>Object()</code> constructor</strong>: Use <code>new Object()</code> with dot notation to add properties.</li>
<li><strong><code>Object.create()</code></strong>: Create new objects using existing objects as prototypes, inheriting properties and methods.</li>
<li><strong>Constructor functions</strong>: Define blueprints for objects using functions, creating instances with <code>new</code>.</li>
<li><strong>ES2015 classes</strong>: Structured syntax similar to other languages, using <code>class</code> and <code>constructor</code> keywords.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties">Explain the difference between dot notation and bracket notation for accessing object properties</h3>

<p>Dot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-string">'favorite color'</span>: <span class="hljs-string">'blue'</span> };

<span class="hljs-comment">// Dot notation</span>
<span class="hljs-built_in">console</span>.log(obj.name); <span class="hljs-comment">// Alice</span>

<span class="hljs-comment">// Bracket notation</span>
<span class="hljs-built_in">console</span>.log(obj[<span class="hljs-string">'favorite color'</span>]); <span class="hljs-comment">// blue</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-different-methods-for-iterating-over-an-array">What are the different methods for iterating over an array?</h3>

<p>There are several methods to iterate over an array in JavaScript. The most common ones include <code>for</code> loops, <code>forEach</code>, <code>map</code>, <code>filter</code>, <code>reduce</code>, and <code>for...of</code>. Each method has its own use case. For example, <code>for</code> loops are versatile and can be used for any kind of iteration, while <code>forEach</code> is specifically for executing a function on each array element. <code>map</code> is used for transforming arrays, <code>filter</code> for filtering elements, <code>reduce</code> for accumulating values, and <code>for...of</code> for iterating over iterable objects.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-add-remove-and-update-elements-in-an-array">How do you add, remove, and update elements in an array?</h3>

<p>To add elements to an array, you can use methods like <code>push</code>, <code>unshift</code>, or <code>splice</code>. To remove elements, you can use <code>pop</code>, <code>shift</code>, or <code>splice</code>. To update elements, you can directly access the array index and assign a new value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// Add elements</span>
arr.push(<span class="hljs-number">4</span>); <span class="hljs-comment">// [1, 2, 3, 4]</span>
arr.unshift(<span class="hljs-number">0</span>); <span class="hljs-comment">// [0, 1, 2, 3, 4]</span>
arr.splice(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1.5</span>); <span class="hljs-comment">// [0, 1, 1.5, 2, 3, 4]</span>

<span class="hljs-comment">// Remove elements</span>
arr.pop(); <span class="hljs-comment">// [0, 1, 1.5, 2, 3]</span>
arr.shift(); <span class="hljs-comment">// [1, 1.5, 2, 3]</span>
arr.splice(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>); <span class="hljs-comment">// [1, 2, 3]</span>

<span class="hljs-comment">// Update elements</span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">5</span>; <span class="hljs-comment">// [1, 5, 3]</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-different-ways-to-copy-an-object-or-an-array">What are the different ways to copy an object or an array?</h3>

<p>To copy an object or an array in JavaScript, you can use several methods. For shallow copies, you can use the spread operator (<code>...</code>) or <code>Object.assign()</code>. For deep copies, you can use <code>JSON.parse(JSON.stringify())</code> or libraries like Lodash's <code>_.cloneDeep()</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Shallow copy of an array</span>
<span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> shallowCopyArray = [...originalArray];

<span class="hljs-comment">// Shallow copy of an object</span>
<span class="hljs-keyword">const</span> originalObject = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> shallowCopyObject = { ...originalObject };

<span class="hljs-comment">// Deep copy using JSON methods</span>
<span class="hljs-keyword">const</span> deepCopyObject = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(originalObject));
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-shallow-copy-and-deep-copy">Explain the difference between shallow copy and deep copy</h3>

<p>A shallow copy duplicates the top-level properties of an object, but nested objects are still referenced. A deep copy duplicates all levels of an object, creating entirely new instances of nested objects. For example, using <code>Object.assign()</code> creates a shallow copy, while using libraries like <code>Lodash</code> or <code>structuredClone()</code> in modern JavaScript can create deep copies.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Shallow copy example</span>
<span class="hljs-keyword">let</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: { <span class="hljs-attr">c</span>: <span class="hljs-number">2</span> } };
<span class="hljs-keyword">let</span> shallowCopy = <span class="hljs-built_in">Object</span>.assign({}, obj1);
shallowCopy.b.c = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(obj1.b.c); <span class="hljs-comment">// Outputs: 3</span>

<span class="hljs-comment">// Deep copy example</span>
<span class="hljs-keyword">let</span> deepCopy = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(obj1));
deepCopy.b.c = <span class="hljs-number">4</span>;
<span class="hljs-built_in">console</span>.log(obj1.b.c); <span class="hljs-comment">// Outputs: 2</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects">What are the advantages of using the spread operator with arrays and objects?</h3>

<p>The spread operator (<code>...</code>) in JavaScript allows you to easily copy arrays and objects, merge them, and add new elements or properties. It simplifies syntax and improves readability. For arrays, it can be used to concatenate or clone arrays. For objects, it can be used to merge objects or add new properties.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Arrays</span>
<span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> arr2 = [...arr1, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]; <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>

<span class="hljs-comment">// Objects</span>
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> obj2 = { ...obj1, <span class="hljs-attr">c</span>: <span class="hljs-number">3</span> }; <span class="hljs-comment">// { a: 1, b: 2, c: 3 }</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-check-if-an-object-has-a-specific-property">How do you check if an object has a specific property?</h3>

<p>To check if an object has a specific property, you can use the <code>in</code> operator or the <code>hasOwnProperty</code> method. The <code>in</code> operator checks for both own and inherited properties, while <code>hasOwnProperty</code> checks only for own properties.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">key</span>: <span class="hljs-string">'value'</span> };

<span class="hljs-comment">// Using the `in` operator</span>
<span class="hljs-keyword">if</span> (<span class="hljs-string">'key'</span> <span class="hljs-keyword">in</span> obj) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Property exists'</span>);
}

<span class="hljs-comment">// Using `hasOwnProperty`</span>
<span class="hljs-keyword">if</span> (obj.hasOwnProperty(<span class="hljs-string">'key'</span>)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Property exists'</span>);
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-mutable-and-immutable-objects-in-javascript-1">Explain the difference between mutable and immutable objects in JavaScript</h3>

<p><strong>Mutable objects</strong> allow for modification of properties and values after creation, which is the default behavior for most objects.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mutableObject = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
};

<span class="hljs-comment">// Modify the object</span>
mutableObject.name = <span class="hljs-string">'Jane'</span>;

<span class="hljs-comment">// The object has been modified</span>
<span class="hljs-built_in">console</span>.log(mutableObject); <span class="hljs-comment">// Output: { name: 'Jane', age: 30 }</span>
</code></pre>
<p><strong>Immutable objects</strong> cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> immutableObject = <span class="hljs-built_in">Object</span>.freeze({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
});

<span class="hljs-comment">// Attempt to modify the object</span>
immutableObject.name = <span class="hljs-string">'Jane'</span>;

<span class="hljs-comment">// The object remains unchanged</span>
<span class="hljs-built_in">console</span>.log(immutableObject); <span class="hljs-comment">// Output: { name: 'John', age: 30 }</span>
</code></pre>
<p>The key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-destructuring-assignment-for-objects-and-arrays">Explain the concept of destructuring assignment for objects and arrays</h3>

<p>Destructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces. For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Array destructuring</span>
<span class="hljs-keyword">const</span> [a, b] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>];

<span class="hljs-comment">// Object destructuring</span>
<span class="hljs-keyword">const</span> { name, age } = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-objectfreeze-for">What is <code>Object.freeze()</code> for?</h3>

<p><code>Object.freeze()</code> is used to make an object immutable. Once an object is frozen, you cannot add, remove, or modify its properties. This is useful for creating constants or ensuring that an object remains unchanged throughout the program.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> };
<span class="hljs-built_in">Object</span>.freeze(obj);
obj.name = <span class="hljs-string">'Doe'</span>; <span class="hljs-comment">// This will not change the name property</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectfreeze-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-objectseal-for">What is <code>Object.seal()</code> for?</h3>

<p><code>Object.seal()</code> is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> };
<span class="hljs-built_in">Object</span>.seal(obj);

obj.name = <span class="hljs-string">'Jane'</span>; <span class="hljs-comment">// Allowed</span>
obj.age = <span class="hljs-number">30</span>; <span class="hljs-comment">// Not allowed</span>
<span class="hljs-keyword">delete</span> obj.name; <span class="hljs-comment">// Not allowed</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectseal-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-objectpreventextensions-for">What is <code>Object.preventExtensions()</code> for?</h3>

<p><code>Object.preventExtensions()</code> is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> };
<span class="hljs-built_in">Object</span>.preventExtensions(obj);

obj.age = <span class="hljs-number">30</span>; <span class="hljs-comment">// This will not work, as the object is not extensible</span>
<span class="hljs-built_in">console</span>.log(obj.age); <span class="hljs-comment">// undefined</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectpreventextensions-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-object-getters-and-setters-for-1">What are JavaScript object getters and setters for?</h3>

<p>JavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.</p>
<p>Getters and setters are defined using the <code>get</code> and <code>set</code> keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.</p>
<p>Here's a code example demonstrating the use of getters and setters:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">_name</span>: <span class="hljs-string">'John Doe'</span>, <span class="hljs-comment">// Private property</span>

  <span class="hljs-keyword">get</span> <span class="hljs-title">name</span>() {
    <span class="hljs-comment">// Getter</span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._name;
  },
  <span class="hljs-keyword">set</span> <span class="hljs-title">name</span>(<span class="hljs-params">newName</span>) {
    <span class="hljs-comment">// Setter</span>
    <span class="hljs-keyword">if</span> (newName.trim().length &gt; <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">this</span>._name = newName;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Invalid name'</span>);
    }
  },
};

<span class="hljs-comment">// Accessing the name property using the getter</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'John Doe'</span>

<span class="hljs-comment">// Setting the name property using the setter</span>
person.name = <span class="hljs-string">'Jane Smith'</span>; <span class="hljs-comment">// Setter is called</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'Jane Smith'</span>

person.name = <span class="hljs-string">''</span>; <span class="hljs-comment">// Setter is called, but the value is not set due to validation</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: 'Jane Smith'</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-object-property-flags-and-descriptors-1">What are JavaScript object property flags and descriptors?</h3>

<p>In JavaScript, property flags and descriptors manage the behavior and attributes of object properties.</p>
<p><strong>Property flags</strong></p>
<p>Property flags are used to specify the behavior of a property on an object. Here are the available flags:</p>
<ul>
<li><code>writable</code>: Specifies whether the property can be written to. Defaults to <code>true</code>.</li>
<li><code>enumerable</code>: Specifies whether the property is enumerable. Defaults to <code>true</code>.</li>
<li><code>configurable</code>: Specifies whether the property can be deleted or its attributes changed. Default is <code>true</code>.</li>
</ul>
<p><strong>Property descriptors</strong></p>
<p>These provide detailed information about an object's property, including its value and flags. They are retrieved using <code>Object.getOwnPropertyDescriptor()</code> and set using <code>Object.defineProperty()</code>.</p>
<p>The use cases of property descriptors are as follows:</p>
<ul>
<li>Making a property non-writable by setting <code>writable: false</code> to ensure data consistency.</li>
<li>Hiding a property from enumeration by setting <code>enumerable: false</code>.</li>
<li>Preventing property deletion and modification by setting <code>configurable: false</code>.</li>
<li>Freezing or sealing objects to prevent modifications globally.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-reliably-determine-whether-an-object-is-empty">How do you reliably determine whether an object is empty?</h3>

<p>To reliably determine whether an object is empty, you can use <code>Object.keys()</code> to check if the object has any enumerable properties. If the length of the array returned by <code>Object.keys()</code> is zero, the object is empty.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isEmpty = <span class="hljs-function">(<span class="hljs-params">obj</span>) =&gt;</span> <span class="hljs-built_in">Object</span>.keys(obj).length === <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> obj = {};
<span class="hljs-built_in">console</span>.log(isEmpty(obj)); <span class="hljs-comment">// true</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-event-loop-in-javascript-runtimes-1">What is the event loop in JavaScript runtimes?</h3>

<p>The event loop is concept within the browser runtime environment regarding how asynchronous operations are executed within JavaScript engines. It works as such:</p>
<ol>
<li>The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.</li>
<li>When an asynchronous operation is encountered (e.g., <code>setTimeout()</code>, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.</li>
<li>Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to "task queue" as "macrotask queue" from here on to better differentiate from the microtask queue.</li>
<li>The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:<ol>
<li>Microtask queue is processed. Microtasks include promise callbacks (<code>then</code>, <code>catch</code>, <code>finally</code>), <code>MutationObserver</code> callbacks, and calls to <code>queueMicrotask()</code>. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.</li>
<li>Macrotask queue is processed. Macrotasks include web APIs like <code>setTimeout()</code>, HTTP requests, user interface event handlers like clicks, scrolls, etc. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!<ol>
<li>If the microtask queue is non-empty, process them as per the previous step.</li>
<li>If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.</li>
</ol>
</li>
</ol>
</li>
<li>This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.</li>
</ol>
<p>The unfortunate truth is that it is extremely hard to explain the event loop well using only text. We recommend checking out one of the following excellent videos explaining the event loop:</p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=eiC58R16hb8">JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue</a> (2024): Lydia Hallie is a popular educator on JavaScript and this is the best recent videos explaining the event loop. There's also an <a target="_blank" href="https://www.lydiahallie.com/blog/event-loop">accompanying blog post</a> for those who prefer detailed text-based explanations.</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=cCOL7MC4Pl0">In the Loop</a> (2018): Jake Archibald previously from the Chrome team provides a visual demonstration of the event loop during JSConf 2018, accounting for different types of tasks.</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">What the heck is the event loop anyway?</a> (2014): Philip Robert's gave this epic talk at JSConf 2014 and it is one of the most viewed JavaScript videos on YouTube.</li>
</ul>
<p>We recommend watching <a target="_blank" href="https://www.youtube.com/watch?v=eiC58R16hb8">Lydia's video</a> as it is the most modern and concise explanation standing at only 13 minutes long whereas the other videos are at least 30 minutes long. Her video is sufficient for the purpose of interviews.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript-1">Explain the difference between synchronous and asynchronous functions in JavaScript</h3>

<p>Synchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Inside sum function'</span>);
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">const</span> result = sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// The program waits for sum() to complete before assigning the result</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Result: '</span>, result); <span class="hljs-comment">// Output: 5</span>

<span class="hljs-comment">// Console output:</span>
<span class="hljs-comment">// Inside sum function</span>
<span class="hljs-comment">// Result: 5</span>
</code></pre>
<p>Asynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
    callback(data); <span class="hljs-comment">// Calling the callback function with data</span>
  }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Simulating a 2-second delay</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Fetching data...'</span>);
fetchData(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data); <span class="hljs-comment">// Output: { name: 'John', age: 30 } (after 2 seconds)</span>
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Call made to fetch data'</span>); <span class="hljs-comment">// Output: This will be printed first</span>

<span class="hljs-comment">// Console output:</span>
<span class="hljs-comment">// Fetching data...</span>
<span class="hljs-comment">// Call made to fetch data</span>
<span class="hljs-comment">// { name: 'John', age: 30 }</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-a-callback-function-in-asynchronous-operations">Explain the concept of a callback function in asynchronous operations</h3>

<p>A callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In asynchronous operations, callbacks are used to handle tasks that take time to complete, such as network requests or file I/O, without blocking the execution of the rest of the code. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> data = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
    callback(data);
  }, <span class="hljs-number">1000</span>);
}

fetchData(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(data);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-promises-and-how-do-they-work">What are Promises and how do they work?</h3>

<p>Promises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: <code>pending</code>, <code>fulfilled</code>, and <code>rejected</code>. You can handle the results of a promise using the <code>.then()</code> method for success and the <code>.catch()</code> method for errors.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-comment">// asynchronous operation</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-comment">/* operation successful */</span>) {
    resolve(<span class="hljs-string">'Success!'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Error!'</span>);
  }
});

promise.then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 'Success!'</span>
}).catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(error); <span class="hljs-comment">// 'Error!'</span>
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-promises-and-how-do-they-work/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-different-states-of-a-promise">Explain the different states of a Promise</h3>

<p>A <code>Promise</code> in JavaScript can be in one of three states: <code>pending</code>, <code>fulfilled</code>, or <code>rejected</code>. When a <code>Promise</code> is created, it starts in the <code>pending</code> state. If the operation completes successfully, the <code>Promise</code> transitions to the <code>fulfilled</code> state, and if it fails, it transitions to the <code>rejected</code> state. Here's a quick example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-comment">// some asynchronous operation</span>
  <span class="hljs-keyword">if</span> (success) {
    resolve(<span class="hljs-string">'Success!'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Error!'</span>);
  }
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-different-states-of-a-promise/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript-1">What are the pros and cons of using Promises instead of callbacks in JavaScript?</h3>

<p>Promises offer a cleaner alternative to callbacks, helping to avoid callback hell and making asynchronous code more readable. They facilitate writing sequential and parallel asynchronous operations with ease. However, using promises may introduce slightly more complex code.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-use-of-promiseall">What is the use of <code>Promise.all()</code></h3>

<p><code>Promise.all()</code> is a method in JavaScript that takes an array of promises and returns a single promise. This returned promise resolves when all the input promises have resolved, or it rejects if any of the input promises reject. It is useful for running multiple asynchronous operations in parallel and waiting for all of them to complete.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise1 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">3</span>);
<span class="hljs-keyword">const</span> promise2 = <span class="hljs-number">42</span>;
<span class="hljs-keyword">const</span> promise3 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">100</span>, <span class="hljs-string">'foo'</span>);
});

<span class="hljs-built_in">Promise</span>.all([promise1, promise2, promise3]).then(<span class="hljs-function">(<span class="hljs-params">values</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(values); <span class="hljs-comment">// [3, 42, 'foo']</span>
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-use-of-promiseall/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-is-promiseall-different-from-promiseallsettled">How is <code>Promise.all()</code> different from <code>Promise.allSettled()</code>?</h3>

<p><code>Promise.all()</code> and <code>Promise.allSettled()</code> are both methods for handling multiple promises in JavaScript, but they behave differently. <code>Promise.all()</code> waits for all promises to resolve and fails fast if any promise rejects, returning a single rejected promise. <code>Promise.allSettled()</code>, on the other hand, waits for all promises to settle (either resolve or reject) and returns an array of objects describing the outcome of each promise.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-is-promiseall-different-from-promiseallsettled/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-asyncawait-and-how-does-it-simplify-asynchronous-code">What is async/await and how does it simplify asynchronous code?</h3>

<p><code>async/await</code> is a modern syntax in JavaScript that simplifies working with promises. By using the <code>async</code> keyword before a function, you can use the <code>await</code> keyword inside that function to pause execution until a promise is resolved. This makes asynchronous code look and behave more like synchronous code, making it easier to read and maintain.</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
  }
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-handle-errors-in-asynchronous-operations">How do you handle errors in asynchronous operations?</h3>

<p>To handle errors in asynchronous operations, you can use <code>try...catch</code> blocks with <code>async/await</code> syntax or <code>.catch()</code> method with Promises. For example, with <code>async/await</code>, you can wrap your code in a <code>try...catch</code> block to catch any errors:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(data);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error);
  }
}
</code></pre>
<p>With Promises, you can use the <code>.catch()</code> method:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching data:'</span>, error));
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-a-microtask-queue">Explain the concept of a microtask queue</h3>

<p>The microtask queue is a queue of tasks that need to be executed after the currently executing script and before any other task. Microtasks are typically used for tasks that need to be executed immediately after the current operation, such as promise callbacks. The microtask queue is processed before the macrotask queue, ensuring that microtasks are executed as soon as possible.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-a-microtask-queue/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-settimeout-setimmediate-and-processnexttick">What is the difference between <code>setTimeout()</code>, <code>setImmediate()</code>, and <code>process.nextTick()</code>?</h3>

<p><code>setTimeout()</code> schedules a callback to run after a minimum delay. <code>setImmediate()</code> schedules a callback to run after the current event loop completes. <code>process.nextTick()</code> schedules a callback to run before the next event loop iteration begins.</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setTimeout'</span>), <span class="hljs-number">0</span>);
setImmediate(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setImmediate'</span>));
process.nextTick(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'nextTick'</span>));
</code></pre>
<p>In this example, <code>process.nextTick()</code> will execute first, followed by either <code>setTimeout()</code> or <code>setImmediate()</code> depending on the environment.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-how-prototypal-inheritance-works-in-javascript-1">Explain how prototypal inheritance works in JavaScript</h3>

<p>Prototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called <code>[[Prototype]]</code> (commonly accessed via <code>__proto__</code> or using <code>Object.getPrototypeOf()</code>) that is a reference to another object, which is called the object's "prototype".</p>
<p>When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's <code>__proto__</code>, and the <code>__proto__</code>'s <code>__proto__</code> and so on, until it finds the property defined on one of the <code>__proto__</code>s or until it reaches the end of the prototype chain.</p>
<p>This behavior simulates classical inheritance, but it is really more of <a target="_blank" href="https://davidwalsh.name/javascript-objects">delegation than inheritance</a>.</p>
<p>Here's an example of prototypal inheritance:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Parent object constructor.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-comment">// Add a method to the parent object's prototype.</span>
Animal.prototype.makeSound = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The '</span> + <span class="hljs-built_in">this</span>.constructor.name + <span class="hljs-string">' makes a sound.'</span>);
};

<span class="hljs-comment">// Child object constructor.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">name</span>) </span>{
  Animal.call(<span class="hljs-built_in">this</span>, name); <span class="hljs-comment">// Call the parent constructor.</span>
}

<span class="hljs-comment">// Set the child object's prototype to be the parent's prototype.</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(Dog.prototype, Animal.prototype);

<span class="hljs-comment">// Add a method to the child object's prototype.</span>
Dog.prototype.bark = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Woof!'</span>);
};

<span class="hljs-comment">// Create a new instance of Dog.</span>
<span class="hljs-keyword">const</span> bolt = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Bolt'</span>);

<span class="hljs-comment">// Call methods on the child object.</span>
<span class="hljs-built_in">console</span>.log(bolt.name); <span class="hljs-comment">// "Bolt"</span>
bolt.makeSound(); <span class="hljs-comment">// "The Dog makes a sound."</span>
bolt.bark(); <span class="hljs-comment">// "Woof!"</span>
</code></pre>
<p>Things to note are:</p>
<ul>
<li><code>.makeSound</code> is not defined on <code>Dog</code>, so the JavaScript engine goes up the prototype chain and finds <code>.makeSound</code> on the inherited <code>Animal</code>.</li>
<li>Using <code>Object.create()</code> to build the inheritance chain is no longer recommended. Use <code>Object.setPrototypeOf()</code> instead.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-prototypal-inheritance-works/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-prototype-chain-and-how-does-it-work">What is the prototype chain and how does it work?</h3>

<p>The prototype chain is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. When you try to access a property on an object, JavaScript will first look for the property on the object itself. If it doesn't find it, it will look at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain, which is <code>null</code>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

Person.prototype.greet = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
};

<span class="hljs-keyword">const</span> alice = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Alice'</span>);
alice.greet(); <span class="hljs-comment">// "Hello, my name is Alice"</span>
</code></pre>
<p>In this example, <code>alice</code> inherits the <code>greet</code> method from <code>Person.prototype</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-classical-inheritance-and-prototypal-inheritance">Explain the difference between classical inheritance and prototypal inheritance</h3>

<p>Classical inheritance is a model where classes inherit from other classes, typically seen in languages like Java and C++. Prototypal inheritance, used in JavaScript, involves objects inheriting directly from other objects. In classical inheritance, you define a class and create instances from it. In prototypal inheritance, you create an object and use it as a prototype for other objects.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-inheritance-in-es2015-classes">Explain the concept of inheritance in ES2015 classes</h3>

<p>Inheritance in ES2015 classes allows one class to extend another, enabling the child class to inherit properties and methods from the parent class. This is done using the <code>extends</code> keyword. The <code>super</code> keyword is used to call the constructor and methods of the parent class. Here's a quick example:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> makes a noise.`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, breed) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.breed = breed;
  }

  speak() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> barks.`</span>);
  }
}

<span class="hljs-keyword">const</span> dog = <span class="hljs-keyword">new</span> Dog(<span class="hljs-string">'Rex'</span>, <span class="hljs-string">'German Shepherd'</span>);
dog.speak(); <span class="hljs-comment">// Rex barks.</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-purpose-of-the-new-keyword">What is the purpose of the <code>new</code> keyword?</h3>

<p>The <code>new</code> keyword in JavaScript is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use <code>new</code>, it does four things: it creates a new object, sets the prototype, binds <code>this</code> to the new object, and returns the new object.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-keyword">const</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Alice'</span>);
<span class="hljs-built_in">console</span>.log(person1.name); <span class="hljs-comment">// Alice</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-create-a-constructor-function">How do you create a constructor function?</h3>

<p>To create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the <code>this</code> keyword to set properties and methods. When creating an instance, use the <code>new</code> keyword.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-keyword">const</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>, <span class="hljs-number">30</span>);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-create-a-constructor-function/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors-1">What are the differences between JavaScript ES2015 classes and ES5 function constructors?</h3>

<p>ES2015 introduces a new way of creating classes, which provides a more intuitive and concise way to define and work with objects and inheritance compared to the ES5 function constructor syntax. Here's an example of each:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 function constructor</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}

<span class="hljs-comment">// ES2015 Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}
</code></pre>
<p>For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a <code>Student</code> class that subclasses <code>Person</code> and add a <code>studentId</code> field, this is what we have to do in addition to the above.</p>
<pre><code class="lang-js"><span class="hljs-comment">// ES5 function constructor</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Student</span>(<span class="hljs-params">name, studentId</span>) </span>{
  <span class="hljs-comment">// Call constructor of superclass to initialize superclass-derived members.</span>
  Person.call(<span class="hljs-built_in">this</span>, name);

  <span class="hljs-comment">// Initialize subclass's own members.</span>
  <span class="hljs-built_in">this</span>.studentId = studentId;
}

Student.prototype = <span class="hljs-built_in">Object</span>.create(Person.prototype);
Student.prototype.constructor = Student;

<span class="hljs-comment">// ES2015 Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, studentId) {
    <span class="hljs-built_in">super</span>(name);
    <span class="hljs-built_in">this</span>.studentId = studentId;
  }
}
</code></pre>
<p>It's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember.</p>
<p><strong>Comparison of ES5 function constructors vs ES2015 classes</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>ES5 Function Constructor</td><td>ES2015 Class</td></tr>
</thead>
<tbody>
<tr>
<td>Syntax</td><td>Uses function constructors and prototypes</td><td>Uses <code>class</code> keyword</td></tr>
<tr>
<td>Constructor</td><td>Function with properties assigned using <code>this</code></td><td><code>constructor</code> method inside the class</td></tr>
<tr>
<td>Method Definition</td><td>Defined on the prototype</td><td>Defined inside the class body</td></tr>
<tr>
<td>Static Methods</td><td>Added directly to the constructor function</td><td>Defined using the <code>static</code> keyword</td></tr>
<tr>
<td>Inheritance</td><td>Uses <code>Object.create()</code> and manually sets prototype chain</td><td>Uses <code>extends</code> keyword and <code>super</code> function</td></tr>
<tr>
<td>Readability</td><td>Less intuitive and more verbose</td><td>More concise and intuitive</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor-1">What advantage is there for using the JavaScript arrow syntax for a method in a constructor?</h3>

<p>The main advantage of using an arrow function as a method inside a constructor is that the value of <code>this</code> gets set at the time of the function creation and can't change after that. When the constructor is used to create a new object, <code>this</code> will always refer to that object.</p>
<p>For example, let's say we have a <code>Person</code> constructor that takes a first name as an argument has two methods to <code>console.log()</code> that name, one as a regular function and one as an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Person = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.sayName1 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  };
  <span class="hljs-built_in">this</span>.sayName2 = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.name);
  };
};

<span class="hljs-keyword">const</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>);
<span class="hljs-keyword">const</span> dave = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Dave'</span>);

john.sayName1(); <span class="hljs-comment">// John</span>
john.sayName2(); <span class="hljs-comment">// John</span>

<span class="hljs-comment">// The regular function can have its `this` value changed, but the arrow function cannot</span>
john.sayName1.call(dave); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.call(dave); <span class="hljs-comment">// John</span>

john.sayName1.apply(dave); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.apply(dave); <span class="hljs-comment">// John</span>

john.sayName1.bind(dave)(); <span class="hljs-comment">// Dave (because `this` is now the dave object)</span>
john.sayName2.bind(dave)(); <span class="hljs-comment">// John</span>

<span class="hljs-keyword">const</span> sayNameFromWindow1 = john.sayName1;
sayNameFromWindow1(); <span class="hljs-comment">// undefined (because `this` is now the window object)</span>

<span class="hljs-keyword">const</span> sayNameFromWindow2 = john.sayName2;
sayNameFromWindow2(); <span class="hljs-comment">// John</span>
</code></pre>
<p>The main takeaway here is that <code>this</code> can be changed for a normal function, but <code>this</code> always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the value of <code>this</code> changing.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-might-you-want-to-create-static-class-members-in-javascript-1">Why might you want to create static class members in JavaScript?</h3>

<p>Static class members (properties/methods) has a <code>static</code> keyword prepended. Such members cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
  <span class="hljs-keyword">static</span> noOfWheels = <span class="hljs-number">4</span>;
  <span class="hljs-keyword">static</span> compare() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Static method has been called.'</span>;
  }
}

<span class="hljs-built_in">console</span>.log(Car.noOfWheels); <span class="hljs-comment">// 4</span>
</code></pre>
<p>Static members are useful under the following scenarios:</p>
<ul>
<li><strong>Namespace organization</strong>: Static properties can be used to define constants or configuration values that are specific to a class. This helps organize related data within the class namespace and prevents naming conflicts with other variables. Examples include <code>Math.PI</code>, <code>Math.SQRT2</code>.</li>
<li><strong>Helper functions</strong>: Static methods can be used as helper functions that operate on the class itself or its instances. This can improve code readability and maintainability by separating utility logic from the core functionality of the class. Examples of frequently used static methods include <code>Object.assign()</code>, <code>Math.max()</code>.</li>
<li><strong>Singleton pattern</strong>: In some rare cases, static properties and methods can be used to implement a singleton pattern, where only one instance of a class ever exists. However, this pattern can be tricky to manage and is generally discouraged in favor of more modern dependency injection techniques.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-you-might-want-to-create-static-class-members/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-a-closure-in-javascript-and-howwhy-would-you-use-one-1">What is a closure in JavaScript, and how/why would you use one?</h3>

<p>In the book <a target="_blank" href="https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures">"You Don't Know JS"</a> (YDKJS) by Kyle Simpson, a closure is defined as follows:</p>
<blockquote>
<p>Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope</p>
</blockquote>
<p>In simple terms, functions have access to variables that were in their scope at the time of their creation. This is what we call the function's lexical scope. A closure is a function that retains access to these variables even after the outer function has finished executing. This is like the function has a memory of its original environment.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> outerVar = <span class="hljs-string">'I am outside of innerFunction'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(outerVar); <span class="hljs-comment">// `innerFunction` can still access `outerVar`.</span>
  }

  <span class="hljs-keyword">return</span> innerFunction;
}

<span class="hljs-keyword">const</span> inner = outerFunction(); <span class="hljs-comment">// `inner` now holds a reference to `innerFunction`.</span>

inner(); <span class="hljs-comment">// "I am outside of innerFunction"</span>
<span class="hljs-comment">// Even though `outerFunction` has completed execution, `inner` still has access to variables defined inside `outerFunction`.</span>
</code></pre>
<p>Key points to remember:</p>
<ul>
<li>Closure occurs when an inner function has access to variables in its outer (lexical) scope, even when the outer function has finished executing.</li>
<li>Closure allows a function to <strong>remember</strong> the environment in which it was created, even if that environment is no longer present.</li>
<li>Closures are used extensively in JavaScript, such as in callbacks, event handlers, and asynchronous functions.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-lexical-scoping">Explain the concept of lexical scoping</h3>

<p>Lexical scoping means that the scope of a variable is determined by its location within the source code, and nested functions have access to variables declared in their outer scope. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> outerVariable = <span class="hljs-string">'I am outside!'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(outerVariable); <span class="hljs-comment">// 'I am outside!'</span>
  }

  innerFunction();
}

outerFunction();
</code></pre>
<p>In this example, <code>innerFunction</code> can access <code>outerVariable</code> because of lexical scoping.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-lexical-scoping/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-scope-in-javascript">Explain the concept of scope in JavaScript</h3>

<p>In JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces <code>{}</code>) it is declared.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Global scope</span>
<span class="hljs-keyword">var</span> globalVar = <span class="hljs-string">'I am global'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Function scope</span>
  <span class="hljs-keyword">var</span> functionVar = <span class="hljs-string">'I am in a function'</span>;

  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-comment">// Block scope</span>
    <span class="hljs-keyword">let</span> blockVar = <span class="hljs-string">'I am in a block'</span>;
    <span class="hljs-built_in">console</span>.log(blockVar); <span class="hljs-comment">// Accessible here</span>
  }

  <span class="hljs-comment">// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined</span>
}

<span class="hljs-built_in">console</span>.log(globalVar); <span class="hljs-comment">// Accessible here</span>
<span class="hljs-comment">// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-closures-be-used-to-create-private-variables">How can closures be used to create private variables?</h3>

<p>Closures in JavaScript can be used to create private variables by defining a function within another function. The inner function has access to the outer function's variables, but those variables are not accessible from outside the outer function. This allows you to encapsulate and protect the variables from being accessed or modified directly.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>; <span class="hljs-comment">// private variable</span>

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">increment</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      count++;
      <span class="hljs-keyword">return</span> count;
    },
    <span class="hljs-attr">decrement</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      count--;
      <span class="hljs-keyword">return</span> count;
    },
    <span class="hljs-attr">getCount</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> count;
    },
  };
}

<span class="hljs-keyword">const</span> counter = createCounter();
<span class="hljs-built_in">console</span>.log(counter.increment()); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(counter.getCount()); <span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(counter.count); <span class="hljs-comment">// undefined</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-potential-pitfalls-of-using-closures">What are the potential pitfalls of using closures?</h3>

<p>Closures can lead to memory leaks if not managed properly, especially when they capture variables that are no longer needed. They can also make debugging more difficult due to the complexity of the scope chain. Additionally, closures can cause performance issues if they are overused or used inappropriately, as they keep references to variables in their scope, which can prevent garbage collection.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-potential-pitfalls-of-using-closures/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-global-scope-function-scope-and-block-scope">Explain the difference between global scope, function scope, and block scope</h3>

<p>Global scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within <code>{}</code>) they are declared in.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> globalVar = <span class="hljs-string">"I'm global"</span>; <span class="hljs-comment">// Global scope</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> functionVar = <span class="hljs-string">"I'm in a function"</span>; <span class="hljs-comment">// Function scope</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">let</span> blockVar = <span class="hljs-string">"I'm in a block"</span>; <span class="hljs-comment">// Block scope</span>
    <span class="hljs-built_in">console</span>.log(blockVar); <span class="hljs-comment">// Accessible here</span>
  }
  <span class="hljs-comment">// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-how-this-works-in-javascript-1">Explain how <code>this</code> works in JavaScript</h3>

<p>There's no simple explanation for <code>this</code>; it is one of the most confusing concepts in JavaScript because it's behavior differs from many other programming languages. The one-liner explanation of the <code>this</code> keyword is that it is a dynamic reference to the context in which a function is executed.</p>
<p>A longer explanation follows is that <code>this</code> follows these rules:</p>
<ol>
<li>If the <code>new</code> keyword is used when calling the function, meaning the function was used as a function constructor, the <code>this</code> inside the function is the newly-created object instance.</li>
<li>If <code>this</code> is used in a <code>class</code> <code>constructor</code>, the <code>this</code> inside the <code>constructor</code> is the newly-created object instance.</li>
<li>If <code>apply()</code>, <code>call()</code>, or <code>bind()</code> is used to call/create a function, <code>this</code> inside the function is the object that is passed in as the argument.</li>
<li>If a function is called as a method (e.g. <code>obj.method()</code>) — <code>this</code> is the object that the function is a property of.</li>
<li>If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, <code>this</code> is the global object. In the browser, the global object is the <code>window</code> object. If in strict mode (<code>'use strict';</code>), <code>this</code> will be <code>undefined</code> instead of the global object.</li>
<li>If multiple of the above rules apply, the rule that is higher wins and will set the <code>this</code> value.</li>
<li>If the function is an ES2015 arrow function, it ignores all the rules above and receives the <code>this</code> value of its surrounding scope at the time it is created.</li>
</ol>
<p>For an in-depth explanation, do check out <a target="_blank" href="https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3">Arnav Aggrawal's article on Medium</a>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-this-works-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-functionprototypebind-in-javascript-1">Explain <code>Function.prototype.bind</code> in JavaScript</h3>

<p><code>Function.prototype.bind</code> is a method in JavaScript that allows you to create a new function with a specific <code>this</code> value and optional initial arguments. It's primary purpose is to:</p>
<ul>
<li><strong>Binding <code>this</code> value to preserve context</strong>: The primary purpose of <code>bind</code> is to bind the <code>this</code> value of a function to a specific object. When you call <code>func.bind(thisArg)</code>, it creates a new function with the same body as <code>func</code>, but with <code>this</code> permanently bound to <code>thisArg</code>.</li>
<li><strong>Partial application of arguments</strong>: <code>bind</code> also allows you to pre-specify arguments for the new function. Any arguments passed to <code>bind</code> after <code>thisArg</code> will be prepended to the arguments list when the new function is called.</li>
<li><strong>Method borrowing</strong>: <code>bind</code> allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.</li>
</ul>
<p>The <code>bind</code> method is particularly useful in scenarios where you need to ensure that a function is called with a specific <code>this</code> context, such as in event handlers, callbacks, or method borrowing.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-function-prototype-bind/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-different-ways-the-this-keyword-can-be-bound">Explain the different ways the <code>this</code> keyword can be bound</h3>

<p>The <code>this</code> keyword in JavaScript can be bound in several ways:</p>
<ul>
<li>Default binding: In non-strict mode, <code>this</code> refers to the global object (window in browsers). In strict mode, <code>this</code> is <code>undefined</code>.</li>
<li>Implicit binding: When a function is called as a method of an object, <code>this</code> refers to the object.</li>
<li>Explicit binding: Using <code>call</code>, <code>apply</code>, or <code>bind</code> methods to explicitly set <code>this</code>.</li>
<li>New binding: When a function is used as a constructor with the <code>new</code> keyword, <code>this</code> refers to the newly created object.</li>
<li>Arrow functions: Arrow functions do not have their own <code>this</code> and inherit <code>this</code> from the surrounding lexical context.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-common-pitfalls-of-using-the-this-keyword">What are the common pitfalls of using the <code>this</code> keyword?</h3>

<p>The <code>this</code> keyword in JavaScript can be tricky because its value depends on how a function is called. Common pitfalls include losing the context of <code>this</code> when passing methods as callbacks, using <code>this</code> in nested functions, and misunderstanding <code>this</code> in arrow functions. To avoid these issues, you can use <code>.bind()</code>, arrow functions, or store the context in a variable.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-this-binding-in-event-handlers">Explain the concept of <code>this</code> binding in event handlers</h3>

<p>In JavaScript, the <code>this</code> keyword refers to the object that is currently executing the code. In event handlers, <code>this</code> typically refers to the element that triggered the event. However, the value of <code>this</code> can change depending on how the event handler is defined and called. To ensure <code>this</code> refers to the desired object, you can use methods like <code>bind()</code>, arrow functions, or assign the context explicitly.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-dom-and-how-is-it-structured">What is the DOM and how is it structured?</h3>

<p>The DOM, or Document Object Model, is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is structured as a tree of objects, where each node represents part of the document, such as elements, attributes, and text.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-dom-and-how-is-it-structured/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-whats-the-difference-between-an-attribute-and-a-property-in-the-dom">What's the difference between an "attribute" and a "property" in the DOM?</h3>

<p>Attributes are defined in the HTML and provide initial values for properties. Properties are part of the DOM and represent the current state of an element. For example, the <code>value</code> attribute of an <code>&lt;input&gt;</code> element sets its initial value, while the <code>value</code> property reflects the current value as the user interacts with it.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-an-attribute-and-a-property/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-documentqueryselector-and-documentgetelementbyid">Explain the difference between <code>document.querySelector()</code> and <code>document.getElementById()</code></h3>

<p><code>document.querySelector()</code> and <code>document.getElementById()</code> are both methods used to select elements from the DOM, but they have key differences. <code>document.querySelector()</code> can select any element using a CSS selector and returns the first match, while <code>document.getElementById()</code> selects an element by its ID and returns the element with that specific ID.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using document.querySelector()</span>
<span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.my-class'</span>);

<span class="hljs-comment">// Using document.getElementById()</span>
<span class="hljs-keyword">const</span> elementById = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'my-id'</span>);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-add-remove-and-modify-html-elements-using-javascript">How do you add, remove, and modify HTML elements using JavaScript?</h3>

<p>To add, remove, and modify HTML elements using JavaScript, you can use methods like <code>createElement</code>, <code>appendChild</code>, <code>removeChild</code>, and properties like <code>innerHTML</code> and <code>textContent</code>. For example, to add an element, you can create it using <code>document.createElement</code> and then append it to a parent element using <code>appendChild</code>. To remove an element, you can use <code>removeChild</code> on its parent. To modify an element, you can change its <code>innerHTML</code> or <code>textContent</code>.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Adding an element</span>
<span class="hljs-keyword">const</span> newElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
newElement.textContent = <span class="hljs-string">'Hello, World!'</span>;
<span class="hljs-built_in">document</span>.body.appendChild(newElement);

<span class="hljs-comment">// Removing an element</span>
<span class="hljs-keyword">const</span> elementToRemove = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'elementId'</span>);
elementToRemove.parentNode.removeChild(elementToRemove);

<span class="hljs-comment">// Modifying an element</span>
<span class="hljs-keyword">const</span> elementToModify = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'elementId'</span>);
elementToModify.innerHTML = <span class="hljs-string">'New Content'</span>;
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-event-listeners-and-how-are-they-used">What are event listeners and how are they used?</h3>

<p>Event listeners are functions that wait for specific events to occur on elements, such as clicks or key presses. They are used to execute code in response to these events. You can add an event listener to an element using the <code>addEventListener</code> method. For example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myButton'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  alert(<span class="hljs-string">'Button was clicked!'</span>);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-event-listeners-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-event-phases-in-a-browser">Explain the event phases in a browser</h3>

<p>In a browser, events go through three phases: capturing, target, and bubbling. During the capturing phase, the event travels from the root to the target element. In the target phase, the event reaches the target element. Finally, in the bubbling phase, the event travels back up from the target element to the root. You can control event handling using <code>addEventListener</code> with the <code>capture</code> option.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-event-phases-in-a-browser/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-event-bubbling-in-javascript-and-browsers-1">Describe event bubbling in JavaScript and browsers</h3>

<p>Event bubbling is a DOM event propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event.</p>
<p>Event bubbling is essential for event delegation, where a single event handler manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-bubbling/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-event-capturing-in-javascript-and-browsers-1">Describe event capturing in JavaScript and browsers</h3>

<p>Event capturing is a lesser-used counterpart to <a target="_blank" href="https://greatfrontend.com/questions/quiz/describe-event-bubbling">event bubbling</a> in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.</p>
<p>Event capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on <code>addEventListener()</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-capturing/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-event-delegation-in-javascript-1">Explain event delegation in JavaScript</h3>

<p>Event delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element's event listener handles the event based on the target element.</p>
<p>Event delegation provides the following benefits:</p>
<ul>
<li><strong>Improved performance</strong>: Attaching a single event listener is more efficient than attaching multiple event listeners to individual elements, especially for large or dynamic lists. This reduces memory usage and improves overall performance.</li>
<li><strong>Simplified event handling</strong>: With event delegation, you only need to write the event handling logic once in the parent element's event listener. This makes the code more maintainable and easier to update.</li>
<li><strong>Dynamic element support</strong>: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There's no need to manually attach or remove event listeners when the DOM structure changes</li>
</ul>
<p>However, do note that:</p>
<ul>
<li>It is important to identify the target element that triggered the event.</li>
<li>Not all events can be delegated because they are not bubbled. Non-bubbling events include: <code>focus</code>, <code>blur</code>, <code>scroll</code>, <code>mouseenter</code>, <code>mouseleave</code>, <code>resize</code>, etc.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-event-delegation/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-prevent-the-default-behavior-of-an-event">How do you prevent the default behavior of an event?</h3>

<p>To prevent the default behavior of an event in JavaScript, you can use the <code>preventDefault</code> method on the event object. For example, if you want to prevent a form from submitting, you can do the following:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'form'</span>).addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  event.preventDefault();
});
</code></pre>
<p>This method stops the default action associated with the event from occurring.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation">What is the difference between <code>event.preventDefault()</code> and <code>event.stopPropagation()</code>?</h3>

<p><code>event.preventDefault()</code> is used to prevent the default action that belongs to the event, such as preventing a form from submitting. <code>event.stopPropagation()</code> is used to stop the event from bubbling up to parent elements, preventing any parent event handlers from being executed.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers-1">What is the difference between <code>mouseenter</code> and <code>mouseover</code> event in JavaScript and browsers?</h3>

<p>The main difference lies in the bubbling behavior of <code>mouseenter</code> and <code>mouseover</code> events. <code>mouseenter</code> does not bubble while <code>mouseover</code> bubbles.</p>
<p><code>mouseenter</code> events do not bubble. The <code>mouseenter</code> event is triggered only when the mouse pointer enters the element itself, not its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the <code>mouseenter</code> event will not be triggered on the parent element again, it's only triggered once upon entry of parent element without regard for its contents. If both parent and child have <code>mouseenter</code> listeners attached and the mouse pointer moves from the parent element to the child element, <code>mouseenter</code> will only fire for the child.</p>
<p><code>mouseover</code> events bubble up the DOM tree. The <code>mouseover</code> event is triggered when the mouse pointer enters the element or one of its descendants. If have a parent element has child elements, and the mouse pointer enters child elements, the <code>mouseover</code> event will be triggered on the parent element again as well. If the parent element has multiple child elements, this can result in multiple event callbacks fired. If there are child elements, and the mouse pointer moves from the parent element to the child element, <code>mouseover</code> will fire for both the parent and the child.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td><code>mouseenter</code></td><td><code>mouseover</code></td></tr>
</thead>
<tbody>
<tr>
<td>Bubbling</td><td>No</td><td>Yes</td></tr>
<tr>
<td>Trigger</td><td>Only when entering itself</td><td>When entering itself and when entering descendants</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-innerhtml-and-textcontent">What is the difference between <code>innerHTML</code> and <code>textContent</code>?</h3>

<p><code>innerHTML</code> and <code>textContent</code> are both properties used to get or set the content of an HTML element, but they serve different purposes. <code>innerHTML</code> returns or sets the HTML markup contained within the element, which means it can parse and render HTML tags. On the other hand, <code>textContent</code> returns or sets the text content of the element, ignoring any HTML tags and rendering them as plain text.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Example of innerHTML</span>
element.innerHTML = <span class="hljs-string">'&lt;strong&gt;Bold Text&lt;/strong&gt;'</span>; <span class="hljs-comment">// Renders as bold text</span>

<span class="hljs-comment">// Example of textContent</span>
element.textContent = <span class="hljs-string">'&lt;strong&gt;Bold Text&lt;/strong&gt;'</span>; <span class="hljs-comment">// Renders as plain text: &lt;strong&gt;Bold Text&lt;/strong&gt;</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-manipulate-css-styles-using-javascript">How do you manipulate CSS styles using JavaScript?</h3>

<p>You can manipulate CSS styles using JavaScript by accessing the <code>style</code> property of an HTML element. For example, to change the background color of a <code>div</code> element with the id <code>myDiv</code>, you can use:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).style.backgroundColor = <span class="hljs-string">'blue'</span>;
</code></pre>
<p>You can also add, remove, or toggle CSS classes using the <code>classList</code> property:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).classList.add(<span class="hljs-string">'newClass'</span>);
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).classList.remove(<span class="hljs-string">'oldClass'</span>);
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).classList.toggle(<span class="hljs-string">'toggleClass'</span>);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-manipulate-css-styles-using-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-the-difference-between-1">Describe the difference between <code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code> and <code>&lt;script defer&gt;</code></h3>

<p>All of these ways (<code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code>, and <code>&lt;script defer&gt;</code>) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:</p>
<ul>
<li><code>&lt;script&gt;</code> is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.</li>
<li><code>&lt;script async&gt;</code> downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. <code>&lt;script async&gt;</code> do not wait for each other and execute in no particular order.</li>
<li><code>&lt;script defer&gt;</code> downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.</li>
</ul>
<p>Here's a table summarizing the 3 ways of loading <code>&lt;script&gt;</code>s in a HTML document.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><code>&lt;script&gt;</code></td><td><code>&lt;script async&gt;</code></td><td><code>&lt;script defer&gt;</code></td></tr>
</thead>
<tbody>
<tr>
<td>Parsing behavior</td><td>Blocks HTML parsing</td><td>Runs parallel to parsing</td><td>Runs parallel to parsing</td></tr>
<tr>
<td>Execution order</td><td>In order of appearance</td><td>Not guaranteed</td><td>In order of appearance</td></tr>
<tr>
<td>DOM dependency</td><td>No</td><td>No</td><td>Yes (waits for DOM)</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-the-window-object-and-the-document-object">What is the difference between the Window object and the Document object?</h3>

<p>The <code>Window</code> object represents the browser window and provides methods to control it, such as opening new windows or accessing the browser history. The <code>Document</code> object represents the content of the web page loaded in the window and provides methods to manipulate the DOM, such as selecting elements or modifying their content.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers-1">Describe the difference between a cookie, <code>sessionStorage</code> and <code>localStorage</code> in browsers</h3>

<p>All of the following are mechanisms of storing data on the client, the user's browser in this case. <code>localStorage</code> and <code>sessionStorage</code> both implement the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API">Web Storage API interface</a>.</p>
<ul>
<li><strong>Cookies</strong>: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.</li>
<li><strong><code>localStorage</code></strong>: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.</li>
<li><strong><code>sessionStorage</code></strong>: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.</li>
</ul>
<p>Here's a table summarizing the 3 client storage mechanisms.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td>Cookie</td><td><code>localStorage</code></td><td><code>sessionStorage</code></td></tr>
</thead>
<tbody>
<tr>
<td>Initiator</td><td>Client or server. Server can use <code>Set-Cookie</code> header</td><td>Client</td><td>Client</td></tr>
<tr>
<td>Lifespan</td><td>As specified</td><td>Until deleted</td><td>Until tab is closed</td></tr>
<tr>
<td>Persistent across browser sessions</td><td>If a future expiry date is set</td><td>Yes</td><td>No</td></tr>
<tr>
<td>Sent to server with every HTTP request</td><td>Yes, sent via <code>Cookie</code> header</td><td>No</td><td>No</td></tr>
<tr>
<td>Total capacity (per domain)</td><td>4kb</td><td>5MB</td><td>5MB</td></tr>
<tr>
<td>Access</td><td>Across windows/tabs</td><td>Across windows/tabs</td><td>Same tab</td></tr>
<tr>
<td>Security</td><td>JavaScript cannot access <code>HttpOnly</code> cookies</td><td>None</td><td>None</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-make-an-http-request-using-the-fetch-api">How do you make an HTTP request using the Fetch API?</h3>

<p>To make an HTTP request using the Fetch API, you can use the <code>fetch</code> function, which returns a promise. You can handle the response using <code>.then()</code> and <code>.catch()</code> for error handling. Here's a basic example of a GET request:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>For a POST request, you can pass an options object as the second argument to <code>fetch</code>:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://api.example.com/data'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">key</span>: <span class="hljs-string">'value'</span> }),
})
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-different-ways-to-make-an-api-call-in-javascript">What are the different ways to make an API call in JavaScript?</h3>

<p>In JavaScript, you can make API calls using several methods. The most common ones are <code>XMLHttpRequest</code>, <code>fetch</code>, and third-party libraries like <code>Axios</code>. <code>XMLHttpRequest</code> is the traditional way but is more verbose. <code>fetch</code> is modern and returns promises, making it easier to work with. <code>Axios</code> is a popular third-party library that simplifies API calls and provides additional features.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-ajax-in-as-much-detail-as-possible-1">Explain AJAX in as much detail as possible</h3>

<p>AJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like <code>XMLHttpRequest</code> or the <code>fetch()</code> API to send and receive data in the background. In modern web applications, the <code>fetch()</code> API is more commonly used to implement AJAX.</p>
<p><strong>Using <code>XMLHttpRequest</code></strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (xhr.readyState === XMLHttpRequest.DONE) {
    <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
      <span class="hljs-built_in">console</span>.log(xhr.responseText);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Request failed: '</span> + xhr.status);
    }
  }
};
xhr.open(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>, <span class="hljs-literal">true</span>);
xhr.send();
</code></pre>
<p><strong>Using <code>fetch()</code></strong></p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!response.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
    }
    <span class="hljs-keyword">return</span> response.json();
  })
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Fetch error:'</span>, error));
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-advantages-and-disadvantages-of-using-ajax-1">What are the advantages and disadvantages of using AJAX?</h3>

<p>AJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page.</p>
<p><strong>Advantages</strong></p>
<ul>
<li><strong>Smoother user experience</strong>: Updates happen without full page reloads, like in mail and chat applications.</li>
<li><strong>Lighter server Load</strong>: Only necessary data is fetched via AJAX, reducing server load and improving perceived performance of webpages.</li>
<li><strong>Maintains client state</strong>: User interactions and any client states are persisted within the page.</li>
</ul>
<p><strong>Disadvantages</strong></p>
<ul>
<li><strong>Reliance on JavaScript</strong>: If disabled, Ajax functionality breaks.</li>
<li><strong>Bookmarking issues</strong>: Dynamic content makes bookmarking specific page states difficult.</li>
<li><strong>SEO Challenges</strong>: Search engines may struggle to index dynamic content.</li>
<li><strong>Performance Concerns</strong>: Processing Ajax data on low-end devices can be slow.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers-1">What are the differences between <code>XMLHttpRequest</code> and <code>fetch()</code> in JavaScript and browsers?</h3>

<p><code>XMLHttpRequest</code> (XHR) and <code>fetch()</code> API are both used for asynchronous HTTP requests in JavaScript (AJAX). <code>fetch()</code> offers a cleaner syntax, promise-based approach, and more modern feature set compared to XHR. However, there are some differences:</p>
<ul>
<li><code>XMLHttpRequest</code> event callbacks, while <code>fetch()</code> utilizes promise chaining.</li>
<li><code>fetch()</code> provides more flexibility in headers and request bodies.</li>
<li><code>fetch()</code> support cleaner error handling with <code>catch()</code>.</li>
<li>Handling caching with <code>XMLHttpRequest</code> is difficult but caching is supported by <code>fetch()</code> by default in the <code>options.cache</code> object (<code>cache</code> value of second parameter) to <code>fetch()</code> or <code>Request()</code>.</li>
<li><code>fetch()</code> requires an <code>AbortController</code> for cancelation, while for <code>XMLHttpRequest</code>, it provides <code>abort()</code> property.</li>
<li><code>XMLHttpRequest</code> has good support for progress tracking, which <code>fetch()</code> lacks.</li>
<li><code>XMLHttpRequest</code> is only available in the browser and not natively supported in Node.js environments. On the other hand <code>fetch()</code> is part of the JavaScript language and is supported on all modern JavaScript runtimes.</li>
</ul>
<p>These days <code>fetch()</code> is preferred for its cleaner syntax and modern features.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-abort-a-web-request-using-abortcontroller-in-javascript-1">How do you abort a web request using <code>AbortController</code> in JavaScript?</h3>

<p><code>AbortController</code> is used to cancel ongoing asynchronous operations like fetch requests.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> AbortController();
<span class="hljs-keyword">const</span> signal = controller.signal;

fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>, { signal })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-comment">// Handle response</span>
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (error.name === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request aborted'</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);
    }
  });

<span class="hljs-comment">// Call abort() to abort the request</span>
controller.abort();
</code></pre>
<p>Aborting web requests is useful for:</p>
<ul>
<li>Canceling requests based on user actions.</li>
<li>Prioritizing the latest requests in scenarios with multiple simultaneous requests.</li>
<li>Canceling requests that are no longer needed, e.g. after the user has navigated away from the page.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-how-jsonp-works-and-how-its-not-really-ajax">Explain how JSONP works (and how it's not really Ajax)</h3>

<p>JSONP (JSON with Padding) is a technique used to overcome the same-origin policy in web browsers, allowing you to request data from a server in a different domain. It works by dynamically creating a <code>&lt;script&gt;</code> tag and setting its <code>src</code> attribute to the URL of the data source. The server responds with a script that calls a predefined callback function with the data as its argument. Unlike Ajax, JSONP does not use the XMLHttpRequest object and is limited to GET requests.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-workers-in-javascript-used-for-1">What are workers in JavaScript used for?</h3>

<p>Workers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface. Their key features include:</p>
<ul>
<li><strong>Parallel processing</strong>: Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks. It's useful for moving CPU-intensive work off the main thread and be free from JavaScript's single-threaded nature.</li>
<li><strong>Communication</strong>: Uses <code>postMessage()</code> and <code>onmessage</code>/ <code>'message'</code> event for messaging.</li>
<li><strong>Access to web APIs</strong>: Workers have access to various Web APIs, including <code>fetch()</code>, IndexedDB, and Web Storage, allowing them to perform tasks like data fetching and persisting data independently.</li>
<li><strong>No DOM access</strong>: Workers cannot directly manipulate the DOM, thus cannot interact with the UI, ensuring they don't accidentally interfere with the main thread's operation.</li>
</ul>
<p>There are three main types of workers in JavaScript:</p>
<ul>
<li><strong>Web workers / Dedicated workers</strong><ul>
<li>Run scripts in background threads, separate from the main UI thread.</li>
<li>Useful for CPU-intensive tasks like data processing, calculations, etc.</li>
<li>Cannot directly access or manipulate the DOM.</li>
</ul>
</li>
<li><strong>Service workers</strong><ul>
<li>Act as network proxies, handling requests between the app and network.</li>
<li>Enable offline functionality, caching, and push notifications.</li>
<li>Runs independently of the web page, even when it's closed.</li>
</ul>
</li>
<li><strong>Shared workers</strong><ul>
<li>Can be shared by multiple scripts running in different windows or frames, as long as they're in the same domain.</li>
<li>Scripts communicate with the shared worker by sending and receiving messages.</li>
<li>Useful for coordinating tasks across different parts of a web page.</li>
</ul>
</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-workers-in-javascript-used-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-the-web-socket-api">Explain the concept of the Web Socket API</h3>

<p>The WebSocket API provides a way to open a persistent connection between a client and a server, allowing for real-time, two-way communication. Unlike HTTP, which is request-response based, WebSocket enables full-duplex communication, meaning both the client and server can send and receive messages independently. This is particularly useful for applications like chat apps, live updates, and online gaming.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Example of creating a WebSocket connection</span>
<span class="hljs-keyword">const</span> socket = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">'ws://example.com/socket'</span>);

<span class="hljs-comment">// Event listener for when the connection is open</span>
socket.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  socket.send(<span class="hljs-string">'Hello Server!'</span>);
});

<span class="hljs-comment">// Event listener for when a message is received from the server</span>
socket.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message from server '</span>, event.data);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-web-socket-api/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-javascript-polyfills-for-1">What are JavaScript polyfills for?</h3>

<p>Polyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.</p>
<p>They can be implemented manually or included through libraries and are often used in conjunction with feature detection.</p>
<p>Common use cases include:</p>
<ul>
<li><strong>New JavaScript Methods</strong>: For example, <code>Array.prototype.includes()</code>, <code>Object.assign()</code>, etc.</li>
<li><strong>New APIs</strong>: Such as <code>fetch()</code>, <code>Promise</code>, <code>IntersectionObserver</code>, etc. Modern browsers support these now but for a long time they have to be polyfilled.</li>
</ul>
<p>Libraries and services for polyfills:</p>
<ul>
<li><p><strong><code>core-js</code></strong>: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'core-js/actual/array/flat-map'</span>; <span class="hljs-comment">// With this, Array.prototype.flatMap is available to be used.</span>

[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>].flatMap(<span class="hljs-function">(<span class="hljs-params">it</span>) =&gt;</span> [it, it]); <span class="hljs-comment">// =&gt; [1, 1, 2, 2]</span>
</code></pre>
</li>
<li><p><strong>Polyfill.io</strong>: A service that provides polyfills based on the features and user agents specified in the request.</p>
<pre><code class="lang-js">&lt;script src=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js"</span>&gt;&lt;/script&gt;
</code></pre>
</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-polyfills-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-detect-if-javascript-is-disabled-on-a-page">How do you detect if JavaScript is disabled on a page?</h3>

<p>To detect if JavaScript is disabled on a page, you can use the <code>&lt;noscript&gt;</code> HTML tag. This tag allows you to display content or messages to users who have JavaScript disabled in their browsers. For example, you can include a message within the <code>&lt;noscript&gt;</code> tag to inform users that JavaScript is required for the full functionality of the page.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">noscript</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    JavaScript is disabled in your browser. Please enable JavaScript for the
    best experience.
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">noscript</span>&gt;</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-intl-namespace-object-for">What is the <code>Intl</code> namespace object for?</h3>

<p>The <code>Intl</code> namespace object in JavaScript is used for internationalization purposes. It provides language-sensitive string comparison, number formatting, and date and time formatting. For example, you can use <code>Intl.DateTimeFormat</code> to format dates according to a specific locale:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> formatter = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">'en-US'</span>);
<span class="hljs-built_in">console</span>.log(formatter.format(date)); <span class="hljs-comment">// Outputs date in 'MM/DD/YYYY' format</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-intl-namespace-object-for/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-validate-form-elements-using-the-constraint-validation-api">How do you validate form elements using the Constraint Validation API?</h3>

<p>The Constraint Validation API provides a way to validate form elements in HTML. You can use properties like <code>validity</code>, <code>validationMessage</code>, and methods like <code>checkValidity()</code> and <code>setCustomValidity()</code>. For example, to check if an input is valid, you can use:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> input = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'input'</span>);
<span class="hljs-keyword">if</span> (input.checkValidity()) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Input is valid'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(input.validationMessage);
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-use-windowhistory-api">How do you use <code>window.history</code> API?</h3>

<p>The <code>window.history</code> API allows you to manipulate the browser's session history. You can use <code>history.pushState()</code> to add a new entry to the history stack, <code>history.replaceState()</code> to modify the current entry, and <code>history.back()</code>, <code>history.forward()</code>, and <code>history.go()</code> to navigate through the history. For example, <code>history.pushState({page: 1}, "title 1", "?page=1")</code> adds a new entry to the history.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-use-windowhistory-api/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-on-a-page-communicate">How do <code>&lt;iframe&gt;</code> on a page communicate?</h3>

<p><code>&lt;iframe&gt;</code> elements on a page can communicate using the <code>postMessage</code> API. This allows for secure cross-origin communication between the parent page and the iframe. The <code>postMessage</code> method sends a message, and the <code>message</code> event listener receives it. Here's a simple example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// In the parent page</span>
<span class="hljs-keyword">const</span> iframe = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'iframe'</span>);
iframe.contentWindow.postMessage(<span class="hljs-string">'Hello from parent'</span>, <span class="hljs-string">'*'</span>);

<span class="hljs-comment">// In the iframe</span>
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(event.data); <span class="hljs-comment">// 'Hello from parent'</span>
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-iframe-on-a-page-communicate/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-difference-between-document-load-event-and-document-domcontentloaded-event">Difference between document <code>load</code> event and document <code>DOMContentLoaded</code> event?</h3>

<p>The <code>DOMContentLoaded</code> event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The <code>load</code> event, on the other hand, fires when the entire page, including all dependent resources such as stylesheets and images, has finished loading.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'DOM fully loaded and parsed'</span>);
});

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Page fully loaded'</span>);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-redirect-to-a-new-page-in-javascript">How do you redirect to a new page in JavaScript?</h3>

<p>To redirect to a new page in JavaScript, you can use the <code>window.location</code> object. The most common methods are <code>window.location.href</code> and <code>window.location.replace()</code>. For example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Using window.location.href</span>
<span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">'https://www.example.com'</span>;

<span class="hljs-comment">// Using window.location.replace()</span>
<span class="hljs-built_in">window</span>.location.replace(<span class="hljs-string">'https://www.example.com'</span>);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-get-the-query-string-values-of-the-current-page-in-javascript">How do you get the query string values of the current page in JavaScript?</h3>

<p>To get the query string values of the current page in JavaScript, you can use the <code>URLSearchParams</code> object. First, create a <code>URLSearchParams</code> instance with <code>window.location.search</code>, then use the <code>get</code> method to retrieve specific query parameters. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> URLSearchParams(<span class="hljs-built_in">window</span>.location.search);
<span class="hljs-keyword">const</span> value = params.get(<span class="hljs-string">'key'</span>);
</code></pre>
<p>This will give you the value of the query parameter named <code>key</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-server-sent-events-1">What are server-sent events?</h3>

<p><a target="_blank" href="https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface">Server-sent events (SSE)</a> is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with <code>EventSource</code> instances that opens a connection with a server and allows client to receive events from the server. Connections created by server-sent events are persistent (similar to the <code>WebSocket</code>s), however there are a few differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Property</td><td><code>WebSocket</code></td><td><code>EventSource</code></td></tr>
</thead>
<tbody>
<tr>
<td>Direction</td><td>Bi-directional – both client and server can exchange messages</td><td>Unidirectional – only server sends data</td></tr>
<tr>
<td>Data type</td><td>Binary and text data</td><td>Only text</td></tr>
<tr>
<td>Protocol</td><td>WebSocket protocol (<code>ws://</code>)</td><td>Regular HTTP (<code>http://</code>)</td></tr>
</tbody>
</table>
</div><p><strong>Creating an event source</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> eventSource = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'/sse-stream'</span>);
</code></pre>
<p><strong>Listening for events</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Fired when the connection is established.</span>
eventSource.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connection opened'</span>);
});

<span class="hljs-comment">// Fired when a message is received from the server.</span>
eventSource.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received message:'</span>, event.data);
});

<span class="hljs-comment">// Fired when an error occurs.</span>
eventSource.addEventListener(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error occurred:'</span>, error);
});
</code></pre>
<p><strong>Sending events from server</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/sse-stream'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-comment">// `Content-Type` need to be set to `text/event-stream`.</span>
  res.setHeader(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/event-stream'</span>);
  res.setHeader(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'no-cache'</span>);
  res.setHeader(<span class="hljs-string">'Connection'</span>, <span class="hljs-string">'keep-alive'</span>);

  <span class="hljs-comment">// Each message should be prefixed with data.</span>
  <span class="hljs-keyword">const</span> sendEvent = <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> res.write(<span class="hljs-string">`data: <span class="hljs-subst">${data}</span>\n\n`</span>);

  sendEvent(<span class="hljs-string">'Hello from server'</span>);

  <span class="hljs-keyword">const</span> intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> sendEvent(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toString()), <span class="hljs-number">1000</span>);

  res.on(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Client closed connection'</span>);
    <span class="hljs-built_in">clearInterval</span>(intervalId);
  });
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server started on port 3000'</span>));
</code></pre>
<p>In this example, the server sends a "Hello from server" message initially, and then sends the current date every second. The connection is kept alive until the client closes it</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-server-sent-events/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-progressive-web-applications-pwas">What are Progressive Web Applications (PWAs)?</h3>

<p>Progressive Web Applications (PWAs) are web applications that use modern web capabilities to deliver an app-like experience to users. They are reliable, fast, and engaging. PWAs can work offline, send push notifications, and be installed on a user's home screen. They leverage technologies like service workers, web app manifests, and HTTPS to provide these features.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-progressive-web-applications-pwas/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-modules-and-why-are-they-useful">What are modules and why are they useful?</h3>

<p>Modules are reusable pieces of code that can be imported and exported between different files in a project. They help in organizing code, making it more maintainable and scalable. By using modules, you can avoid global namespace pollution and manage dependencies more effectively. In JavaScript, you can use <code>import</code> and <code>export</code> statements to work with modules.</p>
<pre><code class="lang-js"><span class="hljs-comment">// myModule.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, World!'</span>);
};

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> { myFunction } <span class="hljs-keyword">from</span> <span class="hljs-string">'./myModule.js'</span>;
myFunction(); <span class="hljs-comment">// Outputs: Hello, World!</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-modules-and-why-are-they-useful/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript-1">Explain the differences between CommonJS modules and ES modules in JavaScript</h3>

<p>In JavaScript, modules are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.</p>
<p><strong>CommonJS</strong> is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the <code>require()</code> function to load modules and the <code>module.exports</code> or <code>exports</code> object to define the exports of a module.</p>
<pre><code class="lang-js"><span class="hljs-comment">// my-module.js</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-number">42</span>;
<span class="hljs-built_in">module</span>.exports = { value };

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./my-module.js'</span>);
<span class="hljs-built_in">console</span>.log(myModule.value); <span class="hljs-comment">// 42</span>
</code></pre>
<p><strong>ES Modules</strong> (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the <code>import</code> and <code>export</code> statements to handle module dependencies.</p>
<pre><code class="lang-js"><span class="hljs-comment">// my-module.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> value = <span class="hljs-number">42</span>;

<span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> { value } <span class="hljs-keyword">from</span> <span class="hljs-string">'./my-module.js'</span>;
<span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 42</span>
</code></pre>
<p><strong>CommonJS vs ES modules</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>CommonJS</td><td>ES modules</td></tr>
</thead>
<tbody>
<tr>
<td>Module Syntax</td><td><code>require()</code> for importing <code>module.exports</code> for exporting</td><td><code>import</code> for importing <code>export</code> for exporting</td></tr>
<tr>
<td>Environment</td><td>Primarily used in Node.js for server-side development</td><td>Designed for both browser and server-side JavaScript (Node.js)</td></tr>
<tr>
<td>Loading</td><td>Synchronous loading of modules</td><td>Asynchronous loading of modules</td></tr>
<tr>
<td>Structure</td><td>Dynamic imports, can be conditionally called</td><td>Static imports/exports at the top level</td></tr>
<tr>
<td>File extensions</td><td><code>.js</code> (default)</td><td><code>.mjs</code> or <code>.js</code> (with <code>type: "module"</code> in <code>package.json</code>)</td></tr>
<tr>
<td>Browser support</td><td>Not natively supported in browsers</td><td>Natively supported in modern browsers</td></tr>
<tr>
<td>Optimization</td><td>Limited optimization due to dynamic nature</td><td>Allows for optimizations like tree-shaking due to static structure</td></tr>
<tr>
<td>Compatibility</td><td>Widely used in existing Node.js codebases and libraries</td><td>Newer standard, but gaining adoption in modern projects</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-import-and-export-modules-in-javascript">How do you import and export modules in JavaScript?</h3>

<p>In JavaScript, you can import and export modules using the <code>import</code> and <code>export</code> statements. To export a module, you can use <code>export</code> before a function, variable, or class, or use <code>export default</code> for a single default export. To import a module, you use the <code>import</code> statement followed by the name of the exported module and the path to the module file.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Exporting a module</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">/* ... */</span>
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> myFunction;

<span class="hljs-comment">// Importing a module</span>
<span class="hljs-keyword">import</span> { myFunction } <span class="hljs-keyword">from</span> <span class="hljs-string">'./myModule'</span>;
<span class="hljs-keyword">import</span> myFunction <span class="hljs-keyword">from</span> <span class="hljs-string">'./myModule'</span>;
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-import-and-export-modules-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-benefits-of-using-a-module-bundler">What are the benefits of using a module bundler?</h3>

<p>Using a module bundler like Webpack, Rollup, or Parcel helps manage dependencies, optimize performance, and improve the development workflow. It combines multiple JavaScript files into a single file or a few files, which reduces the number of HTTP requests and can include features like code splitting, tree shaking, and hot module replacement.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-a-module-bundler/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-tree-shaking-in-module-bundling">Explain the concept of tree shaking in module bundling</h3>

<p>Tree shaking is a technique used in module bundling to eliminate dead code, which is code that is never used or executed. This helps to reduce the final bundle size and improve application performance. It works by analyzing the dependency graph of the code and removing any unused exports. Tools like Webpack and Rollup support tree shaking when using ES6 module syntax (<code>import</code> and <code>export</code>).</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-metadata-fields-of-a-module">What are the metadata fields of a module?</h3>

<p>Metadata fields of a module typically include information such as the module's name, version, description, author, license, and dependencies. These fields are often found in a <code>package.json</code> file in JavaScript projects. For example:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-module"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A sample module"</span>,
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"John Doe"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.17.1"</span>
  }
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-metadata-fields-of-a-module/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-do-you-think-of-amd-vs-commonjs">What do you think of AMD vs CommonJS?</h3>

<p>AMD (Asynchronous Module Definition) and CommonJS are two JavaScript module systems. AMD is designed for asynchronous loading of modules, making it suitable for browsers. CommonJS is designed for synchronous loading, making it more suitable for server-side environments like Node.js. AMD uses <code>define</code> and <code>require</code> for defining and loading modules, while CommonJS uses <code>module.exports</code> and <code>require</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-do-you-think-of-amd-vs-commonjs/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-different-types-of-errors-in-javascript">What are the different types of errors in JavaScript?</h3>

<p>In JavaScript, there are three main types of errors: syntax errors, runtime errors, and logical errors. Syntax errors occur when the code violates the language's grammar rules, such as missing a parenthesis. Runtime errors happen during code execution, like trying to access a property of <code>undefined</code>. Logical errors are mistakes in the code's logic that lead to incorrect results but don't throw an error.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-types-of-errors-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-handle-errors-using-trycatch-blocks">How do you handle errors using <code>try...catch</code> blocks?</h3>

<p>To handle errors using <code>try...catch</code> blocks, you wrap the code that might throw an error inside a <code>try</code> block. If an error occurs, the control is transferred to the <code>catch</code> block where you can handle the error. Optionally, you can use a <code>finally</code> block to execute code regardless of whether an error occurred or not.</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// Code that may throw an error</span>
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// Handle the error</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-comment">// Code that will run regardless of an error</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-purpose-of-the-finally-block">What is the purpose of the <code>finally</code> block?</h3>

<p>The <code>finally</code> block in JavaScript is used to execute code after a <code>try</code> and <code>catch</code> block, regardless of whether an error was thrown or caught. It ensures that certain cleanup or finalization code runs no matter what. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// Code that may throw an error</span>
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-comment">// Code to handle the error</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-comment">// Code that will always run</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-finally-block/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-create-custom-error-objects">How can you create custom error objects?</h3>

<p>To create custom error objects in JavaScript, you can extend the built-in <code>Error</code> class. This allows you to add custom properties and methods to your error objects. Here's a quick example:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomError</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Error</span> </span>{
  <span class="hljs-keyword">constructor</span>(message) {
    <span class="hljs-built_in">super</span>(message);
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">'CustomError'</span>;
  }
}

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> CustomError(<span class="hljs-string">'This is a custom error message'</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.log(error.name); <span class="hljs-comment">// CustomError</span>
  <span class="hljs-built_in">console</span>.log(error.message); <span class="hljs-comment">// This is a custom error message</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-create-custom-error-objects/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-error-propagation-in-javascript">Explain the concept of error propagation in JavaScript</h3>

<p>Error propagation in JavaScript refers to how errors are passed through the call stack. When an error occurs in a function, it can be caught and handled using <code>try...catch</code> blocks. If not caught, the error propagates up the call stack until it is either caught or causes the program to terminate. For example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'An error occurred'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">b</span>(<span class="hljs-params"></span>) </span>{
  a();
}

<span class="hljs-keyword">try</span> {
  b();
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-built_in">console</span>.error(e.message); <span class="hljs-comment">// Outputs: An error occurred</span>
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-error-propagation-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-currying-and-how-does-it-work">What is currying and how does it work?</h3>

<p>Currying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function <code>f(a, b, c)</code> can be curried into <code>f(a)(b)(c)</code>. Here's a simple example in JavaScript:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">b</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">c</span>) </span>{
      <span class="hljs-keyword">return</span> a + b + c;
    };
  };
}

<span class="hljs-keyword">const</span> addOne = add(<span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> addOneAndTwo = addOne(<span class="hljs-number">2</span>);
<span class="hljs-keyword">const</span> result = addOneAndTwo(<span class="hljs-number">3</span>); <span class="hljs-comment">// result is 6</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-currying-and-how-does-it-work/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-partial-application">Explain the concept of partial application</h3>

<p>Partial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function <code>add(a, b)</code>, you can partially apply it to create a new function <code>add5</code> that always adds 5 to its argument.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">const</span> add5 = add.bind(<span class="hljs-literal">null</span>, <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(add5(<span class="hljs-number">10</span>)); <span class="hljs-comment">// Outputs 15</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-partial-application/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-benefits-of-using-currying-and-partial-application">What are the benefits of using currying and partial application?</h3>

<p>Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for more flexible and reusable code. Partial application, on the other hand, allows you to fix a few arguments of a function and generate a new function. Both techniques help in creating more modular and maintainable code.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-provide-some-examples-of-how-currying-and-partial-application-can-be-used">Provide some examples of how currying and partial application can be used</h3>

<p>Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. Partial application fixes a few arguments of a function, producing another function with a smaller number of arguments. For example, currying a function <code>add(a, b)</code> would look like <code>add(a)(b)</code>, while partial application of <code>add(2, b)</code> would fix the first argument to 2, resulting in a function that only needs the second argument.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Currying example</span>
<span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> a + b;
<span class="hljs-keyword">const</span> addTwo = add(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(addTwo(<span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>

<span class="hljs-comment">// Partial application example</span>
<span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
<span class="hljs-keyword">const</span> addTwo = add.bind(<span class="hljs-literal">null</span>, <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(addTwo(<span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-currying-and-partial-application-differ-from-each-other">How do currying and partial application differ from each other?</h3>

<p>Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. For example, a function <code>f(a, b, c)</code> becomes <code>f(a)(b)(c)</code>. Partial application, on the other hand, fixes a few arguments of a function and produces another function with a smaller number of arguments. For example, if you partially apply <code>f(a, b, c)</code> with <code>a</code>, you get a new function <code>f'(b, c)</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-sets-and-maps-and-how-are-they-used">What are <code>Set</code>s and <code>Map</code>s and how are they used?</h3>

<p><code>Set</code>s and <code>Map</code>s are built-in JavaScript objects that help manage collections of data. A <code>Set</code> is a collection of unique values, while a <code>Map</code> is a collection of key-value pairs where keys can be of any type. <code>Set</code>s are useful for storing unique items, and <code>Map</code>s are useful for associating values with keys.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Set example</span>
<span class="hljs-keyword">let</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>]);
mySet.add(<span class="hljs-number">4</span>); <span class="hljs-comment">// Set {1, 2, 3, 4}</span>

<span class="hljs-comment">// Map example</span>
<span class="hljs-keyword">let</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
myMap.set(<span class="hljs-string">'key1'</span>, <span class="hljs-string">'value1'</span>);
myMap.set(<span class="hljs-string">'key2'</span>, <span class="hljs-string">'value2'</span>);
<span class="hljs-built_in">console</span>.log(myMap.get(<span class="hljs-string">'key1'</span>)); <span class="hljs-comment">// 'value1'</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-sets-and-maps-and-how-are-they-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript-1">What are the differences between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript?</h3>

<p>The primary difference between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript lies in how they handle keys. Here's a breakdown:</p>
<p><strong><code>Map</code> vs. <code>WeakMap</code></strong></p>
<p><code>Map</code>s allows any data type (strings, numbers, objects) as keys. The key-value pairs remain in memory as long as the <code>Map</code> object itself is referenced. Thus they are suitable for general-purpose key-value storage where you want to maintain references to both keys and values. Common use cases include storing user data, configuration settings, or relationships between objects.</p>
<p><code>WeakMap</code>s only allows objects as keys. However, these object keys are held weakly. This means the garbage collector can remove them from memory even if the <code>WeakMap</code> itself still exists, as long as there are no other references to those objects. <code>WeakMap</code>s are ideal for scenarios where you want to associate data with objects without preventing those objects from being garbage collected. This can be useful for things like:</p>
<ul>
<li>Caching data based on objects without preventing garbage collection of the objects themselves.</li>
<li>Storing private data associated with DOM nodes without affecting their lifecycle.</li>
</ul>
<p><strong><code>Set</code> vs. <code>WeakSet</code></strong></p>
<p>Similar to <code>Map</code>, <code>Set</code>s allow any data type as keys. The elements within a <code>Set</code> must be unique. <code>Set</code>s are useful for storing unique values and checking for membership efficiently. Common use cases include removing duplicates from arrays or keeping track of completed tasks.</p>
<p>On the other hand, <code>WeakSet</code> only allows objects as elements, and these object elements are held weakly, similar to <code>WeakMap</code> keys. <code>WeakSet</code>s are less commonly used, but applicable when you want a collection of unique objects without affecting their garbage collection. This might be necessary for:</p>
<ul>
<li>Tracking DOM nodes that have been interacted with without affecting their memory management.</li>
<li>Implementing custom object weak references for specific use cases.</li>
</ul>
<p><strong>Here's a table summarizing the key differences:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Map</td><td>WeakMap</td><td>Set</td><td>WeakSet</td></tr>
</thead>
<tbody>
<tr>
<td>Key Types</td><td>Any data type</td><td>Objects (weak references)</td><td>Any data type (unique)</td><td>Objects (weak references, unique)</td></tr>
<tr>
<td>Garbage Collection</td><td>Keys and values are not garbage collected</td><td>Keys can be garbage collected if not referenced elsewhere</td><td>Elements are not garbage collected</td><td>Elements can be garbage collected if not referenced elsewhere</td></tr>
<tr>
<td>Use Cases</td><td>General-purpose key-value storage</td><td>Caching, private DOM node data</td><td>Removing duplicates, membership checks</td><td>Object weak references, custom use cases</td></tr>
</tbody>
</table>
</div><p><strong>Choosing between them</strong></p>
<ul>
<li>Use <code>Map</code> and <code>Set</code> for most scenarios where you need to store key-value pairs or unique elements and want to maintain references to both the keys/elements and the values.</li>
<li>Use <code>WeakMap</code> and <code>WeakSet</code> cautiously in specific situations where you want to associate data with objects without affecting their garbage collection. Be aware of the implications of weak references and potential memory leaks if not used correctly.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-convert-a-set-to-an-array-in-javascript">How do you convert a <code>Set</code> to an array in JavaScript?</h3>

<p>To convert a <code>Set</code> to an array in JavaScript, you can use the <code>Array.from()</code> method or the spread operator. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);
<span class="hljs-keyword">const</span> myArray = <span class="hljs-built_in">Array</span>.from(mySet);
<span class="hljs-comment">// or</span>
<span class="hljs-keyword">const</span> myArray = [...mySet];
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript-1">What is the difference between a <code>Map</code> object and a plain object in JavaScript?</h3>

<p>Both <code>Map</code> objects and plain objects in JavaScript can store key-value pairs, but they have several key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><code>Map</code></td><td>Plain object</td></tr>
</thead>
<tbody>
<tr>
<td>Key type</td><td>Any data type</td><td>String (or Symbol)</td></tr>
<tr>
<td>Key order</td><td>Maintained</td><td>Not guaranteed</td></tr>
<tr>
<td>Size property</td><td>Yes (<code>size</code>)</td><td>None</td></tr>
<tr>
<td>Iteration</td><td><code>forEach</code>, <code>keys()</code>, <code>values()</code>, <code>entries()</code></td><td><code>for...in</code>, <code>Object.keys()</code>, etc.</td></tr>
<tr>
<td>Inheritance</td><td>No</td><td>Yes</td></tr>
<tr>
<td>Performance</td><td>Generally better for larger datasets and frequent additions/deletions</td><td>Faster for small datasets and simple operations</td></tr>
<tr>
<td>Serializable</td><td>No</td><td>Yes</td></tr>
</tbody>
</table>
</div>
<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-sets-and-maps-handle-equality-checks-for-objects">How do <code>Set</code>s and <code>Map</code>s handle equality checks for objects?</h3>

<p><code>Set</code>s and <code>Map</code>s in JavaScript handle equality checks for objects based on reference equality, not deep equality. This means that two objects are considered equal only if they reference the same memory location. For example, if you add two different object literals with the same properties to a <code>Set</code>, they will be treated as distinct entries.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> set = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };

set.add(obj1);
set.add(obj2);

<span class="hljs-built_in">console</span>.log(set.size); <span class="hljs-comment">// Output: 2</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-common-performance-bottlenecks-in-javascript-applications">What are some common performance bottlenecks in JavaScript applications?</h3>

<p>Common performance bottlenecks in JavaScript applications include inefficient DOM manipulation, excessive use of global variables, blocking the main thread with heavy computations, memory leaks, and improper use of asynchronous operations. To mitigate these issues, you can use techniques like debouncing and throttling, optimizing DOM updates, and leveraging web workers for heavy computations.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-debouncing-and-throttling">Explain the concept of debouncing and throttling</h3>

<p>Debouncing and throttling are techniques used to control the rate at which a function is executed. Debouncing ensures that a function is only called after a specified delay has passed since the last time it was invoked. Throttling ensures that a function is called at most once in a specified time interval.</p>
<p>Debouncing delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">debounce</span>(<span class="hljs-params">func, delay</span>) </span>{
  <span class="hljs-keyword">let</span> timeoutId;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">clearTimeout</span>(timeoutId);
    timeoutId = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> func.apply(<span class="hljs-built_in">this</span>, args), delay);
  };
}
</code></pre>
<p>Throttling ensures that a function is called at most once in a specified time interval. This is useful for scenarios like window resizing or scrolling where you want to limit the number of times a function is called.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">throttle</span>(<span class="hljs-params">func, limit</span>) </span>{
  <span class="hljs-keyword">let</span> inThrottle;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">if</span> (!inThrottle) {
      func.apply(<span class="hljs-built_in">this</span>, args);
      inThrottle = <span class="hljs-literal">true</span>;
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> (inThrottle = <span class="hljs-literal">false</span>), limit);
    }
  };
}
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-optimize-dom-manipulation-for-better-performance">How can you optimize DOM manipulation for better performance?</h3>

<p>To optimize DOM manipulation for better performance, minimize direct DOM access and updates. Use techniques like batching DOM changes, using <code>documentFragment</code> for multiple elements, and leveraging virtual DOM libraries like React. Also, consider using <code>requestAnimationFrame</code> for animations and avoid layout thrashing by reading and writing DOM properties separately.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-techniques-for-reducing-reflows-and-repaints">What are some techniques for reducing reflows and repaints?</h3>

<p>To reduce reflows and repaints, you can minimize DOM manipulations, batch DOM changes, use CSS classes for style changes, avoid complex CSS selectors, and use <code>requestAnimationFrame</code> for animations. Additionally, consider using <code>will-change</code> for elements that will change frequently and avoid layout thrashing by reading and writing to the DOM separately.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance">Explain the concept of lazy loading and how it can improve performance</h3>

<p>Lazy loading is a design pattern that delays the loading of resources until they are actually needed. This can significantly improve performance by reducing initial load times and conserving bandwidth. For example, images on a webpage can be lazy-loaded so that they only load when they come into the viewport. This can be achieved using the <code>loading="lazy"</code> attribute in HTML or by using JavaScript libraries.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">"lazy"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Lazy loaded image"</span> /&gt;</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-web-workers-and-how-can-they-be-used-to-improve-performance">What are Web Workers and how can they be used to improve performance?</h3>

<p>Web Workers are a way to run JavaScript in the background, separate from the main execution thread of a web application. This helps in performing heavy computations without blocking the user interface. You can create a Web Worker using the <code>Worker</code> constructor and communicate with it using the <code>postMessage</code> and <code>onmessage</code> methods.</p>
<pre><code class="lang-js"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">'worker.js'</span>);
worker.postMessage(<span class="hljs-string">'Hello, worker!'</span>);

worker.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message from worker:'</span>, event.data);
};

<span class="hljs-comment">// worker.js</span>
onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message from main script:'</span>, event.data);
  postMessage(<span class="hljs-string">'Hello, main script!'</span>);
};
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance">Explain the concept of caching and how it can be used to improve performance</h3>

<p>Caching is a technique used to store copies of files or data in a temporary storage location to reduce the time it takes to access them. It improves performance by reducing the need to fetch data from the original source repeatedly. In front end development, caching can be implemented using browser cache, service workers, and HTTP headers like <code>Cache-Control</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance">What are some tools that can be used to measure and analyze JavaScript performance?</h3>

<p>To measure and analyze JavaScript performance, you can use tools like Chrome DevTools, Lighthouse, WebPageTest, and JSPerf. Chrome DevTools provides a Performance panel for profiling, Lighthouse offers audits for performance metrics, WebPageTest allows for detailed performance testing, and JSPerf helps in comparing the performance of different JavaScript snippets.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-optimize-network-requests-for-better-performance">How can you optimize network requests for better performance?</h3>

<p>To optimize network requests for better performance, you can minimize the number of requests, use caching, compress data, and leverage modern web technologies like HTTP/2 and service workers. For example, you can combine multiple CSS files into one to reduce the number of requests, use <code>Cache-Control</code> headers to cache static assets, and enable Gzip compression on your server to reduce the size of the data being transferred.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-optimize-network-requests-for-better-performance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-the-different-types-of-testing-in-software-development">What are the different types of testing in software development?</h3>

<p>In software development, there are several types of testing to ensure the quality and functionality of the application. These include unit testing, integration testing, system testing, and acceptance testing. Unit testing focuses on individual components, integration testing checks the interaction between components, system testing evaluates the entire system, and acceptance testing ensures the software meets user requirements.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-types-of-testing-in-software-development/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing">Explain the difference between unit testing, integration testing, and end-to-end testing</h3>

<p>Unit testing focuses on testing individual components or functions in isolation to ensure they work as expected. Integration testing checks how different modules or services work together. End-to-end testing simulates real user scenarios to verify the entire application flow from start to finish.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-popular-javascript-testing-frameworks">What are some popular JavaScript testing frameworks?</h3>

<p>Some popular JavaScript testing frameworks include Jest, Mocha, Jasmine, and Cypress. Jest is known for its simplicity and integration with React. Mocha is highly flexible and often used with other libraries like Chai for assertions. Jasmine is a behavior-driven development framework that requires no additional libraries. Cypress is an end-to-end testing framework that provides a great developer experience.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-popular-javascript-testing-frameworks/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-write-unit-tests-for-javascript-code">How do you write unit tests for JavaScript code?</h3>

<p>To write unit tests for JavaScript code, you typically use a testing framework like Jest or Mocha. First, you set up your testing environment by installing the necessary libraries. Then, you write test cases using functions like <code>describe</code>, <code>it</code>, or <code>test</code> to define your tests. Each test case should focus on a small, isolated piece of functionality. You use assertions to check if the output of your code matches the expected result.</p>
<p>Example using Jest:</p>
<pre><code class="lang-js"><span class="hljs-comment">// sum.js</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
<span class="hljs-built_in">module</span>.exports = sum;

<span class="hljs-comment">// sum.test.js</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sum'</span>);

test(<span class="hljs-string">'adds 1 + 2 to equal 3'</span>, <span class="hljs-function">() =&gt;</span> {
  expect(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)).toBe(<span class="hljs-number">3</span>);
});
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-write-unit-tests-for-javascript-code/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-test-driven-development-tdd">Explain the concept of test-driven development (TDD)</h3>

<p>Test-driven development (TDD) is a software development approach where you write tests before writing the actual code. The process involves writing a failing test, writing the minimum code to pass the test, and then refactoring the code while keeping the tests passing. This ensures that the code is always tested and helps in maintaining high code quality.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-test-driven-development-tdd/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-mocks-and-stubs-and-how-are-they-used-in-testing">What are mocks and stubs and how are they used in testing?</h3>

<p>Mocks and stubs are tools used in testing to simulate the behavior of real objects. Stubs provide predefined responses to function calls, while mocks are more complex and can verify interactions, such as whether a function was called and with what arguments. Stubs are used to isolate the code being tested from external dependencies, and mocks are used to ensure that the code interacts correctly with those dependencies.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-test-asynchronous-code-in-javascript">How can you test asynchronous code in JavaScript?</h3>

<p>To test asynchronous code in JavaScript, you can use testing frameworks like Jest or Mocha. These frameworks provide built-in support for handling asynchronous operations. You can use <code>async</code>/<code>await</code> or return promises in your test functions. For example, in Jest, you can write:</p>
<pre><code class="lang-js">test(<span class="hljs-string">'fetches data successfully'</span>, <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetchData();
  expect(data).toBeDefined();
});
</code></pre>
<p>Alternatively, you can use callbacks and the <code>done</code> function to signal the end of an asynchronous test.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-test-asynchronous-code-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-best-practices-for-writing-maintainable-and-effective-tests-in-javascript">What are some best practices for writing maintainable and effective tests in JavaScript?</h3>

<p>To write maintainable and effective tests, ensure they are clear, concise, and focused on a single behavior. Use descriptive names for test cases and avoid hardcoding values. Mock external dependencies and keep tests isolated. Regularly review and refactor tests to keep them up-to-date with the codebase.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality">Explain the concept of code coverage and how it can be used to assess test quality</h3>

<p>Code coverage is a metric that measures the percentage of code that is executed when the test suite runs. It helps in assessing the quality of tests by identifying untested parts of the codebase. Higher code coverage generally indicates more thorough testing, but it doesn't guarantee the absence of bugs. Tools like Istanbul or Jest can be used to measure code coverage.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-tools-that-can-be-used-for-javascript-testing">What are some tools that can be used for JavaScript testing?</h3>

<p>For JavaScript testing, you can use tools like Jest, Mocha, Jasmine, and Cypress. Jest is popular for its ease of use and built-in features. Mocha is flexible and can be paired with other libraries. Jasmine is known for its simplicity and behavior-driven development (BDD) style. Cypress is great for end-to-end testing with a focus on real browser interactions.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-design-patterns-and-why-are-they-useful">What are design patterns and why are they useful?</h3>

<p>Design patterns are reusable solutions to common problems in software design. They provide a template for how to solve a problem that can be used in many different situations. They are useful because they help developers avoid common pitfalls, improve code readability, and make it easier to maintain and scale applications.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-design-patterns-and-why-are-they-useful/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-the-singleton-pattern">Explain the concept of the Singleton pattern</h3>

<p>The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system. In JavaScript, this can be implemented using closures or ES6 classes.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (!Singleton.instance) {
      Singleton.instance = <span class="hljs-built_in">this</span>;
    }
    <span class="hljs-keyword">return</span> Singleton.instance;
  }
}

<span class="hljs-keyword">const</span> instance1 = <span class="hljs-keyword">new</span> Singleton();
<span class="hljs-keyword">const</span> instance2 = <span class="hljs-keyword">new</span> Singleton();

<span class="hljs-built_in">console</span>.log(instance1 === instance2); <span class="hljs-comment">// true</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-singleton-pattern/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-factory-pattern-and-how-is-it-used">What is the Factory pattern and how is it used?</h3>

<p>The Factory pattern is a design pattern used to create objects without specifying the exact class of the object that will be created. It provides a way to encapsulate the instantiation logic and can be particularly useful when the creation process is complex or when the type of object to be created is determined at runtime.</p>
<p>For example, in JavaScript, you can use a factory function to create different types of objects:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createAnimal</span>(<span class="hljs-params">type</span>) </span>{
  <span class="hljs-keyword">if</span> (type === <span class="hljs-string">'dog'</span>) {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">sound</span>: <span class="hljs-string">'woof'</span> };
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (type === <span class="hljs-string">'cat'</span>) {
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">sound</span>: <span class="hljs-string">'meow'</span> };
  }
}

<span class="hljs-keyword">const</span> dog = createAnimal(<span class="hljs-string">'dog'</span>);
<span class="hljs-keyword">const</span> cat = createAnimal(<span class="hljs-string">'cat'</span>);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-observer-pattern-and-its-use-cases">Explain the Observer pattern and its use cases</h3>

<p>The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of any state changes. This pattern is useful for implementing distributed event-handling systems, such as updating the user interface in response to data changes or implementing event-driven architectures.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-observer-pattern-and-its-use-cases/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-module-pattern-and-how-does-it-help-with-encapsulation">What is the Module pattern and how does it help with encapsulation?</h3>

<p>The Module pattern in JavaScript is a design pattern used to create self-contained modules of code. It helps with encapsulation by allowing you to define private and public members within a module. Private members are not accessible from outside the module, while public members are exposed through a returned object. This pattern helps in organizing code, avoiding global namespace pollution, and maintaining a clean separation of concerns.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> myModule = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> privateVar = <span class="hljs-string">'I am private'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">privateMethod</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(privateVar);
  }

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">publicMethod</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      privateMethod();
    },
  };
})();

myModule.publicMethod(); <span class="hljs-comment">// Logs: I am private</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-the-prototype-pattern">Explain the concept of the Prototype pattern</h3>

<p>The Prototype pattern is a creational design pattern used to create new objects by copying an existing object, known as the prototype. This pattern is useful when the cost of creating a new object is more expensive than cloning an existing one. In JavaScript, this can be achieved using the <code>Object.create</code> method or by using the <code>prototype</code> property of a constructor function.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> prototypeObject = {
  greet() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, world!'</span>);
  },
};

<span class="hljs-keyword">const</span> newObject = <span class="hljs-built_in">Object</span>.create(prototypeObject);
newObject.greet(); <span class="hljs-comment">// Outputs: Hello, world!</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-prototype-pattern/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-decorator-pattern-and-how-is-it-used">What is the Decorator pattern and how is it used?</h3>

<p>The Decorator pattern is a structural design pattern that allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. It is used to extend the functionalities of objects by wrapping them with additional behavior. In JavaScript, this can be achieved using higher-order functions or classes.</p>
<p>For example, if you have a <code>Car</code> class and you want to add features like <code>GPS</code> or <code>Sunroof</code> without modifying the <code>Car</code> class itself, you can create decorators for these features.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
  drive() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Driving'</span>;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CarDecorator</span> </span>{
  <span class="hljs-keyword">constructor</span>(car) {
    <span class="hljs-built_in">this</span>.car = car;
  }

  drive() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.car.drive();
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GPSDecorator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CarDecorator</span> </span>{
  drive() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">super</span>.drive()}</span> with GPS`</span>;
  }
}

<span class="hljs-keyword">const</span> myCar = <span class="hljs-keyword">new</span> Car();
<span class="hljs-keyword">const</span> myCarWithGPS = <span class="hljs-keyword">new</span> GPSDecorator(myCar);
<span class="hljs-built_in">console</span>.log(myCarWithGPS.drive()); <span class="hljs-comment">// "Driving with GPS"</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-the-strategy-pattern">Explain the concept of the Strategy pattern</h3>

<p>The Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Context</span> </span>{
  <span class="hljs-keyword">constructor</span>(strategy) {
    <span class="hljs-built_in">this</span>.strategy = strategy;
  }

  executeStrategy(data) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.strategy.doAlgorithm(data);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteStrategyA</span> </span>{
  doAlgorithm(data) {
    <span class="hljs-comment">// Implementation of algorithm A</span>
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteStrategyB</span> </span>{
  doAlgorithm(data) {
    <span class="hljs-comment">// Implementation of algorithm B</span>
  }
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> context = <span class="hljs-keyword">new</span> Context(<span class="hljs-keyword">new</span> ConcreteStrategyA());
context.executeStrategy(data);
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-the-command-pattern-and-how-is-it-used">What is the Command pattern and how is it used?</h3>

<p>The Command pattern is a behavioral design pattern that turns a request into a stand-alone object containing all information about the request. This transformation allows for parameterization of methods with different requests, queuing of requests, and logging of the requests. It also supports undoable operations. In JavaScript, it can be implemented by creating command objects with <code>execute</code> and <code>undo</code> methods.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Command</span> </span>{
  execute() {}
  undo() {}
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LightOnCommand</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Command</span> </span>{
  <span class="hljs-keyword">constructor</span>(light) {
    <span class="hljs-built_in">super</span>();
    <span class="hljs-built_in">this</span>.light = light;
  }
  execute() {
    <span class="hljs-built_in">this</span>.light.on();
  }
  undo() {
    <span class="hljs-built_in">this</span>.light.off();
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Light</span> </span>{
  on() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Light is on'</span>);
  }
  off() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Light is off'</span>);
  }
}

<span class="hljs-keyword">const</span> light = <span class="hljs-keyword">new</span> Light();
<span class="hljs-keyword">const</span> lightOnCommand = <span class="hljs-keyword">new</span> LightOnCommand(light);
lightOnCommand.execute(); <span class="hljs-comment">// Light is on</span>
lightOnCommand.undo(); <span class="hljs-comment">// Light is off</span>
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-command-pattern-and-how-is-it-used/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-why-is-extending-built-in-javascript-objects-not-a-good-idea-1">Why is extending built-in JavaScript objects not a good idea?</h3>

<p>Extending a built-in/native JavaScript object means adding properties/functions to its <code>prototype</code>. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the <code>Array.prototype</code> by adding the same <code>contains</code> method, the implementations will overwrite each other and your code will have unpredictable behavior if these two methods do not work the same way.</p>
<p>The only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-cross-site-scripting-xss-and-how-can-you-prevent-it">What is Cross-Site Scripting (XSS) and how can you prevent it?</h3>

<p>Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. This can lead to data theft, session hijacking, and other malicious activities. To prevent XSS, you should validate and sanitize user inputs, use Content Security Policy (CSP), and escape data before rendering it in the browser.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques">Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques</h3>

<p>Cross-Site Request Forgery (CSRF) is an attack where a malicious website tricks a user's browser into making an unwanted request to another site where the user is authenticated. This can lead to unauthorized actions being performed on behalf of the user. Mitigation techniques include using anti-CSRF tokens, SameSite cookies, and ensuring proper CORS configurations.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications">How can you prevent SQL injection vulnerabilities in JavaScript applications?</h3>

<p>To prevent SQL injection vulnerabilities in JavaScript applications, always use parameterized queries or prepared statements instead of string concatenation to construct SQL queries. This ensures that user input is treated as data and not executable code. Additionally, use ORM libraries that handle SQL injection prevention for you, and always validate and sanitize user inputs.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-best-practices-for-handling-sensitive-data-in-javascript">What are some best practices for handling sensitive data in JavaScript?</h3>

<p>Handling sensitive data in JavaScript requires careful attention to security practices. Avoid storing sensitive data in client-side storage like localStorage or sessionStorage. Use HTTPS to encrypt data in transit. Implement proper authentication and authorization mechanisms. Sanitize and validate all inputs to prevent injection attacks. Consider using environment variables for sensitive data in server-side code.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security">Explain the concept of Content Security Policy (CSP) and how it enhances security</h3>

<p>Content Security Policy (CSP) is a security feature that helps prevent various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks, by specifying which content sources are trusted. It works by allowing developers to define a whitelist of trusted sources for content like scripts, styles, and images. This is done through HTTP headers or meta tags. For example, you can use the <code>Content-Security-Policy</code> header to specify that only scripts from your own domain should be executed:</p>
<pre><code class="lang-http"><span class="hljs-attribute">Content-Security-Policy</span>: script-src 'self'
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-common-security-headers-and-their-purpose">What are some common security headers and their purpose?</h3>

<p>Security headers are HTTP response headers that help protect web applications from various attacks. Some common security headers include:</p>
<ul>
<li><code>Content-Security-Policy (CSP)</code>: Prevents cross-site scripting (XSS) and other code injection attacks by specifying allowed content sources.</li>
<li><code>X-Content-Type-Options</code>: Prevents MIME type sniffing by instructing the browser to follow the declared <code>Content-Type</code>.</li>
<li><code>Strict-Transport-Security (HSTS)</code>: Enforces secure (HTTPS) connections to the server.</li>
<li><code>X-Frame-Options</code>: Prevents clickjacking by controlling whether a page can be displayed in a frame.</li>
<li><code>X-XSS-Protection</code>: Enables the cross-site scripting (XSS) filter built into most browsers.</li>
<li><code>Referrer-Policy</code>: Controls how much referrer information is included with requests.</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-common-security-headers-and-their-purpose/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-prevent-clickjacking-attacks">How can you prevent clickjacking attacks?</h3>

<p>To prevent clickjacking attacks, you can use the <code>X-Frame-Options</code> HTTP header to control whether your site can be embedded in iframes. Set it to <code>DENY</code> to prevent all framing, or <code>SAMEORIGIN</code> to allow framing only from the same origin. Additionally, you can use the <code>Content-Security-Policy</code> (CSP) header with the <code>frame-ancestors</code> directive to specify which origins are allowed to frame your content.</p>
<pre><code class="lang-http"><span class="hljs-attribute">X-Frame-Options</span>: DENY
</code></pre>
<pre><code class="lang-http"><span class="hljs-attribute">Content-Security-Policy</span>: frame-ancestors 'self'
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-prevent-clickjacking-attacks/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-concept-of-input-validation-and-its-importance-in-security">Explain the concept of input validation and its importance in security</h3>

<p>Input validation is the process of ensuring that user input is correct, safe, and meets the application's requirements. It is crucial for security because it helps prevent attacks like SQL injection, cross-site scripting (XSS), and other forms of data manipulation. By validating input, you ensure that only properly formatted data enters your system, reducing the risk of malicious data causing harm.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code">What are some tools and techniques for identifying security vulnerabilities in JavaScript code?</h3>

<p>To identify security vulnerabilities in JavaScript code, you can use static code analysis tools like ESLint with security plugins, dynamic analysis tools like OWASP ZAP, and dependency checkers like npm audit. Additionally, manual code reviews and adhering to secure coding practices are essential techniques.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications">How can you implement secure authentication and authorization in JavaScript applications?</h3>

<p>To implement secure authentication and authorization in JavaScript applications, use HTTPS to encrypt data in transit, and store sensitive data like tokens securely using <code>localStorage</code> or <code>sessionStorage</code>. Implement token-based authentication using JWTs, and validate tokens on the server side. Use libraries like OAuth for third-party authentication and ensure proper role-based access control (RBAC) for authorization.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-the-same-origin-policy-with-regards-to-javascript">Explain the same-origin policy with regards to JavaScript</h3>

<p>The same-origin policy is a security measure implemented in web browsers to prevent malicious scripts on one page from accessing data on another page. It ensures that web pages can only make requests to the same origin, where the origin is defined by the combination of the protocol, domain, and port. For example, a script from <code>http://example.com</code> cannot access data from <code>http://anotherdomain.com</code>.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-is-use-strict-in-javascript-for-1">What is <code>'use strict';</code> in JavaScript for?</h3>

<p><code>'use strict'</code> is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.</p>
<p><strong>Advantages</strong></p>
<ul>
<li>Makes it impossible to accidentally create global variables.</li>
<li>Makes assignments which would otherwise silently fail to throw an exception.</li>
<li>Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).</li>
<li>Requires that function parameter names be unique.</li>
<li><code>this</code> is <code>undefined</code> in the global context.</li>
<li>It catches some common coding bloopers, throwing exceptions.</li>
<li>It disables features that are confusing or poorly thought out.</li>
</ul>
<p><strong>Disadvantages</strong></p>
<ul>
<li>Many missing features that some developers might be used to.</li>
<li>No more access to <code>function.caller</code> and <code>function.arguments</code>.</li>
<li>Concatenation of scripts written in different strict modes might cause issues.</li>
</ul>
<p>Overall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-tools-and-techniques-do-you-use-for-debugging-javascript-code-1">What tools and techniques do you use for debugging JavaScript code?</h3>

<p>Some of the most commonly used tools and techniques for debugging JavaScript:</p>
<ul>
<li>JavaScript language<ul>
<li><code>console</code> methods (e.g. <code>console.log()</code>, <code>console.error()</code>, <code>console.warn()</code>, <code>console.table()</code>)</li>
<li><code>debugger</code> statement</li>
</ul>
</li>
<li>Breakpoints (browser or IDE)</li>
<li>JavaScript frameworks<ul>
<li><a target="_blank" href="https://github.com/facebook/react-devtools">React Devtools</a></li>
<li><a target="_blank" href="https://github.com/gaearon/redux-devtools">Redux Devtools</a></li>
<li><a target="_blank" href="https://github.com/vuejs/vue-devtools">Vue Devtools</a></li>
</ul>
</li>
<li>Browser developer tools<ul>
<li><strong>Chrome DevTools</strong>: The most widely used tool for debugging JavaScript. It provides a rich set of features including the ability to set breakpoints, inspect variables, view the call stack, and more.</li>
<li><strong>Firefox Developer Tools</strong>: Similar to Chrome DevTools with its own set of features for debugging.</li>
<li><strong>Safari Web Inspector</strong>: Provides tools for debugging on Safari.</li>
<li><strong>Edge Developer Tools</strong>: Similar to Chrome DevTools, as Edge is now Chromium-based.</li>
</ul>
</li>
<li>Network requests<ul>
<li><strong>Postman</strong>: Useful for debugging API calls.</li>
<li><strong>Fiddler</strong>: Helps capture and inspect HTTP/HTTPS traffic.</li>
<li><strong>Charles Proxy</strong>: Another tool for intercepting and debugging network calls.</li>
</ul>
</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-does-javascript-garbage-collection-work-1">How does JavaScript garbage collection work?</h3>

<p>Garbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.</p>
<p><strong>Mark-and-sweep</strong></p>
<p>The most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:</p>
<ul>
<li><strong>Marking phase</strong>: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as "in-use".</li>
<li><strong>Sweeping phase</strong>: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.</li>
</ul>
<p>This algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.</p>
<p><strong>Generational garbage collection</strong></p>
<p>Leveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.</p>
<p>Different JavaScript engines (differs according to browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-javascript-garbage-collection-work/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly">Explain what a single page app is and how to make one SEO-friendly</h3>

<p>A single page application (SPA) is a web application that loads a single HTML page and dynamically updates content as the user interacts with the app. This approach provides a more fluid user experience but can be challenging for SEO because search engines may not execute JavaScript to render content. To make an SPA SEO-friendly, you can use server-side rendering (SSR) or static site generation (SSG) to ensure that search engines can index your content. Tools like Next.js for React or Nuxt.js for Vue.js can help achieve this.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-can-you-share-code-between-javascript-files">How can you share code between JavaScript files?</h3>

<p>To share code between JavaScript files, you can use modules. In modern JavaScript, you can use ES6 modules with <code>export</code> and <code>import</code> statements. For example, you can export a function from one file and import it into another:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// file1.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, world!'</span>);
}

<span class="hljs-comment">// file2.js</span>
<span class="hljs-keyword">import</span> { greet } <span class="hljs-keyword">from</span> <span class="hljs-string">'./file1.js'</span>;
greet();
</code></pre>
<p>Alternatively, in Node.js, you can use <code>module.exports</code> and <code>require</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// file1.js</span>
<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, world!'</span>);
};

<span class="hljs-comment">// file2.js</span>
<span class="hljs-keyword">const</span> greet = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./file1.js'</span>);
greet();
</code></pre>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-share-code-between-files/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-how-do-you-organize-your-code">How do you organize your code?</h3>

<p>I organize my code by following a modular approach, using a clear folder structure, and adhering to coding standards and best practices. I separate concerns by dividing code into different layers such as components, services, and utilities. I also use naming conventions and documentation to ensure code readability and maintainability.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript">What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?</h3>

<p>Using languages that compile to JavaScript, like TypeScript or CoffeeScript, can offer several advantages such as improved syntax, type safety, and better tooling. However, they also come with disadvantages like added build steps, potential performance overhead, and the need to learn new syntax.</p>
<p>Advantages:</p>
<ul>
<li>Improved syntax and readability</li>
<li>Type safety and error checking</li>
<li>Better tooling and editor support</li>
</ul>
<p>Disadvantages:</p>
<ul>
<li>Added build steps and complexity</li>
<li>Potential performance overhead</li>
<li>Learning curve for new syntax</li>
</ul>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>
<h3 id="heading-when-would-you-use-documentwrite">When would you use <code>document.write()</code>?</h3>

<p><code>document.write()</code> is rarely used in modern web development because it can overwrite the entire document if called after the page has loaded. It is mainly used for simple tasks like writing content during the initial page load, such as for educational purposes or quick debugging. However, it is generally recommended to use other methods like <code>innerHTML</code>, <code>appendChild()</code>, or modern frameworks for manipulating the DOM.</p>

<p><br /></p>
<p><a class="post-section-overview" href="#table-of-contents-all-questions">Back to top ↑</a>   /   <a target="_blank" href="https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/when-would-you-use-document-write/en-US.mdx">✏️ Edit answer</a></p>
<p><br /></p>

<h2 id="heading-questions-by-difficulty">Questions by Difficulty</h2>
<p>JavaScript interview questions categorized by difficulty.</p>
<h3 id="heading-basic-level-javascript-interviews-questions">Basic-level JavaScript Interviews Questions</h3>

<ol>
<li><a class="post-section-overview" href="#explain-the-concept-of-hoisting-in-javascript">Explain the concept of "hoisting" in JavaScript</a></li>
<li><a class="post-section-overview" href="#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const">What are the differences between JavaScript variables created using <code>let</code>, <code>var</code> or <code>const</code>?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between--and--in-javascript">What is the difference between <code>==</code> and <code>===</code> in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-is-the-event-loop-in-javascript-runtimes">What is the event loop in JavaScript runtimes?</a></li>
<li><a class="post-section-overview" href="#explain-event-delegation-in-javascript">Explain event delegation in JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-how-this-works-in-javascript">Explain how <code>this</code> works in JavaScript</a></li>
<li><a class="post-section-overview" href="#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers">Describe the difference between a cookie, <code>sessionStorage</code> and <code>localStorage</code> in browsers</a></li>
<li><a class="post-section-overview" href="#describe-the-difference-between-script-script-async-and-script-defer">Describe the difference between <code>&lt;script&gt;</code>, <code>&lt;script async&gt;</code> and <code>&lt;script defer&gt;</code></a></li>
<li><a class="post-section-overview" href="#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared">What's the difference between a JavaScript variable that is: <code>null</code>, <code>undefined</code> or undeclared?</a></li>
<li><a class="post-section-overview" href="#whats-the-difference-between-call-and-apply-in-javascript">What's the difference between <code>.call</code> and <code>.apply</code> in JavaScript?</a></li>
<li><a class="post-section-overview" href="#explain-functionprototypebind-in-javascript">Explain <code>Function.prototype.bind</code> in JavaScript</a></li>
<li><a class="post-section-overview" href="#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor">What advantage is there for using the JavaScript arrow syntax for a method in a constructor?</a></li>
<li><a class="post-section-overview" href="#explain-how-prototypal-inheritance-works-in-javascript">Explain how prototypal inheritance works in JavaScript</a></li>
<li><a class="post-section-overview" href="#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript">Difference between: <code>function Person(){}</code>, <code>const person = Person()</code>, and <code>const person = new Person()</code> in JavaScript?</a></li>
<li><a class="post-section-overview" href="#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript">Explain the differences on the usage of <code>foo</code> between <code>function foo() {}</code> and <code>var foo = function() {}</code> in JavaScript</a></li>
<li><a class="post-section-overview" href="#what-are-the-various-ways-to-create-objects-in-javascript">What are the various ways to create objects in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-is-the-definition-of-a-higher-order-function-in-javascript">What is the definition of a higher-order function in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors">What are the differences between JavaScript ES2015 classes and ES5 function constructors?</a></li>
<li><a class="post-section-overview" href="#describe-event-bubbling-in-javascript-and-browsers">Describe event bubbling in JavaScript and browsers</a></li>
<li><a class="post-section-overview" href="#describe-event-capturing-in-javascript-and-browsers">Describe event capturing in JavaScript and browsers</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers">What is the difference between <code>mouseenter</code> and <code>mouseover</code> event in JavaScript and browsers?</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript">Explain the difference between synchronous and asynchronous functions in JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-ajax-in-as-much-detail-as-possible">Explain AJAX in as much detail as possible</a></li>
<li><a class="post-section-overview" href="#what-are-the-advantages-and-disadvantages-of-using-ajax">What are the advantages and disadvantages of using AJAX?</a></li>
<li><a class="post-section-overview" href="#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers">What are the differences between <code>XMLHttpRequest</code> and <code>fetch()</code> in JavaScript and browsers?</a></li>
<li><a class="post-section-overview" href="#what-are-the-various-data-types-in-javascript">What are the various data types in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript">What language constructs do you use for iterating over object properties and array items in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax">What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript">What is the difference between a <code>Map</code> object and a plain object in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript">What are the differences between <code>Map</code>/<code>Set</code> and <code>WeakMap</code>/<code>WeakSet</code> in JavaScript?</a></li>
<li><a class="post-section-overview" href="#can-you-offer-a-use-case-for-the-new-arrow--function-syntax">Can you offer a use case for the new arrow =&gt; function syntax?</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-a-callback-function-in-asynchronous-operations">Explain the concept of a callback function in asynchronous operations</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance">Explain the concept of caching and how it can be used to improve performance</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-debouncing-and-throttling">Explain the concept of debouncing and throttling</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-destructuring-assignment-for-objects-and-arrays">Explain the concept of destructuring assignment for objects and arrays</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-hoisting-with-regards-to-functions">Explain the concept of hoisting with regards to functions</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-inheritance-in-es2015-classes">Explain the concept of inheritance in ES2015 classes</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance">Explain the concept of lazy loading and how it can improve performance</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-lexical-scoping">Explain the concept of lexical scoping</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-scope-in-javascript">Explain the concept of scope in JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-the-prototype-pattern">Explain the concept of the Prototype pattern</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-the-singleton-pattern">Explain the concept of the Singleton pattern</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-the-spread-operator-and-its-uses">Explain the concept of the spread operator and its uses</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-this-binding-in-event-handlers">Explain the concept of <code>this</code> binding in event handlers</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-classical-inheritance-and-prototypal-inheritance">Explain the difference between classical inheritance and prototypal inheritance</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-documentqueryselector-and-documentgetelementbyid">Explain the difference between <code>document.querySelector()</code> and <code>document.getElementById()</code></a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties">Explain the difference between dot notation and bracket notation for accessing object properties</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-global-scope-function-scope-and-block-scope">Explain the difference between global scope, function scope, and block scope</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-shallow-copy-and-deep-copy">Explain the difference between shallow copy and deep copy</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-in-hoisting-between-var-let-and-const">Explain the difference in hoisting between <code>var</code>, <code>let</code>, and <code>const</code></a></li>
<li><a class="post-section-overview" href="#how-can-closures-be-used-to-create-private-variables">How can closures be used to create private variables?</a></li>
<li><a class="post-section-overview" href="#how-can-you-avoid-problems-related-to-hoisting">How can you avoid problems related to hoisting?</a></li>
<li><a class="post-section-overview" href="#how-can-you-share-code-between-javascript-files">How can you share code between JavaScript files?</a></li>
<li><a class="post-section-overview" href="#how-do-sets-and-maps-handle-equality-checks-for-objects">How do <code>Set</code>s and <code>Map</code>s handle equality checks for objects?</a></li>
<li><a class="post-section-overview" href="#how-do-you-access-the-index-of-an-element-in-an-array-during-iteration">How do you access the index of an element in an array during iteration?</a></li>
<li><a class="post-section-overview" href="#how-do-you-add-remove-and-modify-html-elements-using-javascript">How do you add, remove, and modify HTML elements using JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-add-remove-and-update-elements-in-an-array">How do you add, remove, and update elements in an array?</a></li>
<li><a class="post-section-overview" href="#how-do-you-check-if-an-object-has-a-specific-property">How do you check if an object has a specific property?</a></li>
<li><a class="post-section-overview" href="#how-do-you-check-the-data-type-of-a-variable">How do you check the data type of a variable?</a></li>
<li><a class="post-section-overview" href="#how-do-you-convert-a-set-to-an-array-in-javascript">How do you convert a <code>Set</code> to an array in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-convert-a-string-to-a-number-in-javascript">How do you convert a string to a number in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-create-a-constructor-function">How do you create a constructor function?</a></li>
<li><a class="post-section-overview" href="#how-do-you-get-the-query-string-values-of-the-current-page-in-javascript">How do you get the query string values of the current page in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-handle-errors-in-asynchronous-operations">How do you handle errors in asynchronous operations?</a></li>
<li><a class="post-section-overview" href="#how-do-you-handle-errors-using-trycatch-blocks">How do you handle errors using <code>try...catch</code> blocks?</a></li>
<li><a class="post-section-overview" href="#how-do-you-import-and-export-modules-in-javascript">How do you import and export modules in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-make-an-http-request-using-the-fetch-api">How do you make an HTTP request using the Fetch API?</a></li>
<li><a class="post-section-overview" href="#how-do-you-manipulate-css-styles-using-javascript">How do you manipulate CSS styles using JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-prevent-the-default-behavior-of-an-event">How do you prevent the default behavior of an event?</a></li>
<li><a class="post-section-overview" href="#how-do-you-redirect-to-a-new-page-in-javascript">How do you redirect to a new page in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-reliably-determine-whether-an-object-is-empty">How do you reliably determine whether an object is empty?</a></li>
<li><a class="post-section-overview" href="#how-do-you-use-windowhistory-api">How do you use <code>window.history</code> API?</a></li>
<li><a class="post-section-overview" href="#provide-some-examples-of-how-currying-and-partial-application-can-be-used">Provide some examples of how currying and partial application can be used</a></li>
<li><a class="post-section-overview" href="#what-are-callback-functions-and-how-are-they-used">What are callback functions and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-default-parameters-and-how-are-they-used">What are default parameters and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-design-patterns-and-why-are-they-useful">What are design patterns and why are they useful?</a></li>
<li><a class="post-section-overview" href="#what-are-event-listeners-and-how-are-they-used">What are event listeners and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-modules-and-why-are-they-useful">What are modules and why are they useful?</a></li>
<li><a class="post-section-overview" href="#what-are-promises-and-how-do-they-work">What are Promises and how do they work?</a></li>
<li><a class="post-section-overview" href="#what-are-rest-parameters-and-how-are-they-used">What are rest parameters and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-sets-and-maps-and-how-are-they-used">What are <code>Set</code>s and <code>Map</code>s and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-some-popular-javascript-testing-frameworks">What are some popular JavaScript testing frameworks?</a></li>
<li><a class="post-section-overview" href="#what-are-some-tools-that-can-be-used-for-javascript-testing">What are some tools that can be used for JavaScript testing?</a></li>
<li><a class="post-section-overview" href="#what-are-template-literals-and-how-are-they-used">What are template literals and how are they used?</a></li>
<li><a class="post-section-overview" href="#what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects">What are the advantages of using the spread operator with arrays and objects?</a></li>
<li><a class="post-section-overview" href="#what-are-the-common-pitfalls-of-using-the-this-keyword">What are the common pitfalls of using the <code>this</code> keyword?</a></li>
<li><a class="post-section-overview" href="#what-are-the-different-methods-for-iterating-over-an-array">What are the different methods for iterating over an array?</a></li>
<li><a class="post-section-overview" href="#what-are-the-different-ways-to-copy-an-object-or-an-array">What are the different ways to copy an object or an array?</a></li>
<li><a class="post-section-overview" href="#what-are-the-different-ways-to-make-an-api-call-in-javascript">What are the different ways to make an API call in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-do-you-think-of-amd-vs-commonjs">What do you think of AMD vs CommonJS?</a></li>
<li><a class="post-section-overview" href="#what-is-recursion-and-how-is-it-used-in-javascript">What is recursion and how is it used in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-a-parameter-and-an-argument">What is the difference between a parameter and an argument?</a></li>
<li><a class="post-section-overview" href="#what-is-the-dom-and-how-is-it-structured">What is the DOM and how is it structured?</a></li>
<li><a class="post-section-overview" href="#what-is-the-purpose-of-the-break-and-continue-statements">What is the purpose of the <code>break</code> and <code>continue</code> statements?</a></li>
<li><a class="post-section-overview" href="#what-is-the-purpose-of-the-finally-block">What is the purpose of the <code>finally</code> block?</a></li>
<li><a class="post-section-overview" href="#what-is-the-purpose-of-the-new-keyword">What is the purpose of the <code>new</code> keyword?</a></li>
<li><a class="post-section-overview" href="#what-is-the-purpose-of-the-switch-statement">What is the purpose of the <code>switch</code> statement?</a></li>
<li><a class="post-section-overview" href="#what-is-the-spread-operator-and-how-is-it-used">What is the spread operator and how is it used?</a></li>
<li><a class="post-section-overview" href="#what-is-the-ternary-operator-and-how-is-it-used">What is the ternary operator and how is it used?</a></li>
<li><a class="post-section-overview" href="#what-is-the-use-of-promiseall">What is the use of <code>Promise.all()</code></a></li>
</ol>

<h3 id="heading-intermediate-level-javascript-interviews-questions">Intermediate-level JavaScript Interviews Questions</h3>

<ol>
<li><a class="post-section-overview" href="#whats-a-typical-use-case-for-anonymous-functions-in-javascript">What's a typical use case for anonymous functions in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one">What is a closure in JavaScript, and how/why would you use one?</a></li>
<li><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript">What are the pros and cons of using Promises instead of callbacks in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript">How do you abort a web request using <code>AbortController</code> in JavaScript?</a></li>
<li><a class="post-section-overview" href="#why-is-extending-built-in-javascript-objects-not-a-good-idea">Why is extending built-in JavaScript objects not a good idea?</a></li>
<li><a class="post-section-overview" href="#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it">Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?</a></li>
<li><a class="post-section-overview" href="#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript">Explain the differences between CommonJS modules and ES modules in JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-mutable-and-immutable-objects-in-javascript">Explain the difference between mutable and immutable objects in JavaScript</a></li>
<li><a class="post-section-overview" href="#why-might-you-want-to-create-static-class-members-in-javascript">Why might you want to create static class members in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-symbols-used-for-in-javascript">What are <code>Symbol</code>s used for in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-javascript-object-getters-and-setters-for">What are JavaScript object getters and setters for?</a></li>
<li><a class="post-section-overview" href="#what-tools-and-techniques-do-you-use-for-debugging-javascript-code">What tools and techniques do you use for debugging JavaScript code?</a></li>
<li><a class="post-section-overview" href="#difference-between-document-load-event-and-document-domcontentloaded-event">Difference between document <code>load</code> event and document <code>DOMContentLoaded</code> event?</a></li>
<li><a class="post-section-overview" href="#explain-how-jsonp-works-and-how-its-not-really-ajax">Explain how JSONP works (and how it's not really Ajax)</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-a-microtask-queue">Explain the concept of a microtask queue</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality">Explain the concept of code coverage and how it can be used to assess test quality</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security">Explain the concept of Content Security Policy (CSP) and how it enhances security</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques">Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-error-propagation-in-javascript">Explain the concept of error propagation in JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-input-validation-and-its-importance-in-security">Explain the concept of input validation and its importance in security</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-partial-application">Explain the concept of partial application</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-tagged-templates">Explain the concept of tagged templates</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-test-driven-development-tdd">Explain the concept of test-driven development (TDD)</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-the-strategy-pattern">Explain the concept of the Strategy pattern</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-the-web-socket-api">Explain the concept of the Web Socket API</a></li>
<li><a class="post-section-overview" href="#explain-the-concept-of-tree-shaking-in-module-bundling">Explain the concept of tree shaking in module bundling</a></li>
<li><a class="post-section-overview" href="#explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing">Explain the difference between unit testing, integration testing, and end-to-end testing</a></li>
<li><a class="post-section-overview" href="#explain-the-different-states-of-a-promise">Explain the different states of a Promise</a></li>
<li><a class="post-section-overview" href="#explain-the-different-ways-the-this-keyword-can-be-bound">Explain the different ways the <code>this</code> keyword can be bound</a></li>
<li><a class="post-section-overview" href="#explain-the-event-phases-in-a-browser">Explain the event phases in a browser</a></li>
<li><a class="post-section-overview" href="#explain-the-observer-pattern-and-its-use-cases">Explain the Observer pattern and its use cases</a></li>
<li><a class="post-section-overview" href="#explain-the-same-origin-policy-with-regards-to-javascript">Explain the same-origin policy with regards to JavaScript</a></li>
<li><a class="post-section-overview" href="#explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly">Explain what a single page app is and how to make one SEO-friendly</a></li>
<li><a class="post-section-overview" href="#how-can-you-create-custom-error-objects">How can you create custom error objects?</a></li>
<li><a class="post-section-overview" href="#how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications">How can you prevent SQL injection vulnerabilities in JavaScript applications?</a></li>
<li><a class="post-section-overview" href="#how-can-you-test-asynchronous-code-in-javascript">How can you test asynchronous code in JavaScript?</a></li>
<li><a class="post-section-overview" href="#how-do-currying-and-partial-application-differ-from-each-other">How do currying and partial application differ from each other?</a></li>
<li><a class="post-section-overview" href="#how-do-iframe-on-a-page-communicate">How do <code>&lt;iframe&gt;</code> on a page communicate?</a></li>
<li><a class="post-section-overview" href="#how-do-you-detect-if-javascript-is-disabled-on-a-page">How do you detect if JavaScript is disabled on a page?</a></li>
<li><a class="post-section-overview" href="#how-do-you-organize-your-code">How do you organize your code?</a></li>
<li><a class="post-section-overview" href="#how-do-you-write-unit-tests-for-javascript-code">How do you write unit tests for JavaScript code?</a></li>
<li><a class="post-section-overview" href="#how-is-promiseall-different-from-promiseallsettled">How is <code>Promise.all()</code> different from <code>Promise.allSettled()</code>?</a></li>
<li><a class="post-section-overview" href="#what-are-progressive-web-applications-pwas">What are Progressive Web Applications (PWAs)?</a></li>
<li><a class="post-section-overview" href="#what-are-some-best-practices-for-handling-sensitive-data-in-javascript">What are some best practices for handling sensitive data in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-some-best-practices-for-writing-maintainable-and-effective-tests-in-javascript">What are some best practices for writing maintainable and effective tests in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-some-common-performance-bottlenecks-in-javascript-applications">What are some common performance bottlenecks in JavaScript applications?</a></li>
<li><a class="post-section-overview" href="#what-are-some-common-security-headers-and-their-purpose">What are some common security headers and their purpose?</a></li>
<li><a class="post-section-overview" href="#what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code">What are some tools and techniques for identifying security vulnerabilities in JavaScript code?</a></li>
<li><a class="post-section-overview" href="#what-are-the-benefits-of-using-a-module-bundler">What are the benefits of using a module bundler?</a></li>
<li><a class="post-section-overview" href="#what-are-the-benefits-of-using-currying-and-partial-application">What are the benefits of using currying and partial application?</a></li>
<li><a class="post-section-overview" href="#what-are-the-different-types-of-errors-in-javascript">What are the different types of errors in JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-the-different-types-of-testing-in-software-development">What are the different types of testing in software development?</a></li>
<li><a class="post-section-overview" href="#what-are-the-metadata-fields-of-a-module">What are the metadata fields of a module?</a></li>
<li><a class="post-section-overview" href="#what-are-the-potential-issues-caused-by-hoisting">What are the potential issues caused by hoisting?</a></li>
<li><a class="post-section-overview" href="#what-are-the-potential-pitfalls-of-using-closures">What are the potential pitfalls of using closures?</a></li>
<li><a class="post-section-overview" href="#what-is-asyncawait-and-how-does-it-simplify-asynchronous-code">What is async/await and how does it simplify asynchronous code?</a></li>
<li><a class="post-section-overview" href="#what-is-cross-site-scripting-xss-and-how-can-you-prevent-it">What is Cross-Site Scripting (XSS) and how can you prevent it?</a></li>
<li><a class="post-section-overview" href="#what-is-currying-and-how-does-it-work">What is currying and how does it work?</a></li>
<li><a class="post-section-overview" href="#what-is-objectfreeze-for">What is <code>Object.freeze()</code> for?</a></li>
<li><a class="post-section-overview" href="#what-is-objectpreventextensions-for">What is <code>Object.preventExtensions()</code> for?</a></li>
<li><a class="post-section-overview" href="#what-is-objectseal-for">What is <code>Object.seal()</code> for?</a></li>
<li><a class="post-section-overview" href="#what-is-the-command-pattern-and-how-is-it-used">What is the Command pattern and how is it used?</a></li>
<li><a class="post-section-overview" href="#what-is-the-decorator-pattern-and-how-is-it-used">What is the Decorator pattern and how is it used?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation">What is the difference between <code>event.preventDefault()</code> and <code>event.stopPropagation()</code>?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-innerhtml-and-textcontent">What is the difference between <code>innerHTML</code> and <code>textContent</code>?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-settimeout-setimmediate-and-processnexttick">What is the difference between <code>setTimeout()</code>, <code>setImmediate()</code>, and <code>process.nextTick()</code>?</a></li>
<li><a class="post-section-overview" href="#what-is-the-difference-between-the-window-object-and-the-document-object">What is the difference between the Window object and the Document object?</a></li>
<li><a class="post-section-overview" href="#what-is-the-factory-pattern-and-how-is-it-used">What is the Factory pattern and how is it used?</a></li>
<li><a class="post-section-overview" href="#what-is-the-intl-namespace-object-for">What is the <code>Intl</code> namespace object for?</a></li>
<li><a class="post-section-overview" href="#what-is-the-module-pattern-and-how-does-it-help-with-encapsulation">What is the Module pattern and how does it help with encapsulation?</a></li>
<li><a class="post-section-overview" href="#what-is-the-prototype-chain-and-how-does-it-work">What is the prototype chain and how does it work?</a></li>
<li><a class="post-section-overview" href="#whats-the-difference-between-an-attribute-and-a-property-in-the-dom">What's the difference between an "attribute" and a "property" in the DOM?</a></li>
</ol>

<h3 id="heading-advanced-level-javascript-interviews-questions">Advanced-level JavaScript Interviews Questions</h3>

<ol>
<li><a class="post-section-overview" href="#what-is-use-strict-in-javascript-for">What is <code>'use strict';</code> in JavaScript for?</a></li>
<li><a class="post-section-overview" href="#what-are-javascript-polyfills-for">What are JavaScript polyfills for?</a></li>
<li><a class="post-section-overview" href="#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for">What are iterators and generators in JavaScript and what are they used for?</a></li>
<li><a class="post-section-overview" href="#what-are-server-sent-events">What are server-sent events?</a></li>
<li><a class="post-section-overview" href="#what-are-javascript-object-property-flags-and-descriptors">What are JavaScript object property flags and descriptors?</a></li>
<li><a class="post-section-overview" href="#what-are-proxies-in-javascript-used-for">What are proxies in JavaScript used for?</a></li>
<li><a class="post-section-overview" href="#what-are-workers-in-javascript-used-for">What are workers in JavaScript used for?</a></li>
<li><a class="post-section-overview" href="#how-does-javascript-garbage-collection-work">How does JavaScript garbage collection work?</a></li>
<li><a class="post-section-overview" href="#explain-why-the-following-doesnt-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife">Explain why the following doesn't work as an IIFE: <code>function foo(){}();</code>. What needs to be changed to properly make it an IIFE?</a></li>
<li><a class="post-section-overview" href="#how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications">How can you implement secure authentication and authorization in JavaScript applications?</a></li>
<li><a class="post-section-overview" href="#how-can-you-optimize-dom-manipulation-for-better-performance">How can you optimize DOM manipulation for better performance?</a></li>
<li><a class="post-section-overview" href="#how-can-you-optimize-network-requests-for-better-performance">How can you optimize network requests for better performance?</a></li>
<li><a class="post-section-overview" href="#how-can-you-prevent-clickjacking-attacks">How can you prevent clickjacking attacks?</a></li>
<li><a class="post-section-overview" href="#how-do-you-validate-form-elements-using-the-constraint-validation-api">How do you validate form elements using the Constraint Validation API?</a></li>
<li><a class="post-section-overview" href="#how-does-hoisting-affect-function-declarations-and-expressions">How does hoisting affect function declarations and expressions?</a></li>
<li><a class="post-section-overview" href="#what-are-mocks-and-stubs-and-how-are-they-used-in-testing">What are mocks and stubs and how are they used in testing?</a></li>
<li><a class="post-section-overview" href="#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript">What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?</a></li>
<li><a class="post-section-overview" href="#what-are-some-techniques-for-reducing-reflows-and-repaints">What are some techniques for reducing reflows and repaints?</a></li>
<li><a class="post-section-overview" href="#what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance">What are some tools that can be used to measure and analyze JavaScript performance?</a></li>
<li><a class="post-section-overview" href="#what-are-web-workers-and-how-can-they-be-used-to-improve-performance">What are Web Workers and how can they be used to improve performance?</a></li>
<li><a class="post-section-overview" href="#when-would-you-use-documentwrite">When would you use <code>document.write()</code>?</a></li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Javascript Top Interview Questions]]></title><description><![CDATA[There are many ways to create objects in javascript as mentioned below: Object literal syntax: The object literal syntax (or object initializer), is a…]]></description><link>https://articles.tkssharma.com/javascript-top-interview-questions</link><guid isPermaLink="true">https://articles.tkssharma.com/javascript-top-interview-questions</guid><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sat, 19 Oct 2024 17:34:17 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-table-of-contents">Table of Contents</h3>

<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-are-the-possible-ways-to-create-objects-in-javascript">What are the possible ways to create objects in JavaScript</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-is-a-prototype-chain">What is a prototype chain</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#what-is-the-difference-between-call-apply-and-bind">What is the difference between Call, Apply and Bind</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#what-is-json-and-its-common-operations">What is JSON and its common operations</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-array-slice-method">What is the purpose of the array slice method</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-array-splice-method">What is the purpose of the array splice method</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-is-the-difference-between-slice-and-splice">What is the difference between slice and splice</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#how-do-you-compare-object-and-map">How do you compare Object and Map</a></td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#what-is-the-difference-between--and--operators">What is the difference between == and === operators</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#what-are-lambda-expressions-or-arrow-functions">What are lambda expressions or arrow functions</a></td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#what-is-a-first-class-function">What is a first class function</a></td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#what-is-a-first-order-function">What is a first order function</a></td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#what-is-a-higher-order-function">What is a higher order function</a></td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#what-is-a-unary-function">What is a unary function</a></td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#what-is-the-currying-function">What is the currying function</a></td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#what-is-a-pure-function">What is a pure function</a></td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-let-keyword">What is the purpose of the let keyword</a></td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#what-is-the-difference-between-let-and-var">What is the difference between let and var</a></td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#what-is-the-reason-to-choose-the-name-let-as-a-keyword">What is the reason to choose the name let as a keyword</a></td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#how-do-you-redeclare-variables-in-a-switch-block-without-an-error">How do you redeclare variables in a switch block without an error</a></td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#what-is-the-temporal-dead-zone">What is the Temporal Dead Zone</a></td></tr>
<tr>
<td>22</td><td><a class="post-section-overview" href="#what-is-an-iife-immediately-invoked-function-expression">What is an IIFE (Immediately Invoked Function Expression)</a></td></tr>
<tr>
<td>23</td><td><a class="post-section-overview" href="#how-do-you-decode-or-encode-a-url-in-javascript">How do you decode or encode a URL in JavaScript?</a></td></tr>
<tr>
<td>24</td><td><a class="post-section-overview" href="#what-is-memoization">What is memoization</a></td></tr>
<tr>
<td>25</td><td><a class="post-section-overview" href="#what-is-hoisting">What is Hoisting</a></td></tr>
<tr>
<td>26</td><td><a class="post-section-overview" href="#what-are-classes-in-es6">What are classes in ES6</a></td></tr>
<tr>
<td>27</td><td><a class="post-section-overview" href="#what-are-closures">What are closures</a></td></tr>
<tr>
<td>28</td><td><a class="post-section-overview" href="#what-are-modules">What are modules</a></td></tr>
<tr>
<td>29</td><td><a class="post-section-overview" href="#why-do-you-need-modules">Why do you need modules</a></td></tr>
<tr>
<td>30</td><td><a class="post-section-overview" href="#what-is-scope-in-javascript">What is scope in javascript</a></td></tr>
<tr>
<td>31</td><td><a class="post-section-overview" href="#what-is-a-service-worker">What is a service worker</a></td></tr>
<tr>
<td>32</td><td><a class="post-section-overview" href="#how-do-you-manipulate-dom-using-a-service-worker">How do you manipulate DOM using a service worker</a></td></tr>
<tr>
<td>33</td><td><a class="post-section-overview" href="#how-do-you-reuse-information-across-service-worker-restarts">How do you reuse information across service worker restarts</a></td></tr>
<tr>
<td>34</td><td><a class="post-section-overview" href="#what-is-indexeddb">What is IndexedDB</a></td></tr>
<tr>
<td>35</td><td><a class="post-section-overview" href="#what-is-web-storage">What is web storage</a></td></tr>
<tr>
<td>36</td><td><a class="post-section-overview" href="#what-is-a-post-message">What is a post message</a></td></tr>
<tr>
<td>37</td><td><a class="post-section-overview" href="#what-is-a-cookie">What is a Cookie</a></td></tr>
<tr>
<td>38</td><td><a class="post-section-overview" href="#why-do-you-need-a-cookie">Why do you need a Cookie</a></td></tr>
<tr>
<td>39</td><td><a class="post-section-overview" href="#what-are-the-options-in-a-cookie">What are the options in a cookie</a></td></tr>
<tr>
<td>40</td><td><a class="post-section-overview" href="#how-do-you-delete-a-cookie">How do you delete a cookie</a></td></tr>
<tr>
<td>41</td><td><a class="post-section-overview" href="#what-are-the-differences-between-cookie-local-storage-and-session-storage">What are the differences between cookie, local storage and session storage</a></td></tr>
<tr>
<td>42</td><td><a class="post-section-overview" href="#what-is-the-main-difference-between-localstorage-and-sessionstorage">What is the main difference between localStorage and sessionStorage</a></td></tr>
<tr>
<td>43</td><td><a class="post-section-overview" href="#how-do-you-access-web-storage">How do you access web storage</a></td></tr>
<tr>
<td>44</td><td><a class="post-section-overview" href="#what-are-the-methods-available-on-session-storage">What are the methods available on session storage</a></td></tr>
<tr>
<td>45</td><td><a class="post-section-overview" href="#what-is-a-storage-event-and-its-event-handler">What is a storage event and its event handler</a></td></tr>
<tr>
<td>46</td><td><a class="post-section-overview" href="#why-do-you-need-web-storage">Why do you need web storage</a></td></tr>
<tr>
<td>47</td><td><a class="post-section-overview" href="#how-do-you-check-web-storage-browser-support">How do you check web storage browser support</a></td></tr>
<tr>
<td>48</td><td><a class="post-section-overview" href="#how-do-you-check-web-workers-browser-support">How do you check web workers browser support</a></td></tr>
<tr>
<td>49</td><td><a class="post-section-overview" href="#give-an-example-of-a-web-worker">Give an example of a web worker</a></td></tr>
<tr>
<td>50</td><td><a class="post-section-overview" href="#what-are-the-restrictions-of-web-workers-on-dom">What are the restrictions of web workers on DOM</a></td></tr>
<tr>
<td>51</td><td><a class="post-section-overview" href="#what-is-a-promise">What is a promise</a></td></tr>
<tr>
<td>52</td><td><a class="post-section-overview" href="#why-do-you-need-a-promise">Why do you need a promise</a></td></tr>
<tr>
<td>53</td><td><a class="post-section-overview" href="#what-are-the-three-states-of-promise">What are the three states of promise</a></td></tr>
<tr>
<td>54</td><td><a class="post-section-overview" href="#what-is-a-callback-function">What is a callback function</a></td></tr>
<tr>
<td>55</td><td><a class="post-section-overview" href="#why-do-we-need-callbacks">Why do we need callbacks</a></td></tr>
<tr>
<td>56</td><td><a class="post-section-overview" href="#what-is-a-callback-hell">What is a callback hell</a></td></tr>
<tr>
<td>57</td><td><a class="post-section-overview" href="#what-are-server-sent-events">What are server-sent events</a></td></tr>
<tr>
<td>58</td><td><a class="post-section-overview" href="#how-do-you-receive-server-sent-event-notifications">How do you receive server-sent event notifications</a></td></tr>
<tr>
<td>59</td><td><a class="post-section-overview" href="#how-do-you-check-browser-support-for-server-sent-events">How do you check browser support for server-sent events</a></td></tr>
<tr>
<td>60</td><td><a class="post-section-overview" href="#what-are-the-events-available-for-server-sent-events">What are the events available for server sent events</a></td></tr>
<tr>
<td>61</td><td><a class="post-section-overview" href="#what-are-the-main-rules-of-promise">What are the main rules of promise</a></td></tr>
<tr>
<td>62</td><td><a class="post-section-overview" href="#what-is-callback-in-callback">What is callback in callback</a></td></tr>
<tr>
<td>63</td><td><a class="post-section-overview" href="#what-is-promise-chaining">What is promise chaining</a></td></tr>
<tr>
<td>64</td><td><a class="post-section-overview" href="#what-is-promiseall">What is promise.all</a></td></tr>
<tr>
<td>65</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-race-method-in-promise">What is the purpose of the race method in promise</a></td></tr>
<tr>
<td>66</td><td><a class="post-section-overview" href="#what-is-a-strict-mode-in-javascript">What is a strict mode in javascript</a></td></tr>
<tr>
<td>67</td><td><a class="post-section-overview" href="#why-do-you-need-strict-mode">Why do you need strict mode</a></td></tr>
<tr>
<td>68</td><td><a class="post-section-overview" href="#how-do-you-declare-strict-mode">How do you declare strict mode</a></td></tr>
<tr>
<td>69</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-double-exclamation">What is the purpose of double exclamation</a></td></tr>
<tr>
<td>70</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-delete-operator">What is the purpose of the delete operator</a></td></tr>
<tr>
<td>71</td><td><a class="post-section-overview" href="#what-is-typeof-operator">What is typeof operator</a></td></tr>
<tr>
<td>72</td><td><a class="post-section-overview" href="#what-is-undefined-property">What is undefined property</a></td></tr>
<tr>
<td>73</td><td><a class="post-section-overview" href="#what-is-null-value">What is null value</a></td></tr>
<tr>
<td>74</td><td><a class="post-section-overview" href="#what-is-the-difference-between-null-and-undefined">What is the difference between null and undefined</a></td></tr>
<tr>
<td>75</td><td><a class="post-section-overview" href="#what-is-eval">What is eval</a></td></tr>
<tr>
<td>76</td><td><a class="post-section-overview" href="#what-is-the-difference-between-window-and-document">What is the difference between window and document</a></td></tr>
<tr>
<td>77</td><td><a class="post-section-overview" href="#how-do-you-access-history-in-javascript">How do you access history in javascript</a></td></tr>
<tr>
<td>78</td><td><a class="post-section-overview" href="#how-do-you-detect-caps-lock-key-turned-on-or-not">How do you detect caps lock key turned on or not</a></td></tr>
<tr>
<td>79</td><td><a class="post-section-overview" href="#what-is-isnan">What is isNaN</a></td></tr>
<tr>
<td>80</td><td><a class="post-section-overview" href="#what-are-the-differences-between-undeclared-and-undefined-variables">What are the differences between undeclared and undefined variables</a></td></tr>
<tr>
<td>81</td><td><a class="post-section-overview" href="#what-are-global-variables">What are global variables</a></td></tr>
<tr>
<td>82</td><td><a class="post-section-overview" href="#what-are-the-problems-with-global-variables">What are the problems with global variables</a></td></tr>
<tr>
<td>83</td><td><a class="post-section-overview" href="#what-is-nan-property">What is NaN property</a></td></tr>
<tr>
<td>84</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-isfinite-function">What is the purpose of isFinite function</a></td></tr>
<tr>
<td>85</td><td><a class="post-section-overview" href="#what-is-an-event-flow">What is an event flow</a></td></tr>
<tr>
<td>86</td><td><a class="post-section-overview" href="#what-is-event-bubbling">What is event bubbling</a></td></tr>
<tr>
<td>87</td><td><a class="post-section-overview" href="#what-is-event-capturing">What is event capturing</a></td></tr>
<tr>
<td>88</td><td><a class="post-section-overview" href="#how-do-you-submit-a-form-using-javascript">How do you submit a form using JavaScript</a></td></tr>
<tr>
<td>89</td><td><a class="post-section-overview" href="#how-do-you-find-operating-system-details">How do you find operating system details</a></td></tr>
<tr>
<td>90</td><td><a class="post-section-overview" href="#what-is-the-difference-between-document-load-and-domcontentloaded-events">What is the difference between document load and DOMContentLoaded events</a></td></tr>
<tr>
<td>91</td><td><a class="post-section-overview" href="#what-is-the-difference-between-native-host-and-user-objects">What is the difference between native, host and user objects</a></td></tr>
<tr>
<td>92</td><td><a class="post-section-overview" href="#what-are-the-tools-or-techniques-used-for-debugging-javascript-code">What are the tools or techniques used for debugging JavaScript code</a></td></tr>
<tr>
<td>93</td><td><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-promises-over-callbacks">What are the pros and cons of promises over callbacks</a></td></tr>
<tr>
<td>94</td><td><a class="post-section-overview" href="#what-is-the-difference-between-an-attribute-and-a-property">What is the difference between an attribute and a property</a></td></tr>
<tr>
<td>95</td><td><a class="post-section-overview" href="#what-is-same-origin-policy">What is same-origin policy</a></td></tr>
<tr>
<td>96</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-void-0">What is the purpose of void 0</a></td></tr>
<tr>
<td>97</td><td><a class="post-section-overview" href="#is-javascript-a-compiled-or-interpreted-language">Is JavaScript a compiled or interpreted language</a></td></tr>
<tr>
<td>98</td><td><a class="post-section-overview" href="#is-javascript-a-case-sensitive-language">Is JavaScript a case-sensitive language</a></td></tr>
<tr>
<td>99</td><td><a class="post-section-overview" href="#is-there-any-relation-between-java-and-javascript">Is there any relation between Java and JavaScript</a></td></tr>
<tr>
<td>100</td><td><a class="post-section-overview" href="#what-are-events">What are events</a></td></tr>
<tr>
<td>101</td><td><a class="post-section-overview" href="#who-created-javascript">Who created javascript</a></td></tr>
<tr>
<td>102</td><td><a class="post-section-overview" href="#what-is-the-use-of-preventdefault-method">What is the use of preventDefault method</a></td></tr>
<tr>
<td>103</td><td><a class="post-section-overview" href="#what-is-the-use-of-stoppropagation-method">What is the use of stopPropagation method</a></td></tr>
<tr>
<td>104</td><td><a class="post-section-overview" href="#what-are-the-steps-involved-in-return-false-usage">What are the steps involved in return false usage</a></td></tr>
<tr>
<td>105</td><td><a class="post-section-overview" href="#what-is-bom">What is BOM</a></td></tr>
<tr>
<td>106</td><td><a class="post-section-overview" href="#what-is-the-use-of-settimeout">What is the use of setTimeout</a></td></tr>
<tr>
<td>107</td><td><a class="post-section-overview" href="#what-is-the-use-of-setinterval">What is the use of setInterval</a></td></tr>
<tr>
<td>108</td><td><a class="post-section-overview" href="#why-is-javascript-treated-as-single-threaded">Why is JavaScript treated as Single threaded</a></td></tr>
<tr>
<td>109</td><td><a class="post-section-overview" href="#what-is-an-event-delegation">What is an event delegation</a></td></tr>
<tr>
<td>110</td><td><a class="post-section-overview" href="#what-is-ecmascript">What is ECMAScript</a></td></tr>
<tr>
<td>111</td><td><a class="post-section-overview" href="#what-is-json">What is JSON</a></td></tr>
<tr>
<td>112</td><td><a class="post-section-overview" href="#what-are-the-syntax-rules-of-json">What are the syntax rules of JSON</a></td></tr>
<tr>
<td>113</td><td><a class="post-section-overview" href="#what-is-the-purpose-json-stringify">What is the purpose JSON stringify</a></td></tr>
<tr>
<td>114</td><td><a class="post-section-overview" href="#how-do-you-parse-json-string">How do you parse JSON string</a></td></tr>
<tr>
<td>115</td><td><a class="post-section-overview" href="#why-do-you-need-json">Why do you need JSON</a></td></tr>
<tr>
<td>116</td><td><a class="post-section-overview" href="#what-are-pwas">What are PWAs</a></td></tr>
<tr>
<td>117</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-cleartimeout-method">What is the purpose of clearTimeout method</a></td></tr>
<tr>
<td>118</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-clearinterval-method">What is the purpose of clearInterval method</a></td></tr>
<tr>
<td>119</td><td><a class="post-section-overview" href="#how-do-you-redirect-new-page-in-javascript">How do you redirect new page in javascript</a></td></tr>
<tr>
<td>120</td><td><a class="post-section-overview" href="#how-do-you-check-whether-a-string-contains-a-substring">How do you check whether a string contains a substring</a></td></tr>
<tr>
<td>121</td><td><a class="post-section-overview" href="#how-do-you-validate-an-email-in-javascript">How do you validate an email in javascript</a></td></tr>
<tr>
<td>122</td><td><a class="post-section-overview" href="#how-do-you-get-the-current-url-with-javascript">How do you get the current url with javascript</a></td></tr>
<tr>
<td>123</td><td><a class="post-section-overview" href="#what-are-the-various-url-properties-of-location-object">What are the various url properties of location object</a></td></tr>
<tr>
<td>124</td><td><a class="post-section-overview" href="#how-do-get-query-string-values-in-javascript">How do get query string values in javascript</a></td></tr>
<tr>
<td>125</td><td><a class="post-section-overview" href="#how-do-you-check-if-a-key-exists-in-an-object">How do you check if a key exists in an object</a></td></tr>
<tr>
<td>126</td><td><a class="post-section-overview" href="#how-do-you-loop-through-or-enumerate-javascript-object">How do you loop through or enumerate javascript object</a></td></tr>
<tr>
<td>127</td><td><a class="post-section-overview" href="#how-do-you-test-for-an-empty-object">How do you test for an empty object</a></td></tr>
<tr>
<td>128</td><td><a class="post-section-overview" href="#what-is-an-arguments-object">What is an arguments object</a></td></tr>
<tr>
<td>129</td><td><a class="post-section-overview" href="#how-do-you-make-first-letter-of-the-string-in-an-uppercase">How do you make first letter of the string in an uppercase</a></td></tr>
<tr>
<td>130</td><td><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-for-loops">What are the pros and cons of for loops</a></td></tr>
<tr>
<td>131</td><td><a class="post-section-overview" href="#how-do-you-display-the-current-date-in-javascript">How do you display the current date in javascript</a></td></tr>
<tr>
<td>132</td><td><a class="post-section-overview" href="#how-do-you-compare-two-date-objects">How do you compare two date objects</a></td></tr>
<tr>
<td>133</td><td><a class="post-section-overview" href="#how-do-you-check-if-a-string-starts-with-another-string">How do you check if a string starts with another string</a></td></tr>
<tr>
<td>134</td><td><a class="post-section-overview" href="#how-do-you-trim-a-string-in-javascript">How do you trim a string in javascript</a></td></tr>
<tr>
<td>135</td><td><a class="post-section-overview" href="#how-do-you-add-a-key-value-pair-in-javascript">How do you add a key value pair in javascript</a></td></tr>
<tr>
<td>136</td><td><a class="post-section-overview" href="#is-the----notation-represents-a-special-operator">Is the !-- notation represents a special operator</a></td></tr>
<tr>
<td>137</td><td><a class="post-section-overview" href="#how-do-you-assign-default-values-to-variables">How do you assign default values to variables</a></td></tr>
<tr>
<td>138</td><td><a class="post-section-overview" href="#how-do-you-define-multiline-strings">How do you define multiline strings</a></td></tr>
<tr>
<td>139</td><td><a class="post-section-overview" href="#what-is-an-app-shell-model">What is an app shell model</a></td></tr>
<tr>
<td>140</td><td><a class="post-section-overview" href="#can-we-define-properties-for-functions">Can we define properties for functions</a></td></tr>
<tr>
<td>141</td><td><a class="post-section-overview" href="#what-is-the-way-to-find-the-number-of-parameters-expected-by-a-function">What is the way to find the number of parameters expected by a function</a></td></tr>
<tr>
<td>142</td><td><a class="post-section-overview" href="#what-is-a-polyfill">What is a polyfill</a></td></tr>
<tr>
<td>143</td><td><a class="post-section-overview" href="#what-are-break-and-continue-statements">What are break and continue statements</a></td></tr>
<tr>
<td>144</td><td><a class="post-section-overview" href="#what-are-js-labels">What are js labels</a></td></tr>
<tr>
<td>145</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-keeping-declarations-at-the-top">What are the benefits of keeping declarations at the top</a></td></tr>
<tr>
<td>146</td><td><a class="post-section-overview" href="#what-are-the-benefits-of-initializing-variables">What are the benefits of initializing variables</a></td></tr>
<tr>
<td>147</td><td><a class="post-section-overview" href="#what-are-the-recommendations-to-create-new-object">What are the recommendations to create new object</a></td></tr>
<tr>
<td>148</td><td><a class="post-section-overview" href="#how-do-you-define-json-arrays">How do you define JSON arrays</a></td></tr>
<tr>
<td>149</td><td><a class="post-section-overview" href="#how-do-you-generate-random-integers">How do you generate random integers</a></td></tr>
<tr>
<td>150</td><td><a class="post-section-overview" href="#can-you-write-a-random-integers-function-to-print-integers-within-a-range">Can you write a random integers function to print integers within a range</a></td></tr>
<tr>
<td>151</td><td><a class="post-section-overview" href="#what-is-tree-shaking">What is tree shaking</a></td></tr>
<tr>
<td>152</td><td><a class="post-section-overview" href="#what-is-the-need-of-tree-shaking">What is the need of tree shaking</a></td></tr>
<tr>
<td>153</td><td><a class="post-section-overview" href="#is-it-recommended-to-use-eval">Is it recommended to use eval</a></td></tr>
<tr>
<td>154</td><td><a class="post-section-overview" href="#what-is-a-regular-expression">What is a Regular Expression</a></td></tr>
<tr>
<td>155</td><td><a class="post-section-overview" href="#what-are-the-string-methods-that-accept-regular-expression">What are the string methods that accept Regular expression</a></td></tr>
<tr>
<td>156</td><td><a class="post-section-overview" href="#what-are-modifiers-in-regular-expression">What are modifiers in regular expression</a></td></tr>
<tr>
<td>157</td><td><a class="post-section-overview" href="#what-are-regular-expression-patterns">What are regular expression patterns</a></td></tr>
<tr>
<td>158</td><td><a class="post-section-overview" href="#what-is-a-regexp-object">What is a RegExp object</a></td></tr>
<tr>
<td>159</td><td><a class="post-section-overview" href="#how-do-you-search-a-string-for-a-pattern">How do you search a string for a pattern</a></td></tr>
<tr>
<td>160</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-exec-method">What is the purpose of exec method</a></td></tr>
<tr>
<td>161</td><td><a class="post-section-overview" href="#how-do-you-change-the-style-of-a-html-element">How do you change the style of a HTML element</a></td></tr>
<tr>
<td>162</td><td><a class="post-section-overview" href="#what-would-be-the-result-of-123">What would be the result of 1+2+'3'</a></td></tr>
<tr>
<td>163</td><td><a class="post-section-overview" href="#what-is-a-debugger-statement">What is a debugger statement</a></td></tr>
<tr>
<td>164</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-breakpoints-in-debugging">What is the purpose of breakpoints in debugging</a></td></tr>
<tr>
<td>165</td><td><a class="post-section-overview" href="#can-i-use-reserved-words-as-identifiers">Can I use reserved words as identifiers</a></td></tr>
<tr>
<td>166</td><td><a class="post-section-overview" href="#how-do-you-detect-a-mobile-browser">How do you detect a mobile browser</a></td></tr>
<tr>
<td>167</td><td><a class="post-section-overview" href="#how-do-you-detect-a-mobile-browser-without-regexp">How do you detect a mobile browser without regexp</a></td></tr>
<tr>
<td>168</td><td><a class="post-section-overview" href="#how-do-you-get-the-image-width-and-height-using-js">How do you get the image width and height using JS</a></td></tr>
<tr>
<td>169</td><td><a class="post-section-overview" href="#how-do-you-make-synchronous-http-request">How do you make synchronous HTTP request</a></td></tr>
<tr>
<td>170</td><td><a class="post-section-overview" href="#how-do-you-make-asynchronous-http-request">How do you make asynchronous HTTP request</a></td></tr>
<tr>
<td>171</td><td><a class="post-section-overview" href="#how-do-you-convert-date-to-another-timezone-in-javascript">How do you convert date to another timezone in javascript</a></td></tr>
<tr>
<td>172</td><td><a class="post-section-overview" href="#what-are-the-properties-used-to-get-size-of-window">What are the properties used to get size of window</a></td></tr>
<tr>
<td>173</td><td><a class="post-section-overview" href="#what-is-a-conditional-operator-in-javascript">What is a conditional operator in javascript</a></td></tr>
<tr>
<td>174</td><td><a class="post-section-overview" href="#can-you-apply-chaining-on-conditional-operator">Can you apply chaining on conditional operator</a></td></tr>
<tr>
<td>175</td><td><a class="post-section-overview" href="#what-are-the-ways-to-execute-javascript-after-page-load">What are the ways to execute javascript after page load</a></td></tr>
<tr>
<td>176</td><td><a class="post-section-overview" href="#what-is-the-difference-between-proto-and-prototype">What is the difference between proto and prototype</a></td></tr>
<tr>
<td>177</td><td><a class="post-section-overview" href="#can-you-give-an-example-of-when-you-really-need-a-semicolon">Can you give an example of when you really need a semicolon</a></td></tr>
<tr>
<td>178</td><td><a class="post-section-overview" href="#what-is-a-freeze-method">What is a freeze method</a></td></tr>
<tr>
<td>179</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-freeze-method">What is the purpose of freeze method</a></td></tr>
<tr>
<td>180</td><td><a class="post-section-overview" href="#why-do-i-need-to-use-freeze-method">Why do I need to use freeze method</a></td></tr>
<tr>
<td>181</td><td><a class="post-section-overview" href="#how-do-you-detect-a-browser-language-preference">How do you detect a browser language preference</a></td></tr>
<tr>
<td>182</td><td><a class="post-section-overview" href="#how-to-convert-string-to-title-case-with-javascript">How to convert string to title case with javascript</a></td></tr>
<tr>
<td>183</td><td><a class="post-section-overview" href="#how-do-you-detect-javascript-disabled-in-the-page">How do you detect javascript disabled in the page</a></td></tr>
<tr>
<td>184</td><td><a class="post-section-overview" href="#what-are-various-operators-supported-by-javascript">What are various operators supported by javascript</a></td></tr>
<tr>
<td>185</td><td><a class="post-section-overview" href="#what-is-a-rest-parameter">What is a rest parameter</a></td></tr>
<tr>
<td>186</td><td><a class="post-section-overview" href="#what-happens-if-you-do-not-use-rest-parameter-as-a-last-argument">What happens if you do not use rest parameter as a last argument</a></td></tr>
<tr>
<td>187</td><td><a class="post-section-overview" href="#what-are-the-bitwise-operators-available-in-javascript">What are the bitwise operators available in javascript</a></td></tr>
<tr>
<td>188</td><td><a class="post-section-overview" href="#what-is-a-spread-operator">What is a spread operator</a></td></tr>
<tr>
<td>189</td><td><a class="post-section-overview" href="#how-do-you-determine-whether-object-is-frozen-or-not">How do you determine whether object is frozen or not</a></td></tr>
<tr>
<td>190</td><td><a class="post-section-overview" href="#how-do-you-determine-two-values-same-or-not-using-object">How do you determine two values same or not using object</a></td></tr>
<tr>
<td>191</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-using-object-is-method">What is the purpose of using object is method</a></td></tr>
<tr>
<td>192</td><td><a class="post-section-overview" href="#how-do-you-copy-properties-from-one-object-to-other">How do you copy properties from one object to other</a></td></tr>
<tr>
<td>193</td><td><a class="post-section-overview" href="#what-are-the-applications-of-assign-method">What are the applications of assign method</a></td></tr>
<tr>
<td>194</td><td><a class="post-section-overview" href="#what-is-a-proxy-object">What is a proxy object</a></td></tr>
<tr>
<td>195</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-seal-method">What is the purpose of seal method</a></td></tr>
<tr>
<td>196</td><td><a class="post-section-overview" href="#what-are-the-applications-of-seal-method">What are the applications of seal method</a></td></tr>
<tr>
<td>197</td><td><a class="post-section-overview" href="#what-are-the-differences-between-freeze-and-seal-methods">What are the differences between freeze and seal methods</a></td></tr>
<tr>
<td>198</td><td><a class="post-section-overview" href="#how-do-you-determine-if-an-object-is-sealed-or-not">How do you determine if an object is sealed or not</a></td></tr>
<tr>
<td>199</td><td><a class="post-section-overview" href="#how-do-you-get-enumerable-key-and-value-pairs">How do you get enumerable key and value pairs</a></td></tr>
<tr>
<td>200</td><td><a class="post-section-overview" href="#what-is-the-main-difference-between-objectvalues-and-objectentries-method">What is the main difference between Object.values and Object.entries method</a></td></tr>
<tr>
<td>201</td><td><a class="post-section-overview" href="#how-can-you-get-the-list-of-keys-of-any-object">How can you get the list of keys of any object</a></td></tr>
<tr>
<td>202</td><td><a class="post-section-overview" href="#how-do-you-create-an-object-with-prototype">How do you create an object with prototype</a></td></tr>
<tr>
<td>203</td><td><a class="post-section-overview" href="#what-is-a-weakset">What is a WeakSet</a></td></tr>
<tr>
<td>204</td><td><a class="post-section-overview" href="#what-are-the-differences-between-weakset-and-set">What are the differences between WeakSet and Set</a></td></tr>
<tr>
<td>205</td><td><a class="post-section-overview" href="#list-down-the-collection-of-methods-available-on-weakset">List down the collection of methods available on WeakSet</a></td></tr>
<tr>
<td>206</td><td><a class="post-section-overview" href="#what-is-a-weakmap">What is a WeakMap</a></td></tr>
<tr>
<td>207</td><td><a class="post-section-overview" href="#what-are-the-differences-between-weakmap-and-map">What are the differences between WeakMap and Map</a></td></tr>
<tr>
<td>208</td><td><a class="post-section-overview" href="#list-down-the-collection-of-methods-available-on-weakmap">List down the collection of methods available on WeakMap</a></td></tr>
<tr>
<td>209</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-uneval">What is the purpose of uneval</a></td></tr>
<tr>
<td>210</td><td><a class="post-section-overview" href="#how-do-you-encode-an-url">How do you encode an URL</a></td></tr>
<tr>
<td>211</td><td><a class="post-section-overview" href="#how-do-you-decode-an-url">How do you decode an URL</a></td></tr>
<tr>
<td>212</td><td><a class="post-section-overview" href="#how-do-you-print-the-contents-of-web-page">How do you print the contents of web page</a></td></tr>
<tr>
<td>213</td><td><a class="post-section-overview" href="#what-is-the-difference-between-uneval-and-eval">What is the difference between uneval and eval</a></td></tr>
<tr>
<td>214</td><td><a class="post-section-overview" href="#what-is-an-anonymous-function">What is an anonymous function</a></td></tr>
<tr>
<td>215</td><td><a class="post-section-overview" href="#what-is-the-precedence-order-between-local-and-global-variables">What is the precedence order between local and global variables</a></td></tr>
<tr>
<td>216</td><td><a class="post-section-overview" href="#what-are-javascript-accessors">What are javascript accessors</a></td></tr>
<tr>
<td>217</td><td><a class="post-section-overview" href="#how-do-you-define-property-on-object-constructor">How do you define property on Object constructor</a></td></tr>
<tr>
<td>218</td><td><a class="post-section-overview" href="#what-is-the-difference-between-get-and-defineproperty">What is the difference between get and defineProperty</a></td></tr>
<tr>
<td>219</td><td><a class="post-section-overview" href="#what-are-the-advantages-of-getters-and-setters">What are the advantages of Getters and Setters</a></td></tr>
<tr>
<td>220</td><td><a class="post-section-overview" href="#can-i-add-getters-and-setters-using-defineproperty-method">Can I add getters and setters using defineProperty method</a></td></tr>
<tr>
<td>221</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-switch-case">What is the purpose of switch-case</a></td></tr>
<tr>
<td>222</td><td><a class="post-section-overview" href="#what-are-the-conventions-to-be-followed-for-the-usage-of-switch-case">What are the conventions to be followed for the usage of switch case</a></td></tr>
<tr>
<td>223</td><td><a class="post-section-overview" href="#what-are-primitive-data-types">What are primitive data types</a></td></tr>
<tr>
<td>224</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-access-object-properties">What are the different ways to access object properties</a></td></tr>
<tr>
<td>225</td><td><a class="post-section-overview" href="#what-are-the-function-parameter-rules">What are the function parameter rules</a></td></tr>
<tr>
<td>226</td><td><a class="post-section-overview" href="#what-is-an-error-object">What is an error object</a></td></tr>
<tr>
<td>227</td><td><a class="post-section-overview" href="#when-you-get-a-syntax-error">When you get a syntax error</a></td></tr>
<tr>
<td>228</td><td><a class="post-section-overview" href="#what-are-the-different-error-names-from-error-object">What are the different error names from error object</a></td></tr>
<tr>
<td>229</td><td><a class="post-section-overview" href="#what-are-the-various-statements-in-error-handling">What are the various statements in error handling</a></td></tr>
<tr>
<td>230</td><td><a class="post-section-overview" href="#what-are-the-two-types-of-loops-in-javascript">What are the two types of loops in javascript</a></td></tr>
<tr>
<td>231</td><td><a class="post-section-overview" href="#what-is-nodejs">What is nodejs</a></td></tr>
<tr>
<td>232</td><td><a class="post-section-overview" href="#what-is-an-intl-object">What is an Intl object</a></td></tr>
<tr>
<td>233</td><td><a class="post-section-overview" href="#how-do-you-perform-language-specific-date-and-time-formatting">How do you perform language specific date and time formatting</a></td></tr>
<tr>
<td>234</td><td><a class="post-section-overview" href="#what-is-an-iterator">What is an Iterator</a></td></tr>
<tr>
<td>235</td><td><a class="post-section-overview" href="#how-does-synchronous-iteration-works">How does synchronous iteration works</a></td></tr>
<tr>
<td>236</td><td><a class="post-section-overview" href="#what-is-an-event-loop">What is an event loop</a></td></tr>
<tr>
<td>237</td><td><a class="post-section-overview" href="#what-is-call-stack">What is call stack</a></td></tr>
<tr>
<td>238</td><td><a class="post-section-overview" href="#what-is-an-event-queue">What is an event queue</a></td></tr>
<tr>
<td>239</td><td><a class="post-section-overview" href="#what-is-a-decorator">What is a decorator</a></td></tr>
<tr>
<td>240</td><td><a class="post-section-overview" href="#what-are-the-properties-of-intl-object">What are the properties of Intl object</a></td></tr>
<tr>
<td>241</td><td><a class="post-section-overview" href="#what-is-an-unary-operator">What is an Unary operator</a></td></tr>
<tr>
<td>242</td><td><a class="post-section-overview" href="#how-do-you-sort-elements-in-an-array">How do you sort elements in an array</a></td></tr>
<tr>
<td>243</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-comparefunction-while-sorting-arrays">What is the purpose of compareFunction while sorting arrays</a></td></tr>
<tr>
<td>244</td><td><a class="post-section-overview" href="#how-do-you-reversing-an-array">How do you reversing an array</a></td></tr>
<tr>
<td>245</td><td><a class="post-section-overview" href="#how-do-you-find-min-and-max-value-in-an-array">How do you find min and max value in an array</a></td></tr>
<tr>
<td>246</td><td><a class="post-section-overview" href="#how-do-you-find-min-and-max-values-without-math-functions">How do you find min and max values without Math functions</a></td></tr>
<tr>
<td>247</td><td><a class="post-section-overview" href="#what-is-an-empty-statement-and-purpose-of-it">What is an empty statement and purpose of it</a></td></tr>
<tr>
<td>248</td><td><a class="post-section-overview" href="#how-do-you-get-metadata-of-a-module">How do you get metadata of a module</a></td></tr>
<tr>
<td>249</td><td><a class="post-section-overview" href="#what-is-a-comma-operator">What is a comma operator</a></td></tr>
<tr>
<td>250</td><td><a class="post-section-overview" href="#what-is-the-advantage-of-a-comma-operator">What is the advantage of a comma operator</a></td></tr>
<tr>
<td>251</td><td><a class="post-section-overview" href="#what-is-typescript">What is typescript</a></td></tr>
<tr>
<td>252</td><td><a class="post-section-overview" href="#what-are-the-differences-between-javascript-and-typescript">What are the differences between javascript and typescript</a></td></tr>
<tr>
<td>253</td><td><a class="post-section-overview" href="#what-are-the-advantages-of-typescript-over-javascript">What are the advantages of typescript over javascript</a></td></tr>
<tr>
<td>254</td><td><a class="post-section-overview" href="#what-is-an-object-initializer">What is an object initializer</a></td></tr>
<tr>
<td>255</td><td><a class="post-section-overview" href="#what-is-a-constructor-method">What is a constructor method</a></td></tr>
<tr>
<td>256</td><td><a class="post-section-overview" href="#what-happens-if-you-write-constructor-more-than-once-in-a-class">What happens if you write constructor more than once in a class</a></td></tr>
<tr>
<td>257</td><td><a class="post-section-overview" href="#how-do-you-call-the-constructor-of-a-parent-class">How do you call the constructor of a parent class</a></td></tr>
<tr>
<td>258</td><td><a class="post-section-overview" href="#how-do-you-get-the-prototype-of-an-object">How do you get the prototype of an object</a></td></tr>
<tr>
<td>259</td><td><a class="post-section-overview" href="#what-happens-if-i-pass-string-type-for-getprototype-method">What happens If I pass string type for getPrototype method</a></td></tr>
<tr>
<td>260</td><td><a class="post-section-overview" href="#how-do-you-set-prototype-of-one-object-to-another">How do you set prototype of one object to another</a></td></tr>
<tr>
<td>261</td><td><a class="post-section-overview" href="#how-do-you-check-whether-an-object-can-be-extendable-or-not">How do you check whether an object can be extendable or not</a></td></tr>
<tr>
<td>262</td><td><a class="post-section-overview" href="#how-do-you-prevent-an-object-to-extend">How do you prevent an object to extend</a></td></tr>
<tr>
<td>263</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-make-an-object-non-extensible">What are the different ways to make an object non-extensible</a></td></tr>
<tr>
<td>264</td><td><a class="post-section-overview" href="#how-do-you-define-multiple-properties-on-an-object">How do you define multiple properties on an object</a></td></tr>
<tr>
<td>265</td><td><a class="post-section-overview" href="#what-is-mean-in-javascript">What is MEAN in javascript</a></td></tr>
<tr>
<td>266</td><td><a class="post-section-overview" href="#what-is-obfuscation-in-javascript">What Is Obfuscation in javascript</a></td></tr>
<tr>
<td>267</td><td><a class="post-section-overview" href="#why-do-you-need-obfuscation">Why do you need Obfuscation</a></td></tr>
<tr>
<td>268</td><td><a class="post-section-overview" href="#what-is-minification">What is Minification</a></td></tr>
<tr>
<td>269</td><td><a class="post-section-overview" href="#what-are-the-advantages-of-minification">What are the advantages of minification</a></td></tr>
<tr>
<td>270</td><td><a class="post-section-overview" href="#what-are-the-differences-between-obfuscation-and-encryption">What are the differences between Obfuscation and Encryption</a></td></tr>
<tr>
<td>271</td><td><a class="post-section-overview" href="#what-are-the-common-tools-used-for-minification">What are the common tools used for minification</a></td></tr>
<tr>
<td>272</td><td><a class="post-section-overview" href="#how-do-you-perform-form-validation-using-javascript">How do you perform form validation using javascript</a></td></tr>
<tr>
<td>273</td><td><a class="post-section-overview" href="#how-do-you-perform-form-validation-without-javascript">How do you perform form validation without javascript</a></td></tr>
<tr>
<td>274</td><td><a class="post-section-overview" href="#what-are-the-dom-methods-available-for-constraint-validation">What are the DOM methods available for constraint validation</a></td></tr>
<tr>
<td>275</td><td><a class="post-section-overview" href="#what-are-the-available-constraint-validation-dom-properties">What are the available constraint validation DOM properties</a></td></tr>
<tr>
<td>276</td><td><a class="post-section-overview" href="#what-are-the-list-of-validity-properties">What are the list of validity properties</a></td></tr>
<tr>
<td>277</td><td><a class="post-section-overview" href="#give-an-example-usage-of-rangeoverflow-property">Give an example usage of rangeOverflow property</a></td></tr>
<tr>
<td>278</td><td><a class="post-section-overview" href="#is-enums-feature-available-in-javascript">Is enums feature available in javascript</a></td></tr>
<tr>
<td>279</td><td><a class="post-section-overview" href="#what-is-an-enum">What is an enum</a></td></tr>
<tr>
<td>280</td><td><a class="post-section-overview" href="#how-do-you-list-all-properties-of-an-object">How do you list all properties of an object</a></td></tr>
<tr>
<td>281</td><td><a class="post-section-overview" href="#how-do-you-get-property-descriptors-of-an-object">How do you get property descriptors of an object</a></td></tr>
<tr>
<td>282</td><td><a class="post-section-overview" href="#what-are-the-attributes-provided-by-a-property-descriptor">What are the attributes provided by a property descriptor</a></td></tr>
<tr>
<td>283</td><td><a class="post-section-overview" href="#how-do-you-extend-classes">How do you extend classes</a></td></tr>
<tr>
<td>284</td><td><a class="post-section-overview" href="#how-do-i-modify-the-url-without-reloading-the-page">How do I modify the url without reloading the page</a></td></tr>
<tr>
<td>285</td><td><a class="post-section-overview" href="#how-do-you-check-whether-an-array-includes-a-particular-value-or-not">How do you check whether an array includes a particular value or not</a></td></tr>
<tr>
<td>286</td><td><a class="post-section-overview" href="#how-do-you-compare-scalar-arrays">How do you compare scalar arrays</a></td></tr>
<tr>
<td>287</td><td><a class="post-section-overview" href="#how-to-get-the-value-from-get-parameters">How to get the value from get parameters</a></td></tr>
<tr>
<td>288</td><td><a class="post-section-overview" href="#how-do-you-print-numbers-with-commas-as-thousand-separators">How do you print numbers with commas as thousand separators</a></td></tr>
<tr>
<td>289</td><td><a class="post-section-overview" href="#what-is-the-difference-between-java-and-javascript">What is the difference between java and javascript</a></td></tr>
<tr>
<td>290</td><td><a class="post-section-overview" href="#does-javascript-supports-namespace">Does JavaScript supports namespace</a></td></tr>
<tr>
<td>291</td><td><a class="post-section-overview" href="#how-do-you-declare-namespace">How do you declare namespace</a></td></tr>
<tr>
<td>292</td><td><a class="post-section-overview" href="#how-do-you-invoke-javascript-code-in-an-iframe-from-parent-page">How do you invoke javascript code in an iframe from parent page</a></td></tr>
<tr>
<td>293</td><td><a class="post-section-overview" href="#how-do-get-the-timezone-offset-from-date">How do get the timezone offset from date</a></td></tr>
<tr>
<td>294</td><td><a class="post-section-overview" href="#how-do-you-load-css-and-js-files-dynamically">How do you load CSS and JS files dynamically</a></td></tr>
<tr>
<td>295</td><td><a class="post-section-overview" href="#what-are-the-different-methods-to-find-html-elements-in-dom">What are the different methods to find HTML elements in DOM</a></td></tr>
<tr>
<td>296</td><td><a class="post-section-overview" href="#what-is-jquery">What is jQuery</a></td></tr>
<tr>
<td>297</td><td><a class="post-section-overview" href="#what-is-v8-javascript-engine">What is V8 JavaScript engine</a></td></tr>
<tr>
<td>298</td><td><a class="post-section-overview" href="#why-do-we-call-javascript-as-dynamic-language">Why do we call javascript as dynamic language</a></td></tr>
<tr>
<td>299</td><td><a class="post-section-overview" href="#what-is-a-void-operator">What is a void operator</a></td></tr>
<tr>
<td>300</td><td><a class="post-section-overview" href="#how-to-set-the-cursor-to-wait">How to set the cursor to wait</a></td></tr>
<tr>
<td>301</td><td><a class="post-section-overview" href="#how-do-you-create-an-infinite-loop">How do you create an infinite loop</a></td></tr>
<tr>
<td>302</td><td><a class="post-section-overview" href="#why-do-you-need-to-avoid-with-statement">Why do you need to avoid with statement</a></td></tr>
<tr>
<td>303</td><td><a class="post-section-overview" href="#what-is-the-output-of-the-following-for-loops">What is the output of the following for loops</a></td></tr>
<tr>
<td>304</td><td><a class="post-section-overview" href="#list-down-some-of-the-features-of-es6">List down some of the features of ES6</a></td></tr>
<tr>
<td>305</td><td><a class="post-section-overview" href="#what-is-es6">What is ES6</a></td></tr>
<tr>
<td>306</td><td><a class="post-section-overview" href="#can-i-redeclare-let-and-const-variables">Can I redeclare let and const variables</a></td></tr>
<tr>
<td>307</td><td><a class="post-section-overview" href="#does-the-const-variable-make-the-value-immutable">Does the <code>const</code> variable make the value immutable</a></td></tr>
<tr>
<td>308</td><td><a class="post-section-overview" href="#what-are-default-parameters">What are default parameters</a></td></tr>
<tr>
<td>309</td><td><a class="post-section-overview" href="#what-are-template-literals">What are template literals</a></td></tr>
<tr>
<td>310</td><td><a class="post-section-overview" href="#how-do-you-write-multi-line-strings-in-template-literals">How do you write multi-line strings in template literals</a></td></tr>
<tr>
<td>311</td><td><a class="post-section-overview" href="#what-are-nesting-templates">What are nesting templates</a></td></tr>
<tr>
<td>312</td><td><a class="post-section-overview" href="#what-are-tagged-templates">What are tagged templates</a></td></tr>
<tr>
<td>313</td><td><a class="post-section-overview" href="#what-are-raw-strings">What are raw strings</a></td></tr>
<tr>
<td>314</td><td><a class="post-section-overview" href="#what-is-destructuring-assignment">What is destructuring assignment</a></td></tr>
<tr>
<td>315</td><td><a class="post-section-overview" href="#what-are-default-values-in-destructuring-assignment">What are default values in destructuring assignment</a></td></tr>
<tr>
<td>316</td><td><a class="post-section-overview" href="#how-do-you-swap-variables-in-destructuring-assignment">How do you swap variables in destructuring assignment</a></td></tr>
<tr>
<td>317</td><td><a class="post-section-overview" href="#what-are-enhanced-object-literals">What are enhanced object literals</a></td></tr>
<tr>
<td>318</td><td><a class="post-section-overview" href="#what-are-dynamic-imports">What are dynamic imports</a></td></tr>
<tr>
<td>319</td><td><a class="post-section-overview" href="#what-are-the-use-cases-for-dynamic-imports">What are the use cases for dynamic imports</a></td></tr>
<tr>
<td>320</td><td><a class="post-section-overview" href="#what-are-typed-arrays">What are typed arrays</a></td></tr>
<tr>
<td>321</td><td><a class="post-section-overview" href="#what-are-the-advantages-of-module-loaders">What are the advantages of module loaders</a></td></tr>
<tr>
<td>322</td><td><a class="post-section-overview" href="#what-is-collation">What is collation</a></td></tr>
<tr>
<td>323</td><td><a class="post-section-overview" href="#what-is-forof-statement">What is for...of statement</a></td></tr>
<tr>
<td>324</td><td><a class="post-section-overview" href="#what-is-the-output-of-below-spread-operator-array">What is the output of below spread operator array</a></td></tr>
<tr>
<td>325</td><td><a class="post-section-overview" href="#is-postmessage-secure">Is PostMessage secure</a></td></tr>
<tr>
<td>326</td><td><a class="post-section-overview" href="#what-are-the-problems-with-postmessage-target-origin-as-wildcard">What are the problems with postmessage target origin as wildcard</a></td></tr>
<tr>
<td>327</td><td><a class="post-section-overview" href="#how-do-you-avoid-receiving-postmessages-from-attackers">How do you avoid receiving postMessages from attackers</a></td></tr>
<tr>
<td>328</td><td><a class="post-section-overview" href="#can-i-avoid-using-postmessages-completely">Can I avoid using postMessages completely</a></td></tr>
<tr>
<td>329</td><td><a class="post-section-overview" href="#is-postmessages-synchronous">Is postMessages synchronous</a></td></tr>
<tr>
<td>330</td><td><a class="post-section-overview" href="#what-paradigm-is-javascript">What paradigm is Javascript</a></td></tr>
<tr>
<td>331</td><td><a class="post-section-overview" href="#what-is-the-difference-between-internal-and-external-javascript">What is the difference between internal and external javascript</a></td></tr>
<tr>
<td>332</td><td><a class="post-section-overview" href="#is-javascript-faster-than-server-side-script">Is JavaScript faster than server side script</a></td></tr>
<tr>
<td>333</td><td><a class="post-section-overview" href="#how-do-you-get-the-status-of-a-checkbox">How do you get the status of a checkbox</a></td></tr>
<tr>
<td>334</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-double-tilde-operator">What is the purpose of double tilde operator</a></td></tr>
<tr>
<td>335</td><td><a class="post-section-overview" href="#how-do-you-convert-character-to-ascii-code">How do you convert character to ASCII code</a></td></tr>
<tr>
<td>336</td><td><a class="post-section-overview" href="#what-is-arraybuffer">What is ArrayBuffer</a></td></tr>
<tr>
<td>337</td><td><a class="post-section-overview" href="#what-is-the-output-of-below-string-expression">What is the output of below string expression</a></td></tr>
<tr>
<td>338</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-error-object">What is the purpose of Error object</a></td></tr>
<tr>
<td>339</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-evalerror-object">What is the purpose of EvalError object</a></td></tr>
<tr>
<td>340</td><td><a class="post-section-overview" href="#what-are-the-list-of-cases-error-thrown-from-non-strict-mode-to-strict-mode">What are the list of cases error thrown from non-strict mode to strict mode</a></td></tr>
<tr>
<td>341</td><td><a class="post-section-overview" href="#do-all-objects-have-prototypes">Do all objects have prototypes</a></td></tr>
<tr>
<td>342</td><td><a class="post-section-overview" href="#what-is-the-difference-between-a-parameter-and-an-argument">What is the difference between a parameter and an argument</a></td></tr>
<tr>
<td>343</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-some-method-in-arrays">What is the purpose of some method in arrays</a></td></tr>
<tr>
<td>344</td><td><a class="post-section-overview" href="#how-do-you-combine-two-or-more-arrays">How do you combine two or more arrays</a></td></tr>
<tr>
<td>345</td><td><a class="post-section-overview" href="#what-is-the-difference-between-shallow-and-deep-copy">What is the difference between Shallow and Deep copy</a></td></tr>
<tr>
<td>346</td><td><a class="post-section-overview" href="#how-do-you-create-specific-number-of-copies-of-a-string">How do you create specific number of copies of a string</a></td></tr>
<tr>
<td>347</td><td><a class="post-section-overview" href="#how-do-you-return-all-matching-strings-against-a-regular-expression">How do you return all matching strings against a regular expression</a></td></tr>
<tr>
<td>348</td><td><a class="post-section-overview" href="#how-do-you-trim-a-string-at-the-beginning-or-ending">How do you trim a string at the beginning or ending</a></td></tr>
<tr>
<td>349</td><td><a class="post-section-overview" href="#what-is-the-output-of-below-console-statement-with-unary-operator">What is the output of below console statement with unary operator</a></td></tr>
<tr>
<td>350</td><td><a class="post-section-overview" href="#does-javascript-uses-mixins">Does javascript uses mixins</a></td></tr>
<tr>
<td>351</td><td><a class="post-section-overview" href="#what-is-a-thunk-function">What is a thunk function</a></td></tr>
<tr>
<td>352</td><td><a class="post-section-overview" href="#what-are-asynchronous-thunks">What are asynchronous thunks</a></td></tr>
<tr>
<td>353</td><td><a class="post-section-overview" href="#what-is-the-output-of-below-function-calls">What is the output of below function calls</a></td></tr>
<tr>
<td>354</td><td><a class="post-section-overview" href="#how-to-remove-all-line-breaks-from-a-string">How to remove all line breaks from a string</a></td></tr>
<tr>
<td>355</td><td><a class="post-section-overview" href="#what-is-the-difference-between-reflow-and-repaint">What is the difference between reflow and repaint</a></td></tr>
<tr>
<td>356</td><td><a class="post-section-overview" href="#what-happens-with-negating-an-array">What happens with negating an array</a></td></tr>
<tr>
<td>357</td><td><a class="post-section-overview" href="#what-happens-if-we-add-two-arrays">What happens if we add two arrays</a></td></tr>
<tr>
<td>358</td><td><a class="post-section-overview" href="#what-is-the-output-of-prepend-additive-operator-on-falsy-values">What is the output of prepend additive operator on falsy values</a></td></tr>
<tr>
<td>359</td><td><a class="post-section-overview" href="#how-do-you-create-self-string-using-special-characters">How do you create self string using special characters</a></td></tr>
<tr>
<td>360</td><td><a class="post-section-overview" href="#how-do-you-remove-falsy-values-from-an-array">How do you remove falsy values from an array</a></td></tr>
<tr>
<td>361</td><td><a class="post-section-overview" href="#how-do-you-get-unique-values-of-an-array">How do you get unique values of an array</a></td></tr>
<tr>
<td>362</td><td><a class="post-section-overview" href="#what-is-destructuring-aliases">What is destructuring aliases</a></td></tr>
<tr>
<td>363</td><td><a class="post-section-overview" href="#how-do-you-map-the-array-values-without-using-map-method">How do you map the array values without using map method</a></td></tr>
<tr>
<td>364</td><td><a class="post-section-overview" href="#how-do-you-empty-an-array">How do you empty an array</a></td></tr>
<tr>
<td>365</td><td><a class="post-section-overview" href="#how-do-you-round-numbers-to-certain-decimals">How do you round numbers to certain decimals</a></td></tr>
<tr>
<td>366</td><td><a class="post-section-overview" href="#what-is-the-easiest-way-to-convert-an-array-to-an-object">What is the easiest way to convert an array to an object</a></td></tr>
<tr>
<td>367</td><td><a class="post-section-overview" href="#how-do-you-create-an-array-with-some-data">How do you create an array with some data</a></td></tr>
<tr>
<td>368</td><td><a class="post-section-overview" href="#what-are-the-placeholders-from-console-object">What are the placeholders from console object</a></td></tr>
<tr>
<td>369</td><td><a class="post-section-overview" href="#is-it-possible-to-add-css-to-console-messages">Is it possible to add CSS to console messages</a></td></tr>
<tr>
<td>370</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-dir-method-of-console-object">What is the purpose of dir method of console object</a></td></tr>
<tr>
<td>371</td><td><a class="post-section-overview" href="#is-it-possible-to-debug-html-elements-in-console">Is it possible to debug HTML elements in console</a></td></tr>
<tr>
<td>372</td><td><a class="post-section-overview" href="#how-do-you-display-data-in-a-tabular-format-using-console-object">How do you display data in a tabular format using console object</a></td></tr>
<tr>
<td>373</td><td><a class="post-section-overview" href="#how-do-you-verify-that-an-argument-is-a-number-or-not">How do you verify that an argument is a Number or not</a></td></tr>
<tr>
<td>374</td><td><a class="post-section-overview" href="#how-do-you-create-copy-to-clipboard-button">How do you create copy to clipboard button</a></td></tr>
<tr>
<td>375</td><td><a class="post-section-overview" href="#what-is-the-shortcut-to-get-timestamp">What is the shortcut to get timestamp</a></td></tr>
<tr>
<td>376</td><td><a class="post-section-overview" href="#how-do-you-flattening-multi-dimensional-arrays">How do you flattening multi dimensional arrays</a></td></tr>
<tr>
<td>377</td><td><a class="post-section-overview" href="#what-is-the-easiest-multi-condition-checking">What is the easiest multi condition checking</a></td></tr>
<tr>
<td>378</td><td><a class="post-section-overview" href="#how-do-you-capture-browser-back-button">How do you capture browser back button</a></td></tr>
<tr>
<td>379</td><td><a class="post-section-overview" href="#how-do-you-disable-right-click-in-the-web-page">How do you disable right click in the web page</a></td></tr>
<tr>
<td>380</td><td><a class="post-section-overview" href="#what-are-wrapper-objects">What are wrapper objects</a></td></tr>
<tr>
<td>381</td><td><a class="post-section-overview" href="#what-is-ajax">What is AJAX</a></td></tr>
<tr>
<td>382</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-deal-with-asynchronous-code">What are the different ways to deal with Asynchronous Code</a></td></tr>
<tr>
<td>383</td><td><a class="post-section-overview" href="#how-to-cancel-a-fetch-request">How to cancel a fetch request</a></td></tr>
<tr>
<td>384</td><td><a class="post-section-overview" href="#what-is-web-speech-api">What is web speech API</a></td></tr>
<tr>
<td>385</td><td><a class="post-section-overview" href="#what-is-minimum-timeout-throttling">What is minimum timeout throttling</a></td></tr>
<tr>
<td>386</td><td><a class="post-section-overview" href="#how-do-you-implement-zero-timeout-in-modern-browsers">How do you implement zero timeout in modern browsers</a></td></tr>
<tr>
<td>387</td><td><a class="post-section-overview" href="#what-are-tasks-in-event-loop">What are tasks in event loop</a></td></tr>
<tr>
<td>388</td><td><a class="post-section-overview" href="#what-is-microtask">What is microtask</a></td></tr>
<tr>
<td>389</td><td><a class="post-section-overview" href="#what-are-different-event-loops">What are different event loops</a></td></tr>
<tr>
<td>390</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-queuemicrotask">What is the purpose of queueMicrotask</a></td></tr>
<tr>
<td>391</td><td><a class="post-section-overview" href="#how-do-you-use-javascript-libraries-in-typescript-file">How do you use javascript libraries in typescript file</a></td></tr>
<tr>
<td>392</td><td><a class="post-section-overview" href="#what-are-the-differences-between-promises-and-observables">What are the differences between promises and observables</a></td></tr>
<tr>
<td>393</td><td><a class="post-section-overview" href="#what-is-heap">What is heap</a></td></tr>
<tr>
<td>394</td><td><a class="post-section-overview" href="#what-is-an-event-table">What is an event table</a></td></tr>
<tr>
<td>395</td><td><a class="post-section-overview" href="#what-is-a-microtask-queue">What is a microTask queue</a></td></tr>
<tr>
<td>396</td><td><a class="post-section-overview" href="#what-is-the-difference-between-shim-and-polyfill">What is the difference between shim and polyfill</a></td></tr>
<tr>
<td>397</td><td><a class="post-section-overview" href="#how-do-you-detect-primitive-or-non-primitive-value-type">How do you detect primitive or non primitive value type</a></td></tr>
<tr>
<td>398</td><td><a class="post-section-overview" href="#what-is-babel">What is babel</a></td></tr>
<tr>
<td>399</td><td><a class="post-section-overview" href="#is-nodejs-completely-single-threaded">Is Node.js completely single threaded</a></td></tr>
<tr>
<td>400</td><td><a class="post-section-overview" href="#what-are-the-common-use-cases-of-observables">What are the common use cases of observables</a></td></tr>
<tr>
<td>401</td><td><a class="post-section-overview" href="#what-is-rxjs">What is RxJS</a></td></tr>
<tr>
<td>402</td><td><a class="post-section-overview" href="#what-is-the-difference-between-function-constructor-and-function-declaration">What is the difference between Function constructor and function declaration</a></td></tr>
<tr>
<td>403</td><td><a class="post-section-overview" href="#what-is-a-short-circuit-condition">What is a Short circuit condition</a></td></tr>
<tr>
<td>404</td><td><a class="post-section-overview" href="#what-is-the-easiest-way-to-resize-an-array">What is the easiest way to resize an array</a></td></tr>
<tr>
<td>405</td><td><a class="post-section-overview" href="#what-is-an-observable">What is an observable</a></td></tr>
<tr>
<td>406</td><td><a class="post-section-overview" href="#what-is-the-difference-between-function-and-class-declarations">What is the difference between function and class declarations</a></td></tr>
<tr>
<td>407</td><td><a class="post-section-overview" href="#what-is-an-async-function">What is an async function</a></td></tr>
<tr>
<td>408</td><td><a class="post-section-overview" href="#how-do-you-prevent-promises-swallowing-errors">How do you prevent promises swallowing errors</a></td></tr>
<tr>
<td>409</td><td><a class="post-section-overview" href="#what-is-deno">What is deno</a></td></tr>
<tr>
<td>410</td><td><a class="post-section-overview" href="#how-do-you-make-an-object-iterable-in-javascript">How do you make an object iterable in javascript</a></td></tr>
<tr>
<td>411</td><td><a class="post-section-overview" href="#what-is-a-proper-tail-call">What is a Proper Tail Call</a></td></tr>
<tr>
<td>412</td><td><a class="post-section-overview" href="#how-do-you-check-an-object-is-a-promise-or-not">How do you check an object is a promise or not</a></td></tr>
<tr>
<td>413</td><td><a class="post-section-overview" href="#how-to-detect-if-a-function-is-called-as-constructor">How to detect if a function is called as constructor</a></td></tr>
<tr>
<td>414</td><td><a class="post-section-overview" href="#what-are-the-differences-between-arguments-object-and-rest-parameter">What are the differences between arguments object and rest parameter</a></td></tr>
<tr>
<td>415</td><td><a class="post-section-overview" href="#what-are-the-differences-between-spread-operator-and-rest-parameter">What are the differences between spread operator and rest parameter</a></td></tr>
<tr>
<td>416</td><td><a class="post-section-overview" href="#what-are-the-different-kinds-of-generators">What are the different kinds of generators</a></td></tr>
<tr>
<td>417</td><td><a class="post-section-overview" href="#what-are-the-built-in-iterables">What are the built-in iterables</a></td></tr>
<tr>
<td>418</td><td><a class="post-section-overview" href="#what-are-the-differences-between-forof-and-forin-statements">What are the differences between for...of and for...in statements</a></td></tr>
<tr>
<td>419</td><td><a class="post-section-overview" href="#how-do-you-define-instance-and-non-instance-properties">How do you define instance and non-instance properties</a></td></tr>
<tr>
<td>420</td><td><a class="post-section-overview" href="#what-is-the-difference-between-isnan-and-numberisnan">What is the difference between isNaN and Number.isNaN?</a></td></tr>
<tr>
<td>421</td><td><a class="post-section-overview" href="#how-to-invoke-an-iife-without-any-extra-brackets">How to invoke an IIFE without any extra brackets?</a></td></tr>
<tr>
<td>422</td><td><a class="post-section-overview" href="#is-that-possible-to-use-expressions-in-switch-cases">Is that possible to use expressions in switch cases?</a></td></tr>
<tr>
<td>423</td><td><a class="post-section-overview" href="#what-is-the-easiest-way-to-ignore-promise-errors">What is the easiest way to ignore promise errors?</a></td></tr>
<tr>
<td>424</td><td><a class="post-section-overview" href="#how-do-style-the-console-output-using-css">How do style the console output using CSS?</a></td></tr>
<tr>
<td>425</td><td><a class="post-section-overview" href="#what-is-nullish-coalescing-operator-">What is nullish coalescing operator (??)?</a></td></tr>
<tr>
<td>426</td><td><a class="post-section-overview" href="#how-do-you-group-and-nest-console-output">How do you group and nest console output?</a></td></tr>
<tr>
<td>427</td><td><a class="post-section-overview" href="#what-is-the-difference-between-dense-and-sparse-arrays">What is the difference between dense and sparse arrays?</a></td></tr>
<tr>
<td>428</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-create-sparse-arrays">What are the different ways to create sparse arrays?</a></td></tr>
<tr>
<td>429</td><td><a class="post-section-overview" href="#what-is-the-difference-between-settimeout-setimmediate-and-processnexttick">What is the difference between setTimeout, setImmediate and process.nextTick?</a></td></tr>
<tr>
<td>430</td><td><a class="post-section-overview" href="#how-do-you-reverse-an-array-without-modifying-original-array">How do you reverse an array without modifying original array?</a></td></tr>
<tr>
<td>431</td><td><a class="post-section-overview" href="#how-do-you-create-custom-html-element">How do you create custom HTML element?</a></td></tr>
<tr>
<td>432</td><td><a class="post-section-overview" href="#what-is-global-execution-context">What is global execution context?</a></td></tr>
<tr>
<td>433</td><td><a class="post-section-overview" href="#what-is-function-execution-context">What is function execution context?</a></td></tr>
<tr>
<td>434</td><td><a class="post-section-overview" href="#what-is-debouncing">What is debouncing?</a></td></tr>
<tr>
<td>435</td><td><a class="post-section-overview" href="#what-is-throttling">What is throttling?</a></td></tr>
<tr>
<td>436</td><td><a class="post-section-overview" href="#what-is-optional-chaining">What is optional chaining?</a></td></tr>
<tr>
<td>437</td><td><a class="post-section-overview" href="#what-is-an-environment-record">What is an environment record?</a></td></tr>
<tr>
<td>438</td><td><a class="post-section-overview" href="#how-to-verify-if-a-variable-is-an-array">How to verify if a variable is an array?</a></td></tr>
<tr>
<td>439</td><td><a class="post-section-overview" href="#what-is-pass-by-value-and-pass-by-reference">What is pass by value and pass by reference?</a></td></tr>
<tr>
<td>440</td><td><a class="post-section-overview" href="#what-are-the-differences-between-primitives-and-non-primitives">What are the differences between primitives and non-primitives?</a></td></tr>
<tr>
<td>441</td><td><a class="post-section-overview" href="#how-do-you-create-your-own-bind-method-using-either-call-or-apply-method">How do you create your own bind method using either call or apply method?</a></td></tr>
<tr>
<td>442</td><td><a class="post-section-overview" href="#what-are-the-differences-between-pure-and-impure-functions">What are the differences between pure and impure functions?</a></td></tr>
<tr>
<td>443</td><td><a class="post-section-overview" href="#what-is-referential-transparency">What is referential transparency?</a></td></tr>
<tr>
<td>444</td><td><a class="post-section-overview" href="#what-are-the-possible-side-effects-in-javascript">What are the possible side-effects in javascript?</a></td></tr>
<tr>
<td>445</td><td><a class="post-section-overview" href="#what-are-compose-and-pipe-functions">What are compose and pipe functions?</a></td></tr>
<tr>
<td>446</td><td><a class="post-section-overview" href="#what-is-module-pattern">What is module pattern?</a></td></tr>
<tr>
<td>447</td><td><a class="post-section-overview" href="#what-is-function-composition">What is Function Composition?</a></td></tr>
<tr>
<td>448</td><td><a class="post-section-overview" href="#how-to-use-await-outside-of-async-function-prior-to-es2022">How to use await outside of async function prior to ES2022?</a></td></tr>
<tr>
<td>449</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-the-this-keyword-in-javascript">What is the purpose of the this keyword in JavaScript?</a></td></tr>
<tr>
<td>450</td><td><a class="post-section-overview" href="#what-are-the-uses-of-closures">What are the uses of closures?</a></td></tr>
<tr>
<td>451</td><td><a class="post-section-overview" href="#what-are-the-phases-of-execution-context">What are the phases of execution context?</a></td></tr>
<tr>
<td>452</td><td><a class="post-section-overview" href="#what-are-the-possible-reasons-for-memory-leaks">What are the possible reasons for memory leaks?</a></td></tr>
<tr>
<td>453</td><td><a class="post-section-overview" href="#what-are-the-optimization-techniques-of-v8-engine">What are the optimization techniques of V8 engine?</a></td></tr>
<tr>
<td>454</td><td><a class="post-section-overview" href="#what-are-the-examples-of-built-in-higher-order-functions">What are the examples of built-in higher order functions?</a></td></tr>
<tr>
<td>455</td><td><a class="post-section-overview" href="#what-are-the-benefits-higher-order-functions">What are the benefits higher order functions?</a></td></tr>
<tr>
<td>456</td><td><a class="post-section-overview" href="#how-do-you-create-polyfills-for-map-filter-and-reduce-methods">How do you create polyfills for map, filter and reduce methods?</a></td></tr>
<tr>
<td>457</td><td><a class="post-section-overview" href="#what-is-the-difference-between-map-and-foreach-functions">What is the difference between map and forEach functions?</a></td></tr>
<tr>
<td>458</td><td><a class="post-section-overview" href="#give-an-example-of-statements-affected-by-automatic-semicolon-insertion">Give an example of statements affected by automatic semicolon insertion?</a></td></tr>
<tr>
<td>459</td><td><a class="post-section-overview" href="#what-are-the-event-phases-of-a-browser">What are the event phases of a browser?</a></td></tr>
<tr>
<td>460</td><td><a class="post-section-overview" href="#what-are-the-real-world-use-cases-of-proxy">What are the real world use cases of proxy?</a></td></tr>
<tr>
<td>461</td><td><a class="post-section-overview" href="#what-are-hidden-classes">What are hidden classes?</a></td></tr>
<tr>
<td>462</td><td><a class="post-section-overview" href="#what-is-inline-caching">What is inline caching?</a></td></tr>
<tr>
<td>463</td><td><a class="post-section-overview" href="#what-are-the-different-ways-to-execute-external-scripts">What are the different ways to execute external scripts?</a></td></tr>
<tr>
<td>464</td><td><a class="post-section-overview" href="#what-is-lexical-scope">What is Lexical Scope?</a></td></tr>
<tr>
<td>465</td><td><a class="post-section-overview" href="#how-to-detect-system-dark-mode-in-javascript">How to detect system dark mode in javascript?</a></td></tr>
<tr>
<td>466</td><td><a class="post-section-overview" href="#what-is-the-purpose-of-requestanimationframe-method">What is the purpose of requestAnimationFrame method?</a></td></tr>
<tr>
<td>467</td><td><a class="post-section-overview" href="#what-is-the-difference-between-substring-and-substr-methods">What is the difference between substring and substr methods?</a></td></tr>
<tr>
<td>468</td><td><a class="post-section-overview" href="#how-to-find-the-number-of-parameters-expected-by-a-function">How to find the number of parameters expected by a function?</a></td></tr>
<tr>
<td>469</td><td><a class="post-section-overview" href="#what-is-globalthis-and-what-is-the-importance-of-it">What is globalThis, and what is the importance of it?</a></td></tr>
<tr>
<td>470</td><td><a class="post-section-overview" href="#what-are-the-array-mutation-methods">What are the array mutation methods?</a></td></tr>
</tbody>
</table>
</div>

<ol>
<li><h3 id="heading-what-are-the-possible-ways-to-create-objects-in-javascript">What are the possible ways to create objects in JavaScript</h3>
<p>There are many ways to create objects in javascript as mentioned below:</p>
<ol>
<li><p><strong>Object literal syntax:</strong></p>
<p>The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = {
     <span class="hljs-attr">name</span>: <span class="hljs-string">"Sudheer"</span>,
     <span class="hljs-attr">age</span>: <span class="hljs-number">34</span>
};
</code></pre>
<p>Object literal property values can be of any data type, including array, function, and nested object.</p>
<p><strong>Note:</strong> This is one of the easiest ways to create an object.</p>
</li>
<li><p><strong>Object constructor:</strong></p>
<p>The simplest way to create an empty object is using the <code>Object</code> constructor. Currently this approach is not recommended.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();
</code></pre>
<p>The <code>Object()</code> is a built-in constructor function so "new" keyword is not required. The above code snippet can be re-written as:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = <span class="hljs-built_in">Object</span>();
</code></pre>
</li>
<li><p><strong>Object's create method:</strong></p>
<p>The <code>create</code> method of Object is used to create a new object by passing the specified prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects.
The second argument is optional and it is used to create properties on a newly created object.</p>
<p>The following code creates a new empty object whose prototype is null.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = <span class="hljs-built_in">Object</span>.create(<span class="hljs-literal">null</span>);
</code></pre>
<p>The following example creates an object along with additional new properties.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> vehicle = {
  <span class="hljs-attr">wheels</span>: <span class="hljs-string">'4'</span>,
  <span class="hljs-attr">fuelType</span>: <span class="hljs-string">'Gasoline'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'Green'</span>
}
<span class="hljs-keyword">let</span> carProps = {
  <span class="hljs-attr">type</span>: {
    <span class="hljs-attr">value</span>: <span class="hljs-string">'Volkswagen'</span>
  },
  <span class="hljs-attr">model</span>: {
    <span class="hljs-attr">value</span>: <span class="hljs-string">'Golf'</span>
  }
}

<span class="hljs-keyword">var</span> car = <span class="hljs-built_in">Object</span>.create(vehicle, carProps);
<span class="hljs-built_in">console</span>.log(car);
</code></pre>
</li>
<li><p><strong>Function constructor:</strong></p>
<p>In this approach, create any function and apply the new operator to create object instances.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = <span class="hljs-number">21</span>;
}
<span class="hljs-keyword">var</span> object = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Sudheer"</span>);
</code></pre>
</li>
<li><p><strong>Function constructor with prototype:</strong></p>
<p>This is similar to function constructor but it uses prototype for their properties and methods,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params"></span>) </span>{}
Person.prototype.name = <span class="hljs-string">"Sudheer"</span>;
<span class="hljs-keyword">var</span> object = <span class="hljs-keyword">new</span> Person();
</code></pre>
<p>This is equivalent to creating an instance with Object.create method with a function prototype and then calling that function with an instance and parameters as arguments.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>) </span>{}

<span class="hljs-keyword">new</span> func(x, y, z);
</code></pre>
<p><strong>(OR)</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create a new instance using function prototype.</span>
<span class="hljs-keyword">var</span> newInstance = <span class="hljs-built_in">Object</span>.create(func.prototype)

<span class="hljs-comment">// Call the function</span>
<span class="hljs-keyword">var</span> result = func.call(newInstance, x, y, z),

<span class="hljs-comment">// If the result is a non-null object then use it otherwise just use the new instance.</span>
<span class="hljs-built_in">console</span>.log(result &amp;&amp; <span class="hljs-keyword">typeof</span> result === <span class="hljs-string">'object'</span> ? result : newInstance);
</code></pre>
</li>
<li><p><strong>Object's assign method:</strong></p>
<p>The <code>Object.assign</code> method is used to copy all the properties from one or more source objects and stores them into a target object.</p>
<p>The following code creates a new staff object by copying properties of his working company and the car he owns.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> orgObject = { <span class="hljs-attr">company</span>: <span class="hljs-string">'XYZ Corp'</span>};
<span class="hljs-keyword">const</span> carObject = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Toyota'</span>};
<span class="hljs-keyword">const</span> staff = <span class="hljs-built_in">Object</span>.assign({}, orgObject, carObject);
</code></pre>
</li>
<li><p><strong>ES6 Class syntax:</strong></p>
<p>ES6 introduces class feature to create objects.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-keyword">var</span> object = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Sudheer"</span>);
</code></pre>
</li>
<li><p><strong>Singleton pattern:</strong></p>
<p>A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't accidentally create multiple instances.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = <span class="hljs-keyword">new</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Sudheer"</span>;
})();
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
</ol>
</li>
<li><h3 id="heading-what-is-a-prototype-chain">What is a prototype chain</h3>
<p><strong>Prototype chaining</strong> is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. i.e, When you create an object using a constructor function or a class, the created object inherits properties from a prototype object.</p>
<p>The prototype on object instance is available through <strong>Object.getPrototypeOf(object)</strong> or <strong>__proto__</strong> property whereas prototype on constructor function is available through <strong>Object.prototype</strong>.</p>
<p><img src="images/prototype_chain.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-call-apply-and-bind">What is the difference between Call, Apply and Bind</h3>
<p>The difference between Call, Apply and Bind can be explained with below examples,</p>
<p><strong>Call:</strong> The call() method invokes a function with a given <code>this</code> value and arguments provided one by one</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> employee1 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Rodson"</span> };
<span class="hljs-keyword">var</span> employee2 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jimmy"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Baily"</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">invite</span>(<span class="hljs-params">greeting1, greeting2</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    greeting1 + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName + <span class="hljs-string">", "</span> + greeting2
  );
}

invite.call(employee1, <span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>); <span class="hljs-comment">// Hello John Rodson, How are you?</span>
invite.call(employee2, <span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>); <span class="hljs-comment">// Hello Jimmy Baily, How are you?</span>
</code></pre>
<p><strong>Apply:</strong> Invokes the function with a given <code>this</code> value and allows you to pass in arguments as an array</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> employee1 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Rodson"</span> };
<span class="hljs-keyword">var</span> employee2 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jimmy"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Baily"</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">invite</span>(<span class="hljs-params">greeting1, greeting2</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    greeting1 + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName + <span class="hljs-string">", "</span> + greeting2
  );
}

invite.apply(employee1, [<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>]); <span class="hljs-comment">// Hello John Rodson, How are you?</span>
invite.apply(employee2, [<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>]); <span class="hljs-comment">// Hello Jimmy Baily, How are you?</span>
</code></pre>
<p><strong>Bind:</strong> returns a new function, allowing you to pass any number of arguments</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> employee1 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Rodson"</span> };
<span class="hljs-keyword">var</span> employee2 = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Jimmy"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Baily"</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">invite</span>(<span class="hljs-params">greeting1, greeting2</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    greeting1 + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName + <span class="hljs-string">", "</span> + greeting2
  );
}

<span class="hljs-keyword">var</span> inviteEmployee1 = invite.bind(employee1);
<span class="hljs-keyword">var</span> inviteEmployee2 = invite.bind(employee2);
inviteEmployee1(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>); <span class="hljs-comment">// Hello John Rodson, How are you?</span>
inviteEmployee2(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"How are you?"</span>); <span class="hljs-comment">// Hello Jimmy Baily, How are you?</span>
</code></pre>
<p>Call and Apply are pretty much interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for <strong>comma</strong> (separated list) and Apply is for <strong>Array</strong>.</p>
<p>Bind creates a new function that will have <code>this</code> set to the first parameter passed to bind().</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-json-and-its-common-operations">What is JSON and its common operations</h3>
<p><strong>JSON</strong> is a text-based data format following JavaScript object syntax, which was popularized by <code>Douglas Crockford</code>. It is useful when you want to transmit data across a network. It is basically just a text file with an extension of .json, and a MIME type of application/json</p>
<p><strong>Parsing:</strong> Converting a string to a native object</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">JSON</span>.parse(text);
</code></pre>
<p><strong>Stringification:</strong> Converting a native object to a string so that it can be transmitted across the network</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">JSON</span>.stringify(object);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-the-array-slice-method">What is the purpose of the array slice method</h3>
<p>The <strong>slice()</strong> method returns the selected elements in an array as a new array object. It selects the elements starting at the given start argument, and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end of the array. This method can also accept negative index which counts back from the end of the array.</p>
<p>Some of the examples of this method are,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arrayIntegers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">let</span> arrayIntegers1 = arrayIntegers.slice(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// returns [1,2]</span>
<span class="hljs-keyword">let</span> arrayIntegers2 = arrayIntegers.slice(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// returns [3]</span>
<span class="hljs-keyword">let</span> arrayIntegers3 = arrayIntegers.slice(<span class="hljs-number">4</span>); <span class="hljs-comment">//returns [5]</span>
<span class="hljs-keyword">let</span> arrayIntegers4 = arrayIntegers.slice(<span class="hljs-number">-3</span>, <span class="hljs-number">-1</span>); <span class="hljs-comment">//returns [3, 4]</span>
</code></pre>
<p><strong>Note:</strong> Slice method doesn't mutate the original array but it returns the subset as a new array.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-the-array-splice-method">What is the purpose of the array splice method</h3>
<p>The <strong>splice()</strong> method adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position/index for insertion or deletion whereas the optional second argument indicates the number of elements to be deleted. Each additional argument is added to the array.</p>
<p>Some of the examples of this method are:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arrayIntegersOriginal1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">let</span> arrayIntegersOriginal2 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">let</span> arrayIntegersOriginal3 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-keyword">let</span> arrayIntegers1 = arrayIntegersOriginal1.splice(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// returns [1, 2]; original array: [3, 4, 5]</span>
<span class="hljs-keyword">let</span> arrayIntegers2 = arrayIntegersOriginal2.splice(<span class="hljs-number">3</span>); <span class="hljs-comment">// returns [4, 5]; original array: [1, 2, 3]</span>
<span class="hljs-keyword">let</span> arrayIntegers3 = arrayIntegersOriginal3.splice(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>); <span class="hljs-comment">//returns [4]; original array: [1, 2, 3, "a", "b", "c", 5]</span>
</code></pre>
<p><strong>Note:</strong> Splice method modifies the original array and returns the deleted array.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-slice-and-splice">What is the difference between slice and splice</h3>
<p>Some of the major differences in a tabular form:</p>
<p>| Slice                                        | Splice                                          |
| -------------------------------------------- | ----------------------------------------------- |
| Doesn't modify the original array(immutable) | Modifies the original array(mutable)            |
| Returns the subset of original array         | Returns the deleted elements as array           |
| Used to pick the elements from array         | Used to insert/delete elements to/from array |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-compare-object-and-map">How do you compare Object and Map</h3>
<p><strong>Objects</strong> are similar to <strong>Maps</strong> in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Due to this reason, Objects have been used as Maps historically. But there are important differences that make using a Map preferable in certain cases:</p>
<ol>
<li>The keys of an Object can be Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive type.</li>
<li>The keys in a Map are ordered while keys added to Object are not. Thus, when iterating over it, a Map object returns keys in the order of insertion.</li>
<li>You can get the size of a Map easily with the size property, while the number of properties in an Object must be determined manually.</li>
<li>A Map is an iterable and can thus be directly iterated, whereas iterating over an Object requires obtaining its keys in some fashion and iterating over them.</li>
<li>An Object has a prototype, so there are default keys in an object that could collide with your keys if you're not careful. As of ES5 this can be bypassed by creating an object(which can be called a map) using <code>Object.create(null)</code>, but this practice is seldom done.</li>
<li>A Map may perform better in scenarios involving frequent addition and removal of key pairs.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-and-operators">What is the difference between == and === operators</h3>
<p>JavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators take type of variable in consideration, while non-strict operators make type correction/conversion based upon values of variables. The strict operators follow the below conditions for different types,</p>
<ol>
<li>Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.</li>
<li>Two numbers are strictly equal when they are numerically equal, i.e., having the same number value.
There are two special cases in this,<ol>
<li>NaN is not equal to anything, including NaN.</li>
<li>Positive and negative zeros are equal to one another.</li>
</ol>
</li>
<li>Two Boolean operands are strictly equal if both are true or both are false.</li>
<li>Two objects are strictly equal if they refer to the same Object.</li>
<li>Null and Undefined types are not equal with ===, but equal with == .
i.e, <code>null===undefined --&gt; false</code>, but <code>null==undefined --&gt; true</code></li>
</ol>
<p>Some of the example which covers the above cases:</p>
<pre><code class="lang-javascript"><span class="hljs-number">0</span> == <span class="hljs-literal">false</span>   <span class="hljs-comment">// true</span>
<span class="hljs-number">0</span> === <span class="hljs-literal">false</span>  <span class="hljs-comment">// false</span>
<span class="hljs-number">1</span> == <span class="hljs-string">"1"</span>     <span class="hljs-comment">// true</span>
<span class="hljs-number">1</span> === <span class="hljs-string">"1"</span>    <span class="hljs-comment">// false</span>
<span class="hljs-literal">null</span> == <span class="hljs-literal">undefined</span> <span class="hljs-comment">// true</span>
<span class="hljs-literal">null</span> === <span class="hljs-literal">undefined</span> <span class="hljs-comment">// false</span>
<span class="hljs-string">'0'</span> == <span class="hljs-literal">false</span> <span class="hljs-comment">// true</span>
<span class="hljs-string">'0'</span> === <span class="hljs-literal">false</span> <span class="hljs-comment">// false</span>
<span class="hljs-literal">NaN</span> == <span class="hljs-literal">NaN</span> or <span class="hljs-literal">NaN</span> === <span class="hljs-literal">NaN</span> <span class="hljs-comment">// false</span>
[]==[] or []===[] <span class="hljs-comment">//false, refer different objects in memory</span>
{}=={} or {}==={} <span class="hljs-comment">//false, refer different objects in memory</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-lambda-expressions-or-arrow-functions">What are lambda expressions or arrow functions</h3>
<p>An arrow function is a shorter/concise syntax for a function expression and does not have its own <strong>this, arguments, super, or new.target</strong>. These functions are best suited for non-method functions, and they cannot be used as constructors.</p>
<p>Some of the examples of arrow functions are listed as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrowFunc1 = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b; <span class="hljs-comment">// Multiple parameters</span>
<span class="hljs-keyword">const</span> arrowFunc2 = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> a * <span class="hljs-number">10</span>; <span class="hljs-comment">// Single parameter</span>
<span class="hljs-keyword">const</span> arrowFunc3 = <span class="hljs-function">() =&gt;</span> {} <span class="hljs-comment">// no parameters</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-first-class-function">What is a first class function</h3>
<p>In Javascript, functions are first class objects. First-class functions means when functions in that language are treated like any other variable.</p>
<p>For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. For example, in the below example, handler functions assigned to a listener</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> handler = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a click handler function"</span>);
<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"click"</span>, handler);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-first-order-function">What is a first order function</h3>
<p>A first-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstOrder = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am a first order function!"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-higher-order-function">What is a higher order function</h3>
<p>A higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
The syntactic structure of higher order function will be as follows,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstOrderFunc = <span class="hljs-function">() =&gt;</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello, I am a First order function"</span>);
<span class="hljs-keyword">const</span> higherOrder = <span class="hljs-function">(<span class="hljs-params">ReturnFirstOrderFunc</span>) =&gt;</span> ReturnFirstOrderFunc();
higherOrder(firstOrderFunc);
</code></pre>
<p>You can also call the function which you are passing to higher order function as callback function.</p>
<p>The higher order function is helpful to write the modular and reusable code. </p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-unary-function">What is a unary function</h3>
<p>A unary function (i.e. monadic) is a function that accepts exactly one argument. It stands for a single argument accepted by a function.</p>
<p>Let us take an example of unary function,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> unaryFunction = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(a + <span class="hljs-number">10</span>); <span class="hljs-comment">// Add 10 to the given argument and display the value</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-currying-function">What is the currying function</h3>
<p>Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. Currying is named after a mathematician <strong>Haskell Curry</strong>. By applying currying, an n-ary function turns into a unary function.</p>
<p>Let's take an example of n-ary function and how it turns into a currying function,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> multiArgFunction = <span class="hljs-function">(<span class="hljs-params">a, b, c</span>) =&gt;</span> a + b + c;
<span class="hljs-built_in">console</span>.log(multiArgFunction(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 6</span>

<span class="hljs-keyword">const</span> curryUnaryFunction = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">c</span>) =&gt;</span> a + b + c;
curryUnaryFunction(<span class="hljs-number">1</span>); <span class="hljs-comment">// returns a function: b =&gt; c =&gt;  1 + b + c</span>
curryUnaryFunction(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>); <span class="hljs-comment">// returns a function: c =&gt; 3 + c</span>
curryUnaryFunction(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>)(<span class="hljs-number">3</span>); <span class="hljs-comment">// returns the number 6</span>
</code></pre>
<p>Curried functions are great to improve <strong>code reusability</strong> and <strong>functional composition</strong>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-pure-function">What is a pure function</h3>
<p>A <strong>Pure function</strong> is a function where the return value is only determined by its arguments without any side effects. i.e, If you call a function with the same arguments 'n' number of times and 'n' number of places in the application then it will always return the same value.</p>
<p>Let's take an example to see the difference between pure and impure functions,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Impure</span>
<span class="hljs-keyword">let</span> numberArray = [];
<span class="hljs-keyword">const</span> impureAddNumber = <span class="hljs-function">(<span class="hljs-params">number</span>) =&gt;</span> numberArray.push(number);
<span class="hljs-comment">//Pure</span>
<span class="hljs-keyword">const</span> pureAddNumber = <span class="hljs-function">(<span class="hljs-params">number</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">argNumberArray</span>) =&gt;</span>
  argNumberArray.concat([number]);

<span class="hljs-comment">//Display the results</span>
<span class="hljs-built_in">console</span>.log(impureAddNumber(<span class="hljs-number">6</span>)); <span class="hljs-comment">// returns 1</span>
<span class="hljs-built_in">console</span>.log(numberArray); <span class="hljs-comment">// returns [6]</span>
<span class="hljs-built_in">console</span>.log(pureAddNumber(<span class="hljs-number">7</span>)(numberArray)); <span class="hljs-comment">// returns [6, 7]</span>
<span class="hljs-built_in">console</span>.log(numberArray); <span class="hljs-comment">// returns [6]</span>
</code></pre>
<p>As per the above code snippets, the <strong>Push</strong> function is impure itself by altering the array and returning a push number index independent of the parameter value, whereas <strong>Concat</strong> on the other hand takes the array and concatenates it with the other array producing a whole new array without side effects. Also, the return value is a concatenation of the previous array.</p>
<p>Remember that Pure functions are important as they simplify unit testing without any side effects and no need for dependency injection. They also avoid tight coupling and make it harder to break your application by not having any side effects. These principles are coming together with the <strong>Immutability</strong> concept of ES6: giving preference to <strong>const</strong> over <strong>let</strong> usage.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-the-let-keyword">What is the purpose of the let keyword</h3>
<p>The <code>let</code> statement declares a <strong>block scope local variable</strong>. Hence the variables defined with let keyword are limited in scope to the block, statement, or expression on which it is used. Whereas variables declared with the <code>var</code> keyword used to define a variable globally, or locally to an entire function regardless of block scope.</p>
<p>Let's take an example to demonstrate the usage,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> counter = <span class="hljs-number">30</span>;
<span class="hljs-keyword">if</span> (counter === <span class="hljs-number">30</span>) {
  <span class="hljs-keyword">let</span> counter = <span class="hljs-number">31</span>;
  <span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 31</span>
}
<span class="hljs-built_in">console</span>.log(counter); <span class="hljs-comment">// 30 (because the variable in if block won't exist here)</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-let-and-var">What is the difference between let and var</h3>
<p>You can list out the differences in a tabular format</p>
<p>| var                                                   | let                         |
| ----------------------------------------------------- | --------------------------- |
| It has been available from the beginning of JavaScript | Introduced as part of ES6   |
| It has function scope                                 | It has block scope          |
| Variable declaration will be hoisted, initialized as undefined  | Hoisted but not initialized |
| It is possible to re-declare the variable in the same scope | It is not possible to re-declare the variable |</p>
<p>Let's take an example to see the difference,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">userDetails</span>(<span class="hljs-params">username</span>) </span>{
  <span class="hljs-keyword">if</span> (username) {
    <span class="hljs-built_in">console</span>.log(salary); <span class="hljs-comment">// undefined due to hoisting</span>
    <span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// ReferenceError: Cannot access 'age' before initialization</span>
    <span class="hljs-keyword">let</span> age = <span class="hljs-number">30</span>;
    <span class="hljs-keyword">var</span> salary = <span class="hljs-number">10000</span>;
  }
  <span class="hljs-built_in">console</span>.log(salary); <span class="hljs-comment">//10000 (accessible due to function scope)</span>
  <span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">//error: age is not defined(due to block scope)</span>
}
userDetails(<span class="hljs-string">"John"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-reason-to-choose-the-name-let-as-a-keyword">What is the reason to choose the name let as a keyword</h3>
<p><code>let</code> is a mathematical statement that was adopted by early programming languages like <strong>Scheme</strong> and <strong>Basic</strong>. It has been borrowed from dozens of other languages that use <code>let</code> already as a traditional keyword as close to <code>var</code> as possible.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-redeclare-variables-in-a-switch-block-without-an-error">How do you redeclare variables in a switch block without an error</h3>
<p>If you try to redeclare variables in a <code>switch block</code> then it will cause errors because there is only one block. For example, the below code block throws a syntax error as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> counter = <span class="hljs-number">1</span>;
<span class="hljs-keyword">switch</span> (x) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>:
    <span class="hljs-keyword">let</span> name;
    <span class="hljs-keyword">break</span>;

  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-keyword">let</span> name; <span class="hljs-comment">// SyntaxError for redeclaration.</span>
    <span class="hljs-keyword">break</span>;
}
</code></pre>
<p>To avoid this error, you can create a nested block inside a case clause and create a new block scoped lexical environment.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> counter = <span class="hljs-number">1</span>;
<span class="hljs-keyword">switch</span> (x) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">0</span>: {
    <span class="hljs-keyword">let</span> name;
    <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>: {
    <span class="hljs-keyword">let</span> name; <span class="hljs-comment">// No SyntaxError for redeclaration.</span>
    <span class="hljs-keyword">break</span>;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-temporal-dead-zone">What is the Temporal Dead Zone</h3>
<p>The Temporal Dead Zone(TDZ) is a specific period or area of a block where a variable is inaccessible until it has been initialized with a value. This behavior in JavaScript that occurs when declaring a variable with the let and const keywords, but not with var. In ECMAScript 6, accessing a <code>let</code> or <code>const</code> variable before its declaration (within its scope) causes a ReferenceError. </p>
<p>Let's see this behavior with an example,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">somemethod</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(counter1); <span class="hljs-comment">// undefined</span>
  <span class="hljs-built_in">console</span>.log(counter2); <span class="hljs-comment">// ReferenceError</span>
  <span class="hljs-keyword">var</span> counter1 = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">let</span> counter2 = <span class="hljs-number">2</span>;
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-iife-immediately-invoked-function-expression">What is an IIFE (Immediately Invoked Function Expression)</h3>
<p>IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// logic here</span>
})();
</code></pre>
<p>The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables from the IIFE then it throws an error as below,</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> message = <span class="hljs-string">"IIFE"</span>;
  <span class="hljs-built_in">console</span>.log(message);
})();
<span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">//Error: message is not defined</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-decode-or-encode-a-url-in-javascript">How do you decode or encode a URL in JavaScript?</h3>
<p><code>encodeURI()</code> function is used to encode an URL. This function requires a URL string as a parameter and return that encoded string.
<code>decodeURI()</code> function is used to decode an URL. This function requires an encoded URL string as parameter and return that decoded string.</p>
<p><strong>Note:</strong> If you want to encode characters such as <code>/ ? : @ &amp; = + $ #</code> then you need to use <code>encodeURIComponent()</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> uri = <span class="hljs-string">"employeeDetails?name=john&amp;occupation=manager"</span>;
<span class="hljs-keyword">let</span> encoded_uri = <span class="hljs-built_in">encodeURI</span>(uri);
<span class="hljs-keyword">let</span> decoded_uri = <span class="hljs-built_in">decodeURI</span>(encoded_uri);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-memoization">What is memoization</h3>
<p>Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache.
Let's take an example of adding function with memoization,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> memoizAddition = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> cache = {};
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (value <span class="hljs-keyword">in</span> cache) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Fetching from cache"</span>);
      <span class="hljs-keyword">return</span> cache[value]; <span class="hljs-comment">// Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript  identifier. Hence, can only be accessed using the square bracket notation.</span>
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Calculating result"</span>);
      <span class="hljs-keyword">let</span> result = value + <span class="hljs-number">20</span>;
      cache[value] = result;
      <span class="hljs-keyword">return</span> result;
    }
  };
};
<span class="hljs-comment">// returned function from memoizAddition</span>
<span class="hljs-keyword">const</span> addition = memoizAddition();
<span class="hljs-built_in">console</span>.log(addition(<span class="hljs-number">20</span>)); <span class="hljs-comment">//output: 40 calculated</span>
<span class="hljs-built_in">console</span>.log(addition(<span class="hljs-number">20</span>)); <span class="hljs-comment">//output: 40 cached</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-hoisting">What is Hoisting</h3>
<p>Hoisting is a JavaScript mechanism where variables, function declarations and classes are moved to the top of their scope before code execution. Remember that JavaScript only hoists declarations, not initialisation.
Let's take a simple example of variable hoisting,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(message); <span class="hljs-comment">//output : undefined</span>
<span class="hljs-keyword">var</span> message = <span class="hljs-string">"The variable Has been hoisted"</span>;
</code></pre>
<p>The above code looks like as below to the interpreter,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> message;
<span class="hljs-built_in">console</span>.log(message);
message = <span class="hljs-string">"The variable Has been hoisted"</span>;
</code></pre>
<p>In the same fashion, function declarations are hoisted too</p>
<pre><code class="lang-javascript">message(<span class="hljs-string">"Good morning"</span>); <span class="hljs-comment">//Good morning</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">message</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(name);
}
</code></pre>
<p>This hoisting makes functions to be safely used in code before they are declared.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-classes-in-es6">What are classes in ES6</h3>
<p>In ES6, Javascript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance.
For example, the prototype based inheritance written in function expression as below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bike</span>(<span class="hljs-params">model, color</span>) </span>{
  <span class="hljs-built_in">this</span>.model = model;
  <span class="hljs-built_in">this</span>.color = color;
}

Bike.prototype.getDetails = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.model + <span class="hljs-string">" bike has"</span> + <span class="hljs-built_in">this</span>.color + <span class="hljs-string">" color"</span>;
};
</code></pre>
<p>Whereas ES6 classes can be defined as an alternative</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
  <span class="hljs-keyword">constructor</span>(color, model) {
    <span class="hljs-built_in">this</span>.color = color;
    <span class="hljs-built_in">this</span>.model = model;
  }

  getDetails() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.model + <span class="hljs-string">" bike has"</span> + <span class="hljs-built_in">this</span>.color + <span class="hljs-string">" color"</span>;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-closures">What are closures</h3>
<p>A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.</p>
<ol>
<li>Own scope where variables defined between its curly brackets</li>
<li>Outer function's variables</li>
<li>Global variables</li>
</ol>
<p>Let's take an example of closure concept,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Welcome</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">var</span> greetingInfo = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">message</span>) </span>{
    <span class="hljs-built_in">console</span>.log(message + <span class="hljs-string">" "</span> + name);
  };
  <span class="hljs-keyword">return</span> greetingInfo;
}
<span class="hljs-keyword">var</span> myFunction = Welcome(<span class="hljs-string">"John"</span>);
myFunction(<span class="hljs-string">"Welcome "</span>); <span class="hljs-comment">//Output: Welcome John</span>
myFunction(<span class="hljs-string">"Hello Mr."</span>); <span class="hljs-comment">//output: Hello Mr. John</span>
</code></pre>
<p>As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-modules">What are modules</h3>
<p>Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-modules">Why do you need modules</h3>
<p>Below are the list of benefits using modules in javascript ecosystem</p>
<ol>
<li>Maintainability</li>
<li>Reusability</li>
<li>Namespacing</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-scope-in-javascript">What is scope in javascript</h3>
<p>Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-service-worker">What is a service worker</h3>
<p>A Service worker is basically a script (JavaScript file) that runs in the background, separate from a web page and provides features that don't need a web page or user interaction. Some of the major features of service workers are Rich offline experiences(offline first web application development), periodic background syncs, push notifications, intercept and handle network requests and programmatically managing a cache of responses.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-manipulate-dom-using-a-service-worker">How do you manipulate DOM using a service worker</h3>
<p>Service worker can't access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the <code>postMessage</code> interface, and those pages can manipulate the DOM.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-reuse-information-across-service-worker-restarts">How do you reuse information across service worker restarts</h3>
<p>The problem with service worker is that it gets terminated when not in use, and restarted when it's next needed, so you cannot rely on global state within a service worker's <code>onfetch</code> and <code>onmessage</code> handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-indexeddb">What is IndexedDB</h3>
<p>IndexedDB is a low-level API for client-side storage of larger amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-web-storage">What is web storage</h3>
<p>Web storage is an API that provides a mechanism by which browsers can store key/value pairs locally within the user's browser, in a much more intuitive fashion than using cookies. The web storage provides two mechanisms for storing data on the client.</p>
<ol>
<li><strong>Local storage:</strong> It stores data for current origin with no expiration date.</li>
<li><strong>Session storage:</strong> It stores data for one session and the data is lost when the browser tab is closed.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-post-message">What is a post message</h3>
<p>Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-cookie">What is a Cookie</h3>
<p>A cookie is a piece of data that is stored on your computer to be accessed by your browser. Cookies are saved as key/value pairs.
For example, you can create a cookie named username as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"username=John"</span>;
</code></pre>
<p><img src="images/cookie.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-a-cookie">Why do you need a Cookie</h3>
<p>Cookies are used to remember information about the user profile(such as username). It basically involves two steps,</p>
<ol>
<li>When a user visits a web page, the user profile can be stored in a cookie.</li>
<li>Next time the user visits the page, the cookie remembers the user profile.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-options-in-a-cookie">What are the options in a cookie</h3>
<p>There are few below options available for a cookie,</p>
<ol>
<li>By default, the cookie is deleted when the browser is closed but you can change this behavior by setting expiry date (in UTC time).</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"username=John; expires=Sat, 8 Jun 2019 12:00:00 UTC"</span>;
</code></pre>
<ol>
<li>By default, the cookie belongs to a current page. But you can tell the browser what path the cookie belongs to using a path parameter.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"username=John; path=/services"</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-delete-a-cookie">How do you delete a cookie</h3>
<p>You can delete a cookie by setting the expiry date as a passed date. You don't need to specify a cookie value in this case.
For example, you can delete a username cookie in the current page as below.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.cookie =
  <span class="hljs-string">"username=; expires=Fri, 07 Jun 2019 00:00:00 UTC; path=/;"</span>;
</code></pre>
<p><strong>Note:</strong> You should define the cookie path option to ensure that you delete the right cookie. Some browsers doesn't allow to delete a cookie unless you specify a path parameter.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-cookie-local-storage-and-session-storage">What are the differences between cookie, local storage and session storage</h3>
<p>Below are some of the differences between cookie, local storage and session storage,</p>
<p>| Feature                           | Cookie                             | Local storage    | Session storage     |
| --------------------------------- | ---------------------------------- | ---------------- | ------------------- |
| Accessed on client or server side | Both server-side &amp; client-side. The <code>set-cookie</code> HTTP response header is used by server inorder to send it to user.     | client-side only | client-side only    |
| Expiry                          | Manually configured using Expires option | Forever until deleted    | until tab is closed |
| SSL support                       | Supported                          | Not supported    | Not supported       |
| Maximum data size                 | 4KB                                | 5 MB             | 5MB                 |
| Accessible from                            | Any window | Any window | Same tab |
| Sent with requests | Yes | No | No |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-main-difference-between-localstorage-and-sessionstorage">What is the main difference between localStorage and sessionStorage</h3>
<p>LocalStorage is the same as SessionStorage but it persists the data even when the browser is closed and reopened(i.e it has no expiration time) whereas in sessionStorage data gets cleared when the page session ends.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-access-web-storage">How do you access web storage</h3>
<p>The Window object implements the <code>WindowLocalStorage</code> and <code>WindowSessionStorage</code> objects which has <code>localStorage</code>(window.localStorage) and <code>sessionStorage</code>(window.sessionStorage) properties respectively. These properties create an instance of the Storage object, through which data items can be set, retrieved and removed for a specific domain and storage type (session or local).
For example, you can read and write on local storage objects as below</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"logo"</span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"logo"</span>).value);
<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"logo"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-methods-available-on-session-storage">What are the methods available on session storage</h3>
<p>The session storage provided methods for reading, writing and clearing the session data</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Save data to sessionStorage</span>
sessionStorage.setItem(<span class="hljs-string">"key"</span>, <span class="hljs-string">"value"</span>);

<span class="hljs-comment">// Get saved data from sessionStorage</span>
<span class="hljs-keyword">let</span> data = sessionStorage.getItem(<span class="hljs-string">"key"</span>);

<span class="hljs-comment">// Remove saved data from sessionStorage</span>
sessionStorage.removeItem(<span class="hljs-string">"key"</span>);

<span class="hljs-comment">// Remove all saved data from sessionStorage</span>
sessionStorage.clear();
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-storage-event-and-its-event-handler">What is a storage event and its event handler</h3>
<p>The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events.
The syntax would be as below</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.onstorage = functionRef;
</code></pre>
<p>Let's take the example usage of onstorage event handler which logs the storage key and it's values</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.onstorage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"The "</span> +
      e.key +
      <span class="hljs-string">" key has been changed from "</span> +
      e.oldValue +
      <span class="hljs-string">" to "</span> +
      e.newValue +
      <span class="hljs-string">"."</span>
  );
};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-web-storage">Why do you need web storage</h3>
<p>Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Also, the information is never transferred to the server. Hence this is a more recommended approach than Cookies.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-web-storage-browser-support">How do you check web storage browser support</h3>
<p>You need to check browser support for localStorage and sessionStorage before using web storage,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> Storage !== <span class="hljs-string">"undefined"</span>) {
  <span class="hljs-comment">// Code for localStorage/sessionStorage.</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Sorry! No Web Storage support..</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-web-workers-browser-support">How do you check web workers browser support</h3>
<p>You need to check browser support for web workers before using it</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> Worker !== <span class="hljs-string">"undefined"</span>) {
  <span class="hljs-comment">// code for Web worker support.</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Sorry! No Web Worker support..</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-give-an-example-of-a-web-worker">Give an example of a web worker</h3>
<p>You need to follow below steps to start using web workers for counting example</p>
<ol>
<li>Create a Web Worker File: You need to write a script to increment the count value. Let's name it as counter.js</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">timedCount</span>(<span class="hljs-params"></span>) </span>{
  i = i + <span class="hljs-number">1</span>;
  postMessage(i);
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-string">"timedCount()"</span>, <span class="hljs-number">500</span>);
}

timedCount();
</code></pre>
<p>Here postMessage() method is used to post a message back to the HTML page</p>
<ol>
<li>Create a Web Worker Object: You can create a web worker object by checking for browser support. Let's name this file as web_worker_example.js</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> w == <span class="hljs-string">"undefined"</span>) {
  w = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"counter.js"</span>);
}
</code></pre>
<p>and we can receive messages from web worker</p>
<pre><code class="lang-javascript">w.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>).innerHTML = event.data;
};
</code></pre>
<ol>
<li>Terminate a Web Worker:
Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use the terminate() method to terminate listening to the messages.</li>
</ol>
<pre><code class="lang-javascript">w.terminate();
</code></pre>
<ol>
<li>Reuse the Web Worker: If you set the worker variable to undefined you can reuse the code</li>
</ol>
<pre><code class="lang-javascript">w = <span class="hljs-literal">undefined</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-restrictions-of-web-workers-on-dom">What are the restrictions of web workers on DOM</h3>
<p>WebWorkers don't have access to below javascript objects since they are defined in an external files</p>
<ol>
<li>Window object</li>
<li>Document object</li>
<li>Parent object</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-promise">What is a promise</h3>
<p>A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending.</p>
<p>The syntax of Promise creation looks like below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-comment">// promise description</span>
});
</code></pre>
<p>The usage of a promise would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(
  <span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(<span class="hljs-string">"I'm a Promise!"</span>);
    }, <span class="hljs-number">5000</span>);
  },
  <span class="hljs-function">(<span class="hljs-params">reject</span>) =&gt;</span> {}
);

promise.then(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(value));
</code></pre>
<p>The action flow of a promise will be as below,</p>
<p><img src="images/promises.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-a-promise">Why do you need a promise</h3>
<p>Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-three-states-of-promise">What are the three states of promise</h3>
<p>Promises have three states:</p>
<ol>
<li><strong>Pending:</strong> This is an initial state of the Promise before an operation begins</li>
<li><strong>Fulfilled:</strong> This state indicates that the specified operation was completed.</li>
<li><strong>Rejected:</strong> This state indicates that the operation did not complete. In this case an error value will be thrown.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-callback-function">What is a callback function</h3>
<p>A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action.
Let's take a simple example of how to use callback function</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello "</span> + name);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">let</span> name = prompt(<span class="hljs-string">"Please enter your name."</span>);
  callback(name);
}

outerFunction(callbackFunction);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-we-need-callbacks">Why do we need callbacks</h3>
<p>The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events.
Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Simulate a code delay</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"First function called"</span>);
  }, <span class="hljs-number">1000</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Second function called"</span>);
}
firstFunction();
secondFunction();

Output;
<span class="hljs-comment">// Second function called</span>
<span class="hljs-comment">// First function called</span>
</code></pre>
<p>As observed from the output, javascript didn't wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-callback-hell">What is a callback hell</h3>
<p>Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,</p>
<pre><code class="lang-javascript">async1(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    async2(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
        async3(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            async4(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
                ....
            });
        });
    });
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-server-sent-events">What are server-sent events</h3>
<p>Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter updates, stock price updates, news feeds etc.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-receive-server-sent-event-notifications">How do you receive server-sent event notifications</h3>
<p>The EventSource object is used to receive server-sent event notifications. For example, you can receive messages from server as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> EventSource !== <span class="hljs-string">"undefined"</span>) {
  <span class="hljs-keyword">var</span> source = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">"sse_generator.js"</span>);
  source.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"output"</span>).innerHTML += event.data + <span class="hljs-string">"&lt;br&gt;"</span>;
  };
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-browser-support-for-server-sent-events">How do you check browser support for server-sent events</h3>
<p>You can perform browser support for server-sent events before using it as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> EventSource !== <span class="hljs-string">"undefined"</span>) {
  <span class="hljs-comment">// Server-sent events supported. Let's have some code here!</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// No server-sent events supported</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-events-available-for-server-sent-events">What are the events available for server sent events</h3>
<p>Below are the list of events available for server sent events
| Event | Description |
|---- | ---------
| onopen | It is used when a connection to the server is opened |
| onmessage | This event is used when a message is received |
| onerror | It happens when an error occurs|</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-main-rules-of-promise">What are the main rules of promise</h3>
<p>A promise must follow a specific set of rules:</p>
<ol>
<li>A promise is an object that supplies a standard-compliant <code>.then()</code> method</li>
<li>A pending promise may transition into either fulfilled or rejected state</li>
<li>A fulfilled or rejected promise is settled and it must not transition into any other state.</li>
<li>Once a promise is settled, the value must not change.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-callback-in-callback">What is callback in callback</h3>
<p>You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.</p>
<pre><code class="lang-javascript">loadScript(<span class="hljs-string">"/script1.js"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">script</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"first script is loaded"</span>);

  loadScript(<span class="hljs-string">"/script2.js"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">script</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"second script is loaded"</span>);

    loadScript(<span class="hljs-string">"/script3.js"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">script</span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"third script is loaded"</span>);
      <span class="hljs-comment">// after all scripts are loaded</span>
    });
  });
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-promise-chaining">What is promise chaining</h3>
<p>The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. Let's take an example of promise chaining for calculating the final result,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(<span class="hljs-number">1</span>), <span class="hljs-number">1000</span>);
})
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">return</span> result * <span class="hljs-number">2</span>;
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 2</span>
    <span class="hljs-keyword">return</span> result * <span class="hljs-number">3</span>;
  })
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 6</span>
    <span class="hljs-keyword">return</span> result * <span class="hljs-number">4</span>;
  });
</code></pre>
<p>In the above handlers, the result is passed to the chain of .then() handlers with the below work flow,</p>
<ol>
<li>The initial promise resolves in 1 second,</li>
<li>After that <code>.then</code> handler is called by logging the result(1) and then return a promise with the value of result * 2.</li>
<li>After that the value passed to the next <code>.then</code> handler by logging the result(2) and return a promise with result * 3.</li>
<li>Finally the value passed to the last <code>.then</code> handler by logging the result(6) and return a promise with result * 4.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-promiseall">What is promise.all</h3>
<p>Promise.all is a promise that takes an array of promises as an input (an iterable), and it gets resolved when all the promises get resolved or any one of them gets rejected. For example, the syntax of promise.all method is below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.all([Promise1, Promise2, Promise3]) .then(result) =&gt; {   <span class="hljs-built_in">console</span>.log(result) }) .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Error in promises <span class="hljs-subst">${error}</span>`</span>))
</code></pre>
<p><strong>Note:</strong> Remember that the order of the promises(output the result) is maintained as per input order.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-the-race-method-in-promise">What is the purpose of the race method in promise</h3>
<p>Promise.race() method will return the promise instance which is firstly resolved or rejected. Let's take an example of race() method where promise2 is resolved first</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> promise1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">500</span>, <span class="hljs-string">"one"</span>);
});
<span class="hljs-keyword">var</span> promise2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">100</span>, <span class="hljs-string">"two"</span>);
});

<span class="hljs-built_in">Promise</span>.race([promise1, promise2]).then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{
  <span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// "two" // Both promises will resolve, but promise2 is faster</span>
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-strict-mode-in-javascript">What is a strict mode in javascript</h3>
<p>Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This way it prevents certain actions from being taken and throws more exceptions. The literal expression <code>"use strict";</code> instructs the browser to use the javascript code in the Strict mode.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-strict-mode">Why do you need strict mode</h3>
<p>Strict mode is useful to write "secure" JavaScript by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-declare-strict-mode">How do you declare strict mode</h3>
<p>The strict mode is declared by adding "use strict"; to the beginning of a script or a function.
If declared at the beginning of a script, it has global scope.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>;
x = <span class="hljs-number">3.14</span>; <span class="hljs-comment">// This will cause an error because x is not declared</span>
</code></pre>
<p>and if you declare inside a function, it has local scope</p>
<pre><code class="lang-javascript">x = <span class="hljs-number">3.14</span>; <span class="hljs-comment">// This will not cause an error.</span>
myFunction();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-meta">  "use strict"</span>;
  y = <span class="hljs-number">3.14</span>; <span class="hljs-comment">// This will cause an error</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-double-exclamation">What is the purpose of double exclamation</h3>
<p>The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, it will be true.
For example, you can test IE version using this expression as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isIE8 = <span class="hljs-literal">false</span>;
isIE8 = !!navigator.userAgent.match(<span class="hljs-regexp">/MSIE 8.0/</span>);
<span class="hljs-built_in">console</span>.log(isIE8); <span class="hljs-comment">// returns true or false</span>
</code></pre>
<p>If you don't use this expression then it returns the original value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(navigator.userAgent.match(<span class="hljs-regexp">/MSIE 8.0/</span>)); <span class="hljs-comment">// returns either an Array or null</span>
</code></pre>
<p><strong>Note:</strong> The expression !! is not an operator, but it is just twice of ! operator.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-the-delete-operator">What is the purpose of the delete operator</h3>
<p>The delete operator is used to delete the property as well as its value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> user = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">lastName</span>:<span class="hljs-string">"Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">20</span> };
<span class="hljs-keyword">delete</span> user.age;

<span class="hljs-built_in">console</span>.log(user); <span class="hljs-comment">// {firstName: "John", lastName:"Doe"}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-typeof-operator">What is typeof operator</h3>
<p>You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">typeof</span> <span class="hljs-string">"John Abraham"</span>; <span class="hljs-comment">// Returns "string"</span>
<span class="hljs-keyword">typeof</span> (<span class="hljs-number">1</span> + <span class="hljs-number">2</span>); <span class="hljs-comment">// Returns "number"</span>
<span class="hljs-keyword">typeof</span> [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]; <span class="hljs-comment">// Returns "object" because all arrays are also objects</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-undefined-property">What is undefined property</h3>
<p>The undefined property indicates that a variable has not been assigned a value, or declared but not initialized at all. The type of undefined value is undefined too.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> user; <span class="hljs-comment">// Value is undefined, type is undefined</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> user); <span class="hljs-comment">//undefined</span>
</code></pre>
<p>Any variable can be emptied by setting the value to undefined.</p>
<pre><code class="lang-javascript">user = <span class="hljs-literal">undefined</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-null-value">What is null value</h3>
<p>The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values. The type of null value is object.
You can empty the variable by setting the value to null.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> user = <span class="hljs-literal">null</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> user); <span class="hljs-comment">//object</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-null-and-undefined">What is the difference between null and undefined</h3>
<p>Below are the main differences between null and undefined,</p>
<p>| Null                                                                                            | Undefined                                                                                               |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| It is an assignment value which indicates that variable points to no object.                    | It is not an assignment value where a variable has been declared but has not yet been assigned a value. |
| Type of null is object                                                                          | Type of undefined is undefined                                                                          |
| The null value is a primitive value that represents the null, empty, or non-existent reference. | The undefined value is a primitive value used when a variable has not been assigned a value.            |
| Indicates the absence of a value for a variable                                                 | Indicates absence of variable itself                                                                    |
| Converted to zero (0) while performing primitive operations                                     | Converted to NaN while performing primitive operations                                                  |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-eval">What is eval</h3>
<p>The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">eval</span>(<span class="hljs-string">"1 + 2"</span>)); <span class="hljs-comment">//  3</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-window-and-document">What is the difference between window and document</h3>
<p>Below are the main differences between window and document,</p>
<p>| Window                                                                        | Document                                                                                      |
| ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| It is the root level element in any web page                                  | It is the direct child of the window object. This is also known as Document Object Model(DOM) |
| By default window object is available implicitly in the page                  | You can access it via window.document or document.                                            |
| It has methods like alert(), confirm() and properties like document, location | It provides methods like getElementById, getElementsByTagName, createElement etc              |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-access-history-in-javascript">How do you access history in javascript</h3>
<p>The window.history object contains the browser's history. You can load previous and next URLs in the history using back() and next() methods.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">goBack</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">window</span>.history.back();
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">goForward</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">window</span>.history.forward();
}
</code></pre>
<p><strong>Note:</strong> You can also access history without window prefix.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-caps-lock-key-turned-on-or-not">How do you detect caps lock key turned on or not</h3>
<p>The <code>mouseEvent getModifierState()</code> is used to return a boolean value that indicates whether the specified modifier key is activated or not. The modifiers such as CapsLock, ScrollLock and NumLock are activated when they are clicked, and deactivated when they are clicked again.</p>
<p>Let's take an input element to detect the CapsLock on/off behavior with an example,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">onmousedown</span>=<span class="hljs-string">"enterInput(event)"</span> /&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"feedback"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">enterInput</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-keyword">var</span> flag = e.getModifierState(<span class="hljs-string">"CapsLock"</span>);
    <span class="hljs-keyword">if</span> (flag) {
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"feedback"</span>).innerHTML = <span class="hljs-string">"CapsLock activated"</span>;
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"feedback"</span>).innerHTML =
        <span class="hljs-string">"CapsLock not activated"</span>;
    }
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-isnan">What is isNaN</h3>
<p>The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">isNaN</span>(<span class="hljs-string">"Hello"</span>); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">isNaN</span>(<span class="hljs-string">"100"</span>); <span class="hljs-comment">//false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-undeclared-and-undefined-variables">What are the differences between undeclared and undefined variables</h3>
<p>Below are the major differences between undeclared(not defined) and undefined variables,</p>
<p>| undeclared                                                                                  | undefined                                                                              |
| ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| These variables do not exist in a program and are not declared                              | These variables declared in the program but have not assigned any value                |
| If you try to read the value of an undeclared variable, then a runtime error is encountered | If you try to read the value of an undefined variable, an undefined value is returned. |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-global-variables">What are global variables</h3>
<p>Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable</p>
<pre><code class="lang-javascript">msg = <span class="hljs-string">"Hello"</span>; <span class="hljs-comment">// var is missing, it becomes global variable</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-problems-with-global-variables">What are the problems with global variables</h3>
<p>The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-nan-property">What is NaN property</h3>
<p>The NaN property is a global property that represents "Not-a-Number" value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Math</span>.sqrt(<span class="hljs-number">-1</span>);
<span class="hljs-built_in">parseInt</span>(<span class="hljs-string">"Hello"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-isfinite-function">What is the purpose of isFinite function</h3>
<p>The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">isFinite</span>(<span class="hljs-literal">Infinity</span>); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">isFinite</span>(<span class="hljs-literal">NaN</span>); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">isFinite</span>(-<span class="hljs-literal">Infinity</span>); <span class="hljs-comment">// false</span>

<span class="hljs-built_in">isFinite</span>(<span class="hljs-number">100</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-event-flow">What is an event flow</h3>
<p>Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event for each of its parent elements first, starting at the top with the global window object.</p>
<p>There are two ways of event flow</p>
<ol>
<li>Top to Bottom(Event Capturing)</li>
<li>Bottom to Top (Event Bubbling)</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-event-bubbling">What is event bubbling</h3>
<p>Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element(i.e, global window object).</p>
<p>By default, event handlers triggered in event bubbling phase as shown below,</p>
<pre><code class="lang-javascript">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>Hello<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> parent = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
  <span class="hljs-keyword">const</span> child = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".child"</span>);

  parent.addEventListener(<span class="hljs-string">"click"</span>,
    <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Parent"</span>);
    }
  );

  child.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Child"</span>);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="hljs-comment">// Child</span>
<span class="hljs-comment">// Parent</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-event-capturing">What is event capturing</h3>
<p>Event capturing is a type of event propagation where the event is first captured by the outermost element, and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the innermost target DOM element.</p>
<p>You need to pass <code>true</code> value for <code>addEventListener</code> method to trigger event handlers in event capturing phase.</p>
<pre><code class="lang-javascript">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>Hello<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> parent = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
  <span class="hljs-keyword">const</span> child = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".child"</span>);

  parent.addEventListener(<span class="hljs-string">"click"</span>,
    <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Parent"</span>);
    },
    <span class="hljs-literal">true</span>
  );

  child.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Child"</span>);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
<span class="hljs-comment">// Parent</span>
<span class="hljs-comment">// Child</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-submit-a-form-using-javascript">How do you submit a form using JavaScript</h3>
<p>You can submit a form using <code>document.forms[0].submit()</code>. All the form input's information is submitted using onsubmit event handler</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">submit</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">document</span>.forms[<span class="hljs-number">0</span>].submit();
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-find-operating-system-details">How do you find operating system details</h3>
<p>The window.navigator object contains information about the visitor's browser OS details. Some of the OS properties are available under platform property,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(navigator.platform);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-document-load-and-domcontentloaded-events">What is the difference between document load and DOMContentLoaded events</h3>
<p>The <code>DOMContentLoaded</code> event is fired when the initial HTML document has been completely loaded and parsed, without waiting for assets(stylesheets, images, and subframes) to finish loading. Whereas The load event is fired when the whole page has loaded, including all dependent resources(stylesheets, images).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-native-host-and-user-objects">What is the difference between native, host and user objects</h3>
<p><code>Native objects</code> are objects that are part of the JavaScript language defined by the ECMAScript specification. For example, String, Math, RegExp, Object, Function etc core objects defined in the ECMAScript spec.
<code>Host objects</code> are objects provided by the browser or runtime environment (Node). </p>
<p>For example, window, XmlHttpRequest, DOM nodes etc are considered as host objects.
<code>User objects</code> are objects defined in the javascript code. For example, User objects created for profile information.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-tools-or-techniques-used-for-debugging-javascript-code">What are the tools or techniques used for debugging JavaScript code</h3>
<p>You can use below tools or techniques for debugging javascript</p>
<ol>
<li>Chrome Devtools</li>
<li>debugger statement</li>
<li>Good old console.log statement</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-pros-and-cons-of-promises-over-callbacks">What are the pros and cons of promises over callbacks</h3>
<p>Below are the list of pros and cons of promises over callbacks,</p>
<p><strong>Pros:</strong></p>
<ol>
<li>It avoids callback hell which is unreadable</li>
<li>Easy to write sequential asynchronous code with .then()</li>
<li>Easy to write parallel asynchronous code with Promise.all()</li>
<li>Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)</li>
</ol>
<p><strong>Cons:</strong></p>
<ol>
<li>It makes little complex code</li>
<li>You need to load a polyfill if ES6 is not supported</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-an-attribute-and-a-property">What is the difference between an attribute and a property</h3>
<p>Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value,</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">"text"</span> value=<span class="hljs-string">"Name:"</span>&gt;
</code></pre>
<p>You can retrieve the attribute value as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> input = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"input"</span>);
<span class="hljs-built_in">console</span>.log(input.getAttribute(<span class="hljs-string">"value"</span>)); <span class="hljs-comment">// Good morning</span>
<span class="hljs-built_in">console</span>.log(input.value); <span class="hljs-comment">// Good morning</span>
</code></pre>
<p>And after you change the value of the text field to "Good evening", it becomes like</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(input.getAttribute(<span class="hljs-string">"value"</span>)); <span class="hljs-comment">// Good evening</span>
<span class="hljs-built_in">console</span>.log(input.value); <span class="hljs-comment">// Good evening</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-same-origin-policy">What is same-origin policy</h3>
<p>The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-void-0">What is the purpose of void 0</h3>
<p>Void(0) is used to prevent the page from refreshing. This will be helpful to eliminate the unwanted side-effect, because it will return the undefined primitive value. It is commonly used for HTML documents that use href="JavaScript:Void(0);" within an <code>&lt;a&gt;</code> element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression.
For example, the below link notify the message without reloading the page</p>
<pre><code class="lang-javascript">&lt;a href=<span class="hljs-string">"JavaScript:void(0);"</span> onclick=<span class="hljs-string">"alert('Well done!')"</span>&gt;
  Click Me!
&lt;/a&gt;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-javascript-a-compiled-or-interpreted-language">Is JavaScript a compiled or interpreted language</h3>
<p>JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-javascript-a-case-sensitive-language">Is JavaScript a case-sensitive language</h3>
<p>Yes, JavaScript is a case sensitive language. The language keywords, variables, function &amp; object names, and any other identifiers must always be typed with a consistent capitalization of letters.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-there-any-relation-between-java-and-javascript">Is there any relation between Java and JavaScript</h3>
<p>No, they are entirely two different programming languages and have nothing to do with each other. But both of them are Object Oriented Programming languages and like many other languages, they follow similar syntax for basic features(if, else, for, switch, break, continue etc).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-events">What are events</h3>
<p>Events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can <code>react</code> on these events. Some of the examples of HTML events are,</p>
<ol>
<li>Web page has finished loading</li>
<li>Input field was changed</li>
<li>Button was clicked</li>
</ol>
<p>Let's describe the behavior of click event for button element,</p>
<pre><code class="lang-javascript">&lt;!doctype html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
       alert(<span class="hljs-string">'Hello! Good morning'</span>);
     }
   </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"greeting()"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-who-created-javascript">Who created javascript</h3>
<p>JavaScript was created by Brendan Eich in 1995 during his time at Netscape Communications. Initially it was developed under the name <code>Mocha</code>, but later the language was officially called <code>LiveScript</code> when it first shipped in beta releases of Netscape.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-use-of-preventdefault-method">What is the use of preventDefault method</h3>
<p>The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyperlink are some common use cases.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>
  .getElementById(<span class="hljs-string">"link"</span>)
  .addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
    event.preventDefault();
  });
</code></pre>
<p><strong>Note:</strong> Remember that not all events are cancelable.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-use-of-stoppropagation-method">What is the use of stopPropagation method</h3>
<p>The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1)</p>
<pre><code class="lang-javascript">&lt;p&gt;Click DIV1 Element&lt;/p&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"secondFunc()"</span>&gt;</span>DIV 2
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"firstFunc(event)"</span>&gt;</span>DIV 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstFunc</span>(<span class="hljs-params">event</span>) </span>{
  alert(<span class="hljs-string">"DIV 1"</span>);
  event.stopPropagation();
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondFunc</span>(<span class="hljs-params"></span>) </span>{
  alert(<span class="hljs-string">"DIV 2"</span>);
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-steps-involved-in-return-false-usage">What are the steps involved in return false usage</h3>
<p>The return false statement in event handlers performs the below steps,</p>
<ol>
<li>First it stops the browser's default action or behaviour.</li>
<li>It prevents the event from propagating the DOM</li>
<li>Stops callback execution and returns immediately when called.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-bom">What is BOM</h3>
<p>The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It consists of the objects navigator, history, screen, location and document which are children of the window. The Browser Object Model is not standardized and can change based on different browsers.</p>
<p><img src="images/bom.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-use-of-settimeout">What is the use of setTimeout</h3>
<p>The setTimeout() method is used to call a function or evaluate an expression after a specified number of milliseconds. For example, let's log a message after 2 seconds using setTimeout method,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Good morning"</span>);
}, <span class="hljs-number">2000</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-use-of-setinterval">What is the use of setInterval</h3>
<p>The setInterval() method is used to call a function or evaluate an expression at specified intervals (in milliseconds). For example, let's log a message after 2 seconds using setInterval method,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Good morning"</span>);
}, <span class="hljs-number">2000</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-is-javascript-treated-as-single-threaded">Why is JavaScript treated as Single threaded</h3>
<p>JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-event-delegation">What is an event delegation</h3>
<p>Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it.</p>
<p>For example, if you wanted to detect field changes inside a specific form, you can use event delegation technique,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> form = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#registration-form"</span>);

<span class="hljs-comment">// Listen for changes to fields inside the form</span>
form.addEventListener(
  <span class="hljs-string">"input"</span>,
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
    <span class="hljs-comment">// Log the field that was changed</span>
    <span class="hljs-built_in">console</span>.log(event.target);
  },
  <span class="hljs-literal">false</span>
);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-ecmascript">What is ECMAScript</h3>
<p>ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The first edition of ECMAScript was released in 1997.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-json">What is JSON</h3>
<p>JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language in the way objects are built in JavaScript.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-syntax-rules-of-json">What are the syntax rules of JSON</h3>
<p>Below are the list of syntax rules of JSON</p>
<ol>
<li>The data is in name/value pairs</li>
<li>The data is separated by commas</li>
<li>Curly braces hold objects</li>
<li>Square brackets hold arrays</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-json-stringify">What is the purpose JSON stringify</h3>
<p>When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> userJSON = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">31</span> };
<span class="hljs-keyword">var</span> userString = <span class="hljs-built_in">JSON</span>.stringify(userJSON);
<span class="hljs-built_in">console</span>.log(userString); <span class="hljs-comment">//"{"name":"John","age":31}"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-parse-json-string">How do you parse JSON string</h3>
<p>When receiving the data from a web server, the data is always in a string format. But you can convert this string value to a javascript object using parse() method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> userString = <span class="hljs-string">'{"name":"John","age":31}'</span>;
<span class="hljs-keyword">var</span> userJSON = <span class="hljs-built_in">JSON</span>.parse(userString);
<span class="hljs-built_in">console</span>.log(userJSON); <span class="hljs-comment">// {name: "John", age: 31}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-json">Why do you need JSON</h3>
<p>When exchanging data between a browser and a server, the data can only be text. Since JSON is text only, it can easily be sent to and from a server, and used as a data format by any programming language.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-pwas">What are PWAs</h3>
<p>Progressive web applications (PWAs) are a type of mobile app delivered through the web, built using common web technologies including HTML, CSS and JavaScript. These PWAs are deployed to servers, accessible through URLs, and indexed by search engines.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-cleartimeout-method">What is the purpose of clearTimeout method</h3>
<p>The clearTimeout() function is used in javascript to clear the timeout which has been set by setTimeout()function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.</p>
<p>For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by the clearTimeout() method.</p>
<pre><code class="lang-javascript">&lt;script&gt;
     <span class="hljs-keyword">var</span> msg;
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
        alert(<span class="hljs-string">'Good morning'</span>);
     }
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>) </span>{
       msg =<span class="hljs-built_in">setTimeout</span>(greeting, <span class="hljs-number">3000</span>);

     }

     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stop</span>(<span class="hljs-params"></span>) </span>{
         <span class="hljs-built_in">clearTimeout</span>(msg);
     }
&lt;/script&gt;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-clearinterval-method">What is the purpose of clearInterval method</h3>
<p>The clearInterval() function is used in javascript to clear the interval which has been set by setInterval() function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.</p>
<p>For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by the clearInterval() method.</p>
<pre><code class="lang-javascript">&lt;script&gt;
     <span class="hljs-keyword">var</span> msg;
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
        alert(<span class="hljs-string">'Good morning'</span>);
     }
     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>) </span>{
       msg = <span class="hljs-built_in">setInterval</span>(greeting, <span class="hljs-number">3000</span>);

     }

     <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stop</span>(<span class="hljs-params"></span>) </span>{
         <span class="hljs-built_in">clearInterval</span>(msg);
     }
&lt;/script&gt;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-redirect-new-page-in-javascript">How do you redirect new page in javascript</h3>
<p>In vanilla javascript, you can redirect to a new page using the <code>location</code> property of window object. The syntax would be as follows,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">redirect</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">window</span>.location.href = <span class="hljs-string">"newPage.html"</span>;
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-whether-a-string-contains-a-substring">How do you check whether a string contains a substring</h3>
<p>There are 3 possible ways to check whether a string contains a substring or not,</p>
<ol>
<li><strong>Using includes:</strong> ES6 provided <code>String.prototype.includes</code> method to test a string contains a substring</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> mainString = <span class="hljs-string">"hello"</span>,
  subString = <span class="hljs-string">"hell"</span>;
mainString.includes(subString);
</code></pre>
<ol start="2">
<li><strong>Using indexOf:</strong> In an ES5 or older environment, you can use <code>String.prototype.indexOf</code> which returns the index of a substring. If the index value is not equal to -1 then it means the substring exists in the main string.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> mainString = <span class="hljs-string">"hello"</span>,
  subString = <span class="hljs-string">"hell"</span>;
mainString.indexOf(subString) !== <span class="hljs-number">-1</span>;
</code></pre>
<ol start="3">
<li><strong>Using RegEx:</strong> The advanced solution is using Regular expression's test method(<code>RegExp.test</code>), which allows for testing for against regular expressions</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> mainString = <span class="hljs-string">"hello"</span>,
  regex = <span class="hljs-regexp">/hell/</span>;
regex.test(mainString);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-validate-an-email-in-javascript">How do you validate an email in javascript</h3>
<p>You can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead of the client side. Because the javascript can be disabled on the client side.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateEmail</span>(<span class="hljs-params">email</span>) </span>{
  <span class="hljs-keyword">var</span> re =
    <span class="hljs-regexp">/^(([^&lt;&gt;()\[\]\\.,;:\s@"]+(\.[^&lt;&gt;()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/</span>;
  <span class="hljs-keyword">return</span> re.test(<span class="hljs-built_in">String</span>(email).toLowerCase());
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<p>The above regular expression accepts unicode characters.</p>
</li>
<li><h3 id="heading-how-do-you-get-the-current-url-with-javascript">How do you get the current url with javascript</h3>
<p>You can use <code>window.location.href</code> expression to get the current url path and you can use the same expression for updating the URL too. You can also use <code>document.URL</code> for read-only purposes but this solution has issues in FF.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"location.href"</span>, <span class="hljs-built_in">window</span>.location.href); <span class="hljs-comment">// Returns full URL</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-various-url-properties-of-location-object">What are the various url properties of location object</h3>
<p>The below <code>Location</code> object properties can be used to access URL components of the page,</p>
<ol>
<li>href - The entire URL</li>
<li>protocol - The protocol of the URL</li>
<li>host - The hostname and port of the URL</li>
<li>hostname - The hostname of the URL</li>
<li>port - The port number in the URL</li>
<li>pathname - The path name of the URL</li>
<li>search - The query portion of the URL</li>
<li>hash - The anchor portion of the URL</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-get-query-string-values-in-javascript">How do get query string values in javascript</h3>
<p>You can use URLSearchParams to get query string values in javascript. Let's see an example to get the client code value from URL query string,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> urlParams = <span class="hljs-keyword">new</span> URLSearchParams(<span class="hljs-built_in">window</span>.location.search);
<span class="hljs-keyword">const</span> clientCode = urlParams.get(<span class="hljs-string">"clientCode"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-if-a-key-exists-in-an-object">How do you check if a key exists in an object</h3>
<p>You can check whether a key exists in an object or not using three approaches,</p>
<ol>
<li><p><strong>Using in operator:</strong> You can use the in operator whether a key exists in an object or not</p>
<pre><code class="lang-javascript"><span class="hljs-string">"key"</span> <span class="hljs-keyword">in</span> obj;
</code></pre>
<p>and If you want to check if a key doesn't exist, remember to use parenthesis,</p>
<pre><code class="lang-javascript">!(<span class="hljs-string">"key"</span> <span class="hljs-keyword">in</span> obj);
</code></pre>
</li>
<li><p><strong>Using hasOwnProperty method:</strong> You can use <code>hasOwnProperty</code> to particularly test for properties of the object instance (and not inherited properties)</p>
<pre><code class="lang-javascript">obj.hasOwnProperty(<span class="hljs-string">"key"</span>); <span class="hljs-comment">// true</span>
</code></pre>
</li>
<li><p><strong>Using undefined comparison:</strong> If you access a non-existing property from an object, the result is undefined. Let’s compare the properties against undefined to determine the existence of the property.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
};

<span class="hljs-built_in">console</span>.log(user.name !== <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(user.nickName !== <span class="hljs-literal">undefined</span>); <span class="hljs-comment">// false</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-loop-through-or-enumerate-javascript-object">How do you loop through or enumerate javascript object</h3>
<p>You can use the <code>for-in</code> loop to loop through javascript object. You can also make sure that the key you get is an actual property of an object, and doesn't come from the prototype using <code>hasOwnProperty</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = {
  <span class="hljs-attr">k1</span>: <span class="hljs-string">"value1"</span>,
  <span class="hljs-attr">k2</span>: <span class="hljs-string">"value2"</span>,
  <span class="hljs-attr">k3</span>: <span class="hljs-string">"value3"</span>,
};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> key <span class="hljs-keyword">in</span> object) {
  <span class="hljs-keyword">if</span> (object.hasOwnProperty(key)) {
    <span class="hljs-built_in">console</span>.log(key + <span class="hljs-string">" -&gt; "</span> + object[key]); <span class="hljs-comment">// k1 -&gt; value1 ...</span>
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-test-for-an-empty-object">How do you test for an empty object</h3>
<p>There are different solutions based on ECMAScript versions</p>
<ol>
<li><strong>Using Object entries(ECMA 7+):</strong> You can use object entries length along with constructor type.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.entries(obj).length === <span class="hljs-number">0</span> &amp;&amp; obj.constructor === <span class="hljs-built_in">Object</span>; <span class="hljs-comment">// Since date object length is 0, you need to check constructor check as well</span>
</code></pre>
<ol start="2">
<li><strong>Using Object keys(ECMA 5+):</strong> You can use object keys length along with constructor type.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.keys(obj).length === <span class="hljs-number">0</span> &amp;&amp; obj.constructor === <span class="hljs-built_in">Object</span>; <span class="hljs-comment">// Since date object length is 0, you need to check constructor check as well</span>
</code></pre>
<ol start="3">
<li><strong>Using for-in with hasOwnProperty(Pre-ECMA 5):</strong> You can use a for-in loop along with hasOwnProperty.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEmpty</span>(<span class="hljs-params">obj</span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> prop <span class="hljs-keyword">in</span> obj) {
    <span class="hljs-keyword">if</span> (obj.hasOwnProperty(prop)) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
  }

  <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.stringify(obj) === <span class="hljs-built_in">JSON</span>.stringify({});
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-arguments-object">What is an arguments object</h3>
<p>The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let's see how to use arguments object inside sum function,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> total = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>, len = <span class="hljs-built_in">arguments</span>.length; i &lt; len; ++i) {
    total += <span class="hljs-built_in">arguments</span>[i];
  }
  <span class="hljs-keyword">return</span> total;
}

sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">// returns 6</span>
</code></pre>
<p><strong>Note:</strong> You can't apply array methods on arguments object. But you can convert into a regular array as below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> argsArray = <span class="hljs-built_in">Array</span>.prototype.slice.call(<span class="hljs-built_in">arguments</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-make-first-letter-of-the-string-in-an-uppercase">How do you make first letter of the string in an uppercase</h3>
<p>You can create a function which uses a chain of string methods such as charAt, toUpperCase and slice methods to generate a string with the first letter in uppercase.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">capitalizeFirstLetter</span>(<span class="hljs-params">string</span>) </span>{
  <span class="hljs-keyword">return</span> string.charAt(<span class="hljs-number">0</span>).toUpperCase() + string.slice(<span class="hljs-number">1</span>);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-pros-and-cons-of-for-loops">What are the pros and cons of for loops</h3>
<p>The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons</p>
<h4 id="heading-pros">Pros</h4>
<ol>
<li>Works on every environment</li>
<li>You can use break and continue flow control statements</li>
</ol>
<h4 id="heading-cons">Cons</h4>
<ol start="3">
<li>Too verbose</li>
<li>Imperative</li>
<li>You might face off-by-one errors.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-display-the-current-date-in-javascript">How do you display the current date in javascript</h3>
<p>You can use <code>new Date()</code> to generate a new Date object containing the current date and time. For example, let's display the current date in mm/dd/yyyy</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> today = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">var</span> dd = <span class="hljs-built_in">String</span>(today.getDate()).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>);
<span class="hljs-keyword">var</span> mm = <span class="hljs-built_in">String</span>(today.getMonth() + <span class="hljs-number">1</span>).padStart(<span class="hljs-number">2</span>, <span class="hljs-string">"0"</span>); <span class="hljs-comment">//January is 0!</span>
<span class="hljs-keyword">var</span> yyyy = today.getFullYear();

today = mm + <span class="hljs-string">"/"</span> + dd + <span class="hljs-string">"/"</span> + yyyy;
<span class="hljs-built_in">document</span>.write(today);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-compare-two-date-objects">How do you compare two date objects</h3>
<p>You need to use date.getTime() method to compare date values instead of comparison operators (==, !=, ===, and !== operators)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> d1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">var</span> d2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(d1);
<span class="hljs-built_in">console</span>.log(d1.getTime() === d2.getTime()); <span class="hljs-comment">//True</span>
<span class="hljs-built_in">console</span>.log(d1 === d2); <span class="hljs-comment">// False</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-if-a-string-starts-with-another-string">How do you check if a string starts with another string</h3>
<p>You can use ECMAScript 6's <code>String.prototype.startsWith()</code> method to check if a string starts with another string or not. But it is not yet supported in all browsers. Let's see an example to see this usage,</p>
<pre><code class="lang-javascript"><span class="hljs-string">"Good morning"</span>.startsWith(<span class="hljs-string">"Good"</span>); <span class="hljs-comment">// true</span>
<span class="hljs-string">"Good morning"</span>.startsWith(<span class="hljs-string">"morning"</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-trim-a-string-in-javascript">How do you trim a string in javascript</h3>
<p>JavaScript provided a trim method on string types to trim any whitespaces present at the beginning or ending of the string.</p>
<pre><code class="lang-javascript"><span class="hljs-string">"  Hello World   "</span>.trim(); <span class="hljs-comment">//Hello World</span>
</code></pre>
<p>If your browser(&lt;IE9) doesn't support this method then you can use below polyfill.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">String</span>.prototype.trim) {
  (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Make sure we trim BOM and NBSP</span>
    <span class="hljs-keyword">var</span> rtrim = <span class="hljs-regexp">/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g</span>;
    <span class="hljs-built_in">String</span>.prototype.trim = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.replace(rtrim, <span class="hljs-string">""</span>);
    };
  })();
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-add-a-key-value-pair-in-javascript">How do you add a key value pair in javascript</h3>
<p>There are two possible solutions to add new properties to an object. </p>
<p>Let's take a simple object to explain these solutions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> object = {
  <span class="hljs-attr">key1</span>: value1,
  <span class="hljs-attr">key2</span>: value2,
};
</code></pre>
<ol>
<li><strong>Using dot notation:</strong> This solution is useful when you know the name of the property</li>
</ol>
<pre><code class="lang-javascript">object.key3 = <span class="hljs-string">"value3"</span>;
</code></pre>
<ol start="2">
<li><strong>Using square bracket notation:</strong> This solution is useful when the name of the property is dynamically determined.</li>
</ol>
<pre><code class="lang-javascript">obj[<span class="hljs-string">"key3"</span>] = <span class="hljs-string">"value3"</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-the-notation-represents-a-special-operator">Is the !-- notation represents a special operator</h3>
<p>No,that's not a special operator. But it is a combination of 2 standard operators one after the other,</p>
<ol>
<li>A logical not (!)</li>
<li>A prefix decrement (--)</li>
</ol>
<p>At first, the value decremented by one and then tested to see if it is equal to zero or not for determining the truthy/falsy value.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-assign-default-values-to-variables">How do you assign default values to variables</h3>
<p>You can use the logical or operator <code>||</code> in an assignment expression to provide a default value. The syntax looks like as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = b || c;
</code></pre>
<p>As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise 'a' will get the value of 'b'.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-define-multiline-strings">How do you define multiline strings</h3>
<p>You can define multiline string literals using the '\n' character followed by line terminator('\').</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> str =
  <span class="hljs-string">"This is a \n\ very lengthy \n\ sentence!"</span>;
<span class="hljs-built_in">console</span>.log(str);
</code></pre>
<p>But if you have a space after the '\n' character, there will be indentation inconsistencies.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-app-shell-model">What is an app shell model</h3>
<p>An application shell (or app shell) architecture is one way to build a Progressive Web App that reliably and instantly loads on your users' screens, similar to what you see in native applications. It is useful for getting some initial HTML to the screen fast without a network.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-we-define-properties-for-functions">Can we define properties for functions</h3>
<p>Yes, We can define properties for functions because functions are also objects.</p>
<pre><code class="lang-javascript">fn = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x</span>) </span>{
  <span class="hljs-comment">//Function code goes here</span>
};

fn.name = <span class="hljs-string">"John"</span>;

fn.profile = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">y</span>) </span>{
  <span class="hljs-comment">//Profile code goes here</span>
};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-way-to-find-the-number-of-parameters-expected-by-a-function">What is the way to find the number of parameters expected by a function</h3>
<p>You can use <code>function.length</code> syntax to find the number of parameters expected by a function. Let's take an example of <code>sum</code> function to calculate the sum of numbers,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">num1, num2, num3, num4</span>) </span>{
  <span class="hljs-keyword">return</span> num1 + num2 + num3 + num4;
}
sum.length; <span class="hljs-comment">// 4 is the number of parameters expected.</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-polyfill">What is a polyfill</h3>
<p>A polyfill is a piece of JS code used to provide modern functionality on older browsers that do not natively support it. For example, Silverlight plugin polyfill can be used to mimic the functionality of an HTML Canvas element on Microsoft Internet Explorer 7.</p>
<p>There are two main polyfill libraries available,</p>
<ol>
<li><strong>Core.js</strong>: It is a modular javascript library used for cutting-edge ECMAScript features.</li>
<li><strong>Polyfill.io:</strong> It provides polyfills that are required for browser needs.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-break-and-continue-statements">What are break and continue statements</h3>
<p>The break statement is used to "jump out" of a loop. i.e, It breaks the loop and continues executing the code after the loop.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">if</span> (i === <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">break</span>;
  }
  text += <span class="hljs-string">"Number: "</span> + i + <span class="hljs-string">"&lt;br&gt;"</span>;
}
</code></pre>
<p>The continue statement is used to "jump over" one iteration in the loop. i.e, It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) {
  <span class="hljs-keyword">if</span> (i === <span class="hljs-number">5</span>) {
    <span class="hljs-keyword">continue</span>;
  }
  text += <span class="hljs-string">"Number: "</span> + i + <span class="hljs-string">"&lt;br&gt;"</span>;
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-js-labels">What are js labels</h3>
<p>The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> i, j;

loop1: <span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">3</span>; i++) {
  <span class="hljs-attr">loop2</span>: <span class="hljs-keyword">for</span> (j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">3</span>; j++) {
    <span class="hljs-keyword">if</span> (i === j) {
      <span class="hljs-keyword">continue</span> loop1;
    }
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"i = "</span> + i + <span class="hljs-string">", j = "</span> + j);
  }
}

<span class="hljs-comment">// Output is:</span>
<span class="hljs-comment">//   "i = 1, j = 0"</span>
<span class="hljs-comment">//   "i = 2, j = 0"</span>
<span class="hljs-comment">//   "i = 2, j = 1"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-benefits-of-keeping-declarations-at-the-top">What are the benefits of keeping declarations at the top</h3>
<p>It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,</p>
<ol>
<li>Gives cleaner code</li>
<li>It provides a single place to look for local variables</li>
<li>Easy to avoid unwanted global variables</li>
<li>It reduces the possibility of unwanted re-declarations</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-benefits-of-initializing-variables">What are the benefits of initializing variables</h3>
<p>It is recommended to initialize variables because of the below benefits,</p>
<ol>
<li>It gives cleaner code</li>
<li>It provides a single place to initialize variables</li>
<li>Avoid undefined values in the code</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-recommendations-to-create-new-object">What are the recommendations to create new object</h3>
<p>It is recommended to avoid creating new objects using <code>new Object()</code>. Instead you can initialize values based on it's type to create the objects.</p>
<ol>
<li>Assign {} instead of new Object()</li>
<li>Assign "" instead of new String()</li>
<li>Assign 0 instead of new Number()</li>
<li>Assign false instead of new Boolean()</li>
<li>Assign [] instead of new Array()</li>
<li>Assign /()/ instead of new RegExp()</li>
<li>Assign function (){} instead of new Function()</li>
</ol>
<p>You can define them as an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> v1 = {};
<span class="hljs-keyword">var</span> v2 = <span class="hljs-string">""</span>;
<span class="hljs-keyword">var</span> v3 = <span class="hljs-number">0</span>;
<span class="hljs-keyword">var</span> v4 = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">var</span> v5 = [];
<span class="hljs-keyword">var</span> v6 = <span class="hljs-regexp">/()/</span>;
<span class="hljs-keyword">var</span> v7 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-define-json-arrays">How do you define JSON arrays</h3>
<p>JSON arrays are written inside square brackets and arrays contain javascript objects. For example, the JSON array of users would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-string">"users"</span>:[
  {<span class="hljs-string">"firstName"</span>:<span class="hljs-string">"John"</span>, <span class="hljs-string">"lastName"</span>:<span class="hljs-string">"Abrahm"</span>},
  {<span class="hljs-string">"firstName"</span>:<span class="hljs-string">"Anna"</span>, <span class="hljs-string">"lastName"</span>:<span class="hljs-string">"Smith"</span>},
  {<span class="hljs-string">"firstName"</span>:<span class="hljs-string">"Shane"</span>, <span class="hljs-string">"lastName"</span>:<span class="hljs-string">"Warn"</span>}
]
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-generate-random-integers">How do you generate random integers</h3>
<p>You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">10</span>) + <span class="hljs-number">1</span>; <span class="hljs-comment">// returns a random integer from 1 to 10</span>
<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">100</span>) + <span class="hljs-number">1</span>; <span class="hljs-comment">// returns a random integer from 1 to 100</span>
</code></pre>
<p><strong>Note:</strong> Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-you-write-a-random-integers-function-to-print-integers-within-a-range">Can you write a random integers function to print integers within a range</h3>
<p>Yes, you can create a proper random function to return a random number between min and max (both included)</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">randomInteger</span>(<span class="hljs-params">min, max</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * (max - min + <span class="hljs-number">1</span>)) + min;
}
randomInteger(<span class="hljs-number">1</span>, <span class="hljs-number">100</span>); <span class="hljs-comment">// returns a random integer from 1 to 100</span>
randomInteger(<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>); <span class="hljs-comment">// returns a random integer from 1 to 1000</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-tree-shaking">What is tree shaking</h3>
<p>Tree shaking is a form of dead code elimination. It means that unused modules will not be included in the bundle during the build process and for that it relies on the static structure of ES2015 module syntax,( i.e. import and export). Initially this has been popularized by the ES2015 module bundler <code>rollup</code>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-need-of-tree-shaking">What is the need of tree shaking</h3>
<p>Tree Shaking can significantly reduce the code size in any application. i.e, The less code we send over the wire the more performant the application will be. For example, if we just want to create a “Hello World” Application using SPA frameworks then it will take around a few MBs, but by tree shaking it can bring down the size to just a few hundred KBs. Tree shaking is implemented in Rollup and Webpack bundlers.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-it-recommended-to-use-eval">Is it recommended to use eval</h3>
<p>No, it allows arbitrary code to be run which causes a security problem. As we know that the eval() function is used to run text as code. In most of the cases, it should not be necessary to use it.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-regular-expression">What is a Regular Expression</h3>
<p>A regular expression is a sequence of characters that forms a search pattern. You can use this search pattern for searching data in a text. These can be used to perform all types of text search and text replace operations. Let's see the syntax format now,</p>
<pre><code class="lang-javascript">/pattern/modifiers;
</code></pre>
<p>For example, the regular expression or search pattern with case-insensitive username would be,</p>
<pre><code class="lang-javascript">/John/i;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-string-methods-that-accept-regular-expression">What are the string methods that accept Regular expression</h3>
<p>There are six string methods: search(), replace(), replaceAll(), match(), matchAll(), and split().</p>
<p>The search() method uses an expression to search for a match, and returns the position of the match.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = <span class="hljs-string">"Hello John"</span>;
<span class="hljs-keyword">var</span> n = msg.search(<span class="hljs-regexp">/John/i</span>); <span class="hljs-comment">// 6</span>
</code></pre>
<p>The replace() and replaceAll() methods are used to return a modified string where the pattern is replaced.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = <span class="hljs-string">"ball bat"</span>;
<span class="hljs-keyword">var</span> n1 = msg.replace(<span class="hljs-regexp">/b/i</span>, <span class="hljs-string">"c"</span>); <span class="hljs-comment">// call bat</span>
<span class="hljs-keyword">var</span> n2 = msg.replaceAll(<span class="hljs-regexp">/b/i</span>, <span class="hljs-string">"c"</span>); <span class="hljs-comment">// call cat</span>
</code></pre>
<p>The match() and matchAll() methods are used to return the matches when matching a string against a regular expression.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = <span class="hljs-string">"Hello John"</span>;
<span class="hljs-keyword">var</span> n1 = msg.match(<span class="hljs-regexp">/[A-Z]/g</span>); <span class="hljs-comment">// ["H", "J"]</span>
<span class="hljs-keyword">var</span> n2 = msg.matchAll(<span class="hljs-regexp">/[A-Z]/g</span>); <span class="hljs-comment">// this returns an iterator</span>
</code></pre>
<p>The split() method is used to split a string into an array of substrings, and returns the new array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = <span class="hljs-string">"Hello John"</span>;
<span class="hljs-keyword">var</span> n = msg.split(<span class="hljs-regexp">/\s/</span>); <span class="hljs-comment">// ["Hello", "John"]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-modifiers-in-regular-expression">What are modifiers in regular expression</h3>
<p>Modifiers can be used to perform case-insensitive and global searches. Let's list down some of the modifiers,</p>
<p>| Modifier | Description                                             |
| -------- | ------------------------------------------------------- |
| i        | Perform case-insensitive matching                       |
| g        | Perform a global match rather than stops at first match |
| m        | Perform multiline matching                              |</p>
<p>Let's take an example of global modifier,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> text = <span class="hljs-string">"Learn JS one by one"</span>;
<span class="hljs-keyword">var</span> pattern = <span class="hljs-regexp">/one/g</span>;
<span class="hljs-keyword">var</span> result = text.match(pattern); <span class="hljs-comment">// one,one</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-regular-expression-patterns">What are regular expression patterns</h3>
<p>Regular Expressions provide a group of patterns in order to match characters. Basically they are categorized into 3 types,</p>
<ol>
<li><strong>Brackets:</strong> These are used to find a range of characters.
For example, below are some use cases,<ol>
<li>[abc]: Used to find any of the characters between the brackets(a,b,c)</li>
<li>[0-9]: Used to find any of the digits between the brackets</li>
<li>(a|b): Used to find any of the alternatives separated with |</li>
</ol>
</li>
<li><strong>Metacharacters:</strong> These are characters with a special meaning.
For example, below are some use cases,<ol>
<li>\d: Used to find a digit</li>
<li>\s: Used to find a whitespace character</li>
<li>\b: Used to find a match at the beginning or ending of a word</li>
</ol>
</li>
<li><strong>Quantifiers:</strong> These are useful to define quantities.
For example, below are some use cases,<ol>
<li>n+: Used to find matches for any string that contains at least one n</li>
<li>n*: Used to find matches for any string that contains zero or more occurrences of n</li>
<li>n?: Used to find matches for any string that contains zero or one occurrences of n</li>
</ol>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-regexp-object">What is a RegExp object</h3>
<p>RegExp object is a regular expression object with predefined properties and methods. Let's see the simple usage of RegExp object,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> regexp = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"\\w+"</span>);
<span class="hljs-built_in">console</span>.log(regexp);
<span class="hljs-comment">// expected output: /\w+/</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-search-a-string-for-a-pattern">How do you search a string for a pattern</h3>
<p>You can use the test() method of regular expression in order to search a string for a pattern, and return true or false depending on the result.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> pattern = <span class="hljs-regexp">/you/</span>;
<span class="hljs-built_in">console</span>.log(pattern.test(<span class="hljs-string">"How are you?"</span>)); <span class="hljs-comment">//true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-exec-method">What is the purpose of exec method</h3>
<p>The purpose of exec method is similar to test method but it executes a search for a match in a specified string and returns a result array, or null instead of returning true/false.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> pattern = <span class="hljs-regexp">/you/</span>;
<span class="hljs-built_in">console</span>.log(pattern.exec(<span class="hljs-string">"How are you?"</span>)); <span class="hljs-comment">//["you", index: 8, input: "How are you?", groups: undefined]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-change-the-style-of-a-html-element">How do you change the style of a HTML element</h3>
<p>You can change inline style or classname of a HTML element using javascript</p>
<ol>
<li><strong>Using style property:</strong> You can modify inline style using style property</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"title"</span>).style.fontSize = <span class="hljs-string">"30px"</span>;
</code></pre>
<ol start="2">
<li><strong>Using ClassName property:</strong> It is easy to modify element class using className property</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"title"</span>).className = <span class="hljs-string">"custom-title"</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-would-be-the-result-of-123">What would be the result of 1+2+'3'</h3>
<p>The output is going to be <code>33</code>. Since <code>1</code> and <code>2</code> are numeric values, the result of the first two digits is going to be a numeric value <code>3</code>. The next digit is a string type value because of that the addition of numeric value <code>3</code> and string type value <code>3</code> is just going to be a concatenation value <code>33</code>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-debugger-statement">What is a debugger statement</h3>
<p>The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect.
For example, in the below function a debugger statement has been inserted. So
execution is paused at the debugger statement just like a breakpoint in the script source.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getProfile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// code goes here</span>
  <span class="hljs-keyword">debugger</span>;
  <span class="hljs-comment">// code goes here</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-breakpoints-in-debugging">What is the purpose of breakpoints in debugging</h3>
<p>You can set breakpoints in the javascript code once the debugger statement is executed and the debugger window pops up. At each breakpoint, javascript will stop executing, and let you examine the JavaScript values. After examining values, you can resume the execution of code using the play button.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-i-use-reserved-words-as-identifiers">Can I use reserved words as identifiers</h3>
<p>No, you cannot use the reserved words as variables, labels, object or function names. Let's see one simple example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> <span class="hljs-keyword">else</span> = <span class="hljs-string">"hello"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Unexpected token else</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-a-mobile-browser">How do you detect a mobile browser</h3>
<p>You can use regex which returns a true or false value depending on whether or not the user is browsing with a mobile.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.mobilecheck = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> mobileCheck = <span class="hljs-literal">false</span>;
  (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a</span>) </span>{
    <span class="hljs-keyword">if</span> (
      <span class="hljs-regexp">/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i</span>.test(
        a
      ) ||
      <span class="hljs-regexp">/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i</span>.test(
        a.substr(<span class="hljs-number">0</span>, <span class="hljs-number">4</span>)
      )
    )
      mobileCheck = <span class="hljs-literal">true</span>;
  })(navigator.userAgent || navigator.vendor || <span class="hljs-built_in">window</span>.opera);
  <span class="hljs-keyword">return</span> mobileCheck;
};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-a-mobile-browser-without-regexp">How do you detect a mobile browser without regexp</h3>
<p>You can detect mobile browsers by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">detectmob</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (
    navigator.userAgent.match(<span class="hljs-regexp">/Android/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/webOS/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/iPhone/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/iPad/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/iPod/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/BlackBerry/i</span>) ||
    navigator.userAgent.match(<span class="hljs-regexp">/Windows Phone/i</span>)
  ) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-the-image-width-and-height-using-js">How do you get the image width and height using JS</h3>
<p>You can programmatically get the image and check the dimensions(width and height) using Javascript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> img = <span class="hljs-keyword">new</span> Image();
img.onload = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.width + <span class="hljs-string">"x"</span> + <span class="hljs-built_in">this</span>.height);
};
img.src = <span class="hljs-string">"http://www.google.com/intl/en_ALL/images/logo.gif"</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-make-synchronous-http-request">How do you make synchronous HTTP request</h3>
<p>Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">httpGet</span>(<span class="hljs-params">theUrl</span>) </span>{
  <span class="hljs-keyword">var</span> xmlHttpReq = <span class="hljs-keyword">new</span> XMLHttpRequest();
  xmlHttpReq.open(<span class="hljs-string">"GET"</span>, theUrl, <span class="hljs-literal">false</span>); <span class="hljs-comment">// false for synchronous request</span>
  xmlHttpReq.send(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">return</span> xmlHttpReq.responseText;
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-make-asynchronous-http-request">How do you make asynchronous HTTP request</h3>
<p>Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing the 3rd parameter as true.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">httpGetAsync</span>(<span class="hljs-params">theUrl, callback</span>) </span>{
  <span class="hljs-keyword">var</span> xmlHttpReq = <span class="hljs-keyword">new</span> XMLHttpRequest();
  xmlHttpReq.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (xmlHttpReq.readyState == <span class="hljs-number">4</span> &amp;&amp; xmlHttpReq.status == <span class="hljs-number">200</span>)
      callback(xmlHttpReq.responseText);
  };
  xmlHttpReq.open(<span class="hljs-string">"GET"</span>, theUrl, <span class="hljs-literal">true</span>); <span class="hljs-comment">// true for asynchronous</span>
  xmlHttpReq.send(<span class="hljs-literal">null</span>);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-convert-date-to-another-timezone-in-javascript">How do you convert date to another timezone in javascript</h3>
<p>You can use the toLocaleString() method to convert dates in one timezone to another. For example, let's convert current date to British English timezone as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(event.toLocaleString(<span class="hljs-string">"en-GB"</span>, { <span class="hljs-attr">timeZone</span>: <span class="hljs-string">"UTC"</span> })); <span class="hljs-comment">//29/06/2019, 09:56:00</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-properties-used-to-get-size-of-window">What are the properties used to get size of window</h3>
<p>You can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let's use them combination of these properties to calculate the size of a window or document,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> width =
  <span class="hljs-built_in">window</span>.innerWidth ||
  <span class="hljs-built_in">document</span>.documentElement.clientWidth ||
  <span class="hljs-built_in">document</span>.body.clientWidth;

<span class="hljs-keyword">var</span> height =
  <span class="hljs-built_in">window</span>.innerHeight ||
  <span class="hljs-built_in">document</span>.documentElement.clientHeight ||
  <span class="hljs-built_in">document</span>.body.clientHeight;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-conditional-operator-in-javascript">What is a conditional operator in javascript</h3>
<p>The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> isAuthenticated = <span class="hljs-literal">false</span>;
<span class="hljs-built_in">console</span>.log(
  isAuthenticated ? <span class="hljs-string">"Hello, welcome"</span> : <span class="hljs-string">"Sorry, you are not authenticated"</span>
); <span class="hljs-comment">//Sorry, you are not authenticated</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-you-apply-chaining-on-conditional-operator">Can you apply chaining on conditional operator</h3>
<p>Yes, you can apply chaining on conditional operators similar to <strong>if … else if … else if … else</strong> chain. The syntax is going to be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">traceValue</span>(<span class="hljs-params">someParam</span>) </span>{
  <span class="hljs-keyword">return</span> condition1
    ? value1
    : condition2
    ? value2
    : condition3
    ? value3
    : value4;
}

<span class="hljs-comment">// The above conditional operator is equivalent to:</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">traceValue</span>(<span class="hljs-params">someParam</span>) </span>{
  <span class="hljs-keyword">if</span> (condition1) {
    <span class="hljs-keyword">return</span> value1;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (condition2) {
    <span class="hljs-keyword">return</span> value2;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (condition3) {
    <span class="hljs-keyword">return</span> value3;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> value4;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-ways-to-execute-javascript-after-page-load">What are the ways to execute javascript after page load</h3>
<p>You can execute javascript after page load in many different ways,</p>
<ol>
<li><strong>window.onload:</strong></li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.onload = <span class="hljs-function"><span class="hljs-keyword">function</span> ...</span>
</code></pre>
<ol start="2">
<li><strong>document.onload:</strong></li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.onload = <span class="hljs-function"><span class="hljs-keyword">function</span> ...</span>
</code></pre>
<ol start="3">
<li><strong>body onload:</strong></li>
</ol>
<pre><code class="lang-javascript">&lt;body onload=<span class="hljs-string">"script();"</span>&gt;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-proto-and-prototype">What is the difference between proto and prototype</h3>
<p>The <code>__proto__</code> object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas <code>prototype</code> is the object that is used to build <code>__proto__</code> when you create an object with new.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> Employee().__proto__ === Employee.prototype;
<span class="hljs-keyword">new</span> Employee().prototype === <span class="hljs-literal">undefined</span>;
</code></pre>
<p>There are few more differences,</p>
<p>| feature    | Prototype                                                    | proto                                                      |
| ---------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| Access     | All the function constructors have prototype properties.     | All the objects have __proto__ property                |
| Purpose    | Used to reduce memory wastage with a single copy of function | Used in lookup chain to resolve methods, constructors etc. |
| ECMAScript | Introduced in ES6                                            | Introduced in ES5                                          |
| Usage      | Frequently used                                              | Rarely used                                                |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-you-give-an-example-of-when-you-really-need-a-semicolon">Can you give an example of when you really need a semicolon</h3>
<p>It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// define a function</span>
<span class="hljs-keyword">var</span> fn = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
})(
  <span class="hljs-comment">// semicolon missing at this line</span>

  <span class="hljs-comment">// then execute some code inside a closure</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//...</span>
  }
)();
</code></pre>
<p>and it will be interpreted as</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> fn = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
})(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">//...</span>
})();
</code></pre>
<p>In this case, we are passing the second function as an argument to the first function and then trying to call the result of the first function call as a function. Hence, the second function will fail with a "... is not a function" error at runtime.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-freeze-method">What is a freeze method</h3>
<p>The <strong>freeze()</strong> method is used to freeze an object. Freezing an object does not allow adding new properties to an object, prevents removing, and prevents changing the enumerability, configurability, or writability of existing properties. i.e. It returns the passed object and does not create a frozen copy.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">prop</span>: <span class="hljs-number">100</span>,
};

<span class="hljs-built_in">Object</span>.freeze(obj);
obj.prop = <span class="hljs-number">200</span>; <span class="hljs-comment">// Throws an error in strict mode</span>

<span class="hljs-built_in">console</span>.log(obj.prop); <span class="hljs-comment">//100</span>
</code></pre>
<p>Remember freezing is only applied to the top-level properties in objects but not for nested objects.
For example, let's try to freeze user object which has employment details as nested object and observe that details have been changed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">employment</span>: {
    <span class="hljs-attr">department</span>: <span class="hljs-string">"IT"</span>,
  },
};

<span class="hljs-built_in">Object</span>.freeze(user);
user.employment.department = <span class="hljs-string">"HR"</span>;
</code></pre>
<p><strong>Note:</strong> It causes a TypeError if the argument passed is not an object.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-freeze-method">What is the purpose of freeze method</h3>
<p>Below are the main benefits of using freeze method,</p>
<ol>
<li>It is used for freezing objects and arrays.</li>
<li>It is used to make an object immutable.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-i-need-to-use-freeze-method">Why do I need to use freeze method</h3>
<p>In the Object-oriented paradigm, an existing API contains certain elements that are not intended to be extended, modified, or re-used outside of their current context. Hence it works as the <code>final</code> keyword which is used in various languages.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-a-browser-language-preference">How do you detect a browser language preference</h3>
<p>You can use navigator object to detect a browser language preference as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> language =
  (navigator.languages &amp;&amp; navigator.languages[<span class="hljs-number">0</span>]) || <span class="hljs-comment">// Chrome / Firefox</span>
  navigator.language || <span class="hljs-comment">// All browsers</span>
  navigator.userLanguage; <span class="hljs-comment">// IE &lt;= 10</span>

<span class="hljs-built_in">console</span>.log(language);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-convert-string-to-title-case-with-javascript">How to convert string to title case with javascript</h3>
<p>Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toTitleCase</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">return</span> str.replace(<span class="hljs-regexp">/\w\S*/g</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">txt</span>) </span>{
    <span class="hljs-keyword">return</span> txt.charAt(<span class="hljs-number">0</span>).toUpperCase() + txt.substring(<span class="hljs-number">1</span>).toLowerCase();
  });
}
toTitleCase(<span class="hljs-string">"good morning john"</span>); <span class="hljs-comment">// Good Morning John</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-javascript-disabled-in-the-page">How do you detect javascript disabled in the page</h3>
<p>You can use the <code>&lt;noscript&gt;</code> tag to detect javascript disabled or not. The code block inside <code>&lt;noscript&gt;</code> gets executed when JavaScript is disabled, and is typically used to display alternative content when the page generated in JavaScript.</p>
<pre><code class="lang-javascript">&lt;script type=<span class="hljs-string">"javascript"</span>&gt;
    <span class="hljs-comment">// JS related code goes here</span>
&lt;/script&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">noscript</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"next_page.html?noJS=true"</span>&gt;</span>JavaScript is disabled in the page. Please click Next Page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">noscript</span>&gt;</span></span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-various-operators-supported-by-javascript">What are various operators supported by javascript</h3>
<p>An operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,</p>
<ol>
<li><strong>Arithmetic Operators:</strong> Includes + (Addition), – (Subtraction), * (Multiplication), / (Division), % (Modulus), ++ (Increment) and – – (Decrement)</li>
<li><strong>Comparison Operators:</strong> Includes == (Equal), != (Not Equal), === (Equal with type), &gt; (Greater than), &gt;= (Greater than or Equal to), &lt; (Less than), &lt;= (Less than or Equal to)</li>
<li><strong>Logical Operators:</strong> Includes &amp;&amp; (Logical AND), || (Logical OR), ! (Logical NOT)</li>
<li><strong>Assignment Operators:</strong> Includes = (Assignment Operator), += (Add and Assignment Operator), –= (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)</li>
<li><strong>Ternary Operators:</strong> It includes conditional(: ?) Operator</li>
<li><strong>typeof Operator:</strong> It uses to find type of variable. The syntax looks like <code>typeof variable</code></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-rest-parameter">What is a rest parameter</h3>
<p>Rest parameter is an improved way to handle function parameters which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params">a, b, ...theArgs</span>) </span>{
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>For example, let's take a sum example to calculate on dynamic number of parameters,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> i <span class="hljs-keyword">of</span> args) {
    total += i;
  }
  <span class="hljs-keyword">return</span> total;
}

<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)); <span class="hljs-comment">//3</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">//6</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)); <span class="hljs-comment">//10</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">//15</span>
</code></pre>
<p><strong>Note:</strong> Rest parameter is added in ES2015 or ES6</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-happens-if-you-do-not-use-rest-parameter-as-a-last-argument">What happens if you do not use rest parameter as a last argument</h3>
<p>The rest parameter should be the last argument, as its job is to collect all the remaining arguments into an array. For example, if you define a function like below it doesn’t make any sense and will throw an error.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">someFunc</span>(<span class="hljs-params">a,…b,c</span>)</span>{
<span class="hljs-comment">//You code goes here</span>
<span class="hljs-keyword">return</span>;
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-bitwise-operators-available-in-javascript">What are the bitwise operators available in javascript</h3>
<p>Below are the list of bitwise logical operators used in JavaScript</p>
<ol>
<li>Bitwise AND ( &amp; )</li>
<li>Bitwise OR ( | )</li>
<li>Bitwise XOR ( ^ )</li>
<li>Bitwise NOT ( ~ )</li>
<li>Left Shift ( &lt;&lt; )</li>
<li>Sign Propagating Right Shift ( &gt;&gt; )</li>
<li>Zero fill Right Shift ( &gt;&gt;&gt; )</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-spread-operator">What is a spread operator</h3>
<p>Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. Let's take an example to see this behavior,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateSum</span>(<span class="hljs-params">x, y, z</span>) </span>{
  <span class="hljs-keyword">return</span> x + y + z;
}

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-built_in">console</span>.log(calculateSum(...numbers)); <span class="hljs-comment">// 6</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-determine-whether-object-is-frozen-or-not">How do you determine whether object is frozen or not</h3>
<p>Object.isFrozen() method is used to determine if an object is frozen or not.An object is frozen if all of the below conditions hold true,</p>
<ol>
<li>If it is not extensible.</li>
<li>If all of its properties are non-configurable.</li>
<li>If all its data properties are non-writable.
The usage is going to be as follows,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = {
  <span class="hljs-attr">property</span>: <span class="hljs-string">"Welcome JS world"</span>,
};
<span class="hljs-built_in">Object</span>.freeze(object);
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isFrozen(object));
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-determine-two-values-same-or-not-using-object">How do you determine two values same or not using object</h3>
<p>The Object.is() method determines whether two values are the same value. For example, the usage with different types of values would be,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.is(<span class="hljs-string">"hello"</span>, <span class="hljs-string">"hello"</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">Object</span>.is(<span class="hljs-built_in">window</span>, <span class="hljs-built_in">window</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">Object</span>.is([], []); <span class="hljs-comment">// false</span>
</code></pre>
<p>Two values are the same if one of the following holds:</p>
<ol>
<li>both undefined</li>
<li>both null</li>
<li>both true or both false</li>
<li>both strings of the same length with the same characters in the same order</li>
<li>both the same object (means both object have same reference)</li>
<li>both numbers and
both +0
both -0
both NaN
both non-zero and both not NaN and both have the same value.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-using-object-is-method">What is the purpose of using object is method</h3>
<p>Some of the applications of Object's <code>is</code> method are follows,</p>
<ol>
<li>It is used for comparison of two strings.</li>
<li>It is used for comparison of two numbers.</li>
<li>It is used for comparing the polarity of two numbers.</li>
<li>It is used for comparison of two objects.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-copy-properties-from-one-object-to-other">How do you copy properties from one object to other</h3>
<p>You can use the Object.assign() method which is used to copy the values and properties from one or more source objects to a target object. It returns the target object which has properties and values copied from the source objects. The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.assign(target, ...sources);
</code></pre>
<p>Let's take example with one source and one target object,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> target = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> source = { <span class="hljs-attr">b</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">c</span>: <span class="hljs-number">4</span> };

<span class="hljs-keyword">const</span> returnedTarget = <span class="hljs-built_in">Object</span>.assign(target, source);

<span class="hljs-built_in">console</span>.log(target); <span class="hljs-comment">// { a: 1, b: 3, c: 4 }</span>

<span class="hljs-built_in">console</span>.log(returnedTarget); <span class="hljs-comment">// { a: 1, b: 3, c: 4 }</span>
</code></pre>
<p>As observed in the above code, there is a common property(<code>b</code>) from source to target so it's value has been overwritten.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-applications-of-assign-method">What are the applications of assign method</h3>
<p>Below are the some of main applications of Object.assign() method,</p>
<ol>
<li>It is used for cloning an object.</li>
<li>It is used to merge objects with the same properties.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-proxy-object">What is a proxy object</h3>
<p>The Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc. </p>
<p>A proxy is created with two parameters: a target object which you want to proxy and a handler object which contains methods to intercept fundamental operations. The syntax would be as follows,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(target, handler);
</code></pre>
<p>Let's take a look at below examples of proxy object and how the get method which customize the lookup behavior,</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">//Example1:</span>

   <span class="hljs-keyword">const</span> person = {
     <span class="hljs-attr">name</span>: <span class="hljs-string">'Sudheer Jonna'</span>,
     <span class="hljs-attr">age</span>: <span class="hljs-number">35</span>
   };

 <span class="hljs-keyword">const</span> handler = {
   get(target, prop) {
     <span class="hljs-keyword">if</span> (prop === <span class="hljs-string">'name'</span>) {
       <span class="hljs-keyword">return</span> <span class="hljs-string">'Mr. '</span> + target[prop];
     }
     <span class="hljs-keyword">return</span> target[prop];
   }
 };

 <span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>(person, handler);

 <span class="hljs-comment">//Example2: </span>

 <span class="hljs-keyword">var</span> handler1 = {
   <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">obj, prop</span>) </span>{
     <span class="hljs-keyword">return</span> prop <span class="hljs-keyword">in</span> obj ? obj[prop] : <span class="hljs-number">100</span>;
   },
 };

 <span class="hljs-keyword">var</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Proxy</span>({}, handler1);
 p.a = <span class="hljs-number">10</span>;
 p.b = <span class="hljs-literal">null</span>;

 <span class="hljs-built_in">console</span>.log(p.a, p.b); <span class="hljs-comment">// 10, null</span>
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"c"</span> <span class="hljs-keyword">in</span> p, p.c); <span class="hljs-comment">// false, 100</span>
</code></pre>
<p>In the above code, it uses <code>get</code> handler which define the behavior of the proxy when an operation is performed on it. These proxies are mainly used for some of the below cross-cutting concerns.</p>
<ol>
<li>Logging</li>
<li>Authentication or Authorization</li>
<li>Data binding and observables</li>
<li>Function parameter validation</li>
</ol>
<p><strong>Note:</strong> This is a new feature in ES6.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-seal-method">What is the purpose of seal method</h3>
<p>The <strong>Object.seal()</strong> method is used to seal an object, by preventing new properties from being added to it and marking all existing properties as non-configurable. But values of present properties can still be changed as long as they are writable. Let's see the below example to understand more about seal() method</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = {
  <span class="hljs-attr">property</span>: <span class="hljs-string">"Welcome JS world"</span>,
};
<span class="hljs-built_in">Object</span>.seal(object);
object.property = <span class="hljs-string">"Welcome to object world"</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isSealed(object)); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">delete</span> object.property; <span class="hljs-comment">// You cannot delete when sealed</span>
<span class="hljs-built_in">console</span>.log(object.property); <span class="hljs-comment">//Welcome to object world</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-applications-of-seal-method">What are the applications of seal method</h3>
<p>Below are the main applications of Object.seal() method,</p>
<ol>
<li>It is used for sealing objects and arrays.</li>
<li>It is used to make an object immutable.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-freeze-and-seal-methods">What are the differences between freeze and seal methods</h3>
<p>If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object.seal() method then the changes can be made in the existing properties of the object.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-determine-if-an-object-is-sealed-or-not">How do you determine if an object is sealed or not</h3>
<p>The Object.isSealed() method is used to determine if an object is sealed or not. An object is sealed if all of the below conditions hold true</p>
<ol>
<li>If it is not extensible.</li>
<li>If all of its properties are non-configurable.</li>
<li>If it is not removable (but not necessarily non-writable).
Let's see it in the action</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = {
  <span class="hljs-attr">property</span>: <span class="hljs-string">"Hello, Good morning"</span>,
};

<span class="hljs-built_in">Object</span>.seal(object); <span class="hljs-comment">// Using seal() method to seal the object</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isSealed(object)); <span class="hljs-comment">// checking whether the object is sealed or not</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-enumerable-key-and-value-pairs">How do you get enumerable key and value pairs</h3>
<p>The Object.entries() method is used to return an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. Let's see the functionality of object.entries() method in an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = {
  <span class="hljs-attr">a</span>: <span class="hljs-string">"Good morning"</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">100</span>,
};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> [key, value] <span class="hljs-keyword">of</span> <span class="hljs-built_in">Object</span>.entries(object)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${value}</span>`</span>); <span class="hljs-comment">// a: 'Good morning'</span>
  <span class="hljs-comment">// b: 100</span>
}
</code></pre>
<p><strong>Note:</strong> The order is not guaranteed as object defined.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-main-difference-between-objectvalues-and-objectentries-method">What is the main difference between Object.values and Object.entries method</h3>
<p>The Object.values() method's behavior is similar to Object.entries() method but it returns an array of values instead [key,value] pairs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> object = {
  <span class="hljs-attr">a</span>: <span class="hljs-string">"Good morning"</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">100</span>,
};

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> value <span class="hljs-keyword">of</span> <span class="hljs-built_in">Object</span>.values(object)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${value}</span>`</span>); <span class="hljs-comment">// 'Good morning \n100'</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-can-you-get-the-list-of-keys-of-any-object">How can you get the list of keys of any object</h3>
<p>You can use the <code>Object.keys()</code> method which is used to return an array of a given object's own property names, in the same order as we get with a normal loop. For example, you can get the keys of a user object,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">40</span>,
};

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(user)); <span class="hljs-comment">//['name', 'gender', 'age']</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-an-object-with-prototype">How do you create an object with prototype</h3>
<p>The Object.create() method is used to create a new object with the specified prototype object and properties. i.e, It uses an existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">printInfo</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>.`</span>);
  },
};

<span class="hljs-keyword">const</span> admin = <span class="hljs-built_in">Object</span>.create(user);

admin.name = <span class="hljs-string">"Nick"</span>; <span class="hljs-comment">// Remember that "name" is a property set on "admin" but not on "user" object</span>

admin.printInfo(); <span class="hljs-comment">// My name is Nick</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-weakset">What is a WeakSet</h3>
<p>WeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>([iterable]);
</code></pre>
<p>Let's see the below example to explain it's behavior,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> ws = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">var</span> user = {};
ws.add(user);
ws.has(user); <span class="hljs-comment">// true</span>
ws.delete(user); <span class="hljs-comment">// removes user from the set</span>
ws.has(user); <span class="hljs-comment">// false, user has been removed</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-weakset-and-set">What are the differences between WeakSet and Set</h3>
<p>The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it.
Other differences are,</p>
<ol>
<li>Sets can store any value Whereas WeakSets can store only collections of objects</li>
<li>WeakSet does not have size property unlike Set</li>
<li>WeakSet does not have methods such as clear, keys, values, entries, forEach.</li>
<li>WeakSet is not iterable.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-list-down-the-collection-of-methods-available-on-weakset">List down the collection of methods available on WeakSet</h3>
<p>Below are the list of methods available on WeakSet,</p>
<ol>
<li>add(value): A new object is appended with the given value to the weakset</li>
<li>delete(value): Deletes the value from the WeakSet collection.</li>
<li>has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.</li>
</ol>
<p>Let's see the functionality of all the above methods in an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> weakSetObject = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">var</span> firstObject = {};
<span class="hljs-keyword">var</span> secondObject = {};
<span class="hljs-comment">// add(value)</span>
weakSetObject.add(firstObject);
weakSetObject.add(secondObject);
<span class="hljs-built_in">console</span>.log(weakSetObject.has(firstObject)); <span class="hljs-comment">//true</span>
weakSetObject.delete(secondObject);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-weakmap">What is a WeakMap</h3>
<p>The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax looks like the following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>([iterable]);
</code></pre>
<p>Let's see the below example to explain it's behavior,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> ws = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">var</span> user = {};
ws.set(user);
ws.has(user); <span class="hljs-comment">// true</span>
ws.delete(user); <span class="hljs-comment">// removes user from the map</span>
ws.has(user); <span class="hljs-comment">// false, user has been removed</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-weakmap-and-map">What are the differences between WeakMap and Map</h3>
<p>The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it.
Other differences are,</p>
<ol>
<li>Maps can store any key type Whereas WeakMaps can store only collections of key objects</li>
<li>WeakMap does not have size property unlike Map</li>
<li>WeakMap does not have methods such as clear, keys, values, entries, forEach.</li>
<li>WeakMap is not iterable.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-list-down-the-collection-of-methods-available-on-weakmap">List down the collection of methods available on WeakMap</h3>
<p>Below are the list of methods available on WeakMap,</p>
<ol>
<li>set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.</li>
<li>delete(key): Removes any value associated to the key.</li>
<li>has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.</li>
<li>get(key): Returns the value associated to the key, or undefined if there is none.
Let's see the functionality of all the above methods in an example,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> weakMapObject = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">var</span> firstObject = {};
<span class="hljs-keyword">var</span> secondObject = {};
<span class="hljs-comment">// set(key, value)</span>
weakMapObject.set(firstObject, <span class="hljs-string">"John"</span>);
weakMapObject.set(secondObject, <span class="hljs-number">100</span>);
<span class="hljs-built_in">console</span>.log(weakMapObject.has(firstObject)); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(weakMapObject.get(firstObject)); <span class="hljs-comment">// John</span>
weakMapObject.delete(secondObject);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-uneval">What is the purpose of uneval</h3>
<p>The uneval() is an inbuilt function which is used to create a string representation of the source code of an Object. It is a top-level function and is not associated with any object. Let's see the below example to know more about it's functionality,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>;
uneval(a); <span class="hljs-comment">// returns a String containing 1</span>
uneval(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">user</span>(<span class="hljs-params"></span>) </span>{}); <span class="hljs-comment">// returns "(function user(){})"</span>
</code></pre>
<p>The <code>uneval()</code> function has been deprecated. It is recommended to use <code>toString()</code> for functions and <code>JSON.toStringify()</code> for other cases.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">user</span>(<span class="hljs-params"></span>) </span>{}
<span class="hljs-built_in">console</span>.log(user.toString()); <span class="hljs-comment">// returns "(function user(){})"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-encode-an-url">How do you encode an URL</h3>
<p>The encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ &amp; = + $ #) characters.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> uri = <span class="hljs-string">"https://mozilla.org/?x=шеллы"</span>;
<span class="hljs-keyword">var</span> encoded = <span class="hljs-built_in">encodeURI</span>(uri);
<span class="hljs-built_in">console</span>.log(encoded); <span class="hljs-comment">// https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-decode-an-url">How do you decode an URL</h3>
<p>The decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> uri = <span class="hljs-string">"https://mozilla.org/?x=шеллы"</span>;
<span class="hljs-keyword">var</span> encoded = <span class="hljs-built_in">encodeURI</span>(uri);
<span class="hljs-built_in">console</span>.log(encoded); <span class="hljs-comment">// https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">decodeURI</span>(encoded)); <span class="hljs-comment">// "https://mozilla.org/?x=шеллы"</span>
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-comment">// catches a malformed URI</span>
  <span class="hljs-built_in">console</span>.error(e);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-print-the-contents-of-web-page">How do you print the contents of web page</h3>
<p>The window object provided a print() method which is used to print the contents of the current window. It opens a Print dialog box which lets you choose between various printing options. Let's see the usage of print method in an example,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Print"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"window.print()"</span> /&gt;</span>
</code></pre>
<p><strong>Note:</strong> In most browsers, it will block while the print dialog is open.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-uneval-and-eval">What is the difference between uneval and eval</h3>
<p>The <code>uneval</code> function returns the source of a given object; whereas the <code>eval</code> function does the opposite, by evaluating that source code in a different memory area. Let's see an example to clarify the difference,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = uneval(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, Good morning"</span>;
});
<span class="hljs-keyword">var</span> greeting = <span class="hljs-built_in">eval</span>(msg);
greeting(); <span class="hljs-comment">// returns "Hello, Good morning"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-anonymous-function">What is an anonymous function</h3>
<p>An anonymous function is a function without a name! Anonymous functions are commonly assigned to a variable name or used as a callback function. The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">optionalParameters</span>) </span>{
  <span class="hljs-comment">//do something</span>
}

<span class="hljs-keyword">const</span> myFunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{ <span class="hljs-comment">//Anonymous function assigned to a variable</span>
  <span class="hljs-comment">//do something</span>
};

[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>].map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">element</span>)</span>{ <span class="hljs-comment">//Anonymous function used as a callback function</span>
  <span class="hljs-comment">//do something</span>
});
</code></pre>
<p>Let's see the above anonymous function in an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a * b;
};
<span class="hljs-keyword">var</span> z = x(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(z); <span class="hljs-comment">// 50</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-precedence-order-between-local-and-global-variables">What is the precedence order between local and global variables</h3>
<p>A local variable takes precedence over a global variable with the same name. Let's see this behavior in an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> msg = <span class="hljs-string">"Good morning"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
  msg = <span class="hljs-string">"Good Evening"</span>;
  <span class="hljs-built_in">console</span>.log(msg); <span class="hljs-comment">// Good Evening</span>
}
greeting();
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-javascript-accessors">What are javascript accessors</h3>
<p>ECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses the <code>get</code> keyword whereas Setters uses the <code>set</code> keyword.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Abraham"</span>,
  <span class="hljs-attr">language</span>: <span class="hljs-string">"en"</span>,
  <span class="hljs-keyword">get</span> <span class="hljs-title">lang</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.language;
  },
  <span class="hljs-keyword">set</span> <span class="hljs-title">lang</span>(<span class="hljs-params">lang</span>) {
    <span class="hljs-built_in">this</span>.language = lang;
  },
};
<span class="hljs-built_in">console</span>.log(user.lang); <span class="hljs-comment">// getter access lang as en</span>
user.lang = <span class="hljs-string">"fr"</span>;
<span class="hljs-built_in">console</span>.log(user.lang); <span class="hljs-comment">// setter used to set lang as fr</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-define-property-on-object-constructor">How do you define property on Object constructor</h3>
<p>The Object.defineProperty() static method is used to define a new property directly on an object, or modify an existing property on an object, and returns the object. Let's see an example to know how to define property,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {};

<span class="hljs-built_in">Object</span>.defineProperty(newObject, <span class="hljs-string">"newProperty"</span>, {
  <span class="hljs-attr">value</span>: <span class="hljs-number">100</span>,
  <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span>,
});

<span class="hljs-built_in">console</span>.log(newObject.newProperty); <span class="hljs-comment">// 100</span>

newObject.newProperty = <span class="hljs-number">200</span>; <span class="hljs-comment">// It throws an error in strict mode due to writable setting</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-get-and-defineproperty">What is the difference between get and defineProperty</h3>
<p>Both have similar results unless you use classes. If you use <code>get</code> the property will be defined on the prototype of the object whereas using <code>Object.defineProperty()</code> the property will be defined on the instance it is applied to.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-advantages-of-getters-and-setters">What are the advantages of Getters and Setters</h3>
<p>Below are the list of benefits of Getters and Setters,</p>
<ol>
<li>They provide simpler syntax</li>
<li>They are used for defining computed properties, or accessors in JS.</li>
<li>Useful to provide equivalence relation between properties and methods</li>
<li>They can provide better data quality</li>
<li>Useful for doing things behind the scenes with the encapsulated logic.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-i-add-getters-and-setters-using-defineproperty-method">Can I add getters and setters using defineProperty method</h3>
<p>Yes, You can use the <code>Object.defineProperty()</code> method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and subtract properties,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> obj = { <span class="hljs-attr">counter</span>: <span class="hljs-number">0</span> };

<span class="hljs-comment">// Define getters</span>
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"increment"</span>, {
  <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">this</span>.counter++;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.counter;
  },
});
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"decrement"</span>, {
  <span class="hljs-attr">get</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">this</span>.counter--;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.counter;
  },
});

<span class="hljs-comment">// Define setters</span>
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"add"</span>, {
  <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{
    <span class="hljs-built_in">this</span>.counter += value;
  },
});
<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">"subtract"</span>, {
  <span class="hljs-attr">set</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value</span>) </span>{
    <span class="hljs-built_in">this</span>.counter -= value;
  },
});

obj.add = <span class="hljs-number">10</span>;
obj.subtract = <span class="hljs-number">5</span>;
<span class="hljs-built_in">console</span>.log(obj.increment); <span class="hljs-comment">//6</span>
<span class="hljs-built_in">console</span>.log(obj.decrement); <span class="hljs-comment">//5</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-switch-case">What is the purpose of switch-case</h3>
<p>The switch case statement in JavaScript is used for decision making purposes. In a few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">switch</span> (expression)
{
    <span class="hljs-keyword">case</span> value1:
        statement1;
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> value2:
        statement2;
        <span class="hljs-keyword">break</span>;
    .
    .
    case valueN:
        statementN;
        <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">default</span>:
        statementDefault;
}
</code></pre>
<p>The above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-conventions-to-be-followed-for-the-usage-of-switch-case">What are the conventions to be followed for the usage of switch case</h3>
<p>Below are the list of conventions should be taken care,</p>
<ol>
<li>The expression can be of type either number or string.</li>
<li>Duplicate values are not allowed for the expression.</li>
<li>The default statement is optional. If the expression passed to switch does not match with any case value then the statement within default case will be executed.</li>
<li>The break statement is used inside the switch to terminate a statement sequence.</li>
<li>The break statement is optional. But if it is omitted, the execution will continue on into the next case.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-primitive-data-types">What are primitive data types</h3>
<p>A primitive data type is data that has a primitive value (which has no properties or methods). There are 7 types of primitive data types.</p>
<ol>
<li>string</li>
<li>number</li>
<li>boolean</li>
<li>null</li>
<li>undefined</li>
<li>bigint</li>
<li>symbol</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-ways-to-access-object-properties">What are the different ways to access object properties</h3>
<p>There are 3 possible ways for accessing the property of an object.</p>
<ol>
<li><strong>Dot notation:</strong> It uses dot for accessing the properties</li>
</ol>
<pre><code class="lang-javascript">objectName.property;
</code></pre>
<ol start="2">
<li><strong>Square brackets notation:</strong> It uses square brackets for property access</li>
</ol>
<pre><code class="lang-javascript">objectName[<span class="hljs-string">"property"</span>];
</code></pre>
<ol start="3">
<li><strong>Expression notation:</strong> It uses expression in the square brackets</li>
</ol>
<pre><code class="lang-javascript">objectName[expression];
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-function-parameter-rules">What are the function parameter rules</h3>
<p>JavaScript functions follow below rules for parameters,</p>
<ol>
<li>The function definitions do not specify data types for parameters.</li>
<li>Do not perform type checking on the passed arguments.</li>
<li>Do not check the number of arguments received.
i.e, The below function follows the above rules,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span>(<span class="hljs-params">parameter1, parameter2, parameter3</span>) </span>{
  <span class="hljs-built_in">console</span>.log(parameter1); <span class="hljs-comment">// 1</span>
}
functionName(<span class="hljs-number">1</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-error-object">What is an error object</h3>
<p>An error object is a built in error object that provides error information when an error occurs. It has two properties: name and message. For example, the below function logs error details,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  greeting(<span class="hljs-string">"Welcome"</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(err.name + <span class="hljs-string">"&lt;br&gt;"</span> + err.message);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-when-you-get-a-syntax-error">When you get a syntax error</h3>
<p>A SyntaxError is thrown if you try to evaluate code with a syntax error. For example, the below missing quote for the function parameter throws a syntax error</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">eval</span>(<span class="hljs-string">"greeting('welcome)"</span>); <span class="hljs-comment">// Missing ' will produce an error</span>
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(err.name);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-error-names-from-error-object">What are the different error names from error object</h3>
<p>There are 7 different types of error names returned from error object,
| Error Name | Description |
|---- | ---------
| AggregateError | An error indicating that multiple errors occurred |
| EvalError | An error has occurred in the eval() function |
| RangeError | An error has occurred with a number "out of range" |
| ReferenceError | An error due to an illegal reference|
| SyntaxError | An error due to a syntax error|
| TypeError | An error due to a type error |
| URIError | An error due to encodeURI() |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-various-statements-in-error-handling">What are the various statements in error handling</h3>
<p>Below are the list of statements used in an error handling,</p>
<ol>
<li><strong>try:</strong> This statement is used to test a block of code for errors</li>
<li><strong>catch:</strong> This statement is used to handle the error</li>
<li><strong>throw:</strong> This statement is used to create custom errors.</li>
<li><strong>finally:</strong> This statement is used to execute code after try and catch regardless of the result.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-two-types-of-loops-in-javascript">What are the two types of loops in javascript</h3>
<ol>
<li><strong>Entry Controlled loops:</strong> In this kind of loop type, the test condition is tested before entering the loop body. For example, For Loop and While Loop comes under this category.</li>
<li><strong>Exit Controlled Loops:</strong> In this kind of loop type, the test condition is tested or evaluated at the end of the loop body. i.e, the loop body will execute at least once irrespective of test condition true or false. For example, do-while loop comes under this category.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-nodejs">What is nodejs</h3>
<p>Node.js is a server-side platform built on Chrome's JavaScript runtime for easily building fast and scalable network applications. It is an event-based, non-blocking, asynchronous I/O runtime that uses Google's V8 JavaScript engine and libuv library.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-intl-object">What is an Intl object</h3>
<p>The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. It provides access to several constructors and language sensitive functions.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-perform-language-specific-date-and-time-formatting">How do you perform language specific date and time formatting</h3>
<p>You can use the <code>Intl.DateTimeFormat</code> object which is a constructor for objects that enable language-sensitive date and time formatting. Let's see this behavior with an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Date</span>.UTC(<span class="hljs-number">2019</span>, <span class="hljs-number">07</span>, <span class="hljs-number">07</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>));
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">"en-GB"</span>).format(date)); <span class="hljs-comment">// 07/08/2019</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.DateTimeFormat(<span class="hljs-string">"en-AU"</span>).format(date)); <span class="hljs-comment">// 07/08/2019</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-iterator">What is an Iterator</h3>
<p>An iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a <code>next()</code> method which returns an object with two properties: <code>value</code> (the next value in the sequence) and <code>done</code> (which is true if the last value in the sequence has been consumed).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-does-synchronous-iteration-works">How does synchronous iteration works</h3>
<p>Synchronous iteration was introduced in ES6 and it works with below set of components,</p>
<p><strong>Iterable:</strong> It is an object which can be iterated over via a method whose key is Symbol.iterator.</p>
<p><strong>Iterator:</strong> It is an object returned by invoking <code>[Symbol.iterator]()</code> on an iterable. This iterator object wraps each iterated element in an object and returns it via <code>next()</code> method one by one.</p>
<p><strong>IteratorResult:</strong> It is an object returned by <code>next()</code> method. The object contains two properties; the <code>value</code> property contains an iterated element and the <code>done</code> property determines whether the element is the last element or not.</p>
<p>Let's demonstrate synchronous iteration with an array as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> iterable = [<span class="hljs-string">"one"</span>, <span class="hljs-string">"two"</span>, <span class="hljs-string">"three"</span>];
<span class="hljs-keyword">const</span> iterator = iterable[<span class="hljs-built_in">Symbol</span>.iterator]();
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// { value: 'one', done: false }</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// { value: 'two', done: false }</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// { value: 'three', done: false }</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// { value: 'undefined, done: true }</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-event-loop">What is an event loop</h3>
<p>The event loop is a process that continuously monitors both the call stack and the event queue and checks whether or not the call stack is empty. If the call stack is empty and there are pending events in the event queue, the event loop dequeues the event from the event queue and pushes it to the call stack. The call stack executes the event, and any additional events generated during the execution are added to the end of the event queue.</p>
<p><strong>Note:</strong> The event loop allows Node.js to perform non-blocking I/O operations, even though JavaScript is single-threaded, by offloading operations to the system kernel whenever possible. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-call-stack">What is call stack</h3>
<p>Call Stack is a data structure for javascript interpreters to keep track of function calls(creates execution context) in the program. It has two major actions,</p>
<ol>
<li>Whenever you call a function for its execution, you are pushing it to the stack.</li>
<li>Whenever the execution is completed, the function is popped out of the stack.</li>
</ol>
<p>Let's take an example and it's state representation in a diagram format</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hungry</span>(<span class="hljs-params"></span>) </span>{
  eatFruits();
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">eatFruits</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"I'm eating fruits"</span>;
}

<span class="hljs-comment">// Invoke the `hungry` function</span>
hungry();
</code></pre>
<p>The above code processed in a call stack as below,</p>
<ol start="3">
<li>Add the <code>hungry()</code> function to the call stack list and execute the code.</li>
<li>Add the <code>eatFruits()</code> function to the call stack list and execute the code.</li>
<li>Delete the <code>eatFruits()</code> function from our call stack list.</li>
<li>Delete the <code>hungry()</code> function from the call stack list since there are no items anymore.</li>
</ol>
<p><img src="images/call-stack.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-event-queue">What is an event queue</h3>
<p>The event queue follows the queue data structure. It stores async callbacks to be added to the call stack. It is also known as the Callback Queue or Macrotask Queue.</p>
<p>Whenever the call stack receives an async function, it is moved into the Web API. Based on the function, Web API executes it and awaits the result. Once it is finished, it moves the callback into the event queue (the callback of the promise is moved into the microtask queue).</p>
<p>The event loop constantly checks whether or not the call stack is empty. Once the call stack is empty and there is a callback in the event queue, the event loop moves the callback into the call stack. But if there is a callback in the microtask queue as well, it is moved first. The microtask queue has a higher priority than the event queue.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-decorator">What is a decorator</h3>
<p>A decorator is an expression that evaluates to a function and that takes the target, name, and decorator descriptor as arguments. Also, it optionally returns a decorator descriptor to install on the target object. Let's define admin decorator for user class at design time,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">admin</span>(<span class="hljs-params">isAdmin</span>) </span>{
   <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">target</span>) </span>{
       target.isAdmin = isAdmin;
   }
}

@admin(<span class="hljs-literal">true</span>)
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>() </span>{
}
<span class="hljs-built_in">console</span>.log(User.isAdmin); <span class="hljs-comment">//true</span>

 @admin(<span class="hljs-literal">false</span>)
 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>() </span>{
 }
 <span class="hljs-built_in">console</span>.log(User.isAdmin); <span class="hljs-comment">//false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-properties-of-intl-object">What are the properties of Intl object</h3>
<p>Below are the list of properties available on Intl object,</p>
<ol>
<li><strong>Collator:</strong> These are the objects that enable language-sensitive string comparison.</li>
<li><strong>DateTimeFormat:</strong> These are the objects that enable language-sensitive date and time formatting.</li>
<li><strong>ListFormat:</strong> These are the objects that enable language-sensitive list formatting.</li>
<li><strong>NumberFormat:</strong> Objects that enable language-sensitive number formatting.</li>
<li><strong>PluralRules:</strong> Objects that enable plural-sensitive formatting and language-specific rules for plurals.</li>
<li><strong>RelativeTimeFormat:</strong> Objects that enable language-sensitive relative time formatting.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-unary-operator">What is an Unary operator</h3>
<p>The unary(+) operator is used to convert a variable to a number.If the variable cannot be converted, it will still become a number but with the value NaN. Let's see this behavior in an action.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-string">"100"</span>;
<span class="hljs-keyword">var</span> y = +x;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x, <span class="hljs-keyword">typeof</span> y); <span class="hljs-comment">// string, number</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">var</span> b = +a;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> a, <span class="hljs-keyword">typeof</span> b, b); <span class="hljs-comment">// string, number, NaN</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-sort-elements-in-an-array">How do you sort elements in an array</h3>
<p>The sort() method is used to sort the elements of an array in place and returns the sorted array. The default sort order is ascending, based on the string Unicode order. The example usage would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> months = [<span class="hljs-string">"Aug"</span>, <span class="hljs-string">"Sep"</span>, <span class="hljs-string">"Jan"</span>, <span class="hljs-string">"June"</span>];
months.sort();
<span class="hljs-built_in">console</span>.log(months); <span class="hljs-comment">//  ["Aug", "Jan", "June", "Sep"]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-comparefunction-while-sorting-arrays">What is the purpose of compareFunction while sorting arrays</h3>
<p>The compareFunction is used to define the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. </p>
<p>Let's take an example to see the usage of compareFunction,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
numbers.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b - a);
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [5, 4, 3, 2, 1]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-reversing-an-array">How do you reversing an array</h3>
<p>You can use the reverse() method to reverse the elements in an array. This method is useful to sort an array in descending order. Let's see the usage of reverse() method in an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
numbers.sort(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b - a);
numbers.reverse();
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [1, 2, 3, 4 ,5]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-find-min-and-max-value-in-an-array">How do you find min and max value in an array</h3>
<p>You can use <code>Math.min</code> and <code>Math.max</code> methods on array variables to find the minimum and maximum elements within an array. Let's create two functions to find the min and max value with in an array,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> marks = [<span class="hljs-number">50</span>, <span class="hljs-number">20</span>, <span class="hljs-number">70</span>, <span class="hljs-number">60</span>, <span class="hljs-number">45</span>, <span class="hljs-number">30</span>];
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMin</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.min.apply(<span class="hljs-literal">null</span>, arr);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMax</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.max.apply(<span class="hljs-literal">null</span>, arr);
}

<span class="hljs-built_in">console</span>.log(findMin(marks));
<span class="hljs-built_in">console</span>.log(findMax(marks));
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-find-min-and-max-values-without-math-functions">How do you find min and max values without Math functions</h3>
<p>You can write functions which loop through an array comparing each value with the lowest value or highest value to find the min and max values. Let's create those functions to find min and max values,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> marks = [<span class="hljs-number">50</span>, <span class="hljs-number">20</span>, <span class="hljs-number">70</span>, <span class="hljs-number">60</span>, <span class="hljs-number">45</span>, <span class="hljs-number">30</span>];
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMin</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">var</span> length = arr.length;
  <span class="hljs-keyword">var</span> min = <span class="hljs-literal">Infinity</span>;
  <span class="hljs-keyword">while</span> (length--) {
    <span class="hljs-keyword">if</span> (arr[length] &lt; min) {
      min = arr[length];
    }
  }
  <span class="hljs-keyword">return</span> min;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMax</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">var</span> length = arr.length;
  <span class="hljs-keyword">var</span> max = -<span class="hljs-literal">Infinity</span>;
  <span class="hljs-keyword">while</span> (length--) {
    <span class="hljs-keyword">if</span> (arr[length] &gt; max) {
      max = arr[length];
    }
  }
  <span class="hljs-keyword">return</span> max;
}

<span class="hljs-built_in">console</span>.log(findMin(marks));
<span class="hljs-built_in">console</span>.log(findMax(marks));
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-empty-statement-and-purpose-of-it">What is an empty statement and purpose of it</h3>
<p>The empty statement is a semicolon (;) indicating that no statement will be executed, even if JavaScript syntax requires one. Since there is no action with an empty statement you might think that it's usage is quite less, but the empty statement is occasionally useful when you want to create a loop that has an empty body. For example, you can initialize an array with zero values as below,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Initialize an array a</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; a.length; a[i++] = <span class="hljs-number">0</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-metadata-of-a-module">How do you get metadata of a module</h3>
<p>You can use the <code>import.meta</code> object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as the module's URL. In browsers, you might get different meta data than NodeJS.</p>
<pre><code class="lang-javascript">&lt;script type=<span class="hljs-string">"module"</span> src=<span class="hljs-string">"welcome-module.js"</span>&gt;&lt;/script&gt;;
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">import</span>.meta); <span class="hljs-comment">// { url: "file:///home/user/welcome-module.js" }</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-comma-operator">What is a comma operator</h3>
<p>The comma operator is used to evaluate each of its operands from left to right and returns the value of the last operand. This is totally different from comma usage within arrays, objects, and function arguments and parameters. For example, the usage for numeric expressions would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">1</span>;
x = (x++, x);

<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 2</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-advantage-of-a-comma-operator">What is the advantage of a comma operator</h3>
<p>It is normally used to include multiple expressions in a location that requires a single expression. One of the common usages of this comma operator is to supply multiple parameters in a <code>for</code> loop. For example, the below for loop uses multiple expressions in a single location using comma operator,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> a = <span class="hljs-number">0</span>, b =<span class="hljs-number">10</span>; a &lt;= <span class="hljs-number">10</span>; a++, b--)
</code></pre>
<p>You can also use the comma operator in a return statement where it processes before returning.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">return</span> (a += <span class="hljs-number">10</span>), a; <span class="hljs-comment">// 11</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-typescript">What is typescript</h3>
<p>TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular is built entirely in TypeScript and is used as the primary language. You can install it globally as</p>
<pre><code class="lang-bash">npm install -g typescript
</code></pre>
<p>Let's see a simple example of TypeScript usage,</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params">name: <span class="hljs-built_in">string</span></span>): <span class="hljs-title">string</span> </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, "</span> + name;
}

<span class="hljs-keyword">let</span> user = <span class="hljs-string">"Sudheer"</span>;

<span class="hljs-built_in">console</span>.log(greeting(user));
</code></pre>
<p>The greeting method allows only string type as argument.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-javascript-and-typescript">What are the differences between javascript and typescript</h3>
<p>Below are the list of differences between javascript and typescript,</p>
<p>| feature             | typescript                            | javascript                                      |
| ------------------- | ------------------------------------- | ----------------------------------------------- |
| Language paradigm   | Object oriented programming language  | Scripting language                              |
| Typing support      | Supports static typing                | It has dynamic typing                           |
| Modules             | Supported                             | Not supported                                   |
| Interface           | It has interfaces concept             | Doesn't support interfaces                      |
| Optional parameters | Functions support optional parameters | No support of optional parameters for functions |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-advantages-of-typescript-over-javascript">What are the advantages of typescript over javascript</h3>
<p>Below are some of the advantages of typescript over javascript,</p>
<ol>
<li>TypeScript is able to find compile time errors at the development time only and it makes sures less runtime errors. Whereas javascript is an interpreted language.</li>
<li>TypeScript is strongly-typed or supports static typing which allows for checking type correctness at compile time. This is not available in javascript.</li>
<li>TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 unlike ES6 features of javascript which may not be supported in some browsers.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-object-initializer">What is an object initializer</h3>
<p>An object initializer is an expression that describes the initialization of an Object. The syntax for this expression is represented as a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). This is also known as literal notation. It is one of the ways to create an object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> initObject = { <span class="hljs-attr">a</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">50</span>, <span class="hljs-attr">c</span>: {} };

<span class="hljs-built_in">console</span>.log(initObject.a); <span class="hljs-comment">// John</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-constructor-method">What is a constructor method</h3>
<p>The constructor method is a special method for creating and initializing an object created within a class. If you do not specify a constructor method, a default constructor is used. The example usage of constructor would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"John"</span>;
  }
}

<span class="hljs-keyword">var</span> employeeObject = <span class="hljs-keyword">new</span> Employee();

<span class="hljs-built_in">console</span>.log(employeeObject.name); <span class="hljs-comment">// John</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-happens-if-you-write-constructor-more-than-once-in-a-class">What happens if you write constructor more than once in a class</h3>
<p>The "constructor" in a class is a special method and it should be defined only once in a class. i.e, If you write a constructor method more than once in a class it will throw a <code>SyntaxError</code> error.</p>
<pre><code class="lang-javascript"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> </span>{
   <span class="hljs-keyword">constructor</span>() {
     <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"John"</span>;
   }
   <span class="hljs-keyword">constructor</span>() {   <span class="hljs-comment">//  Uncaught SyntaxError: A class may only have one constructor</span>
     <span class="hljs-built_in">this</span>.age = <span class="hljs-number">30</span>;
   }
 }

 <span class="hljs-keyword">var</span> employeeObject = <span class="hljs-keyword">new</span> Employee();

 <span class="hljs-built_in">console</span>.log(employeeObject.name);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-call-the-constructor-of-a-parent-class">How do you call the constructor of a parent class</h3>
<p>You can use the <code>super</code> keyword to call the constructor of a parent class. Remember that <code>super()</code> must be called before using 'this' reference. Otherwise it will cause a reference error. Let's the usage of it,</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Rectangle</span> </span>{
  <span class="hljs-keyword">constructor</span>(length) {
    <span class="hljs-built_in">super</span>(length, length);
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Square"</span>;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">area</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.width * <span class="hljs-built_in">this</span>.height;
  }

  <span class="hljs-keyword">set</span> <span class="hljs-title">area</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-built_in">this</span>.area = value;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-the-prototype-of-an-object">How do you get the prototype of an object</h3>
<p>You can use the <code>Object.getPrototypeOf(obj)</code> method to return the prototype of the specified object. i.e. The value of the internal <code>prototype</code> property. If there are no inherited properties then <code>null</code> value is returned.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newPrototype = {};
<span class="hljs-keyword">const</span> newObject = <span class="hljs-built_in">Object</span>.create(newPrototype);

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(newObject) === newPrototype); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-happens-if-i-pass-string-type-for-getprototype-method">What happens If I pass string type for getPrototype method</h3>
<p>In ES5, it will throw a TypeError exception if the obj parameter isn't an object. Whereas in ES2015, the parameter will be coerced to an <code>Object</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ES5</span>
<span class="hljs-built_in">Object</span>.getPrototypeOf(<span class="hljs-string">"James"</span>); <span class="hljs-comment">// TypeError: "James" is not an object</span>
<span class="hljs-comment">// ES2015</span>
<span class="hljs-built_in">Object</span>.getPrototypeOf(<span class="hljs-string">"James"</span>); <span class="hljs-comment">// String.prototype</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-set-prototype-of-one-object-to-another">How do you set prototype of one object to another</h3>
<p>You can use the <code>Object.setPrototypeOf()</code> method that sets the prototype (i.e., the internal <code>Prototype</code> property) of a specified object to another object or null. For example, if you want to set prototype of a square object to rectangle object would be as follows,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.setPrototypeOf(Square.prototype, Rectangle.prototype);
<span class="hljs-built_in">Object</span>.setPrototypeOf({}, <span class="hljs-literal">null</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-whether-an-object-can-be-extendable-or-not">How do you check whether an object can be extendable or not</h3>
<p>The <code>Object.isExtensible()</code> method is used to determine if an object is extendable or not. i.e, Whether it can have new properties added to it or not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {};
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.isExtensible(newObject)); <span class="hljs-comment">//true</span>
</code></pre>
<p><strong>Note:</strong> By default, all the objects are extendable. i.e, The new properties can be added or modified.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-prevent-an-object-to-extend">How do you prevent an object to extend</h3>
<p>The <code>Object.preventExtensions()</code> method is used to prevent new properties from ever being added to an object. In other words, it prevents future extensions to the object. Let's see the usage of this property,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {};
<span class="hljs-built_in">Object</span>.preventExtensions(newObject); <span class="hljs-comment">// NOT extendable</span>

<span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">Object</span>.defineProperty(newObject, <span class="hljs-string">"newProperty"</span>, {
    <span class="hljs-comment">// Adding new property</span>
    <span class="hljs-attr">value</span>: <span class="hljs-number">100</span>,
  });
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-built_in">console</span>.log(e); <span class="hljs-comment">// TypeError: Cannot define property newProperty, object is not extensible</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-ways-to-make-an-object-non-extensible">What are the different ways to make an object non-extensible</h3>
<p>You can mark an object non-extensible in 3 ways,</p>
<ol>
<li>Object.preventExtensions</li>
<li>Object.seal</li>
<li>Object.freeze</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> newObject = {};

<span class="hljs-built_in">Object</span>.preventExtensions(newObject); <span class="hljs-comment">// Prevent objects are non-extensible</span>
<span class="hljs-built_in">Object</span>.isExtensible(newObject); <span class="hljs-comment">// false</span>

<span class="hljs-keyword">var</span> sealedObject = <span class="hljs-built_in">Object</span>.seal({}); <span class="hljs-comment">// Sealed objects are non-extensible</span>
<span class="hljs-built_in">Object</span>.isExtensible(sealedObject); <span class="hljs-comment">// false</span>

<span class="hljs-keyword">var</span> frozenObject = <span class="hljs-built_in">Object</span>.freeze({}); <span class="hljs-comment">// Frozen objects are non-extensible</span>
<span class="hljs-built_in">Object</span>.isExtensible(frozenObject); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-define-multiple-properties-on-an-object">How do you define multiple properties on an object</h3>
<p>The <code>Object.defineProperties()</code> method is used to define new or modify existing properties directly on an object and returning the object. Let's define multiple properties on an empty object,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {};

<span class="hljs-built_in">Object</span>.defineProperties(newObject, {
  <span class="hljs-attr">newProperty1</span>: {
    <span class="hljs-attr">value</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>,
  },
  <span class="hljs-attr">newProperty2</span>: {},
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-mean-in-javascript">What is MEAN in javascript</h3>
<p>The MEAN (MongoDB, Express, AngularJS, and Node.js) stack is the most popular open-source JavaScript software tech stack available for building dynamic web apps where you can write both the server-side and client-side halves of the web project entirely in JavaScript.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-obfuscation-in-javascript">What Is Obfuscation in javascript</h3>
<p>Obfuscation is the deliberate act of creating obfuscated javascript code(i.e, source or machine code) that is difficult for humans to understand. It is something similar to encryption, but a machine can understand the code and execute it.
Let's see the below function before Obfuscation,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello, welcome to JS world"</span>);
}
</code></pre>
<p>And after the code Obfuscation, it would be appeared as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">eval</span>(
  (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">p, a, c, k, e, d</span>) </span>{
    e = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">c</span>) </span>{
      <span class="hljs-keyword">return</span> c;
    };
    <span class="hljs-keyword">if</span> (!<span class="hljs-string">""</span>.replace(<span class="hljs-regexp">/^/</span>, <span class="hljs-built_in">String</span>)) {
      <span class="hljs-keyword">while</span> (c--) {
        d[c] = k[c] || c;
      }
      k = [
        <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
          <span class="hljs-keyword">return</span> d[e];
        },
      ];
      e = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"\\w+"</span>;
      };
      c = <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">while</span> (c--) {
      <span class="hljs-keyword">if</span> (k[c]) {
        p = p.replace(<span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">"\\b"</span> + e(c) + <span class="hljs-string">"\\b"</span>, <span class="hljs-string">"g"</span>), k[c]);
      }
    }
    <span class="hljs-keyword">return</span> p;
  })(
    <span class="hljs-string">"2 1(){0.3('4, 7 6 5 8')}"</span>,
    <span class="hljs-number">9</span>,
    <span class="hljs-number">9</span>,
    <span class="hljs-string">"console|greeting|function|log|Hello|JS|to|welcome|world"</span>.split(<span class="hljs-string">"|"</span>),
    <span class="hljs-number">0</span>,
    {}
  )
);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-obfuscation">Why do you need Obfuscation</h3>
<p>Below are the few reasons for Obfuscation,</p>
<ol>
<li>The Code size will be reduced. So data transfers between server and client will be fast.</li>
<li>It hides the business logic from outside world and protects the code from others</li>
<li>Reverse engineering is highly difficult</li>
<li>The download time will be reduced</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-minification">What is Minification</h3>
<p>Minification is the process of removing all unnecessary characters(empty spaces are removed) and variables will be renamed without changing it's functionality. It is also a type of obfuscation .</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-advantages-of-minification">What are the advantages of minification</h3>
<p>Normally it is recommended to use minification for heavy traffic and intensive requirements of resources. It reduces file sizes with below benefits,</p>
<ol>
<li>Decreases loading times of a web page</li>
<li>Saves bandwidth usages</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-obfuscation-and-encryption">What are the differences between Obfuscation and Encryption</h3>
<p>Below are the main differences between Obfuscation and Encryption,</p>
<p>| Feature            | Obfuscation                                     | Encryption                                                              |
| ------------------ | ----------------------------------------------- | ----------------------------------------------------------------------- |
| Definition         | Changing the form of any data in any other form | Changing the form of information to an unreadable format by using a key |
| A key to decode    | It can be decoded without any key               | It is required                                                          |
| Target data format | It will be converted to a complex form          | Converted into an unreadable format                                     |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-common-tools-used-for-minification">What are the common tools used for minification</h3>
<p>There are many online/offline tools to minify the javascript files,</p>
<ol>
<li>Google's Closure Compiler</li>
<li>UglifyJS2</li>
<li>jsmin</li>
<li>javascript-minifier.com/</li>
<li>prettydiff.com</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-perform-form-validation-using-javascript">How do you perform form validation using javascript</h3>
<p>JavaScript can be used to perform HTML form validation. For example, if the form field is empty, the function needs to notify, and return false, to prevent the form being submitted.
Lets' perform user login in an html form,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"myForm"</span> <span class="hljs-attr">onsubmit</span>=<span class="hljs-string">"return validateForm()"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
  User name: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"uname"</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>And the validation on user login is below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> x = <span class="hljs-built_in">document</span>.forms[<span class="hljs-string">"myForm"</span>][<span class="hljs-string">"uname"</span>].value;
  <span class="hljs-keyword">if</span> (x == <span class="hljs-string">""</span>) {
    alert(<span class="hljs-string">"The username shouldn't be empty"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-perform-form-validation-without-javascript">How do you perform form validation without javascript</h3>
<p>You can perform HTML form validation automatically without using javascript. The validation enabled by applying the <code>required</code> attribute to prevent form submission when the input is empty.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"uname"</span> <span class="hljs-attr">required</span> /&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Submit"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p><strong>Note:</strong> Automatic form validation does not work in Internet Explorer 9 or earlier.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-dom-methods-available-for-constraint-validation">What are the DOM methods available for constraint validation</h3>
<p>The below DOM methods are available for constraint validation on an invalid input,</p>
<ol>
<li>checkValidity(): It returns true if an input element contains valid data.</li>
<li>setCustomValidity(): It is used to set the validationMessage property of an input element.
Let's take an user login form with DOM validations</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> userName = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"uname"</span>);
  <span class="hljs-keyword">if</span> (!userName.checkValidity()) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>).innerHTML =
      userName.validationMessage;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>).innerHTML =
      <span class="hljs-string">"Entered a valid username"</span>;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-available-constraint-validation-dom-properties">What are the available constraint validation DOM properties</h3>
<p>Below are the list of some of the constraint validation DOM properties available,</p>
<ol>
<li>validity: It provides a list of boolean properties related to the validity of an input element.</li>
<li>validationMessage: It displays the message when the validity is false.</li>
<li>willValidate: It indicates if an input element will be validated or not.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-list-of-validity-properties">What are the list of validity properties</h3>
<p>The validity property of an input element provides a set of properties related to the validity of data.</p>
<ol>
<li>customError: It returns true, if a custom validity message is set.</li>
<li>patternMismatch: It returns true, if an element's value does not match its pattern attribute.</li>
<li>rangeOverflow: It returns true, if an element's value is greater than its max attribute.</li>
<li>rangeUnderflow: It returns true, if an element's value is less than its min attribute.</li>
<li>stepMismatch: It returns true, if an element's value is invalid according to step attribute.</li>
<li>tooLong: It returns true, if an element's value exceeds its maxLength attribute.</li>
<li>typeMismatch: It returns true, if an element's value is invalid according to type attribute.</li>
<li>valueMissing: It returns true, if an element with a required attribute has no value.</li>
<li>valid: It returns true, if an element's value is valid.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-give-an-example-usage-of-rangeoverflow-property">Give an example usage of rangeOverflow property</h3>
<p>If an element's value is greater than its max attribute then rangeOverflow property returns true. For example, the below form submission throws an error if the value is more than 100,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"100"</span> /&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"myOverflowFunction()"</span>&gt;</span>OK<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myOverflowFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"age"</span>).validity.rangeOverflow) {
    alert(<span class="hljs-string">"The mentioned age is not allowed"</span>);
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-enums-feature-available-in-javascript">Is enums feature available in javascript</h3>
<p>No, javascript does not natively support enums. But there are different kinds of solutions to simulate them even though they may not provide exact equivalents. For example, you can use freeze or seal on object,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> DaysEnum = <span class="hljs-built_in">Object</span>.freeze({<span class="hljs-string">"monday"</span>:<span class="hljs-number">1</span>, <span class="hljs-string">"tuesday"</span>:<span class="hljs-number">2</span>, <span class="hljs-string">"wednesday"</span>:<span class="hljs-number">3</span>, ...})
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-enum">What is an enum</h3>
<p>An enum is a type restricting variables to one value from a predefined set of constants. JavaScript has no enums but typescript provides built-in enum support.</p>
<pre><code class="lang-javascript">enum Color {
 RED, GREEN, BLUE
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-list-all-properties-of-an-object">How do you list all properties of an object</h3>
<p>You can use the <code>Object.getOwnPropertyNames()</code> method which returns an array of all properties found directly in a given object. Let's see the usage of this in an example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getOwnPropertyNames(newObject));
[<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>];
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-property-descriptors-of-an-object">How do you get property descriptors of an object</h3>
<p>You can use the <code>Object.getOwnPropertyDescriptors()</code> method which returns all own property descriptors of a given object. The example usage of this method is below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newObject = {
  <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-number">3</span>,
};
<span class="hljs-keyword">const</span> descriptorsObject = <span class="hljs-built_in">Object</span>.getOwnPropertyDescriptors(newObject);
<span class="hljs-built_in">console</span>.log(descriptorsObject.a.writable); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(descriptorsObject.a.configurable); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(descriptorsObject.a.enumerable); <span class="hljs-comment">//true</span>
<span class="hljs-built_in">console</span>.log(descriptorsObject.a.value); <span class="hljs-comment">// 1</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-attributes-provided-by-a-property-descriptor">What are the attributes provided by a property descriptor</h3>
<p>A property descriptor is a record which has the following attributes</p>
<ol>
<li>value: The value associated with the property</li>
<li>writable: Determines whether the value associated with the property can be changed or not</li>
<li>configurable: Returns true if the type of this property descriptor can be changed and if the property can be deleted from the corresponding object.</li>
<li>enumerable: Determines whether the property appears during enumeration of the properties on the corresponding object or not.</li>
<li>set: A function which serves as a setter for the property</li>
<li>get: A function which serves as a getter for the property</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-extend-classes">How do you extend classes</h3>
<p>The <code>extends</code> keyword is used in class declarations/expressions to create a class which is a child of another class. It can be used to subclass custom classes as well as built-in objects. The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentClass</span> </span>{ ... }
</code></pre>
<p>Let's take an example of Square subclass from Polygon parent class,</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Rectangle</span> </span>{
  <span class="hljs-keyword">constructor</span>(length) {
    <span class="hljs-built_in">super</span>(length, length);
    <span class="hljs-built_in">this</span>.name = <span class="hljs-string">"Square"</span>;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">area</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.width * <span class="hljs-built_in">this</span>.height;
  }

  <span class="hljs-keyword">set</span> <span class="hljs-title">area</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-built_in">this</span>.area = value;
  }
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-i-modify-the-url-without-reloading-the-page">How do I modify the url without reloading the page</h3>
<p>The <code>window.location.href</code> property will be helpful to modify the url but it reloads the page. HTML5 introduced the <code>history.pushState()</code> and <code>history.replaceState()</code> methods, which allow you to add and modify history entries, respectively. For example, you can use pushState as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.history.pushState(<span class="hljs-string">"page2"</span>, <span class="hljs-string">"Title"</span>, <span class="hljs-string">"/page2.html"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-whether-an-array-includes-a-particular-value-or-not">How do you check whether an array includes a particular value or not</h3>
<p>The <code>Array#includes()</code> method is used to determine whether an array includes a particular value among its entries by returning either true or false. Let's see an example to find an element(numeric and string) within an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> numericArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-built_in">console</span>.log(numericArray.includes(<span class="hljs-number">3</span>)); <span class="hljs-comment">// true</span>

<span class="hljs-keyword">var</span> stringArray = [<span class="hljs-string">"green"</span>, <span class="hljs-string">"yellow"</span>, <span class="hljs-string">"blue"</span>];
<span class="hljs-built_in">console</span>.log(stringArray.includes(<span class="hljs-string">"blue"</span>)); <span class="hljs-comment">//true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-compare-scalar-arrays">How do you compare scalar arrays</h3>
<p>You can use length and every method of arrays to compare two scalar(compared directly using ===) arrays. The combination of these expressions can give the expected result,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrayFirst = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> arraySecond = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(
  arrayFirst.length === arraySecond.length &amp;&amp;
    arrayFirst.every(<span class="hljs-function">(<span class="hljs-params">value, index</span>) =&gt;</span> value === arraySecond[index])
); <span class="hljs-comment">// true</span>
</code></pre>
<p>If you would like to compare arrays irrespective of order then you should sort them before,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrayFirst = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> arraySecond = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(
  arrayFirst.length === arraySecond.length &amp;&amp;
    arrayFirst.sort().every(<span class="hljs-function">(<span class="hljs-params">value, index</span>) =&gt;</span> value === arraySecond[index])
); <span class="hljs-comment">//true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-get-the-value-from-get-parameters">How to get the value from get parameters</h3>
<p>The <code>new URL()</code> object accepts the url string and <code>searchParams</code> property of this object can be used to access the get parameters. Remember that you may need to use polyfill or <code>window.location</code> to access the URL in older browsers(including IE).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> urlString = <span class="hljs-string">"http://www.some-domain.com/about.html?x=1&amp;y=2&amp;z=3"</span>; <span class="hljs-comment">//window.location.href</span>
<span class="hljs-keyword">let</span> url = <span class="hljs-keyword">new</span> URL(urlString);
<span class="hljs-keyword">let</span> parameterZ = url.searchParams.get(<span class="hljs-string">"z"</span>);
<span class="hljs-built_in">console</span>.log(parameterZ); <span class="hljs-comment">// 3</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-print-numbers-with-commas-as-thousand-separators">How do you print numbers with commas as thousand separators</h3>
<p>You can use the <code>Number.prototype.toLocaleString()</code> method which returns a string with a language-sensitive representation such as thousand separator,currency etc of this number.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">convertToThousandFormat</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> x.toLocaleString(); <span class="hljs-comment">// 12,345.679</span>
}

<span class="hljs-built_in">console</span>.log(convertToThousandFormat(<span class="hljs-number">12345.6789</span>));
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-java-and-javascript">What is the difference between java and javascript</h3>
<p>Both are totally unrelated programming languages and no relation between them. Java is statically typed, compiled, runs on its own VM. Whereas Javascript is dynamically typed, interpreted, and runs in a browser and nodejs environments. Let's see the major differences in a tabular format,
| Feature | Java | JavaScript |
|---- | ---- | -----
| Typed | It's a strongly typed language | It's a dynamic typed language |
| Paradigm | Object oriented programming | Prototype based programming |
| Scoping | Block scoped | Function-scoped |
| Concurrency | Thread based | event based |
| Memory | Uses more memory | Uses less memory. Hence it will be used for web pages |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-does-javascript-supports-namespace">Does JavaScript supports namespace</h3>
<p>JavaScript doesn’t support namespace by default. So if you create any element(function, method, object, variable) then it becomes global and pollutes the global namespace. Let's take an example of defining two functions without any namespace,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a first definition"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a second definition"</span>);
}
func1(); <span class="hljs-comment">// This is a second definition</span>
</code></pre>
<p>It always calls the second function definition. In this case, namespace will solve the name collision problem.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-declare-namespace">How do you declare namespace</h3>
<p>Even though JavaScript lacks namespaces, we can use Objects , IIFE to create namespaces.</p>
<ol>
<li><p><strong>Using Object Literal Notation:</strong> Let's wrap variables and functions inside an Object literal which acts as a namespace. After that you can access them using object notation</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> namespaceOne = {
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a first definition"</span>);
    }
}
<span class="hljs-keyword">var</span> namespaceTwo = {
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func1</span>(<span class="hljs-params"></span>) </span>{
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a second definition"</span>);
      }
  }
namespaceOne.func1(); <span class="hljs-comment">// This is a first definition</span>
namespaceTwo.func1(); <span class="hljs-comment">// This is a second definition</span>
</code></pre>
</li>
<li><p><strong>Using IIFE (Immediately invoked function expression):</strong> The outer pair of parentheses of IIFE creates a local scope for all the code inside of it and makes the anonymous function a function expression. Due to that, you can create the same function in two different function expressions to act as a namespace.</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a first definition"</span>);
  }
  fun1();
})();

(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a second definition"</span>);
  }
  fun1();
})();
</code></pre>
</li>
<li><p><strong>Using a block and a let/const declaration:</strong> In ECMAScript 6, you can simply use a block and a let declaration to restrict the scope of a variable to a block.</p>
<pre><code class="lang-javascript">{
  <span class="hljs-keyword">let</span> myFunction = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a first definition"</span>);
  };
  myFunction();
}
<span class="hljs-comment">//myFunction(): ReferenceError: myFunction is not defined.</span>

{
  <span class="hljs-keyword">let</span> myFunction = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fun1</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a second definition"</span>);
  };
  myFunction();
}
<span class="hljs-comment">//myFunction(): ReferenceError: myFunction is not defined.</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-invoke-javascript-code-in-an-iframe-from-parent-page">How do you invoke javascript code in an iframe from parent page</h3>
<p>Initially iFrame needs to be accessed using either <code>document.getElementBy</code> or <code>window.frames</code>. After that <code>contentWindow</code> property of iFrame gives the access for targetFunction</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"targetFrame"</span>).contentWindow.targetFunction();
<span class="hljs-built_in">window</span>.frames[<span class="hljs-number">0</span>].frameElement.contentWindow.targetFunction(); <span class="hljs-comment">// Accessing iframe this way may not work in latest versions chrome and firefox</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-get-the-timezone-offset-from-date">How do get the timezone offset from date</h3>
<p>You can use the <code>getTimezoneOffset</code> method of the date object. This method returns the time zone difference, in minutes, from current locale (host system settings) to UTC</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> offset = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTimezoneOffset();
<span class="hljs-built_in">console</span>.log(offset); <span class="hljs-comment">// -480</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-load-css-and-js-files-dynamically">How do you load CSS and JS files dynamically</h3>
<p>You can create both link and script elements in the DOM and append them as child to head tag. Let's create a function to add script and style resources as below,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadAssets</span>(<span class="hljs-params">filename, filetype</span>) </span>{
  <span class="hljs-keyword">if</span> (filetype == <span class="hljs-string">"css"</span>) {
    <span class="hljs-comment">// External CSS file</span>
    <span class="hljs-keyword">var</span> fileReference = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"link"</span>);
    fileReference.setAttribute(<span class="hljs-string">"rel"</span>, <span class="hljs-string">"stylesheet"</span>);
    fileReference.setAttribute(<span class="hljs-string">"type"</span>, <span class="hljs-string">"text/css"</span>);
    fileReference.setAttribute(<span class="hljs-string">"href"</span>, filename);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (filetype == <span class="hljs-string">"js"</span>) {
    <span class="hljs-comment">// External JavaScript file</span>
    <span class="hljs-keyword">var</span> fileReference = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"script"</span>);
    fileReference.setAttribute(<span class="hljs-string">"type"</span>, <span class="hljs-string">"text/javascript"</span>);
    fileReference.setAttribute(<span class="hljs-string">"src"</span>, filename);
  }
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> fileReference != <span class="hljs-string">"undefined"</span>)
    <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"head"</span>)[<span class="hljs-number">0</span>].appendChild(fileReference);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-methods-to-find-html-elements-in-dom">What are the different methods to find HTML elements in DOM</h3>
<p>If you want to access any element in an HTML page, you need to start with accessing the document object. Later you can use any of the below methods to find the HTML element,</p>
<ol>
<li>document.getElementById(id): It finds an element by Id</li>
<li>document.getElementsByTagName(name): It finds an element by tag name</li>
<li>document.getElementsByClassName(name): It finds an element by class name</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-jquery">What is jQuery</h3>
<p>jQuery is a popular cross-browser JavaScript library that provides Document Object Model (DOM) traversal, event handling, animations and AJAX interactions by minimizing the discrepancies across browsers. It is widely famous with its philosophy of “Write less, do more”. For example, you can display welcome message on the page load using jQuery as below,</p>
<pre><code class="lang-javascript">$(<span class="hljs-built_in">document</span>).ready(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// It selects the document and apply the function on page load</span>
  alert(<span class="hljs-string">"Welcome to jQuery world"</span>);
});
</code></pre>
<p><strong>Note:</strong> You can download it from jquery's official site or install it from CDNs, like google.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-v8-javascript-engine">What is V8 JavaScript engine</h3>
<p>V8 is an open source high-performance JavaScript engine used by the Google Chrome browser, written in C++. It is also being used in the node.js project. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors.
<strong>Note:</strong> It can run standalone, or can be embedded into any C++ application.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-we-call-javascript-as-dynamic-language">Why do we call javascript as dynamic language</h3>
<p>JavaScript is a loosely typed or a dynamic language because variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned/reassigned with values of all types.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">50</span>; <span class="hljs-comment">// age is a number now</span>
age = <span class="hljs-string">"old"</span>; <span class="hljs-comment">// age is a string now</span>
age = <span class="hljs-literal">true</span>; <span class="hljs-comment">// age is a boolean</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-void-operator">What is a void operator</h3>
<p>The <code>void</code> operator evaluates the given expression and then returns undefined(i.e, without returning value). The syntax would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">void</span> expression;
<span class="hljs-keyword">void</span> expression;
</code></pre>
<p>Let's display a message without any redirection or reload</p>
<pre><code class="lang-javascript">&lt;a href=<span class="hljs-string">"javascript:void(alert('Welcome to JS world'))"</span>&gt;
  Click here to see a message
&lt;/a&gt;
</code></pre>
<p><strong>Note:</strong> This operator is often used to obtain the undefined primitive value, using "void(0)".</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-set-the-cursor-to-wait">How to set the cursor to wait</h3>
<p>The cursor can be set to wait in JavaScript by using the property "cursor". Let's perform this behavior on page load using the below function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">window</span>.document.body.style.cursor = <span class="hljs-string">"wait"</span>;
}
</code></pre>
<p>and this function invoked on page load</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onload</span>=<span class="hljs-string">"myFunction()"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-an-infinite-loop">How do you create an infinite loop</h3>
<p>You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (;;) {}
<span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-why-do-you-need-to-avoid-with-statement">Why do you need to avoid with statement</h3>
<p>JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects. So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. Let's take an example where it is used to avoid redundancy when accessing an object several times.</p>
<pre><code class="lang-javascript">a.b.c.greeting = <span class="hljs-string">"welcome"</span>;
a.b.c.age = <span class="hljs-number">32</span>;
</code></pre>
<p>Using <code>with</code> it turns this into:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">with</span> (a.b.c) {
  greeting = <span class="hljs-string">"welcome"</span>;
  age = <span class="hljs-number">32</span>;
}
</code></pre>
<p>But this <code>with</code> statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-the-following-for-loops">What is the output of the following for loops</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++) {
  <span class="hljs-comment">// global scope</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(i));
}

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++) {
  <span class="hljs-comment">// block scope</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(i));
}
</code></pre>
<p>The output of the above for loops is 4 4 4 4 and 0 1 2 3</p>
<p><strong>Explanation:</strong> Due to the event queue/loop of javascript, the <code>setTimeout</code> callback function is called after the loop has been executed. Since the variable i is declared with the <code>var</code> keyword it became a global variable and the value was equal to 4 using iteration when the time <code>setTimeout</code> function is invoked. Hence, the output of the second loop is <code>4 4 4 4</code>.</p>
<p>Whereas in the second loop, the variable i is declared as the <code>let</code> keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is <code>0 1 2 3</code>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-list-down-some-of-the-features-of-es6">List down some of the features of ES6</h3>
<p>Below are the list of some new features of ES6,</p>
<ol>
<li>Support for constants or immutable variables</li>
<li>Block-scope support for variables, constants and functions</li>
<li>Arrow functions</li>
<li>Default parameters</li>
<li>Rest and Spread Parameters</li>
<li>Template Literals</li>
<li>Multi-line Strings</li>
<li>Destructuring Assignment</li>
<li>Enhanced Object Literals</li>
<li>Promises</li>
<li>Classes</li>
<li>Modules</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-es6">What is ES6</h3>
<p>ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-i-redeclare-let-and-const-variables">Can I redeclare let and const variables</h3>
<p>No, you cannot redeclare let and const variables. If you do, it throws below error</p>
<pre><code class="lang-bash">Uncaught SyntaxError: Identifier <span class="hljs-string">'someVariable'</span> has already been declared
</code></pre>
<p><strong>Explanation:</strong> The variable declaration with <code>var</code> keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> name = <span class="hljs-string">"John"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Nick"</span>;
  <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Abraham"</span>; <span class="hljs-comment">// Re-assigned in the same function block</span>
  alert(name); <span class="hljs-comment">// Abraham</span>
}
myFunc();
alert(name); <span class="hljs-comment">// John</span>
</code></pre>
<p>The block-scoped multi-declaration throws syntax error,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"John"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">"Nick"</span>;
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">"Abraham"</span>; <span class="hljs-comment">// Uncaught SyntaxError: Identifier 'name' has already been declared</span>
  alert(name);
}

myFunc();
alert(name);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-does-the-const-variable-make-the-value-immutable">Does the <code>const</code> variable make the value immutable</h3>
<p>No, the <code>const</code> variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can't assign another value later)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userList = [];
userList.push(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// Can mutate even though it can't re-assign</span>
<span class="hljs-built_in">console</span>.log(userList); <span class="hljs-comment">// ['John']</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-default-parameters">What are default parameters</h3>
<p>In ES5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let's compare the behavior with an examples,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//ES5</span>
<span class="hljs-keyword">var</span> calculateArea = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">height, width</span>) </span>{
  height = height || <span class="hljs-number">50</span>;
  width = width || <span class="hljs-number">60</span>;

  <span class="hljs-keyword">return</span> width * height;
};
<span class="hljs-built_in">console</span>.log(calculateArea()); <span class="hljs-comment">//300</span>
</code></pre>
<p>The default parameters makes the initialization more simpler,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//ES6</span>
<span class="hljs-keyword">var</span> calculateArea = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">height = <span class="hljs-number">50</span>, width = <span class="hljs-number">60</span></span>) </span>{
  <span class="hljs-keyword">return</span> width * height;
};

<span class="hljs-built_in">console</span>.log(calculateArea()); <span class="hljs-comment">//300</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-template-literals">What are template literals</h3>
<p>Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes.
In ES6, this feature enables using dynamic expressions as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greeting = <span class="hljs-string">`Welcome to JS World, Mr. <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>;
</code></pre>
<p>In ES5, you need break string like below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greeting = <span class="hljs-string">'Welcome to JS World, Mr. '</span> + firstName + <span class="hljs-string">' '</span> + lastName.<span class="hljs-string">`</span>
</code></pre>
<p><strong>Note:</strong> You can use multi-line strings and string interpolation features with template literals.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-write-multi-line-strings-in-template-literals">How do you write multi-line strings in template literals</h3>
<p>In ES5, you would have to use newline escape characters('\n') and concatenation symbols(+) in order to get multi-line strings.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is string sentence 1\n"</span> + <span class="hljs-string">"This is string sentence 2"</span>);
</code></pre>
<p>Whereas in ES6, You don't need to mention any newline sequence character,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is string sentence
'This is string sentence 2`</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-nesting-templates">What are nesting templates</h3>
<p>The nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder ${ } within the template. For example, the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> iconStyles = <span class="hljs-string">`icon <span class="hljs-subst">${
  isMobilePlatform()
    ? <span class="hljs-string">""</span>
    : <span class="hljs-string">`icon-<span class="hljs-subst">${user.isAuthorized ? <span class="hljs-string">"submit"</span> : <span class="hljs-string">"disabled"</span>}</span>`</span>
}</span>`</span>;
</code></pre>
<p>You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and readable.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Without nesting templates</span>
<span class="hljs-keyword">const</span> iconStyles = <span class="hljs-string">`icon <span class="hljs-subst">${
  isMobilePlatform()
    ? <span class="hljs-string">""</span>
    : user.isAuthorized
    ? <span class="hljs-string">"icon-submit"</span>
    : <span class="hljs-string">"icon-disabled"</span>
}</span>`</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-tagged-templates">What are tagged templates</h3>
<p>Tagged templates are the advanced form of templates in which tags allow you to parse template literals with a function. The tag function accepts the first parameter as an array of strings and remaining parameters as expressions. This function can also return manipulated strings based on parameters. Let's see the usage of this tagged template behavior of an IT professional skill set in an organization,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> user1 = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">var</span> skill1 = <span class="hljs-string">"JavaScript"</span>;
<span class="hljs-keyword">var</span> experience1 = <span class="hljs-number">15</span>;

<span class="hljs-keyword">var</span> user2 = <span class="hljs-string">"Kane"</span>;
<span class="hljs-keyword">var</span> skill2 = <span class="hljs-string">"JavaScript"</span>;
<span class="hljs-keyword">var</span> experience2 = <span class="hljs-number">5</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myInfoTag</span>(<span class="hljs-params">strings, userExp, experienceExp, skillExp</span>) </span>{
  <span class="hljs-keyword">var</span> str0 = strings[<span class="hljs-number">0</span>]; <span class="hljs-comment">// "Mr/Ms. "</span>
  <span class="hljs-keyword">var</span> str1 = strings[<span class="hljs-number">1</span>]; <span class="hljs-comment">// " is a/an "</span>
  <span class="hljs-keyword">var</span> str2 = strings[<span class="hljs-number">2</span>]; <span class="hljs-comment">// "in"</span>

  <span class="hljs-keyword">var</span> expertiseStr;
  <span class="hljs-keyword">if</span> (experienceExp &gt; <span class="hljs-number">10</span>) {
    expertiseStr = <span class="hljs-string">"expert developer"</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (skillExp &gt; <span class="hljs-number">5</span> &amp;&amp; skillExp &lt;= <span class="hljs-number">10</span>) {
    expertiseStr = <span class="hljs-string">"senior developer"</span>;
  } <span class="hljs-keyword">else</span> {
    expertiseStr = <span class="hljs-string">"junior developer"</span>;
  }

  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${str0}</span><span class="hljs-subst">${userExp}</span><span class="hljs-subst">${str1}</span><span class="hljs-subst">${expertiseStr}</span><span class="hljs-subst">${str2}</span><span class="hljs-subst">${skillExp}</span>`</span>;
}

<span class="hljs-keyword">var</span> output1 = myInfoTag<span class="hljs-string">`Mr/Ms. <span class="hljs-subst">${user1}</span> is a/an <span class="hljs-subst">${experience1}</span> in <span class="hljs-subst">${skill1}</span>`</span>;
<span class="hljs-keyword">var</span> output2 = myInfoTag<span class="hljs-string">`Mr/Ms. <span class="hljs-subst">${user2}</span> is a/an <span class="hljs-subst">${experience2}</span> in <span class="hljs-subst">${skill2}</span>`</span>;

<span class="hljs-built_in">console</span>.log(output1); <span class="hljs-comment">// Mr/Ms. John is a/an expert developer in JavaScript</span>
<span class="hljs-built_in">console</span>.log(output2); <span class="hljs-comment">// Mr/Ms. Kane is a/an junior developer in JavaScript</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-raw-strings">What are raw strings</h3>
<p>ES6 provides a raw strings feature using the <code>String.raw()</code> method which is used to get the raw string form of template strings. This feature allows you to access the raw strings as they were entered, without processing escape sequences. For example, the usage would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> calculationString = <span class="hljs-built_in">String</span>.raw<span class="hljs-string">`The sum of numbers is \n<span class="hljs-subst">${
  <span class="hljs-number">1</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span> + <span class="hljs-number">4</span>
}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(calculationString); <span class="hljs-comment">// The sum of numbers is \n10!</span>
</code></pre>
<p>If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> calculationString = <span class="hljs-string">`The sum of numbers is \n<span class="hljs-subst">${<span class="hljs-number">1</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span> + <span class="hljs-number">4</span>}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(calculationString);
<span class="hljs-comment">// The sum of numbers is</span>
<span class="hljs-comment">// 10!</span>
</code></pre>
<p>Also, the raw property is available on the first argument to the tag function</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">tag</span>(<span class="hljs-params">strings</span>) </span>{
  <span class="hljs-built_in">console</span>.log(strings.raw[<span class="hljs-number">0</span>]);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-destructuring-assignment">What is destructuring assignment</h3>
<p>The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables.
Let's get the month values from an array using destructuring assignment</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> [one, two, three] = [<span class="hljs-string">"JAN"</span>, <span class="hljs-string">"FEB"</span>, <span class="hljs-string">"MARCH"</span>];

<span class="hljs-built_in">console</span>.log(one); <span class="hljs-comment">// "JAN"</span>
<span class="hljs-built_in">console</span>.log(two); <span class="hljs-comment">// "FEB"</span>
<span class="hljs-built_in">console</span>.log(three); <span class="hljs-comment">// "MARCH"</span>
</code></pre>
<p>and you can get user properties of an object using destructuring assignment,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> { name, age } = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">32</span> };

<span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// John</span>
<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// 32</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-default-values-in-destructuring-assignment">What are default values in destructuring assignment</h3>
<p>A variable can be assigned a default value when the value unpacked from the array or object is undefined during destructuring assignment. It helps to avoid setting default values separately for each assignment. Let's take an example for both arrays and object use cases,</p>
<p><strong>Arrays destructuring:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x, y, z;

[x = <span class="hljs-number">2</span>, y = <span class="hljs-number">4</span>, z = <span class="hljs-number">6</span>] = [<span class="hljs-number">10</span>];
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// 4</span>
<span class="hljs-built_in">console</span>.log(z); <span class="hljs-comment">// 6</span>
</code></pre>
<p><strong>Objects destructuring:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> { x = <span class="hljs-number">2</span>, y = <span class="hljs-number">4</span>, z = <span class="hljs-number">6</span> } = { <span class="hljs-attr">x</span>: <span class="hljs-number">10</span> };

<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// 4</span>
<span class="hljs-built_in">console</span>.log(z); <span class="hljs-comment">// 6</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-swap-variables-in-destructuring-assignment">How do you swap variables in destructuring assignment</h3>
<p>If you don't use destructuring assignment, swapping two values requires a temporary variable. Whereas using a destructuring feature, two variable values can be swapped in one destructuring expression. Let's swap two number variables in array destructuring assignment,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>,
  y = <span class="hljs-number">20</span>;

[x, y] = [y, x];
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 20</span>
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// 10</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-enhanced-object-literals">What are enhanced object literals</h3>
<p>Object literals make it easy to quickly create objects with properties inside the curly braces. For example, it provides shorter syntax for common object property definition as below.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//ES6</span>
<span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>,
  y = <span class="hljs-number">20</span>;
obj = { x, y };
<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// {x: 10, y:20}</span>
<span class="hljs-comment">//ES5</span>
<span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>,
  y = <span class="hljs-number">20</span>;
obj = { <span class="hljs-attr">x</span>: x, <span class="hljs-attr">y</span>: y };
<span class="hljs-built_in">console</span>.log(obj); <span class="hljs-comment">// {x: 10, y:20}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-dynamic-imports">What are dynamic imports</h3>
<p>The dynamic imports using <code>import()</code> function syntax allows us to load modules on demand by using promises or the async/await syntax. Currently this feature is in <a target="_blank" href="https://github.com/tc39/proposal-dynamic-import">stage4 proposal</a>. The main advantage of dynamic imports is reduction of our bundle's sizes, the size/payload response of our requests and overall improvements in the user experience.
The syntax of dynamic imports would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span>(<span class="hljs-string">"./Module"</span>).then(<span class="hljs-function">(<span class="hljs-params">Module</span>) =&gt;</span> Module.method());
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-use-cases-for-dynamic-imports">What are the use cases for dynamic imports</h3>
<p>Below are some of the use cases of using dynamic imports over static imports,</p>
<ol>
<li><p>Import a module on-demand or conditionally. For example, if you want to load a polyfill on legacy browser</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (isLegacyBrowser()) {
    <span class="hljs-keyword">import</span>(···)
    .then(···);
}
</code></pre>
</li>
<li><p>Compute the module specifier at runtime. For example, you can use it for internationalization.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span>(<span class="hljs-string">`messages_<span class="hljs-subst">${getLocale()}</span>.js`</span>).then(···);
</code></pre>
</li>
<li><p>Import a module from within a regular script instead a module.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-typed-arrays">What are typed arrays</h3>
<p>Typed arrays are array-like objects from ECMAScript 6 API for handling binary data. JavaScript provides 12 Typed array types,</p>
<ol>
<li>Int8Array: An array of 8-bit signed integers</li>
<li>Uint8Array: An array of 8-bit unsigned integers</li>
<li>Uint8ClampedArray: An array of 8-bit unsigned integers clamped to 0-255</li>
<li>Int16Array: An array of 16-bit signed integers</li>
<li>Uint16Array: An array of 16-bit unsigned integers</li>
<li>Int32Array: An array of 32-bit signed integers</li>
<li>Uint32Array: An array of 32-bit unsigned integers</li>
<li>BigInt64Array: An array of 64-bit signed BigInts</li>
<li>BigUint64Array: An array of 64-bit unsigned BigInts</li>
<li>Float16Array: An array of 16-bit floating point numbers</li>
<li>Float32Array: An array of 32-bit floating point numbers</li>
<li>Float64Array: An array of 64-bit floating point numbers</li>
</ol>
<p>For example, you can create an array of 8-bit signed integers as below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Int8Array</span>();
<span class="hljs-comment">// You can pre-allocate n bytes</span>
<span class="hljs-keyword">const</span> bytes = <span class="hljs-number">1024</span>;
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Int8Array</span>(bytes);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-advantages-of-module-loaders">What are the advantages of module loaders</h3>
<p>The module loaders provides the below features,</p>
<ol>
<li>Dynamic loading</li>
<li>State isolation</li>
<li>Global namespace isolation</li>
<li>Compilation hooks</li>
<li>Nested virtualization</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-collation">What is collation</h3>
<p>Collation is used for sorting a set of strings and searching within a set of strings. It is parameterized by locale and aware of Unicode. Let's take comparison and sorting features,</p>
<ol>
<li><strong>Comparison:</strong></li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> list = [<span class="hljs-string">"ä"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"z"</span>]; <span class="hljs-comment">// In German,  "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"</span>
<span class="hljs-keyword">var</span> l10nDE = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.Collator(<span class="hljs-string">"de"</span>);
<span class="hljs-keyword">var</span> l10nSV = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.Collator(<span class="hljs-string">"sv"</span>);
<span class="hljs-built_in">console</span>.log(l10nDE.compare(<span class="hljs-string">"ä"</span>, <span class="hljs-string">"z"</span>) === <span class="hljs-number">-1</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(l10nSV.compare(<span class="hljs-string">"ä"</span>, <span class="hljs-string">"z"</span>) === +<span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>
</code></pre>
<ol start="2">
<li><strong>Sorting:</strong></li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> list = [<span class="hljs-string">"ä"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"z"</span>]; <span class="hljs-comment">// In German,  "ä" sorts with "a" Whereas in Swedish, "ä" sorts after "z"</span>
<span class="hljs-keyword">var</span> l10nDE = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.Collator(<span class="hljs-string">"de"</span>);
<span class="hljs-keyword">var</span> l10nSV = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.Collator(<span class="hljs-string">"sv"</span>);
<span class="hljs-built_in">console</span>.log(list.sort(l10nDE.compare)); <span class="hljs-comment">// [ "a", "ä", "z" ]</span>
<span class="hljs-built_in">console</span>.log(list.sort(l10nSV.compare)); <span class="hljs-comment">// [ "a", "z", "ä" ]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-forof-statement">What is for...of statement</h3>
<p>The for...of statement creates a loop iterating over iterable objects or elements such as built-in String, Array, Array-like objects (like arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. The basic usage of for...of statement on arrays would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arrayIterable = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> value <span class="hljs-keyword">of</span> arrayIterable) {
  value++;
  <span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// 11 21 31 41 51</span>
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-below-spread-operator-array">What is the output of below spread operator array</h3>
<pre><code class="lang-javascript">[...<span class="hljs-string">"John Resig"</span>];
</code></pre>
<p>The output of the array is ['J', 'o', 'h', 'n', ' ', 'R', 'e', 's', 'i', 'g']</p>
<p><strong>Explanation:</strong> The string is an iterable type and the spread operator within an array maps every character of an iterable to one element. Hence, each character of a string becomes an element within an Array.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-postmessage-secure">Is PostMessage secure</h3>
<p>Yes, postMessages can be considered very secure as long as the programmer/developer is careful about checking the origin and source of an arriving message. But if you try to send/receive a message without verifying its source will create cross-site scripting attacks.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-problems-with-postmessage-target-origin-as-wildcard">What are the problems with postmessage target origin as wildcard</h3>
<p>The second argument of postMessage method specifies which origin is allowed to receive the message. If you use the wildcard “*” as an argument then any origin is allowed to receive the message. In this case, there is no way for the sender window to know if the target window is at the target origin when sending the message. If the target window has been navigated to another origin, the other origin would receive the data. Hence, this may lead to XSS vulnerabilities.</p>
<pre><code class="lang-javascript">targetWindow.postMessage(message, <span class="hljs-string">"*"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-avoid-receiving-postmessages-from-attackers">How do you avoid receiving postMessages from attackers</h3>
<p>Since the listener listens for any message, an attacker can trick the application by sending a message from the attacker’s origin, which gives an impression that the receiver received the message from the actual sender’s window. You can avoid this issue by validating the origin of the message on the receiver's end using the “message.origin” attribute. </p>
<p>For example, let's check the sender's origin <a target="_blank" href="http://www.some-sender.com">http://www.some-sender.com</a> on receiver side <a target="_blank" href="www.some-receiver.com">www.some-receiver.com</a>,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Listener on http://www.some-receiver.com/</span>
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"message"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">message</span>)</span>{
    <span class="hljs-keyword">if</span>(<span class="hljs-regexp">/^http:/</span><span class="hljs-regexp">/www\.some-sender\.com$/</span>.test(message.origin)){
         <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'You received the data from valid sender'</span>, message.data);
   }
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-can-i-avoid-using-postmessages-completely">Can I avoid using postMessages completely</h3>
<p>You cannot avoid using postMessages completely(or 100%). Even though your application doesn’t use postMessage considering the risks, a lot of third party scripts use postMessage to communicate with the third party service. So your application might be using postMessage without your knowledge.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-postmessages-synchronous">Is postMessages synchronous</h3>
<p>The postMessages are synchronous in IE8 browser but they are asynchronous in IE9 and all other modern browsers (i.e, IE9+, Firefox, Chrome, Safari).Due to this asynchronous behaviour, we use a callback mechanism when the postMessage is returned.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-paradigm-is-javascript">What paradigm is Javascript</h3>
<p>JavaScript is a multi-paradigm language, supporting imperative/procedural programming, Object-Oriented Programming and functional programming. JavaScript supports Object-Oriented Programming with prototypical inheritance.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-internal-and-external-javascript">What is the difference between internal and external javascript</h3>
<p><strong>Internal JavaScript:</strong> It is the source code within the script tag.
<strong>External JavaScript:</strong> The source code is stored in an external file(stored with .js extension) and referred with in the tag.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-javascript-faster-than-server-side-script">Is JavaScript faster than server side script</h3>
<p>Yes, JavaScript is faster than server side scripts. Because JavaScript is a client-side script it does not require any web server’s help for its computation or calculation. So JavaScript is always faster than any server-side script like ASP, PHP, etc.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-the-status-of-a-checkbox">How do you get the status of a checkbox</h3>
<p>You can apply the <code>checked</code> property on the selected checkbox in the DOM. If the value is <code>true</code> it means the checkbox is checked, otherwise it is unchecked. For example, the below HTML checkbox element can be access using javascript as below:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"checkboxname"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Agree"</span> /&gt;</span> Agree the
conditions<span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.getElementById(‘checkboxname’).checked); <span class="hljs-comment">// true or false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-double-tilde-operator">What is the purpose of double tilde operator</h3>
<p>The double tilde operator(~~) is known as double NOT bitwise operator. This operator is a slightly quicker substitute for Math.floor().</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-convert-character-to-ascii-code">How do you convert character to ASCII code</h3>
<p>You can use the <code>String.prototype.charCodeAt()</code> method to convert string characters to ASCII numbers. For example, let's find ASCII code for the first letter of 'ABC' string,</p>
<pre><code class="lang-javascript"><span class="hljs-string">"ABC"</span>.charCodeAt(<span class="hljs-number">0</span>); <span class="hljs-comment">// returns 65</span>
</code></pre>
<p>Whereas <code>String.fromCharCode()</code> method converts numbers to equal ASCII characters.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">String</span>.fromCharCode(<span class="hljs-number">65</span>, <span class="hljs-number">66</span>, <span class="hljs-number">67</span>); <span class="hljs-comment">// returns 'ABC'</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-arraybuffer">What is ArrayBuffer</h3>
<p>An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. You can create it as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">16</span>); <span class="hljs-comment">// create a buffer of length 16</span>
alert(buffer.byteLength); <span class="hljs-comment">// 16</span>
</code></pre>
<p>To manipulate an ArrayBuffer, we need to use a “view” object.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Create a DataView referring to the buffer</span>
<span class="hljs-keyword">let</span> view = <span class="hljs-keyword">new</span> <span class="hljs-built_in">DataView</span>(buffer);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-below-string-expression">What is the output of below string expression</h3>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome to JS world"</span>[<span class="hljs-number">0</span>]);
</code></pre>
<p>The output of the above expression is "W".
<strong>Explanation:</strong> The bracket notation with specific index on a string returns the character at a specific location. Hence, it returns the character "W" of the string. Since this is not supported in IE7 and below versions, you may need to use the .charAt() method to get the desired result.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-error-object">What is the purpose of Error object</h3>
<p>The Error constructor creates an error object and the instances of error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. The syntax of error object would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>([message[, fileName[, lineNumber]]])
</code></pre>
<p>You can throw user defined exceptions or errors using Error object in try...catch block as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">if</span> (withdraw &gt; balance)
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Oops! You don't have enough balance"</span>);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-built_in">console</span>.log(e.name + <span class="hljs-string">": "</span> + e.message);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-evalerror-object">What is the purpose of EvalError object</h3>
<p>The EvalError object indicates an error regarding the global <code>eval()</code> function. Even though this exception is not thrown by JavaScript anymore, the EvalError object remains for compatibility. The syntax of this expression would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">new</span> <span class="hljs-built_in">EvalError</span>([message[, fileName[, lineNumber]]])
</code></pre>
<p>You can throw EvalError with in try...catch block as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">EvalError</span>(<span class="hljs-string">'Eval function error'</span>, <span class="hljs-string">'someFile.js'</span>, <span class="hljs-number">100</span>);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-built_in">console</span>.log(e.message, e.name, e.fileName);              <span class="hljs-comment">// "Eval function error", "EvalError", "someFile.js"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-list-of-cases-error-thrown-from-non-strict-mode-to-strict-mode">What are the list of cases error thrown from non-strict mode to strict mode</h3>
<p>When you apply 'use strict'; syntax, some of the below cases will throw a SyntaxError before executing the script</p>
<ol>
<li>When you use Octal syntax</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> n = <span class="hljs-number">022</span>;
</code></pre>
<ol start="2">
<li>Using <code>with</code> statement</li>
<li>When you use delete operator on a variable name</li>
<li>Using eval or arguments as variable or function argument name</li>
<li>When you use newly reserved keywords</li>
<li>When you declare a function in a block and access it from outside of the block</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (someCondition) {
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{}
}
f(); <span class="hljs-comment">// ReferenceError: f is not defined</span>
</code></pre>
<p>Hence, the errors from above cases are helpful to avoid errors in development/production environments.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-do-all-objects-have-prototypes">Do all objects have prototypes</h3>
<p>No. All objects have prototypes except the base object or an object created with Object.create(null) method. The base object is Object.prototype, and its prototype is null.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-a-parameter-and-an-argument">What is the difference between a parameter and an argument</h3>
<p>Parameter is the variable name of a function definition whereas an argument represents the value given to a function when it is invoked. Let's explain this with a simple function</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params">parameter1, parameter2, parameter3</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>[<span class="hljs-number">0</span>]); <span class="hljs-comment">// "argument1"</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>[<span class="hljs-number">1</span>]); <span class="hljs-comment">// "argument2"</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>[<span class="hljs-number">2</span>]); <span class="hljs-comment">// "argument3"</span>
}
myFunction(<span class="hljs-string">"argument1"</span>, <span class="hljs-string">"argument2"</span>, <span class="hljs-string">"argument3"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-some-method-in-arrays">What is the purpose of some method in arrays</h3>
<p>The some() method is used to test whether at least one element in the array passes the test implemented by the provided function. The method returns a boolean value. Let's take an example to test for any odd elements,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>];

<span class="hljs-keyword">var</span> odd = <span class="hljs-function">(<span class="hljs-params">element</span>) =&gt;</span> element % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>;

<span class="hljs-built_in">console</span>.log(array.some(odd)); <span class="hljs-comment">// true (the odd element exists)</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-combine-two-or-more-arrays">How do you combine two or more arrays</h3>
<p>The concat() method is used to join two or more arrays by returning a new array containing all the elements. The syntax would be as below,</p>
<pre><code class="lang-javascript">array1.concat(array2, array3, ..., arrayX)
</code></pre>
<p>Let's take an example of array's concatenation with veggies and fruits arrays,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> veggies = [<span class="hljs-string">"Tomato"</span>, <span class="hljs-string">"Carrot"</span>, <span class="hljs-string">"Cabbage"</span>];
<span class="hljs-keyword">var</span> fruits = [<span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Orange"</span>, <span class="hljs-string">"Pears"</span>];
<span class="hljs-keyword">var</span> veggiesAndFruits = veggies.concat(fruits);
<span class="hljs-built_in">console</span>.log(veggiesAndFruits); <span class="hljs-comment">// Tomato, Carrot, Cabbage, Apple, Orange, Pears</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-shallow-and-deep-copy">What is the difference between Shallow and Deep copy</h3>
<p>There are two ways to copy an object,</p>
<p><strong>Shallow Copy:</strong>
Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.</p>
<p><strong>Example</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> empDetails = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
  <span class="hljs-attr">expertise</span>: <span class="hljs-string">"Software Developer"</span>,
};
</code></pre>
<p>to create a duplicate</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> empDetailsShallowCopy = empDetails; <span class="hljs-comment">//Shallow copying!</span>
</code></pre>
<p>if we change some property value in the duplicate one like this:</p>
<pre><code class="lang-javascript">empDetailsShallowCopy.name = <span class="hljs-string">"Johnson"</span>;
</code></pre>
<p>The above statement will also change the name of <code>empDetails</code>, since we have a shallow copy. That means we're losing the original data as well.</p>
<p><strong>Deep copy:</strong>
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.</p>
<p><strong>Example</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> empDetails = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
  <span class="hljs-attr">expertise</span>: <span class="hljs-string">"Software Developer"</span>,
};
</code></pre>
<p>Create a deep copy by using the properties from the original object into new variable</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> empDetailsDeepCopy = {
  <span class="hljs-attr">name</span>: empDetails.name,
  <span class="hljs-attr">age</span>: empDetails.age,
  <span class="hljs-attr">expertise</span>: empDetails.expertise,
};
</code></pre>
<p>Now if you change <code>empDetailsDeepCopy.name</code>, it will only affect <code>empDetailsDeepCopy</code> &amp; not <code>empDetails</code></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-specific-number-of-copies-of-a-string">How do you create specific number of copies of a string</h3>
<p>The <code>repeat()</code> method is used to construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification.
Let's take an example of Hello string to repeat it 4 times,</p>
<pre><code class="lang-javascript"><span class="hljs-string">"Hello"</span>.repeat(<span class="hljs-number">4</span>); <span class="hljs-comment">// 'HelloHelloHelloHello'</span>
</code></pre>
</li>
<li><h3 id="heading-how-do-you-return-all-matching-strings-against-a-regular-expression">How do you return all matching strings against a regular expression</h3>
<p>The <code>matchAll()</code> method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> regexp = <span class="hljs-regexp">/Hello(\d?)/g</span>;
<span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello1Hello2Hello3"</span>;

<span class="hljs-keyword">let</span> greetingList = [...greeting.matchAll(regexp)];

<span class="hljs-built_in">console</span>.log(greetingList[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">//Hello1</span>
<span class="hljs-built_in">console</span>.log(greetingList[<span class="hljs-number">1</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">//Hello2</span>
<span class="hljs-built_in">console</span>.log(greetingList[<span class="hljs-number">2</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">//Hello3</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-trim-a-string-at-the-beginning-or-ending">How do you trim a string at the beginning or ending</h3>
<p>The <code>trim</code> method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use <code>trimStart/trimLeft</code> and <code>trimEnd/trimRight</code> methods. Let's see an example of these methods on a greeting message,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greeting = <span class="hljs-string">"   Hello, Goodmorning!   "</span>;

<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// "   Hello, Goodmorning!   "</span>
<span class="hljs-built_in">console</span>.log(greeting.trimStart()); <span class="hljs-comment">// "Hello, Goodmorning!   "</span>
<span class="hljs-built_in">console</span>.log(greeting.trimLeft()); <span class="hljs-comment">// "Hello, Goodmorning!   "</span>

<span class="hljs-built_in">console</span>.log(greeting.trimEnd()); <span class="hljs-comment">// "   Hello, Goodmorning!"</span>
<span class="hljs-built_in">console</span>.log(greeting.trimRight()); <span class="hljs-comment">// "   Hello, Goodmorning!"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-below-console-statement-with-unary-operator">What is the output of below console statement with unary operator</h3>
<p>Let's take console statement with unary operator as given below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(+<span class="hljs-string">"Hello"</span>); <span class="hljs-comment">// NaN</span>
</code></pre>
<p>The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-does-javascript-uses-mixins">Does javascript uses mixins</h3>
<p>Mixin is a generic object-oriented programming term - is a class containing methods that can be used by other classes without a need to inherit from it. In JavaScript we can only inherit from a single object. ie. There can be only one <code>[[prototype]]</code> for an object.</p>
<p>But sometimes we require to extend more than one, to overcome this we can use Mixin which helps to copy methods to the prototype of another class.</p>
<p>Say for instance, we've two classes <code>User</code> and <code>CleanRoom</code>. Suppose we need to add <code>CleanRoom</code> functionality to <code>User</code>, so that user can clean the room at demand. Here's where concept called mixins comes into picture.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// mixin</span>
<span class="hljs-keyword">let</span> cleanRoomMixin = {
  cleanRoom() {
    alert(<span class="hljs-string">`Hello <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, your room is clean now`</span>);
  },
  sayBye() {
    alert(<span class="hljs-string">`Bye <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
  },
};

<span class="hljs-comment">// usage:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-comment">// copy the methods</span>
<span class="hljs-built_in">Object</span>.assign(User.prototype, cleanRoomMixin);

<span class="hljs-comment">// now User can clean the room</span>
<span class="hljs-keyword">new</span> User(<span class="hljs-string">"Dude"</span>).cleanRoom(); <span class="hljs-comment">// Hello Dude, your room is clean now!</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-thunk-function">What is a thunk function</h3>
<p>A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let's take a synchronous example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y;

<span class="hljs-keyword">const</span> thunk = <span class="hljs-function">() =&gt;</span> add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

thunk(); <span class="hljs-comment">// 5</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-asynchronous-thunks">What are asynchronous thunks</h3>
<p>The asynchronous thunks are useful to make network requests. Let's see an example of network requests,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">fn</span>) </span>{
  fetch(<span class="hljs-string">"https://jsonplaceholder.typicode.com/todos/1"</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> fn(json));
}

<span class="hljs-keyword">const</span> asyncThunk = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> fetchData(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params">data</span>) </span>{
    <span class="hljs-built_in">console</span>.log(data);
  });
};

asyncThunk();
</code></pre>
<p>The <code>getData</code> function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-below-function-calls">What is the output of below function calls</h3>
<p><strong>Code snippet:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> circle = {
  <span class="hljs-attr">radius</span>: <span class="hljs-number">20</span>,
  diameter() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.radius * <span class="hljs-number">2</span>;
  },
  <span class="hljs-attr">perimeter</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-number">2</span> * <span class="hljs-built_in">Math</span>.PI * <span class="hljs-built_in">this</span>.radius,
};
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(circle.diameter());
<span class="hljs-built_in">console</span>.log(circle.perimeter());
</code></pre>
<p><strong>Output:</strong></p>
<p>The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The <code>this</code> keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-remove-all-line-breaks-from-a-string">How to remove all line breaks from a string</h3>
<p>The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">remove_linebreaks</span>(<span class="hljs-params"> var message </span>) </span>{
    <span class="hljs-keyword">return</span> message.replace( <span class="hljs-regexp">/[\r\n]+/gm</span>, <span class="hljs-string">""</span> );
}
</code></pre>
<p>In the above expression, g and m are for global and multiline flags.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-reflow-and-repaint">What is the difference between reflow and repaint</h3>
<p>A <em>repaint</em> occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A <em>reflow</em> involves changes that affect the layout of a portion of the page (or the whole page). Resizing the browser window, changing the font, content changing (such as user typing text), using JavaScript methods involving computed styles, adding or removing elements from the DOM, and changing an element's classes are a few of the things that can trigger reflow. Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-happens-with-negating-an-array">What happens with negating an array</h3>
<p>Negating an array with <code>!</code> character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will return <code>false</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(![]); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-happens-if-we-add-two-arrays">What happens if we add two arrays</h3>
<p>If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log([<span class="hljs-string">"a"</span>] + [<span class="hljs-string">"b"</span>]); <span class="hljs-comment">// "ab"</span>
<span class="hljs-built_in">console</span>.log([] + []); <span class="hljs-comment">// ""</span>
<span class="hljs-built_in">console</span>.log(![] + []); <span class="hljs-comment">// "false", because ![] returns false.</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-output-of-prepend-additive-operator-on-falsy-values">What is the output of prepend additive operator on falsy values</h3>
<p>If you prepend the additive(+) operator on falsy values(null, undefined, NaN, false, ""), the falsy value converts to a number value zero. Let's display them on browser console as below,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(+<span class="hljs-literal">null</span>); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(+<span class="hljs-literal">undefined</span>); <span class="hljs-comment">// NaN</span>
<span class="hljs-built_in">console</span>.log(+<span class="hljs-literal">false</span>); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(+<span class="hljs-literal">NaN</span>); <span class="hljs-comment">// NaN</span>
<span class="hljs-built_in">console</span>.log(+<span class="hljs-string">""</span>); <span class="hljs-comment">// 0</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-self-string-using-special-characters">How do you create self string using special characters</h3>
<p>The self string can be formed with the combination of <code>[]()!+</code> characters. You need to remember the below conventions to achieve this pattern.</p>
<ol>
<li>Since Arrays are truthful values, negating the arrays will produce false: ![] === false</li>
<li>As per JavaScript coercion rules, the addition of arrays together will toString them: [] + [] === ""</li>
<li>Prepend an array with + operator will convert an array to false, the negation will make it true and finally converting the result will produce value '1': +(!(+[])) === 1</li>
</ol>
<p>By applying the above rules, we can derive below conditions</p>
<pre><code class="lang-javascript">(![] + [] === <span class="hljs-string">"false"</span> + !+[]) === <span class="hljs-number">1</span>;
</code></pre>
<p>Now the character pattern would be created as below,</p>
<pre><code class="lang-javascript">      s               e               l               f
 ^^^^^^^^^^^^^   ^^^^^^^^^^^^^   ^^^^^^^^^^^^^   ^^^^^^^^^^^^^

 (![] + [])[<span class="hljs-number">3</span>] + (![] + [])[<span class="hljs-number">4</span>] + (![] + [])[<span class="hljs-number">2</span>] + (![] + [])[<span class="hljs-number">0</span>]
 ^^^^^^^^^^^^^   ^^^^^^^^^^^^^   ^^^^^^^^^^^^^   ^^^^^^^^^^^^^
(![] + [])[+!+[]+!+[]+!+[]] +
(![] + [])[+!+[]+!+[]+!+[]+!+[]] +
(![] + [])[+!+[]+!+[]] +
(![] + [])[+[]]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
(![]+[])[+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]+!+[]+!+[]]+(![]+[])[+!+[]+!+[]]+(![]+[])[+[]]
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-remove-falsy-values-from-an-array">How do you remove falsy values from an array</h3>
<p>You can apply the filter method on the array by passing Boolean as a parameter. This way it removes all falsy values(0, undefined, null, false and "") from the array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-literal">false</span>, <span class="hljs-literal">null</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5</span>, <span class="hljs-literal">undefined</span>];
myArray.filter(<span class="hljs-built_in">Boolean</span>); <span class="hljs-comment">// [1, 5] // is same as myArray.filter(x =&gt; x);</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-get-unique-values-of-an-array">How do you get unique values of an array</h3>
<p>You can get unique values of an array with the combination of <code>Set</code> and rest expression/spread(...) syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log([...new <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">4</span>, <span class="hljs-number">3</span>])]); <span class="hljs-comment">// [1, 2, 4, 3]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-destructuring-aliases">What is destructuring aliases</h3>
<p>Sometimes you would like to have a destructured variable with a different name than the property name. In that case, you'll use a <code>: newName</code> to specify a name for the variable. This process is called destructuring aliases.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">x</span>: <span class="hljs-number">1</span> };
<span class="hljs-comment">// Grabs obj.x as as { otherName }</span>
<span class="hljs-keyword">const</span> { <span class="hljs-attr">x</span>: otherName } = obj;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-map-the-array-values-without-using-map-method">How do you map the array values without using map method</h3>
<p>You can map the array values without using the <code>map</code> method by just using the <code>from</code> method of Array. Let's map city names from Countries array,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> countries = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"India"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Delhi"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"US"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Washington"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Russia"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Moscow"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Singapore"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Singapore"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"China"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Beijing"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"France"</span>, <span class="hljs-attr">capital</span>: <span class="hljs-string">"Paris"</span> },
];

<span class="hljs-keyword">const</span> cityNames = <span class="hljs-built_in">Array</span>.from(countries, <span class="hljs-function">(<span class="hljs-params">{ capital }</span>) =&gt;</span> capital);
<span class="hljs-built_in">console</span>.log(cityNames); <span class="hljs-comment">// ['Delhi, 'Washington', 'Moscow', 'Singapore', 'Beijing', 'Paris']</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-empty-an-array">How do you empty an array</h3>
<p>You can empty an array quickly by setting the array length to zero.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> cities = [<span class="hljs-string">"Singapore"</span>, <span class="hljs-string">"Delhi"</span>, <span class="hljs-string">"London"</span>];
cities.length = <span class="hljs-number">0</span>; <span class="hljs-comment">// cities becomes []</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-round-numbers-to-certain-decimals">How do you round numbers to certain decimals</h3>
<p>You can round numbers to a certain number of decimals using <code>toFixed</code> method from native javascript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> pie = <span class="hljs-number">3.141592653</span>;
pie = pie.toFixed(<span class="hljs-number">3</span>); <span class="hljs-comment">// 3.142</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-easiest-way-to-convert-an-array-to-an-object">What is the easiest way to convert an array to an object</h3>
<p>You can convert an array to an object with the same data using spread(...) operator.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> fruits = [<span class="hljs-string">"banana"</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-string">"orange"</span>, <span class="hljs-string">"watermelon"</span>];
<span class="hljs-keyword">var</span> fruitsObject = { ...fruits };
<span class="hljs-built_in">console</span>.log(fruitsObject); <span class="hljs-comment">// {0: "banana", 1: "apple", 2: "orange", 3: "watermelon"}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-an-array-with-some-data">How do you create an array with some data</h3>
<p>You can create an array with some data or an array with the same values using <code>fill</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> newArray = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">5</span>).fill(<span class="hljs-string">"0"</span>);
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// ["0", "0", "0", "0", "0"]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-placeholders-from-console-object">What are the placeholders from console object</h3>
<p>Below are the list of placeholders available from console object,</p>
<ol>
<li>%o — It takes an object,</li>
<li>%s — It takes a string,</li>
<li>%d — It is used for a decimal or integer
These placeholders can be represented in the console.log as below</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">"Delhi"</span> };
<span class="hljs-built_in">console</span>.log(
  <span class="hljs-string">"Hello %s, your details %o are available in the object form"</span>,
  <span class="hljs-string">"John"</span>,
  user
); <span class="hljs-comment">// Hello John, your details {name: "John", id: 1, city: "Delhi"} are available in object</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-it-possible-to-add-css-to-console-messages">Is it possible to add CSS to console messages</h3>
<p>Yes, you can apply CSS styles to console messages similar to html text on the web page.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(
  <span class="hljs-string">"%c The text has blue color, with large font and red background"</span>,
  <span class="hljs-string">"color: blue; font-size: x-large; background: red"</span>
);
</code></pre>
<p>The text will be displayed as below,
<img src="images/console-css.png" alt="Screenshot" /></p>
<p><strong>Note:</strong> All CSS styles can be applied to console messages.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-dir-method-of-console-object">What is the purpose of dir method of console object</h3>
<p>The <code>console.dir()</code> is used to display an interactive list of the properties of the specified JavaScript object as JSON.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">"Delhi"</span> };
<span class="hljs-built_in">console</span>.dir(user);
</code></pre>
<p>The user object displayed in JSON representation
<img src="images/console-dir.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-it-possible-to-debug-html-elements-in-console">Is it possible to debug HTML elements in console</h3>
<p>Yes, it is possible to get and debug HTML elements in the console just like inspecting elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"body"</span>)[<span class="hljs-number">0</span>];
<span class="hljs-built_in">console</span>.log(element);
</code></pre>
<p>It prints the HTML element in the console,</p>
<p><img src="images/console-html.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-display-data-in-a-tabular-format-using-console-object">How do you display data in a tabular format using console object</h3>
<p>The <code>console.table()</code> is used to display data in the console in a tabular format to visualize complex arrays or objects.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">"Delhi"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Max"</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">"London"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Rod"</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">city</span>: <span class="hljs-string">"Paris"</span> },
];
<span class="hljs-built_in">console</span>.table(users);
</code></pre>
<p>The data visualized in a table format,</p>
<p><img src="images/console-table.png" alt="Screenshot" />
<strong>Not:</strong> Remember that <code>console.table()</code> is not supported in IE.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-verify-that-an-argument-is-a-number-or-not">How do you verify that an argument is a Number or not</h3>
<p>The combination of IsNaN and isFinite methods are used to confirm whether an argument is a number or not.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isNumber</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">return</span> !<span class="hljs-built_in">isNaN</span>(<span class="hljs-built_in">parseFloat</span>(n)) &amp;&amp; <span class="hljs-built_in">isFinite</span>(n);
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-copy-to-clipboard-button">How do you create copy to clipboard button</h3>
<p>You need to select the content(using .select() method) of the input element and execute the copy command with execCommand (i.e, execCommand('copy')). You can also execute other system commands like cut and paste.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#copy-button"</span>).onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Select the content</span>
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#copy-input"</span>).select();
  <span class="hljs-comment">// Copy to the clipboard</span>
  <span class="hljs-built_in">document</span>.execCommand(<span class="hljs-string">"copy"</span>);
};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-shortcut-to-get-timestamp">What is the shortcut to get timestamp</h3>
<p>You can use <code>new Date().getTime()</code> to get the current timestamp. There is an alternative shortcut to get the value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(+<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Date</span>.now());
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-flattening-multi-dimensional-arrays">How do you flattening multi dimensional arrays</h3>
<p>Flattening bi-dimensional arrays is trivial with Spread operator.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> biDimensionalArr = [<span class="hljs-number">11</span>, [<span class="hljs-number">22</span>, <span class="hljs-number">33</span>], [<span class="hljs-number">44</span>, <span class="hljs-number">55</span>], [<span class="hljs-number">66</span>, <span class="hljs-number">77</span>], <span class="hljs-number">88</span>, <span class="hljs-number">99</span>];
<span class="hljs-keyword">const</span> flattenArr = [].concat(...biDimensionalArr); <span class="hljs-comment">// [11, 22, 33, 44, 55, 66, 77, 88, 99]</span>
</code></pre>
<p>But you can make it work with multi-dimensional arrays by recursive calls,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">flattenMultiArray</span>(<span class="hljs-params">arr</span>) </span>{
  <span class="hljs-keyword">const</span> flattened = [].concat(...arr);
  <span class="hljs-keyword">return</span> flattened.some(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> <span class="hljs-built_in">Array</span>.isArray(item))
    ? flattenMultiArray(flattened)
    : flattened;
}
<span class="hljs-keyword">const</span> multiDimensionalArr = [<span class="hljs-number">11</span>, [<span class="hljs-number">22</span>, <span class="hljs-number">33</span>], [<span class="hljs-number">44</span>, [<span class="hljs-number">55</span>, <span class="hljs-number">66</span>, [<span class="hljs-number">77</span>, [<span class="hljs-number">88</span>]], <span class="hljs-number">99</span>]]];
<span class="hljs-keyword">const</span> flatArr = flattenMultiArray(multiDimensionalArr); <span class="hljs-comment">// [11, 22, 33, 44, 55, 66, 77, 88, 99]</span>
</code></pre>
<p>Also you can use the <code>flat</code> method of Array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, [<span class="hljs-number">6</span>, <span class="hljs-number">7</span>]];
<span class="hljs-keyword">const</span> fllattenArr = arr.flat(); <span class="hljs-comment">// [1, 2, 3, 4, 5, 6, 7]</span>

<span class="hljs-comment">// And for multiDimensional arrays</span>
<span class="hljs-keyword">const</span> multiDimensionalArr = [<span class="hljs-number">11</span>, [<span class="hljs-number">22</span>, <span class="hljs-number">33</span>], [<span class="hljs-number">44</span>, [<span class="hljs-number">55</span>, <span class="hljs-number">66</span>, [<span class="hljs-number">77</span>, [<span class="hljs-number">88</span>]], <span class="hljs-number">99</span>]]];
<span class="hljs-keyword">const</span> oneStepFlat = multiDimensionalArr.flat(<span class="hljs-number">1</span>); <span class="hljs-comment">// [11, 22, 33, 44, [55, 66, [77, [88]], 99]]</span>
<span class="hljs-keyword">const</span> towStep = multiDimensionalArr.flat(<span class="hljs-number">2</span>); <span class="hljs-comment">// [11, 22, 33, 44, 55, 66, [77, [88]], 99]</span>
<span class="hljs-keyword">const</span> fullyFlatArray = multiDimensionalArr.flat(<span class="hljs-literal">Infinity</span>); <span class="hljs-comment">// [11, 22, 33, 44, 55, 66, 77, 88, 99]</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-easiest-multi-condition-checking">What is the easiest multi condition checking</h3>
<p>You can use <code>indexOf</code> to compare input with multiple values instead of checking each value as one condition.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Verbose approach</span>
<span class="hljs-keyword">if</span> (
  input === <span class="hljs-string">"first"</span> ||
  input === <span class="hljs-number">1</span> ||
  input === <span class="hljs-string">"second"</span> ||
  input === <span class="hljs-number">2</span>
) {
  someFunction();
}
<span class="hljs-comment">// Shortcut</span>
<span class="hljs-keyword">if</span> ([<span class="hljs-string">"first"</span>, <span class="hljs-number">1</span>, <span class="hljs-string">"second"</span>, <span class="hljs-number">2</span>].indexOf(input) !== <span class="hljs-number">-1</span>) {
  someFunction();
}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-capture-browser-back-button">How do you capture browser back button</h3>
<p>The <code>beforeunload</code> event is triggered when the window, the document and its resources are about to be unloaded. This event is helpful to warn users about losing the current data and detect back button event.</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'beforeunload'</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked browser back button'</span>);
 });
</code></pre>
<p>You can also use <code>popstate</code> event to detect the browser back button. 
<strong>Note:</strong> The history entry has been activated using <code>history.pushState</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'popstate'</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked browser back button'</span>);
   box.style.backgroundColor = <span class="hljs-string">'white'</span>;
 });

<span class="hljs-keyword">const</span> box = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'div'</span>);

box.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
 box.style.backgroundColor = <span class="hljs-string">'blue'</span>;
 <span class="hljs-built_in">window</span>.history.pushState({}, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>);
});
</code></pre>
<p>In the preceeding code, When the box element clicked, its background color appears in blue color and changed to while color upon clicking the browser back button using <code>popstate</code> event handler. The <code>state</code> property of <code>popstate</code> contains the copy of history entry's state object.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-disable-right-click-in-the-web-page">How do you disable right click in the web page</h3>
<p>The right click on the page can be disabled by returning false from the <code>oncontextmenu</code> attribute on the body element.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">oncontextmenu</span>=<span class="hljs-string">"return false;"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-wrapper-objects">What are wrapper objects</h3>
<p>Primitive Values like string,number and boolean don't have properties and methods but they are temporarily converted or coerced to an object(Wrapper object) when you try to perform actions on them. For example, if you apply toUpperCase() method on a primitive string value, it does not throw an error but returns uppercase of the string.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"john"</span>;

<span class="hljs-built_in">console</span>.log(name.toUpperCase()); <span class="hljs-comment">// Behind the scenes treated as console.log(new String(name).toUpperCase());</span>
</code></pre>
<p>i.e, Every primitive except null and undefined have Wrapper Objects and the list of wrapper objects are String,Number,Boolean,Symbol and BigInt.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-ajax">What is AJAX</h3>
<p>AJAX stands for Asynchronous JavaScript and XML and it is a group of related technologies(HTML, CSS, JavaScript, XMLHttpRequest API etc) used to display data asynchronously. i.e. We can send data to the server and get data from the server without reloading the web page.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-ways-to-deal-with-asynchronous-code">What are the different ways to deal with Asynchronous Code</h3>
<p>Below are the list of different ways to deal with Asynchronous code.</p>
<ol>
<li>Callbacks</li>
<li>Promises</li>
<li>Async/await</li>
<li>Third-party libraries such as async.js,bluebird etc</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-cancel-a-fetch-request">How to cancel a fetch request</h3>
<p>Until a few days back, One shortcoming of native promises is no direct way to cancel a fetch request. But the new <code>AbortController</code> from js specification allows you to use a signal to abort one or multiple fetch calls.
The basic flow of cancelling a fetch request would be as below,</p>
<ol>
<li>Create an <code>AbortController</code> instance</li>
<li>Get the signal property of an instance and pass the signal as a fetch option for signal</li>
<li>Call the AbortController's abort property to cancel all fetches that use that signal
For example, passing the same signal to multiple fetch calls will cancel all requests with that signal,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> AbortController();
<span class="hljs-keyword">const</span> { signal } = controller;

fetch(<span class="hljs-string">"http://localhost:8000"</span>, { signal })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Request 1 is complete!`</span>);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (e.name === <span class="hljs-string">"AbortError"</span>) {
      <span class="hljs-comment">// We know it's been canceled!</span>
    }
  });

fetch(<span class="hljs-string">"http://localhost:8000"</span>, { signal })
  .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Request 2 is complete!`</span>);
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (e.name === <span class="hljs-string">"AbortError"</span>) {
      <span class="hljs-comment">// We know it's been canceled!</span>
    }
  });

<span class="hljs-comment">// Wait 2 seconds to abort both requests</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> controller.abort(), <span class="hljs-number">2000</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-web-speech-api">What is web speech API</h3>
<p>Web speech API is used to enable modern browsers recognize and synthesize speech(i.e, voice data into web apps). This API was introduced by W3C Community in the year 2012. It has two main parts:</p>
<ol>
<li><strong>SpeechRecognition (Asynchronous Speech Recognition or Speech-to-Text):</strong> It provides the ability to recognize voice context from an audio input and respond accordingly. This is accessed by the <code>SpeechRecognition</code> interface.
The example below shows how to use this API to get text from speech,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.SpeechRecognition =
  <span class="hljs-built_in">window</span>.webkitSpeechRecognition || <span class="hljs-built_in">window</span>.SpeechRecognition; <span class="hljs-comment">// webkitSpeechRecognition for Chrome and SpeechRecognition for FF</span>
<span class="hljs-keyword">const</span> recognition = <span class="hljs-keyword">new</span> <span class="hljs-built_in">window</span>.SpeechRecognition();
recognition.onresult = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-comment">// SpeechRecognitionEvent type</span>
  <span class="hljs-keyword">const</span> speechToText = event.results[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>].transcript;
  <span class="hljs-built_in">console</span>.log(speechToText);
};
recognition.start();
</code></pre>
<p>In this API, browser is going to ask you for permission to use your microphone</p>
<ol start="2">
<li><strong>SpeechSynthesis (Text-to-Speech):</strong> It provides the ability to recognize voice context from an audio input and respond. This is accessed by the <code>SpeechSynthesis</code> interface.
For example, the below code is used to get voice/speech from text,</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-string">"speechSynthesis"</span> <span class="hljs-keyword">in</span> <span class="hljs-built_in">window</span>) {
  <span class="hljs-keyword">var</span> speech = <span class="hljs-keyword">new</span> SpeechSynthesisUtterance(<span class="hljs-string">"Hello World!"</span>);
  speech.lang = <span class="hljs-string">"en-US"</span>;
  <span class="hljs-built_in">window</span>.speechSynthesis.speak(speech);
}
</code></pre>
<p>The above examples can be tested on chrome(33+) browser's developer console.
<strong>Note:</strong> This API is still a working draft and only available in Chrome and Firefox browsers(ofcourse Chrome only implemented the specification)</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-minimum-timeout-throttling">What is minimum timeout throttling</h3>
<p>Both browser and NodeJS javascript environments throttles with a minimum delay that is greater than 0ms. That means even though setting a delay of 0ms will not happen instantaneously.
<strong>Browsers:</strong> They have a minimum delay of 4ms. This throttle occurs when successive calls are triggered due to callback nesting(certain depth) or after a certain number of successive intervals.
Note: The older browsers have a minimum delay of 10ms.
<strong>Nodejs:</strong> They have a minimum delay of 1ms. This throttle happens when the delay is larger than 2147483647 or less than 1.
The best example to explain this timeout throttling behavior is the order of below code snippet.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMeFirst</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My script is initialized"</span>);
}
<span class="hljs-built_in">setTimeout</span>(runMeFirst, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Script loaded"</span>);
</code></pre>
<p>and the output would be in</p>
<pre><code class="lang-cmd">Script loaded
My script is initialized
</code></pre>
<p>If you don't use <code>setTimeout</code>, the order of logs will be sequential.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMeFirst</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My script is initialized"</span>);
}
runMeFirst();
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Script loaded"</span>);
</code></pre>
<p>and the output is,</p>
<pre><code class="lang-cmd">My script is initialized
Script loaded
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-implement-zero-timeout-in-modern-browsers">How do you implement zero timeout in modern browsers</h3>
<p>You can't use setTimeout(fn, 0) to execute the code immediately due to minimum delay of greater than 0ms. But you can use window.postMessage() to achieve this behavior.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-tasks-in-event-loop">What are tasks in event loop</h3>
<p>A task is any javascript code/program which is scheduled to be run by the standard mechanisms such as initially starting to run a program, run an event callback, or an interval or timeout being fired. All these tasks are scheduled on a task queue.
Below are the list of use cases to add tasks to the task queue,</p>
<ol>
<li>When a new javascript program is executed directly from console or running by the <code>&lt;script&gt;</code> element, the task will be added to the task queue.</li>
<li>When an event fires, the event callback added to task queue</li>
<li>When a setTimeout or setInterval is reached, the corresponding callback added to task queue</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-microtask">What is microtask</h3>
<p>Microtask is used for the javascript code which needs to be executed immediately after the currently executing task/microtask is completed. They are kind of blocking in nature. i.e, The main thread will be blocked until the microtask queue is empty.
The main sources of microtasks are Promise.resolve, Promise.reject, MutationObservers, IntersectionObservers etc</p>
<p><strong>Note:</strong> All of these microtasks are processed in the same turn of the event loop.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-different-event-loops">What are different event loops</h3>
<p>In JavaScript, there are multiple event loops that can be used depending on the context of your application. The most common event loops are:</p>
<ol>
<li>The Browser Event Loop</li>
<li>The Node.js Event Loop</li>
</ol>
</li>
</ol>
<ul>
<li><p>Browser Event Loop: The Browser Event Loop is used in client-side JavaScript applications and is responsible for handling events that occur within the browser environment, such as user interactions (clicks, keypresses, etc.), HTTP requests, and other asynchronous actions.</p>
</li>
<li><p>The Node.js Event Loop is used in server-side JavaScript applications and is responsible for handling events that occur within the Node.js runtime environment, such as file I/O, network I/O, and other asynchronous actions.</p>
<p> <strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
</ul>
<ol start="390">
<li><h3 id="heading-what-is-the-purpose-of-queuemicrotask">What is the purpose of queueMicrotask</h3>
<p>The <code>queueMicrotask</code> function is used to schedule a microtask, which is a function that will be executed asynchronously in the microtask queue. The purpose of <code>queueMicrotask</code> is to ensure that a function is executed after the current task has finished, but before the browser performs any rendering or handles user events.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start"</span>); <span class="hljs-comment">//1</span>

queueMicrotask(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Inside microtask"</span>); <span class="hljs-comment">// 3</span>
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"End"</span>); <span class="hljs-comment">//2</span>
</code></pre>
<p>By using queueMicrotask, you can ensure that certain tasks or callbacks are executed at the earliest opportunity during the JavaScript event loop, making it useful for performing work that needs to be done asynchronously but with higher priority than regular <code>setTimeout</code> or <code>setInterval</code> callbacks.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-use-javascript-libraries-in-typescript-file">How do you use javascript libraries in typescript file</h3>
<p>It is known that not all JavaScript libraries or frameworks have TypeScript declaration files. But if you still want to use libraries or frameworks in your TypeScript files without getting compilation errors, the only solution is <code>declare</code> keyword along with a variable declaration. For example, let's imagine you have a library called <code>customLibrary</code> that doesn’t have a TypeScript declaration and have a namespace called <code>customLibrary</code> in the global namespace. You can use this library in typescript code as below,</p>
<pre><code class="lang-javascript">declare <span class="hljs-keyword">var</span> customLibrary;
</code></pre>
<p>In the runtime, typescript will provide the type to the <code>customLibrary</code> variable as <code>any</code> type. The another alternative without using declare keyword is below</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> customLibrary: any;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-promises-and-observables">What are the differences between promises and observables</h3>
<p>Some of the major difference in a tabular form</p>
<p>| Promises                                                           | Observables                                                                              |
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
| Emits only a single value at a time                                | Emits multiple values over a period of time(stream of values ranging from 0 to multiple) |
| Eager in nature; they are going to be called immediately           | Lazy in nature; they require subscription to be invoked                                  |
| Promise is always asynchronous even though it resolved immediately | Observable can be either synchronous or asynchronous                                     |
| Doesn't provide any operators                                      | Provides operators such as map, forEach, filter, reduce, retry, and retryWhen etc        |
| Cannot be canceled                                                 | Canceled by using unsubscribe() method                                                   |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-heap">What is heap</h3>
<p>Heap(Or memory heap) is the memory location where objects are stored when we define variables. i.e, This is the place where all the memory allocations and de-allocation take place. Both heap and call-stack are two containers of JS runtime.
Whenever runtime comes across variables and function declarations in the code it stores them in the Heap.</p>
<p><img src="images/heap.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-event-table">What is an event table</h3>
<p>Event Table is a data structure that stores and keeps track of all the events which will be executed asynchronously like after some time interval or after the resolution of some API requests. i.e Whenever you call a setTimeout function or invoke async operation, it is added to the Event Table.
It doesn't not execute functions on it’s own. The main purpose of the event table is to keep track of events and send them to the Event Queue as shown in the below diagram.</p>
<p><img src="images/event-table.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-microtask-queue">What is a microTask queue</h3>
<p>Microtask Queue is the new queue where all the tasks initiated by promise objects get processed before the callback queue.
The microtasks queue are processed before the next rendering and painting jobs. But if these microtasks are running for a long time then it leads to visual degradation.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-shim-and-polyfill">What is the difference between shim and polyfill</h3>
<p>A shim is a library that brings a new API to an older environment, using only the means of that environment. It isn't necessarily restricted to a web application. For example, es5-shim.js is used to emulate ES5 features on older browsers (mainly pre IE9).
Whereas polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively.
In a simple sentence, a polyfill is a shim for a browser API.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-detect-primitive-or-non-primitive-value-type">How do you detect primitive or non primitive value type</h3>
<p>In JavaScript, primitive types include boolean, string, number, BigInt, null, Symbol and undefined. Whereas non-primitive types include the Objects. But you can easily identify them with the below function,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myPrimitive = <span class="hljs-number">30</span>;
<span class="hljs-keyword">var</span> myNonPrimitive = {};
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isPrimitive</span>(<span class="hljs-params">val</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Object</span>(val) !== val;
}

isPrimitive(myPrimitive);
isPrimitive(myNonPrimitive);
</code></pre>
<p>If the value is a primitive data type, the Object constructor creates a new wrapper object for the value. But If the value is a non-primitive data type (an object), the Object constructor will give the same object.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-babel">What is babel</h3>
<p>Babel is a JavaScript transpiler to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Some of the main features are listed below,</p>
<ol>
<li>Transform syntax</li>
<li>Polyfill features that are missing in your target environment (using @babel/polyfill)</li>
<li>Source code transformations (or codemods)</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-nodejs-completely-single-threaded">Is Node.js completely single threaded</h3>
<p>Node is a single thread, but some of the functions included in the Node.js standard library(e.g, fs module functions) are not single threaded. i.e, Their logic runs outside of the Node.js single thread to improve the speed and performance of a program.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-common-use-cases-of-observables">What are the common use cases of observables</h3>
<p>Some of the most common use cases of observables are web sockets with push notifications, user input changes, repeating intervals, etc</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-rxjs">What is RxJS</h3>
<p>RxJS (Reactive Extensions for JavaScript) is a library for implementing reactive programming using observables that makes it easier to compose asynchronous or callback-based code. It also provides utility functions for creating and working with observables.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-function-constructor-and-function-declaration">What is the difference between Function constructor and function declaration</h3>
<p>The functions which are created with <code>Function constructor</code> do not create closures to their creation contexts but they are always created in the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.</p>
<p>Let's see this difference with an example,</p>
<p><strong>Function Constructor:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-number">200</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Function</span>(<span class="hljs-string">"return a;"</span>);
}
<span class="hljs-built_in">console</span>.log(createFunction()()); <span class="hljs-comment">// 100</span>
</code></pre>
<p><strong>Function declaration:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> a = <span class="hljs-number">200</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> a;
  };
}
<span class="hljs-built_in">console</span>.log(createFunction()()); <span class="hljs-comment">// 200</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-short-circuit-condition">What is a Short circuit condition</h3>
<p>Short circuit conditions are meant for condensed way of writing simple if statements. Let's demonstrate the scenario using an example. If you would like to login to a portal with an authentication condition, the expression would be as below,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (authenticate) {
  loginToPorta();
}
</code></pre>
<p>Since the javascript logical operators evaluated from left to right, the above expression can be simplified using &amp;&amp; logical operator</p>
<pre><code class="lang-javascript">authenticate &amp;&amp; loginToPorta();
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-easiest-way-to-resize-an-array">What is the easiest way to resize an array</h3>
<p>The length property of an array is useful to resize or empty an array quickly. Let's apply length property on number array to resize the number of elements from 5 to 2,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(array.length); <span class="hljs-comment">// 5</span>

array.length = <span class="hljs-number">2</span>;
<span class="hljs-built_in">console</span>.log(array.length); <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(array); <span class="hljs-comment">// [1,2]</span>
</code></pre>
<p>and the array can be emptied too</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
array.length = <span class="hljs-number">0</span>;
<span class="hljs-built_in">console</span>.log(array.length); <span class="hljs-comment">// 0</span>
<span class="hljs-built_in">console</span>.log(array); <span class="hljs-comment">// []</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-observable">What is an observable</h3>
<p>An Observable is basically a function that can return a stream of values either synchronously or asynchronously to an observer over time. The consumer can get the value by calling <code>subscribe()</code> method.
Let's look at a simple example of an Observable</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Observable } <span class="hljs-keyword">from</span> <span class="hljs-string">"rxjs"</span>;

<span class="hljs-keyword">const</span> observable = <span class="hljs-keyword">new</span> Observable(<span class="hljs-function">(<span class="hljs-params">observer</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    observer.next(<span class="hljs-string">"Message from a Observable!"</span>);
  }, <span class="hljs-number">3000</span>);
});

observable.subscribe(<span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(value));
</code></pre>
<p><img src="images/observables.png" alt="Screenshot" /></p>
<p><strong>Note:</strong> Observables are not part of the JavaScript language yet but they are being proposed to be added to the language</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-function-and-class-declarations">What is the difference between function and class declarations</h3>
<p>The main difference between function declarations and class declarations is <code>hoisting</code>. The function declarations are hoisted but not class declarations.</p>
<p><strong>Classes:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(); <span class="hljs-comment">// ReferenceError</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{}
</code></pre>
<p><strong>Constructor Function:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User(); <span class="hljs-comment">// No error</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-async-function">What is an async function</h3>
<p>An async function is a function declared with the <code>async</code> keyword which enables asynchronous, promise-based behavior to be written in a cleaner style by avoiding promise chains. These functions can contain zero or more <code>await</code> expressions.</p>
<p>Let's take a below async function example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logger</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> data = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"http://someapi.com/users"</span>); <span class="hljs-comment">// pause until fetch returns</span>
  <span class="hljs-built_in">console</span>.log(data);
}
logger();
</code></pre>
<p>It is basically syntax sugar over ES2015 promises and generators.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-prevent-promises-swallowing-errors">How do you prevent promises swallowing errors</h3>
<p>While using asynchronous code, JavaScript’s ES6 promises can make your life a lot easier without having callback pyramids and error handling on every second line. But Promises have some pitfalls and the biggest one is swallowing errors by default.</p>
<p>Let's say you expect to print an error to the console for all the below cases,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"promised value"</span>).then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"error"</span>);
});

<span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"error value"</span>).catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"error"</span>);
});

<span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"error"</span>);
});
</code></pre>
<p>But there are many modern JavaScript environments that won't print any errors. You can fix this problem in different ways,</p>
<ol>
<li><p><strong>Add catch block at the end of each chain:</strong> You can add catch block to the end of each of your promise chains</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"promised value"</span>)
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"error"</span>);
  })
  .catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
    <span class="hljs-built_in">console</span>.error(error.stack);
  });
</code></pre>
<p>But it is quite difficult to type for each promise chain and verbose too.</p>
</li>
<li><p><strong>Add done method:</strong> You can replace first solution's then and catch blocks with done method</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"promised value"</span>).done(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"error"</span>);
});
</code></pre>
<p>Let's say you want to fetch data using HTTP and later perform processing on the resulting data asynchronously. You can write <code>done</code> block as below,</p>
<pre><code class="lang-javascript">getDataFromHttp()
  .then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-keyword">return</span> processDataAsync(result);
  })
  .done(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">processed</span>) </span>{
    displayData(processed);
  });
</code></pre>
<p>In future, if the processing library API changed to synchronous then you can remove <code>done</code> block as below,</p>
<pre><code class="lang-javascript">getDataFromHttp().then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
  <span class="hljs-keyword">return</span> displayData(processDataAsync(result));
});
</code></pre>
<p>and then you forgot to add <code>done</code> block to <code>then</code> block leads to silent errors.</p>
</li>
<li><p><strong>Extend ES6 Promises by Bluebird:</strong>
Bluebird extends the ES6 Promises API to avoid the issue in the second solution. This library has a “default” onRejection handler which will print all errors from rejected Promises to stderr. After installation, you can process unhandled rejections</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.onPossiblyUnhandledRejection(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
  <span class="hljs-keyword">throw</span> error;
});
</code></pre>
<p>and discard a rejection, just handle it with an empty catch</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">"error value"</span>).catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{});
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-deno">What is deno</h3>
<p>Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 JavaScript engine and the Rust programming language. It solves the inherent problems of Node.Js and has been officially released in May 2018. Unlike Node.JS, by default Deno  executes the code in a sandbox, which means that runtime has no access to below areas:</p>
<ol>
<li>The file system</li>
<li>The network</li>
<li>Execution of other scripts</li>
<li>The environment variables</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-make-an-object-iterable-in-javascript">How do you make an object iterable in javascript</h3>
<p>By default, plain objects are not iterable. But you can make the object iterable by defining a <code>Symbol.iterator</code> property on it.</p>
<p>Let's demonstrate this with an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> collection = {
  <span class="hljs-attr">one</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">two</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">three</span>: <span class="hljs-number">3</span>,
  [<span class="hljs-built_in">Symbol</span>.iterator]() {
    <span class="hljs-keyword">const</span> values = <span class="hljs-built_in">Object</span>.keys(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">next</span>: <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> {
          <span class="hljs-attr">value</span>: <span class="hljs-built_in">this</span>[values[i++]],
          <span class="hljs-attr">done</span>: i &gt; values.length,
        };
      },
    };
  },
};

<span class="hljs-keyword">const</span> iterator = collection[<span class="hljs-built_in">Symbol</span>.iterator]();

<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// → {value: 1, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// → {value: 2, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// → {value: 3, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// → {value: undefined, done: true}</span>
</code></pre>
<p>The above process can be simplified using a generator function,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> collection = {
  <span class="hljs-attr">one</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">two</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">three</span>: <span class="hljs-number">3</span>,
  [<span class="hljs-built_in">Symbol</span>.iterator]: <span class="hljs-function"><span class="hljs-keyword">function</span>* (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> <span class="hljs-built_in">this</span>) {
      <span class="hljs-keyword">yield</span> <span class="hljs-built_in">this</span>[key];
    }
  },
};
<span class="hljs-keyword">const</span> iterator = collection[<span class="hljs-built_in">Symbol</span>.iterator]();
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// {value: 1, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// {value: 2, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// {value: 3, done: false}</span>
<span class="hljs-built_in">console</span>.log(iterator.next()); <span class="hljs-comment">// {value: undefined, done: true}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-a-proper-tail-call">What is a Proper Tail Call</h3>
<p>First, we should know about tail call before talking about "Proper Tail Call". A tail call is a subroutine or function call performed as the final action of a calling function. Whereas <strong>Proper tail call(PTC)</strong> is a technique where the program or code will not create additional stack frames for a recursion when the function call is a tail call.</p>
<p>For example, the below classic or head recursion of factorial function relies on stack for each step. Each step need to be processed upto <code>n * factorial(n - 1)</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }
  <span class="hljs-keyword">return</span> n * factorial(n - <span class="hljs-number">1</span>);
}
<span class="hljs-built_in">console</span>.log(factorial(<span class="hljs-number">5</span>)); <span class="hljs-comment">//120</span>
</code></pre>
<p>But if you use Tail recursion functions, they keep passing all the necessary data it needs down the recursion without relying on the stack.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n, acc = <span class="hljs-number">1</span></span>) </span>{
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> acc;
  }
  <span class="hljs-keyword">return</span> factorial(n - <span class="hljs-number">1</span>, n * acc);
}
<span class="hljs-built_in">console</span>.log(factorial(<span class="hljs-number">5</span>)); <span class="hljs-comment">//120</span>
</code></pre>
<p>The above pattern returns the same output as the first one. But the accumulator keeps track of total as an argument without using stack memory on recursive calls.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-check-an-object-is-a-promise-or-not">How do you check an object is a promise or not</h3>
<p>If you don't know if a value is a promise or not, wrapping the value as <code>Promise.resolve(value)</code> which returns a promise</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isPromise</span>(<span class="hljs-params">object</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Promise</span> &amp;&amp; <span class="hljs-built_in">Promise</span>.resolve) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.resolve(object) == object;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-string">"Promise not supported in your environment"</span>;
  }
}

<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>;
<span class="hljs-keyword">var</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  resolve();
});

<span class="hljs-built_in">console</span>.log(isPromise(i)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isPromise(promise)); <span class="hljs-comment">// true</span>
</code></pre>
<p>Another way is to check for <code>.then()</code> handler type</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isPromise</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Boolean</span>(value &amp;&amp; <span class="hljs-keyword">typeof</span> value.then === <span class="hljs-string">"function"</span>);
}
<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>;
<span class="hljs-keyword">var</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">resolve, reject</span>) </span>{
  resolve();
});

<span class="hljs-built_in">console</span>.log(isPromise(i)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isPromise(promise)); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-detect-if-a-function-is-called-as-constructor">How to detect if a function is called as constructor</h3>
<p>You can use <code>new.target</code> pseudo-property to detect whether a function was called as a constructor(using the new operator) or as a regular function call.</p>
<ol>
<li>If a constructor or function invoked using the new operator, new.target returns a reference to the constructor or function.</li>
<li>For function calls, new.target is undefined.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Myfunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span>.target) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"called with new"</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"not called with new"</span>);
  }
}

<span class="hljs-keyword">new</span> Myfunc(); <span class="hljs-comment">// called with new</span>
Myfunc(); <span class="hljs-comment">// not called with new</span>
Myfunc.call({}); <span class="hljs-comment">// not called with new</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-arguments-object-and-rest-parameter">What are the differences between arguments object and rest parameter</h3>
<p>There are three main differences between arguments object and rest parameters</p>
<ol>
<li>The arguments object is an array-like but not an array. Whereas the rest parameters are array instances.</li>
<li>The arguments object does not support methods such as sort, map, forEach, or pop. Whereas these methods can be used in rest parameters.</li>
<li>The rest parameters are only the ones that haven’t been given a separate name, while the arguments object contains all arguments passed to the function</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-spread-operator-and-rest-parameter">What are the differences between spread operator and rest parameter</h3>
<p>Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. i.e, Rest parameter is opposite to the spread operator.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-kinds-of-generators">What are the different kinds of generators</h3>
<p>There are five kinds of generators,</p>
<ol>
<li><p><strong>Generator function declaration:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">myGenFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
}
<span class="hljs-keyword">const</span> genObj = myGenFunc();
</code></pre>
</li>
<li><p><strong>Generator function expressions:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myGenFunc = <span class="hljs-function"><span class="hljs-keyword">function</span>* (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
};
<span class="hljs-keyword">const</span> genObj = myGenFunc();
</code></pre>
</li>
<li><p><strong>Generator method definitions in object literals:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObj = {
  *myGeneratorMethod() {
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
  },
};
<span class="hljs-keyword">const</span> genObj = myObj.myGeneratorMethod();
</code></pre>
</li>
<li><p><strong>Generator method definitions in class:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
  *myGeneratorMethod() {
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
  }
}
<span class="hljs-keyword">const</span> myObject = <span class="hljs-keyword">new</span> MyClass();
<span class="hljs-keyword">const</span> genObj = myObject.myGeneratorMethod();
</code></pre>
</li>
<li><p><strong>Generator as a computed property:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> SomeObj = {
  *[<span class="hljs-built_in">Symbol</span>.iterator]() {
    <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
  },
};

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.from(SomeObj)); <span class="hljs-comment">// [ 1, 2, 3 ]</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-built-in-iterables">What are the built-in iterables</h3>
<p>Below are the list of built-in iterables in javascript,</p>
<ol>
<li>Arrays and TypedArrays</li>
<li>Strings: Iterate over each character or Unicode code-points</li>
<li>Maps: iterate over its key-value pairs</li>
<li>Sets: iterates over their elements</li>
<li>arguments: An array-like special variable in functions</li>
<li>DOM collection such as NodeList</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-forof-and-forin-statements">What are the differences between for...of and for...in statements</h3>
<p>Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:</p>
<ol>
<li>for..in iterates over all enumerable property keys of an object</li>
<li>for..of iterates over the values of an iterable object.</li>
</ol>
<p>Let's explain this difference with an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>];

arr.newProp = <span class="hljs-string">"newVlue"</span>;

<span class="hljs-comment">// key are the property keys</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> key <span class="hljs-keyword">in</span> arr) {
  <span class="hljs-built_in">console</span>.log(key); <span class="hljs-comment">// 0, 1, 2 &amp; newProp</span>
}

<span class="hljs-comment">// value are the property values</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> value <span class="hljs-keyword">of</span> arr) {
  <span class="hljs-built_in">console</span>.log(value); <span class="hljs-comment">// a, b, c</span>
}
</code></pre>
<p>Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of loop iterates over the values of a arr data structure and logs a, b, c in the console.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-define-instance-and-non-instance-properties">How do you define instance and non-instance properties</h3>
<p>The Instance properties must be defined inside of class methods. For example, name and age properties defined inside constructor as below,</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, age) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
  }
}
</code></pre>
<p>But Static(class) and prototype data properties must be defined outside of the ClassBody declaration. Let's assign the age value for Person class as below,</p>
<pre><code class="lang-javascript">Person.staticAge = <span class="hljs-number">30</span>;
Person.prototype.prototypeAge = <span class="hljs-number">40</span>;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-isnan-and-numberisnan">What is the difference between isNaN and Number.isNaN?</h3>
<ol>
<li><strong>isNaN</strong>: The global function <code>isNaN</code> converts the argument to a Number and returns true if the resulting value is NaN.</li>
<li><strong>Number.isNaN</strong>: This method does not convert the argument. But it returns true when the type is a Number and value is NaN.</li>
</ol>
<p>Let's see the difference with an example,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">isNaN</span>(‘hello’);   <span class="hljs-comment">// true</span>
<span class="hljs-built_in">Number</span>.isNaN(<span class="hljs-string">'hello'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-invoke-an-iife-without-any-extra-brackets">How to invoke an IIFE without any extra brackets?</h3>
<p>Immediately Invoked Function Expressions(IIFE) requires a pair of parenthesis to wrap the function which contains set of statements.</p>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dt</span>) </span>{
  <span class="hljs-built_in">console</span>.log(dt.toLocaleTimeString());
})(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
</code></pre>
<p>Since both IIFE and void operator discard the result of an expression, you can avoid the extra brackets using <code>void operator</code> for IIFE as below,</p>
<pre><code class="lang-js"><span class="hljs-keyword">void</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">dt</span>) </span>{
  <span class="hljs-built_in">console</span>.log(dt.toLocaleTimeString());
}(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>());
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-is-that-possible-to-use-expressions-in-switch-cases">Is that possible to use expressions in switch cases?</h3>
<p>You might have seen expressions used in switch condition but it is also possible to use for switch cases by assigning true value for the switch condition. Let's see the weather condition based on temperature as an example,</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> weather = (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getWeather</span>(<span class="hljs-params">temp</span>) </span>{
  <span class="hljs-keyword">switch</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">case</span> temp &lt; <span class="hljs-number">0</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"freezing"</span>;
    <span class="hljs-keyword">case</span> temp &lt; <span class="hljs-number">10</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"cold"</span>;
    <span class="hljs-keyword">case</span> temp &lt; <span class="hljs-number">24</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"cool"</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-string">"unknown"</span>;
  }
})(<span class="hljs-number">10</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-easiest-way-to-ignore-promise-errors">What is the easiest way to ignore promise errors?</h3>
<p>The easiest and safest way to ignore promise errors is void that error. This approach is ESLint friendly too.</p>
<pre><code class="lang-js"><span class="hljs-keyword">await</span> promise.catch(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> <span class="hljs-keyword">void</span> e);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-style-the-console-output-using-css">How do style the console output using CSS?</h3>
<p>You can add CSS styling to the console output using the CSS format content specifier %c. The console string message can be appended after the specifier and CSS style in another argument. Let's print the red color text using console.log and CSS specifier as below,</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"%cThis is a red text"</span>, <span class="hljs-string">"color:red"</span>);
</code></pre>
<p>It is also possible to add more styles for the content. For example, the font-size can be modified for the above text</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(
  <span class="hljs-string">"%cThis is a red text with bigger font"</span>,
  <span class="hljs-string">"color:red; font-size:20px"</span>
);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-nullish-coalescing-operator">What is nullish coalescing operator (??)?</h3>
<p>It is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This can be contrasted with the logical OR (||) operator, which returns the right-hand side operand if the left operand is any falsy value, not only null or undefined.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-literal">null</span> ?? <span class="hljs-literal">true</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">false</span> ?? <span class="hljs-literal">true</span>); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">undefined</span> ?? <span class="hljs-literal">true</span>); <span class="hljs-comment">// true</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-group-and-nest-console-output">How do you group and nest console output?</h3>
<p>The <code>console.group()</code> can be used to group related log messages to be able to easily read the logs and use console.groupEnd()to close the group. Along with this, you can also nest groups which allows to output message in hierarchical manner.</p>
<p>For example, if you’re logging a user’s details:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.group(<span class="hljs-string">"User Details"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"name: Sudheer Jonna"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"job: Software Developer"</span>);

<span class="hljs-comment">// Nested Group</span>
<span class="hljs-built_in">console</span>.group(<span class="hljs-string">"Address"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Street: Commonwealth"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"City: Los Angeles"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"State: California"</span>);

<span class="hljs-comment">// Close nested group</span>
<span class="hljs-built_in">console</span>.groupEnd();

<span class="hljs-comment">// Close outer group</span>
<span class="hljs-built_in">console</span>.groupEnd();
</code></pre>
<p>You can also use <code>console.groupCollapsed()</code> instead of <code>console.group()</code> if you want the groups to be collapsed by default.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-dense-and-sparse-arrays">What is the difference between dense and sparse arrays?</h3>
<p>An array contains items at each index starting from first(0) to last(array.length - 1) is called as Dense array. Whereas if at least one item is missing at any index, the array is called as sparse.</p>
<p>Let's see the below two kind of arrays,</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> avengers = [<span class="hljs-string">"Ironman"</span>, <span class="hljs-string">"Hulk"</span>, <span class="hljs-string">"CaptainAmerica"</span>];
<span class="hljs-built_in">console</span>.log(avengers[<span class="hljs-number">0</span>]); <span class="hljs-comment">// 'Ironman'</span>
<span class="hljs-built_in">console</span>.log(avengers[<span class="hljs-number">1</span>]); <span class="hljs-comment">// 'Hulk'</span>
<span class="hljs-built_in">console</span>.log(avengers[<span class="hljs-number">2</span>]); <span class="hljs-comment">// 'CaptainAmerica'</span>
<span class="hljs-built_in">console</span>.log(avengers.length); <span class="hljs-comment">// 3</span>

<span class="hljs-keyword">const</span> justiceLeague = [<span class="hljs-string">"Superman"</span>, <span class="hljs-string">"Aquaman"</span>, , <span class="hljs-string">"Batman"</span>];
<span class="hljs-built_in">console</span>.log(justiceLeague[<span class="hljs-number">0</span>]); <span class="hljs-comment">// 'Superman'</span>
<span class="hljs-built_in">console</span>.log(justiceLeague[<span class="hljs-number">1</span>]); <span class="hljs-comment">// 'Aquaman'</span>
<span class="hljs-built_in">console</span>.log(justiceLeague[<span class="hljs-number">2</span>]); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(justiceLeague[<span class="hljs-number">3</span>]); <span class="hljs-comment">// 'Batman'</span>
<span class="hljs-built_in">console</span>.log(justiceLeague.length); <span class="hljs-comment">// 4</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-ways-to-create-sparse-arrays">What are the different ways to create sparse arrays?</h3>
<p>There are 4 different ways to create sparse arrays in JavaScript</p>
<ol>
<li><strong>Array literal:</strong> Omit a value when using the array literal<pre><code class="lang-js"><span class="hljs-keyword">const</span> justiceLeague = [<span class="hljs-string">"Superman"</span>, <span class="hljs-string">"Aquaman"</span>, , <span class="hljs-string">"Batman"</span>];
<span class="hljs-built_in">console</span>.log(justiceLeague); <span class="hljs-comment">// ['Superman', 'Aquaman', empty ,'Batman']</span>
</code></pre>
</li>
<li><strong>Array() constructor:</strong> Invoking Array(length) or new Array(length)<pre><code class="lang-js"><span class="hljs-keyword">const</span> array = <span class="hljs-built_in">Array</span>(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(array); <span class="hljs-comment">// [empty, empty ,empty]</span>
</code></pre>
</li>
<li><strong>Delete operator:</strong> Using delete array[index] operator on the array<pre><code class="lang-js"><span class="hljs-keyword">const</span> justiceLeague = [<span class="hljs-string">"Superman"</span>, <span class="hljs-string">"Aquaman"</span>, <span class="hljs-string">"Batman"</span>];
<span class="hljs-keyword">delete</span> justiceLeague[<span class="hljs-number">1</span>];
<span class="hljs-built_in">console</span>.log(justiceLeague); <span class="hljs-comment">// ['Superman', empty, ,'Batman']</span>
</code></pre>
</li>
<li><strong>Increase length property:</strong> Increasing length property of an array<pre><code class="lang-js"><span class="hljs-keyword">const</span> justiceLeague = [<span class="hljs-string">"Superman"</span>, <span class="hljs-string">"Aquaman"</span>, <span class="hljs-string">"Batman"</span>];
justiceLeague.length = <span class="hljs-number">5</span>;
<span class="hljs-built_in">console</span>.log(justiceLeague); <span class="hljs-comment">// ['Superman', 'Aquaman', 'Batman', empty, empty]</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-settimeout-setimmediate-and-processnexttick">What is the difference between setTimeout, setImmediate and process.nextTick?</h3>
<ol>
<li><strong>Set Timeout:</strong> setTimeout() is to schedule execution of a one-time callback after delay milliseconds.</li>
<li><strong>Set Immediate:</strong> The setImmediate function is used to execute a function right after the current event loop finishes.</li>
<li><strong>Process NextTick:</strong> If process.nextTick() is called in a given phase, all the callbacks passed to process.nextTick() will be resolved before the event loop continues. This will block the event loop and create I/O Starvation if process.nextTick() is called recursively.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-reverse-an-array-without-modifying-original-array">How do you reverse an array without modifying original array?</h3>
<p>The <code>reverse()</code> method reverses the order of the elements in an array but it mutates the original array. Let's take a simple example to demonistrate this case,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = originalArray.reverse();

<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
<p>There are few solutions that won't mutate the original array. Let's take a look.</p>
<ol>
<li><p><strong>Using slice and reverse methods:</strong>
In this case, just invoke the <code>slice()</code> method on the array to create a shallow copy followed by <code>reverse()</code> method call on the copy.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = originalArray.slice().reverse(); <span class="hljs-comment">//Slice an array gives a new copy</span>

<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
</li>
<li><p><strong>Using spread and reverse methods:</strong>
In this case, let's use the spread syntax (...) to create a copy of the array followed by <code>reverse()</code> method call on the copy.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = [...originalArray].reverse();

<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
</li>
<li><p><strong>Using reduce and spread methods:</strong>
Here execute a reducer function on an array elements and append the accumulated array on right side using spread syntax</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = originalArray.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, value</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> [value, ...accumulator];
}, []);

<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
</li>
<li><p><strong>Using reduceRight and spread methods:</strong>
Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and append the accumulated array on left side using spread syntax</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = originalArray.reduceRight(<span class="hljs-function">(<span class="hljs-params">accumulator, value</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> [...accumulator, value];
}, []);

<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
</li>
<li><p><strong>Using reduceRight and push methods:</strong>
Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and push the iterated value to the accumulator</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> originalArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> newArray = originalArray.reduceRight(<span class="hljs-function">(<span class="hljs-params">accumulator, value</span>) =&gt;</span> {
  accumulator.push(value);
  <span class="hljs-keyword">return</span> accumulator;
}, []);

<span class="hljs-built_in">console</span>.log(originalArray); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// [ 5, 4, 3, 2, 1]</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-custom-html-element">How do you create custom HTML element?</h3>
<p>The creation of custom HTML elements involves two main steps,</p>
<ol>
<li><strong>Define your custom HTML element:</strong> First you need to define some custom class by extending HTMLElement class.
After that define your component properties (styles,text etc) using <code>connectedCallback</code> method.
<strong>Note:</strong> The browser exposes a function called <code>customElements.define</code> inorder to reuse the element.<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomElement</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HTMLElement</span> </span>{
  connectedCallback() {
    <span class="hljs-built_in">this</span>.innerHTML = <span class="hljs-string">"This is a custom element"</span>;
  }
}
customElements.define(<span class="hljs-string">"custom-element"</span>, CustomElement);
</code></pre>
</li>
<li><strong>Use custom element just like other HTML element:</strong> Declare your custom element as a HTML tag.</li>
</ol>
<pre><code class="lang-javascript">   &lt;body&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">custom-element</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span></span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-global-execution-context">What is global execution context?</h3>
<p>The global execution context is the default or first execution context that is created by the JavaScript engine before any code is executed(i.e, when the file first loads in the browser). All the global code that is not inside a function or object will be executed inside this global execution context. Since JS engine is single threaded there will be only one global environment and there will be only one global execution context.</p>
<p>For example, the below code other than code inside any function or object is executed inside the global execution context.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">A</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Start function A"</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">B</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"In function B"</span>);
  }

  B();
}

A();

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"GlobalContext"</span>);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-function-execution-context">What is function execution context?</h3>
<p>Whenever a function is invoked, the JavaScript engine creates a different type of Execution Context known as a Function Execution Context (FEC) within the Global Execution Context (GEC) to evaluate and execute the code within that function.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-debouncing">What is debouncing?</h3>
<p>Debouncing is a programming pattern that allows delaying execution of some piece of code until a specified time to avoid unnecessary <em>CPU cycles and API calls</em>. This in turn enhance the web page performance. The debounce function make sure that your code is only triggered once per user input. The common usecases are Search box suggestions, text-field auto-saves, and eliminating double-button clicks.</p>
<p>Let's say you want to show suggestions for a search query, but only after a visitor has finished typing it. So here you write a debounce function where the user keeps writing the characters with in 500ms then previous timer cleared out using <code>clearTimeout</code> and reschedule API call/DB query for a new time—300 ms in the future.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">debounce</span>(<span class="hljs-params">func, timeout = <span class="hljs-number">500</span></span>) </span>{
  <span class="hljs-keyword">let</span> timer;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">...args</span>)  </span>{
    <span class="hljs-built_in">clearTimeout</span>(timer);
    timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      func.apply(<span class="hljs-built_in">this</span>, args);
    }, timeout);
  };
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchResults</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Fetching input suggestions"</span>);
}
<span class="hljs-keyword">const</span> processChange = debounce(<span class="hljs-function">() =&gt;</span> fetchResults());
</code></pre>
<p>The <em>debounce()</em> function can be used on input, button and window events.</p>
<p><strong>Input:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">onkeyup</span>=<span class="hljs-string">"processChange()"</span> /&gt;</span>
</code></pre>
<p><strong>Button:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"processChange()"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p><strong>Windows event:</strong></p>
<pre><code class="lang-html">window.addEventListener("scroll", processChange);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-throttling">What is throttling?</h3>
<p>Throttling is a technique used to limit the execution of an event handler function in a given period of time, even when this event triggers continuously due to user actions. The common use cases are browser resizing, window scrolling, mouse movements etc.</p>
<p>The below example creates a throttle function to reduce the number of events for each pixel change and trigger scroll event for each 100ms except for the first event.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> throttle = <span class="hljs-function">(<span class="hljs-params">func, limit</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> inThrottle;
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!inThrottle) {
      func.apply(<span class="hljs-built_in">this</span>, args);
      inThrottle = <span class="hljs-literal">true</span>;
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> (inThrottle = <span class="hljs-literal">false</span>), limit);
    }
  };
};
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"scroll"</span>, <span class="hljs-function">() =&gt;</span> {
  throttle(handleScrollAnimation, <span class="hljs-number">100</span>);
});
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-optional-chaining">What is optional chaining?</h3>
<p>According to MDN official docs, the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.</p>
<p>The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> adventurer = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>,
  <span class="hljs-attr">cat</span>: {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Dinah"</span>,
  },
};

<span class="hljs-keyword">const</span> dogName = adventurer.dog?.name;
<span class="hljs-built_in">console</span>.log(dogName);
<span class="hljs-comment">// expected output: undefined</span>

<span class="hljs-built_in">console</span>.log(adventurer.someNonExistentMethod?.());
<span class="hljs-comment">// expected output: undefined</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-an-environment-record">What is an environment record?</h3>
<p>According to ECMAScript specification 262 (9.1):</p>
<blockquote>
<p><a target="_blank" href="https://262.ecma-international.org/12.0/#sec-environment-records">Environment Record</a> is a specification type used to define the association of Identifiers to specific variables and functions, based upon the lexical nesting structure of ECMAScript code.</p>
</blockquote>
<p>Usually an Environment Record is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement.</p>
<p>Each time such code is evaluated, a new Environment Record is created to record the identifier bindings that are created by that code.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-verify-if-a-variable-is-an-array">How to verify if a variable is an array?</h3>
<p>It is possible to check if a variable is an array instance using 3 different ways,</p>
<ol>
<li><p>Array.isArray() method:</p>
<p>The <code>Array.isArray(value)</code> utility function is used to determine whether value is an array or not. This function returns a true boolean value if the variable is an array and a false value if it is not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span> };
<span class="hljs-built_in">Array</span>.isArray(numbers); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">Array</span>.isArray(user); <span class="hljs-comment">//false</span>
</code></pre>
</li>
<li><p>instanceof operator:</p>
<p>The instanceof operator is used to check the type of an array at run time. It returns true if the type of a variable is an Array other false for other type.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span> };
<span class="hljs-built_in">console</span>.log(numbers <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Array</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(user <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Array</span>); <span class="hljs-comment">// false</span>
</code></pre>
</li>
<li><p>Checking constructor type:</p>
<p>The constructor property of the variable is used to determine whether the variable Array type or not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span> };
<span class="hljs-built_in">console</span>.log(numbers.constructor === <span class="hljs-built_in">Array</span>); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(user.constructor === <span class="hljs-built_in">Array</span>); <span class="hljs-comment">// false</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-pass-by-value-and-pass-by-reference">What is pass by value and pass by reference?</h3>
<p>Pass-by-value creates a new space in memory and makes a copy of a value. Primitives such as string, number, boolean etc will actually create a new copy. Hence, updating one value doesn't impact the other value. i.e, The values are independent of each other.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> b = a;

b++;
<span class="hljs-built_in">console</span>.log(a, b); <span class="hljs-comment">//5, 6</span>
</code></pre>
<p>In the above code snippet, the value of <code>a</code> is assigned to <code>b</code> and the variable <code>b</code> has been incremented. Since there is a new space created for variable <code>b</code>, any update on this variable doesn't impact the variable <code>a</code>.</p>
<p>Pass by reference doesn't create a new space in memory but the new variable adopts a memory address of an initial variable. Non-primitives such as objects, arrays and functions gets the reference of the initiable variable. i.e, updating one value will impact the other variable.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user1 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">27</span>,
};
<span class="hljs-keyword">let</span> user2 = user1;
user2.age = <span class="hljs-number">30</span>;

<span class="hljs-built_in">console</span>.log(user1.age, user2.age); <span class="hljs-comment">// 30, 30</span>
</code></pre>
<p>In the above code snippet, updating the <code>age</code> property of one object will impact the other property due to the same reference.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-primitives-and-non-primitives">What are the differences between primitives and non-primitives?</h3>
<p>JavaScript language has both primitives and non-primitives but there are few differences between them as below,</p>
<p>| Primitives                 | Non-primitives       |
| -------------------------- | -------------------- |
| These types are predefined | Created by developer |
| These are immutable        | Mutable              |
| Compare by value           | Compare by reference |
| Stored in Stack            | Stored in heap       |
| Contain certain value      | Can contain NULL too |</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-do-you-create-your-own-bind-method-using-either-call-or-apply-method">How do you create your own bind method using either call or apply method?</h3>
<p>The custom bind function needs to be created on Function prototype inorder to use it as other builtin functions. This custom function should return a function similar to original bind method and the implementation of inner function needs to use apply method call.</p>
<p>The function which is going to bind using custom <code>myOwnBind</code> method act as the attached function(<code>boundTargetFunction</code>) and argument as the object for <code>apply</code> method call.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Function</span>.prototype.myOwnBind = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">whoIsCallingMe</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">this</span> !== <span class="hljs-string">"function"</span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-built_in">this</span> + <span class="hljs-string">"cannot be bound as it's not callable"</span>);
  }
  <span class="hljs-keyword">const</span> boundTargetFunction = <span class="hljs-built_in">this</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    boundTargetFunction.apply(whoIsCallingMe, <span class="hljs-built_in">arguments</span>);
  };
};
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-differences-between-pure-and-impure-functions">What are the differences between pure and impure functions?</h3>
<p>Some of the major differences between pure and impure function are as below,</p>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pure function</td><td>Impure function</td></tr>
</thead>
<tbody>
<tr>
<td>It has no side effects</td><td>It causes side effects</td></tr>
<tr>
<td>It is always return the same result</td><td>It returns different result on each call</td></tr>
<tr>
<td>Easy to read and debug</td><td>Difficult to read and debug because they are affected by external code</td></tr>
</tbody>
</table>
</div><p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="443">
<li><h3 id="heading-what-is-referential-transparency">What is referential transparency?</h3>
</li>
</ol>
<p>An expression in javascript that can be replaced by its value without affecting the behaviour of the program is called referential transparency. Pure functions are referentially transparent.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y;
<span class="hljs-keyword">const</span> multiplyBy2 = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * <span class="hljs-number">2</span>;

<span class="hljs-comment">//Now add (2, 3) can be replaced by 5.</span>

multiplyBy2(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="444">
<li><h3 id="heading-what-are-the-possible-side-effects-in-javascript">What are the possible side-effects in javascript?</h3>
<p>A side effect is the modification of the state through the invocation of a function or expression. These side effects make our function impure by default. Below are some side effects which make function impure,</p>
</li>
<li><p>Making an HTTP request. Asynchronous functions such as fetch and promise are impure.</p>
</li>
<li>DOM manipulations</li>
<li>Mutating the input data</li>
<li>Printing to a screen or console: For example, console.log() and alert()</li>
<li>Fetching the current time</li>
<li>Math.random() calls: Modifies the internal state of Math object</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="445">
<li><h3 id="heading-what-are-compose-and-pipe-functions">What are compose and pipe functions?</h3>
<p>The "compose" and "pipe" are two techniques commonly used in functional programming to simplify complex operations and make code more readable. They are not native to JavaScript and higher-order functions. the <code>compose()</code> applies right to left any number of functions to the output of the previous function.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-module-pattern">What is module pattern?</h3>
<p>Module pattern is a designed pattern used to wrap a set of variables and functions together in a single scope returned as an object. JavaScript doesn't have access specifiers similar to other languages(Java, Python, etc) to provide private scope. It uses IIFE (Immediately invoked function expression) to allow for private scopes. i.e., a closure that protect variables and methods.</p>
<p>The module pattern looks like below,</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Private variables or functions goes here.</span>

  <span class="hljs-keyword">return</span> {
    <span class="hljs-comment">// Return public variables or functions here.</span>
  };
})();
</code></pre>
<p>Let's see an example of a module pattern for an employee with private and public access,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> createEmployee = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Private</span>
  <span class="hljs-keyword">const</span> name = <span class="hljs-string">"John"</span>;
  <span class="hljs-keyword">const</span> department = <span class="hljs-string">"Sales"</span>;
  <span class="hljs-keyword">const</span> getEmployeeName = <span class="hljs-function">() =&gt;</span> name;
  <span class="hljs-keyword">const</span> getDepartmentName = <span class="hljs-function">() =&gt;</span> department;

  <span class="hljs-comment">// Public</span>
  <span class="hljs-keyword">return</span> {
    name,
    department,
    <span class="hljs-attr">getName</span>: <span class="hljs-function">() =&gt;</span> getEmployeeName(),
    <span class="hljs-attr">getDepartment</span>: <span class="hljs-function">() =&gt;</span> getDepartmentName(),
  };
})();

<span class="hljs-built_in">console</span>.log(createEmployee.name);
<span class="hljs-built_in">console</span>.log(createEmployee.department);
<span class="hljs-built_in">console</span>.log(createEmployee.getName());
<span class="hljs-built_in">console</span>.log(createEmployee.getDepartment());
</code></pre>
<p><strong>Note:</strong> It mimic the concepts of classes with private variables and methods.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-function-composition">What is Function Composition?</h3>
<p>It is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//example</span>
<span class="hljs-keyword">const</span> double = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * <span class="hljs-number">2</span>;
<span class="hljs-keyword">const</span> square = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> x * x;

<span class="hljs-keyword">var</span> output1 = double(<span class="hljs-number">2</span>);
<span class="hljs-keyword">var</span> output2 = square(output1);
<span class="hljs-built_in">console</span>.log(output2);

<span class="hljs-keyword">var</span> output_final = square(double(<span class="hljs-number">2</span>));
<span class="hljs-built_in">console</span>.log(output_final);
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-use-await-outside-of-async-function-prior-to-es2022">How to use await outside of async function prior to ES2022?</h3>
<p>Prior to ES2022, if you attempted to use an await outside of an async function resulted in a SyntaxError.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello await"</span>)); <span class="hljs-comment">// SyntaxError: await is only valid in async function</span>
</code></pre>
<p>But you can fix this issue with an alternative IIFE (Immediately Invoked Function Expression) to get access to the feature.</p>
<pre><code class="lang-javascript">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello await"</span>)); <span class="hljs-comment">// Hello await</span>
})();
</code></pre>
<p>In ES2022, you can write top-level await without writing any hacks.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello await"</span>)); <span class="hljs-comment">//Hello await</span>
</code></pre>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="449">
<li><h3 id="heading-what-is-the-purpose-of-the-this-keyword-in-javascript">What is the purpose of the this keyword in JavaScript?</h3>
</li>
<li>The <code>this</code> keyword in JavaScript is a special variable that is used within a function to refer to the object on which the function is invoked. The value of this depends on how the function is called. It allows functions to access and interact with the object they are bound to.</li>
<li><p>The this keyword in JavaScript is a reference to the object that owns or invokes the current function. Its value is determined by the calling context.</p>
<p><strong>Example 1: this in a Global Context</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
</code></pre>
<ul>
<li>In a global context, this refers to the global object (e.g., window in a browser).</li>
</ul>
<p><strong>Example 2: this in a Function</strong></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayThis</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}

displayThis();
</code></pre>
<ul>
<li>In a regular function, this refers to the global object.</li>
</ul>
<p><strong>Example 3: this in a Method</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
  <span class="hljs-attr">greet</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, '</span> + <span class="hljs-built_in">this</span>.name);
  }
};

person.greet();
</code></pre>
<ul>
<li>In a method, this refers to the object that owns the method (person in the case).</li>
</ul>
<p><strong>Example 4: this in an Event Handler</strong></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myButton'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
});
</code></pre>
<ul>
<li>In an event handler, this refers to the element that triggered the event (the button in this case).</li>
</ul>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="450">
<li><h3 id="heading-what-are-the-uses-of-closures">What are the uses of closures?</h3>
<p>Closures are a powerful feature in programming languages like JavaScript. They allow functions to retain access to variables from their containing (enclosing) scope even after the outer function has finished executing. This means that a function defined within another function can access variables from the outer function, even if the outer function has already returned.
Here are some common use cases of closures:</p>
</li>
<li><p>Data Privacy: Closures can be used to create private variables and methods. By defining variables within a function's scope and returning inner functions that have access to those variables, you can create     a form of encapsulation, limiting access to certain data or functionality.</p>
</li>
<li><p>Function Factories: Closures are often used to create functions with pre-set parameters. This is useful when you need to create multiple functions with similar behavior but different configurations.</p>
</li>
<li><p>Callback Functions: Closures are frequently used in asynchronous programming, such as handling event listeners or AJAX requests. The inner function captures variables from the outer scope and can access        them when the callback is invoked.</p>
</li>
<li><p>Memoization: Closures can be used for memoization, a technique to optimize performance by caching the results of expensive function calls. The inner function can remember the results of previous calls and      return the cached result if the same input is provided again.</p>
</li>
<li><p>iterators and Generators: Closures can be used to create iterators and generators, which are essential for working with collections of data in modern JavaScript.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="451">
<li><h3 id="heading-what-are-the-phases-of-execution-context">What are the phases of execution context?</h3>
The execution context in JavaScript is a data structure that stores the information necessary for executing a piece of code. It includes the code itself, the values of the variables used in the code, and the scope chain. The scope chain is a list of objects that are used to resolve variable names.</li>
</ol>
<p>The execution context has two phases:</p>
<ul>
<li>Creation phase: In this phase, the JavaScript engine creates the execution context and sets up the script's environment. This includes creating the variable object and the scope chain.</li>
<li>Execution phase: In this phase, the JavaScript engine executes the code in the execution context. This includes evaluating expressions, assigning values to variables, and calling functions.</li>
</ul>
<p>The execution context is created when a function is called. The function's code is then executed in the execution context. When the function returns, the execution context is destroyed.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="452">
<li><h3 id="heading-what-are-the-possible-reasons-for-memory-leaks">What are the possible reasons for memory leaks?</h3>
<p>Memory leaks can lead to poor performance, slow loading times and even crashes in web applications. Some of the common causes of memory leaks are listed below,</p>
<ol>
<li>The execessive usage of global variables or omitting the <code>var</code> keyword in local scope.</li>
<li>Forgetting to clear the timers set up by <code>setTimeout</code> or <code>setInterval</code>.</li>
<li>Closures retain references to variables from their parent scope, which leads to variables might not garbage collected even they are no longer used.</li>
</ol>
</li>
<li><h3 id="heading-what-are-the-optimization-techniques-of-v8-engine">What are the optimization techniques of V8 engine?</h3>
<p>V8 engine uses the below optimization techniques.</p>
<ol>
<li><strong>Inline expansion:</strong> It is a compiler optimization by replacing the function calls with the corresponding function blocks.</li>
<li><strong>Copy elision:</strong> This is a compiler optimization method to prevent expensive extra objects from being duplicated or copied.</li>
<li><strong>Inline caching:</strong> It is a runtime optimization technique where it caches the execution of older tasks those can be lookup while executing the same task in the future. </li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-examples-of-built-in-higher-order-functions">What are the examples of built-in higher order functions?</h3>
<p>There are several built-in higher order functions exists on arrays, strings, DOM and promise methods in javascript. These higher order functions provides significant level of abstraction. The list of functions on these categories are listed below,</p>
<ol>
<li><strong>arrays:</strong> map, filter, reduce, sort, forEach, some etc.</li>
<li><strong>DOM</strong>: The DOM method <code>element.addEventListener(type, handler)</code> also accepts the function handler as a second argument.</li>
<li><strong>Strings:</strong> replace() method.</li>
</ol>
</li>
</ol>
<p>     <strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="455">
<li><h3 id="heading-what-are-the-benefits-higher-order-functions">What are the benefits higher order functions?</h3>
The main benefits of higher order functions are:<ol>
<li>Abstraction</li>
<li>Reusability</li>
<li>Immutability</li>
<li>Modularity</li>
</ol>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="456">
<li><h3 id="heading-how-do-you-create-polyfills-for-map-filter-and-reduce-methods">How do you create polyfills for map, filter and reduce methods?</h3>
<p>The polyfills for array methods such as map, filter and reduce methods can be created using array prototype. </p>
<ol>
<li><strong>map:</strong></li>
</ol>
<p>The built-in <code>Array.map</code> method syntax will be helpful to write polyfill. The map method takes the callback function as an argument and that callback function can have below three arguments passed into it.</p>
<p> i. Current value
 ii. Index of current value(optional)
 iii. array(optional)</p>
<p>The syntax would like below,</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> newArray = arr.map(callback(currentValue[, index, arr) {
  <span class="hljs-comment">// return new array after executing the code</span>
})
</code></pre>
<p>Let's build our map polyfill based on the above syntax, </p>
<pre><code class="lang-js"> <span class="hljs-built_in">Array</span>.prototype.myMap = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">cb</span>) </span>{
   <span class="hljs-keyword">let</span> newArr = [];
   <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt; <span class="hljs-built_in">this</span>.length; i++) {
     newArr.push(cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>));
   }
   <span class="hljs-keyword">return</span> newArr;
 };

 <span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
 <span class="hljs-keyword">const</span> multiplyByTwo = nums.myMap(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * <span class="hljs-number">2</span>);
 <span class="hljs-built_in">console</span>.log(multiplyByTwo); <span class="hljs-comment">// [2, 4, 6, 8, 10]</span>
</code></pre>
<p>In the above code, custom method name 'myMap' has been used to avoid conflicts with built-in method.</p>
<ol start="2">
<li><p><strong>filter:</strong> 
Similar to map method, <code>Array.filter</code> method takes callback function as an argument and the callback function can have three agurguments passed into it.</p>
<p>  i. Current value
  ii. Index of current value(optional)
  iii. array(optional)</p>
<p>The syntax looks like below,</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> newArray = arr.filter(callback(currentValue[, index, arr) {
<span class="hljs-comment">// return new array whose elements satisfy the callback conditions</span>
})
</code></pre>
<p>Let's build our filter polyfill based on the above syntax, </p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.myFilter = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">cb</span>) </span>{
<span class="hljs-keyword">let</span> newArr = [];
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt; <span class="hljs-built_in">this</span>.length; i++) {
   <span class="hljs-keyword">if</span>(cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>)) {
     newArr.push(<span class="hljs-built_in">this</span>[i]);
   }
}
<span class="hljs-keyword">return</span> newArr;
}

<span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">const</span> evenNums = nums.myFilter(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x % <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(evenNums); <span class="hljs-comment">// [2, 4, 6]</span>
</code></pre>
</li>
<li><p><strong>reduce:</strong></p>
<p>The built-in <code>Array.reduce</code> method syntax will be helpful to write our own polyfill. The reduce method takes the callback function as first argument and the initial value as second argument.</p>
<p>The callback function can have four arguments passed into it.
i. Accumulator
ii. Current value
iii. Index of current value(optional)
iv. array(optional)</p>
</li>
</ol>
<p>The syntax would like below,</p>
<pre><code class="lang-js">arr.reduce(callback(<span class="hljs-function">(<span class="hljs-params">acc, curr, i, arr</span>) =&gt;</span> {}), initValue);
</code></pre>
<p>Let's build our reduce polyfill based on the above syntax, </p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.myReduce = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">cb, initialValue</span>) </span>{
   <span class="hljs-keyword">let</span> accumulator = initialValue;
   <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt; <span class="hljs-built_in">this</span>.length; i++) {
       accumulator = accumulator ? cb(accumulator, <span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>) : <span class="hljs-built_in">this</span>[i];
   }
   <span class="hljs-keyword">return</span> accumulator;
}
 <span class="hljs-keyword">const</span> nums = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
 <span class="hljs-keyword">const</span> sum = nums.myReduce(<span class="hljs-function">(<span class="hljs-params">acc, curr, i, arr</span>) =&gt;</span> {
   <span class="hljs-keyword">return</span> acc += curr
 }, <span class="hljs-number">0</span>);
 <span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// 21</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-difference-between-map-and-foreach-functions">What is the difference between map and forEach functions?</h3>
<p>Both map and forEach functions are used to iterate over an arrays but there are some differences in their functionality.</p>
<ol>
<li><p><strong>Returning values:</strong> The <code>map</code> method returns a new array with transformed elements whereas <code>forEach</code> method returns <code>undefined</code> eventhough both of them are doing the same job.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
arr.map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * x); <span class="hljs-comment">// [1, 4, 9, 16, 25]</span>
arr.forEach(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * x); <span class="hljs-comment">// </span>

The <span class="hljs-string">`forEach()`</span> method <span class="hljs-keyword">in</span> JavaScript always returns <span class="hljs-literal">undefined</span>. This is because forEach() is used to iterate over arrays and perform side effects on each element, rather than returning a <span class="hljs-string">`new array or transforming the original array`</span>
</code></pre>
</li>
<li><p><strong>Chaining methods:</strong> The <code>map</code> method is chainable. i.e, It can be attached with <code>reduce</code>, <code>filter</code>, <code>sort</code> and other methods as well. Whereas <code>forEach</code> cannot be attached with any other methods because it returns <code>undefined</code> value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
arr.map(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * x).reduce(<span class="hljs-function">(<span class="hljs-params">total, cur</span>) =&gt;</span> total + cur); <span class="hljs-comment">// 55</span>
arr.forEach(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x * x).reduce(<span class="hljs-function">(<span class="hljs-params">total, cur</span>) =&gt;</span> total + cur);; <span class="hljs-comment">//Uncaught TypeError: Cannot read properties of undefine(reading 'reduce')</span>
</code></pre>
</li>
<li><strong>Mutation:</strong> The <code>map</code> method doesn't mutate the original array by returning new array. Whereas <code>forEach</code> method also doesn't mutate the original array but it's callback is allowed to mutate the original array.</li>
</ol>
<p><strong>Note:</strong> Both these methods existed since ES5 onwards.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="458">
<li><h3 id="heading-give-an-example-of-statements-affected-by-automatic-semicolon-insertion">Give an example of statements affected by automatic semicolon insertion?</h3>
<p>The javascript parser will automatically add a semicolon while parsing the source code. For example, the below common statements affected by Automatic Semicolon Insertion(ASI).</p>
<ol>
<li>An empty statement</li>
<li>var statement</li>
<li>An expression statement</li>
<li>do-while statement</li>
<li>continue statement</li>
<li>break statement</li>
<li>return statement</li>
<li>throw statement</li>
</ol>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="459">
<li><h3 id="heading-what-are-the-event-phases-of-a-browser">What are the event phases of a browser?</h3>
<p>There are 3 phases in the lifecycle of an event propagation in JavaScript,</p>
<ol>
<li><p><strong>Capturing phase:</strong> This phase goes down gradually from the top of the DOM tree to the target element when a nested element clicked. Before the click event reaching the final destination element, the click event of each parent's element must be triggered.</p>
</li>
<li><p><strong>Target phase:</strong> This is the phase where the event originally occurred reached the target element .</p>
</li>
<li><p><strong>Bubbling phase:</strong> This is reverse of the capturing phase. In this pase, the event bubbles up from the target element through it's parent element, an ancestor and goes all the way to the global window object.</p>
</li>
</ol>
<p>The pictorial representation of these 3 event phases in DOM looks like below,</p>
<p><img src="images/event-flow.png" alt="Screenshot" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-real-world-use-cases-of-proxy">What are the real world use cases of proxy?</h3>
<p>Proxies are not used in regular day to day JavaScript work but they enabled many exciting programming patterns. Some of the real world use cases are listed below,</p>
<ol>
<li>Vue3 used proxy concept to implement reactive state </li>
<li>SolidJS implemented reactive stores </li>
<li>Immerjs built upon proxy to track updates to immutable updates</li>
<li>ZenStack improved Prisma ORM for access control layer</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-hidden-classes">What are hidden classes?</h3>
<p>Since JavaScript is a dynamic programming language, you can add or remove properties and methods from objects on the fly at runtime. This nature of JavaScript increases the dynamic dictionary lookups(because objects implemented as HashTables in memory) for retrieving a property on an object. </p>
<p>Let's consider the following example to see how the additional properties <code>age</code> and <code>gender</code> added at runtime.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
   <span class="hljs-built_in">this</span>.name = name;
 }

 <span class="hljs-keyword">var</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'John'</span>);
 <span class="hljs-keyword">var</span> person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Randy'</span>);

 person1.age = <span class="hljs-number">40</span>;
 person1.gender = <span class="hljs-string">"Male"</span>;

 person2.gender = <span class="hljs-string">"Female"</span>;
 person2.age = <span class="hljs-number">50</span>;
</code></pre>
<p>As a result, this behavior leads to lower JavaScript performance compared to the contiguous buffer method used in non-dynamic languages. The V8 engine provided a solution named <strong>hidden classes</strong> to optimize the access time when retrieving a property on an object. This optimization is achieved by sharing hidden classes among objects created in a similar fashion. These hidden classes are attached to each and every object to track its shape.</p>
<p>When V8 engine sees the constructor function(e.g, Person) is declared, it creates a hidden class (let's say Class01) without any offsets. Once the first property assignment statement (<code>this.name = name</code>) is executed, V8 engine will create a new hidden class (let's say Class02), inheriting all properties from the previous hidden class (Class01), and assign the property to offset 0. This process enables compiler to skip dictionary lookup when you try to retrieve the same property(i.e, name). Instead, V8 will directly point to Class02. The same procedure happens when you add new properties to the object. </p>
<p>For example, adding <code>age</code> and <code>gender</code> properties to <code>Person</code> constructor leads to transition of hidden classes(Class02 -&gt; Class03 -&gt; Class04). If you create a second object(Person2) based on the same Person object, both Class01 and Class02 hidden classes are going to be shared. However, the hidden classes Class03 and Class04 cannot be shared because second object has been modified with a different order of properties assignment. </p>
<p>Since both the objects(person1 and person2) do not share the hidden classes, now V8 engine cannot use <strong>Inline Caching</strong> technique for the faster access of properties. </p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-inline-caching">What is inline caching?</h3>
<p>Inline caching is an optimization technique based on the observation that repeated calls to same function tends to occur on same type of objects. The V8 compiler stores a cache of the type of objects that were passed as a parameter in recent method calls. Upon next time when same function is called, compiler can directly search for the type in cache.</p>
<p>Let's consider an example where the compiler stores the shape type in cache for repeated calls in the loop.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> shape = {<span class="hljs-attr">width</span> : <span class="hljs-number">30</span>,  <span class="hljs-attr">height</span>: <span class="hljs-number">20</span>}; <span class="hljs-comment">// Compiler store the type in cache as { width: &lt;int&gt;, height: &lt;int&gt;} after repeated calls</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">area</span>(<span class="hljs-params">obj</span>) </span>{
 <span class="hljs-comment">//Calculate area</span>
}
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i=<span class="hljs-number">0</span>; i&lt;<span class="hljs-number">100</span>; i++) {
 area(shape);
}
</code></pre>
<p>After few successful calls of the same area method to its same hidden class, V8 engine omits the hidden class lookup and simply adds the offset of the property to the object pointer itself. As a result, it increases the execution speed.</p>
<p>There are mainly 3 types of inline caching possible:</p>
<ol>
<li>Monomorphic: This is a optimized caching technique in which there can be always same type of objects passed.</li>
<li>Polymorphic: This ia slightly optimized  caching technique in which limited number of different types of objects can be passed.</li>
<li>Megamorphic: It is an unoptimized caching in which any number of different objects can be passed.</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-are-the-different-ways-to-execute-external-scripts">What are the different ways to execute external scripts?</h3>
<p>  There are three different ways to execute external scripts,</p>
<ol>
<li><p>async: The script is downloaded in parallel to parsing the page, and executed as soon as it is available even before parsing completes. The parsing of the page is going to be interuppted once the script is downloaded completely and then the script is executed. Thereafter, the parsing of the remaining page will continue.</p>
<p>The syntax for async usage is as shown below,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"demo.js"</span> <span class="hljs-attr">async</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
</li>
<li><p>defer: The script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.</p>
<p>The syntax for defer usage is as shown below,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"demo.js"</span> <span class="hljs-attr">defer</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
</li>
<li><p>Neither async or defer: The script is downloaded and executed immediately by blocking parsing of the page until the script execution is completed.</p>
<p><strong>Note:</strong> You should only use either async or defer attribute if the <code>src</code> attribute is present.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
</ol>
</li>
<li><h3 id="heading-what-is-lexical-scope">What is Lexical Scope?</h3>
<p>   Lexical scope is the ability for a function scope to access variables from the parent scope.</p>
<pre><code class="lang-js"> &lt;script&gt;
         <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">x</span>(<span class="hljs-params"></span>)</span>{
           <span class="hljs-keyword">var</span> a=<span class="hljs-number">10</span>;
           <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">y</span>(<span class="hljs-params"></span>)</span>{
               <span class="hljs-built_in">console</span>.log(a); <span class="hljs-comment">// will print a , because of lexical scope, it will first look 'a' in </span>
           <span class="hljs-comment">//its local memory space and then in its parent functions memory space</span>
           }
           y();
       }
       x();
 &lt;/script&gt;
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-how-to-detect-system-dark-mode-in-javascript">How to detect system dark mode in javascript?</h3>
<p> The combination of <code>Window.matchMedia()</code> utility method along with media query is used to check if the user has selected a dark color scheme in their operating system settings or not. The CSS media query <code>prefers-color-scheme</code> needs to be passed to identify system color theme.</p>
<p> The following javascript code describes the usage,</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> hasDarkColorScheme = <span class="hljs-function">() =&gt;</span>
     <span class="hljs-built_in">window</span>.matchMedia &amp;&amp;
     <span class="hljs-built_in">window</span>.matchMedia(<span class="hljs-string">'(prefers-color-scheme: dark)'</span>).matches;
</code></pre>
<p> You can also watch changes to system color scheme using <code>addEventListener</code>,</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">window</span>
 .matchMedia(<span class="hljs-string">"(prefers-color-scheme: dark)"</span>)
 .addEventListener(<span class="hljs-string">"change"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
     <span class="hljs-keyword">const</span> theme = event.matches ? <span class="hljs-string">"dark"</span> : <span class="hljs-string">"light"</span>;
 });
</code></pre>
<p> <strong>Note:</strong> The matchMedia method returns <strong>MediaQueryList</strong> object stores information from a media query.</p>
<p> <strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
</li>
<li><h3 id="heading-what-is-the-purpose-of-requestanimationframe-method">What is the purpose of requestAnimationFrame method?</h3>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="467">
<li><h3 id="heading-what-is-the-difference-between-substring-and-substr-methods">What is the difference between substring and substr methods?</h3>
<p>There are subtle differences between the substring() and substr() methods, so you should be careful not to get them confused.</p>
</li>
<li><p>The two parameters of substr() are start and length, while for substring(), they are start and end.</p>
</li>
<li>substr()'s start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0.</li>
<li>Negative lengths in substr() are treated as zero, while substring() will swap the two indexes if end is less than start.</li>
</ol>
<p>Furthermore, substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> text = <span class="hljs-string">"Mozilla"</span>;
<span class="hljs-built_in">console</span>.log(text.substring(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">// "zil"</span>
<span class="hljs-built_in">console</span>.log(text.substr(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// "zil"</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="468">
<li><h3 id="heading-how-to-find-the-number-of-parameters-expected-by-a-function">How to find the number of parameters expected by a function?</h3>
<p>The function's object has a <strong>length</strong> property which tells you how many formal parameters expected by a function. This is a static value defined by the function, not the number of arguments the function is called with(<strong>arguments.length</strong>). The basic usage of length propery is,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
<span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b, c</span>) </span>{
<span class="hljs-keyword">return</span> a + b +c;
}

<span class="hljs-built_in">console</span>.log(multiply.length); <span class="hljs-comment">//2</span>
<span class="hljs-built_in">console</span>.log(sum.length); <span class="hljs-comment">//3</span>
</code></pre>
<p>But there are few important rules which needs to be noted while using length property.</p>
<ol>
<li><strong>Default values:</strong> Only the parameters which exists before a default value are considered.<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b=<span class="hljs-number">2</span>, c=<span class="hljs-number">3</span></span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}
<span class="hljs-built_in">console</span>.log(sum.length); <span class="hljs-comment">// 1</span>
</code></pre>
</li>
<li><strong>Rest params:</strong> The rest parameters are excluded with in length property.<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b, ...moreArgs</span>) </span>{
  <span class="hljs-keyword">let</span> total = a + b;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> arg <span class="hljs-keyword">of</span> moreArgs) {
    total += arg;
  }
  <span class="hljs-keyword">return</span> total;
}
<span class="hljs-built_in">console</span>.log(sum.length); <span class="hljs-comment">// 2</span>
</code></pre>
</li>
<li><p><strong>Destructuring patterns:</strong> Each destructuring pattern counted as a single parameter.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params">[a, b], {x, y}</span>)</span>{
<span class="hljs-built_in">console</span>.log(a+b, x, y);
}

<span class="hljs-built_in">console</span>.log(func.length); <span class="hljs-comment">// 2</span>
</code></pre>
</li>
</ol>
<p><strong>Note:</strong> The Function constructor is itself a function object and it has a length property of 1.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="469">
<li><h3 id="heading-what-is-globalthis-and-what-is-the-importance-of-it">What is globalThis, and what is the importance of it?</h3>
<p>Nowadays JavaScript language is used in a wide variety of environments and each environment has its own object model. Due to this fact, there are different ways(syntax) to access the global object.</p>
<ol>
<li>In web browser, the global object is accessible via <code>window</code>, <code>self</code>, or <code>frames</code>.</li>
<li>In Node environment, you have to use <code>global</code>.</li>
<li>In Web workers, the global object is available through <code>self</code>.</li>
</ol>
</li>
</ol>
<p>The <code>globalThis</code> property provides a standard way of accessing the global object without writing various code snippet to support multiple environments. For example, the global object retuned from multiple environments as shown below,</p>
<pre><code class="lang-javascript">   <span class="hljs-comment">//1. browser environment</span>
   <span class="hljs-built_in">console</span>.log(globalThis);    <span class="hljs-comment">// =&gt; Window {...}</span>

   <span class="hljs-comment">//2. node.js environment</span>
   <span class="hljs-built_in">console</span>.log(globalThis);    <span class="hljs-comment">// =&gt; Object [global] {...}</span>

   <span class="hljs-comment">//3. web worker environment</span>
   <span class="hljs-built_in">console</span>.log(globalThis);    <span class="hljs-comment">// =&gt; DedicatedWorkerGlobalScope {...}</span>
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<ol start="470">
<li><h3 id="heading-what-are-the-array-mutation-methods">What are the array mutation methods?</h3>
<p>JavaScript array methods can be categorized into two groups: </p>
<ol>
<li>Mutating methods: These are the methods that directly modify the original array.</li>
<li>Non-mutating methods: These methods return a new array without altering the original one.</li>
</ol>
<p>There are 9 methods in total that mutate the arrays,</p>
<ol>
<li><strong>push:</strong> Adds one or more elements to the end of the array and returns the new length.</li>
<li><strong>pop:</strong>  Removes the last element from the array and returns that element.</li>
<li><strong>unshift:</strong>  Adds one or more elements to the beginning of the array and returns the new length..</li>
<li><strong>shift:</strong> Removes the first element from the array and returns that element.</li>
<li><strong>splice:</strong> Adds or removes elements from the array at a specific index position.</li>
<li><strong>sort:</strong> Sorts the elements of the array in-place based on a given sorting criteria.</li>
<li><strong>reverse:</strong> Reverses the order of elements in the given array.</li>
<li><strong>fill:</strong>  Fills all elements of the array with a specific value.</li>
<li><strong>copyWithIn:</strong> Copies a sequence of elements within the array to a specified target index in the same array.</li>
</ol>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>

<h3 id="heading-coding-exercise">Coding Exercise</h3>
<h4 id="heading-1-what-is-the-output-of-below-code">1. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> car = <span class="hljs-keyword">new</span> Vehicle(<span class="hljs-string">"Honda"</span>, <span class="hljs-string">"white"</span>, <span class="hljs-string">"2010"</span>, <span class="hljs-string">"UK"</span>);
<span class="hljs-built_in">console</span>.log(car);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Vehicle</span>(<span class="hljs-params">model, color, year, country</span>) </span>{
  <span class="hljs-built_in">this</span>.model = model;
  <span class="hljs-built_in">this</span>.color = color;
  <span class="hljs-built_in">this</span>.year = year;
  <span class="hljs-built_in">this</span>.country = country;
}
</code></pre>
<ul>
<li>1: Undefined</li>
<li>2: ReferenceError</li>
<li>3: null</li>
<li>4: {model: "Honda", color: "white", year: "2010", country: "UK"}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The function declarations are hoisted similar to any variables. So the placement for <code>Vehicle</code> function declaration doesn't make any difference.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-2-what-is-the-output-of-below-code">2. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> x = (y = <span class="hljs-number">0</span>);
  x++;
  y++;
  <span class="hljs-keyword">return</span> x;
}

<span class="hljs-built_in">console</span>.log(foo(), <span class="hljs-keyword">typeof</span> x, <span class="hljs-keyword">typeof</span> y);
</code></pre>
<ul>
<li>1: 1, undefined and undefined</li>
<li>2: ReferenceError: X is not defined</li>
<li>3: 1, undefined and number</li>
<li>4: 1, number and number</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Of course the return value of <code>foo()</code> is 1 due to the increment operator. But the statement <code>let x = y = 0</code> declares a local variable x. Whereas y declared as a global variable accidentally. This statement is equivalent to,

<code>javascript
let x;
window.y = 0;
x = window.y;</code>

Since the block scoped variable x is undefined outside of the function, the type will be undefined too. Whereas the global variable <code>y</code> is available outside the function, the value is 0 and type is number.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-3-what-is-the-output-of-below-code">3. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"A"</span>);
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"B"</span>);
  }, <span class="hljs-number">0</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"C"</span>);
}
main();
</code></pre>
<ul>
<li>1: A, B and C</li>
<li>2: B, A and C</li>
<li>3: A and C</li>
<li>4: A, C and B</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The statements order is based on the event loop mechanism. The order of statements follows the below order,

1. At first, the main function is pushed to the stack.
2. Then the browser pushes the first statement of the main function( i.e, A's console.log) to the stack, executing and popping out immediately.
3. But <code>setTimeout</code> statement moved to Browser API to apply the delay for callback.
4. In the meantime, C's console.log added to stack, executed and popped out.
5. The callback of <code>setTimeout</code> moved from Browser API to message queue.
6. The <code>main</code> function popped out from stack because there are no statements to execute
7. The callback moved from message queue to the stack since the stack is empty.
8. The <code>console.log</code> for B is added to the stack and display on the console.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-4-what-is-the-output-of-below-equality-check">4. What is the output of below equality check</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">0.1</span> + <span class="hljs-number">0.2</span> === <span class="hljs-number">0.3</span>);
</code></pre>
<ul>
<li>1: false</li>
<li>2: true</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

This is due to the float point math problem. Since the floating point numbers are encoded in binary format, the addition operations on them lead to rounding errors. Hence, the comparison of floating points doesn't give expected results.
You can find more details about the explanation here <a target="_blank" href="https://0.30000000000000004.com/">0.30000000000000004.com/</a>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-5-what-is-the-output-of-below-code">5. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> y = <span class="hljs-number">1</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{}) {
  y += <span class="hljs-keyword">typeof</span> f;
}
<span class="hljs-built_in">console</span>.log(y);
</code></pre>
<ul>
<li>1: 1function</li>
<li>2: 1object</li>
<li>3: ReferenceError</li>
<li>4: 1undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The main points in the above code snippets are,

1. You can see function expression instead function declaration inside if statement. So it always returns true.
2. Since it is not declared(or assigned) anywhere, f is undefined and typeof f is undefined too.

In other words, it is same as

<code>javascript
var y = 1;
if ("foo") {
  y += typeof f;
}
console.log(y);</code>

<strong>Note:</strong> It returns 1object for MS Edge browser

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-6-what-is-the-output-of-below-code">6. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span>;
  {
    <span class="hljs-attr">message</span>: <span class="hljs-string">"Hello World"</span>;
  }
}
<span class="hljs-built_in">console</span>.log(foo());
</code></pre>
<ul>
<li>1: Hello World</li>
<li>2: Object {message: "Hello World"}</li>
<li>3: Undefined</li>
<li>4: SyntaxError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

This is a semicolon issue. Normally semicolons are optional in JavaScript. So if there are any statements(in this case, return) missing semicolon, it is automatically inserted immediately. Hence, the function returned as undefined.

Whereas if the opening curly brace is along with the return keyword then the function is going to be returned as expected.

<code>javascript
function foo() {
  return {
    message: "Hello World",
  };
}
console.log(foo()); // {message: "Hello World"}</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-7-what-is-the-output-of-below-code">7. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> myChars = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>, <span class="hljs-string">"d"</span>];
<span class="hljs-keyword">delete</span> myChars[<span class="hljs-number">0</span>];
<span class="hljs-built_in">console</span>.log(myChars);
<span class="hljs-built_in">console</span>.log(myChars[<span class="hljs-number">0</span>]);
<span class="hljs-built_in">console</span>.log(myChars.length);
</code></pre>
<ul>
<li>1: [empty, 'b', 'c', 'd'], empty, 3</li>
<li>2: [null, 'b', 'c', 'd'], empty, 3</li>
<li>3: [empty, 'b', 'c', 'd'], undefined, 4</li>
<li>4: [null, 'b', 'c', 'd'], undefined, 4</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

The <code>delete</code> operator will delete the object property but it will not reindex the array or change its length. So the number or elements or length of the array won't be changed.
If you try to print myChars then you can observe that it doesn't set an undefined value, rather the property is removed from the array. The newer versions of Chrome use <code>empty</code> instead of <code>undefined</code> to make the difference a bit clearer.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-8-what-is-the-output-of-below-code-in-latest-chrome">8. What is the output of below code in latest Chrome</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> array1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(array1);

<span class="hljs-keyword">var</span> array2 = [];
array2[<span class="hljs-number">2</span>] = <span class="hljs-number">100</span>;
<span class="hljs-built_in">console</span>.log(array2);

<span class="hljs-keyword">var</span> array3 = [, , ,];
<span class="hljs-built_in">console</span>.log(array3);
</code></pre>
<ul>
<li>1: [undefined × 3], [undefined × 2, 100], [undefined × 3]</li>
<li>2: [empty × 3], [empty × 2, 100], [empty × 3]</li>
<li>3: [null × 3], [null × 2, 100], [null × 3]</li>
<li>4: [], [100], []</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

The latest chrome versions display <code>sparse array</code>(they are filled with holes) using this empty x n notation. Whereas the older versions have undefined x n notation.
<strong>Note:</strong> The latest version of FF displays <code>n empty slots</code> notation.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-9-what-is-the-output-of-below-code">9. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {
  <span class="hljs-attr">prop1</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
  },
  prop2() {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  },
  [<span class="hljs-string">"prop"</span> + <span class="hljs-number">3</span>]() {
    <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>;
  },
};

<span class="hljs-built_in">console</span>.log(obj.prop1());
<span class="hljs-built_in">console</span>.log(obj.prop2());
<span class="hljs-built_in">console</span>.log(obj.prop3());
</code></pre>
<ul>
<li>1: 0, 1, 2</li>
<li>2: 0, { return 1 }, 2</li>
<li>3: 0, { return 1 }, { return 2 }</li>
<li>4: 0, 1, undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

ES6 provides method definitions and property shorthands for objects. So both prop2 and prop3 are treated as regular function values.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-10-what-is-the-output-of-below-code">10. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span> &lt; <span class="hljs-number">2</span> &lt; <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span> &gt; <span class="hljs-number">2</span> &gt; <span class="hljs-number">1</span>);
</code></pre>
<ul>
<li>1: true, true</li>
<li>2: true, false</li>
<li>3: SyntaxError, SyntaxError,</li>
<li>4: false, false</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

The important point is that if the statement contains the same operators(e.g, &lt; or &gt;) then it can be evaluated from left to right.
The first statement follows the below order,

1. console.log(1 &lt; 2 &lt; 3);
2. console.log(true &lt; 3);
3. console.log(1 &lt; 3); // True converted as <code>1</code> during comparison
4. True

Whereas the second statement follows the below order,

1. console.log(3 &gt; 2 &gt; 1);
2. console.log(true &gt; 1);
3. console.log(1 &gt; 1); // False converted as <code>0</code> during comparison
4. False

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-11-what-is-the-output-of-below-code-in-non-strict-mode">11. What is the output of below code in non-strict mode</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printNumbers</span>(<span class="hljs-params">first, second, first</span>) </span>{
  <span class="hljs-built_in">console</span>.log(first, second, first);
}
printNumbers(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
</code></pre>
<ul>
<li>1: 1, 2, 3</li>
<li>2: 3, 2, 3</li>
<li>3: SyntaxError: Duplicate parameter name not allowed in this context</li>
<li>4: 1, 2, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

In non-strict mode, the regular JavaScript functions allow duplicate named parameters. The above code snippet has duplicate parameters on 1st and 3rd parameters.
The value of the first parameter is mapped to the third argument which is passed to the function. Hence, the 3rd argument overrides the first parameter.

<strong>Note:</strong> In strict mode, duplicate parameters will throw a Syntax Error.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-12-what-is-the-output-of-below-code">12. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> printNumbersArrow = <span class="hljs-function">(<span class="hljs-params">first, second, first</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(first, second, first);
};
printNumbersArrow(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
</code></pre>
<ul>
<li>1: 1, 2, 3</li>
<li>2: 3, 2, 3</li>
<li>3: SyntaxError: Duplicate parameter name not allowed in this context</li>
<li>4: 1, 2, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Unlike regular functions, the arrow functions doesn't not allow duplicate parameters in either strict or non-strict mode. So you can see <code>SyntaxError</code> in the console.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-13-what-is-the-output-of-below-code">13. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arrowFunc = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">arguments</span>.length;
<span class="hljs-built_in">console</span>.log(arrowFunc(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<ul>
<li>1: ReferenceError: arguments is not defined</li>
<li>2: 3</li>
<li>3: undefined</li>
<li>4: null</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Arrow functions do not have an <code>arguments, super, this, or new.target</code> bindings. So any reference to <code>arguments</code> variable tries to resolve to a binding in a lexically enclosing environment. In this case, the arguments variable is not defined outside of the arrow function. Hence, you will receive a reference error.

Where as the normal function provides the number of arguments passed to the function

<code>javascript
const func = function () {
  return arguments.length;
};
console.log(func(1, 2, 3));</code>

But If you still want to use an arrow function then rest operator on arguments provides the expected arguments

<code>javascript
const arrowFunc = (...args) =&gt; args.length;
console.log(arrowFunc(1, 2, 3));</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-14-what-is-the-output-of-below-code">14. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">String</span>.prototype.trimLeft.name === <span class="hljs-string">"trimLeft"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">String</span>.prototype.trimLeft.name === <span class="hljs-string">"trimStart"</span>);
</code></pre>
<ul>
<li>1: True, False</li>
<li>2: False, True</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

In order to be consistent with functions like <code>String.prototype.padStart</code>, the standard method name for trimming the whitespaces is considered as <code>trimStart</code>. Due to web web compatibility reasons, the old method name 'trimLeft' still acts as an alias for 'trimStart'. Hence, the prototype for 'trimLeft' is always 'trimStart'

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-15-what-is-the-output-of-below-code">15. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.max());
</code></pre>
<ul>
<li>1: undefined</li>
<li>2: Infinity</li>
<li>3: 0</li>
<li>4: -Infinity</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

-Infinity is the initial comparant because almost every other value is bigger. So when no arguments are provided, -Infinity is going to be returned.
<strong>Note:</strong> Zero number of arguments is a valid case.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-16-what-is-the-output-of-below-code">16. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> == [<span class="hljs-number">10</span>]);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> == [[[[[[[<span class="hljs-number">10</span>]]]]]]]);
</code></pre>
<ul>
<li>1: True, True</li>
<li>2: True, False</li>
<li>3: False, False</li>
<li>4: False, True</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

As per the comparison algorithm in the ECMAScript specification(ECMA-262), the above expression converted into JS as below

<code>javascript
10 === Number([10].valueOf().toString()); // 10</code>

So it doesn't matter about number brackets([]) around the number, it is always converted to a number in the expression.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-17-what-is-the-output-of-below-code">17. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> + <span class="hljs-string">"10"</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span> - <span class="hljs-string">"10"</span>);
</code></pre>
<ul>
<li>1: 20, 0</li>
<li>2: 1010, 0</li>
<li>3: 1010, 10-10</li>
<li>4: NaN, NaN</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

The concatenation operator(+) is applicable for both number and string types. So if any operand is string type then both operands concatenated as strings. Whereas subtract(-) operator tries to convert the operands as number type.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-18-what-is-the-output-of-below-code">18. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log([<span class="hljs-number">0</span>] == <span class="hljs-literal">false</span>);
<span class="hljs-keyword">if</span> ([<span class="hljs-number">0</span>]) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm True"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm False"</span>);
}
</code></pre>
<ul>
<li>1: True, I'm True</li>
<li>2: True, I'm False</li>
<li>3: False, I'm True</li>
<li>4: False, I'm False</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

In comparison operators, the expression <code>[0]</code> converted to Number([0].valueOf().toString()) which is resolved to false. Whereas <code>[0]</code> just becomes a truthy value without any conversion because there is no comparison operator.

</p>
</details>

<h4 id="heading-19-what-is-the-output-of-below-code">19. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] + [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
</code></pre>
<ul>
<li>1: [1,2,3,4]</li>
<li>2: [1,2][3,4]</li>
<li>3: SyntaxError</li>
<li>4: 1,23,4</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The + operator is not meant or defined for arrays. So it converts arrays into strings and concatenates them.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-20-what-is-the-output-of-below-code">20. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
<span class="hljs-built_in">console</span>.log(numbers);

<span class="hljs-keyword">const</span> browser = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(<span class="hljs-string">"Firefox"</span>);
<span class="hljs-built_in">console</span>.log(browser);
</code></pre>
<ul>
<li>1: {1, 2, 3, 4}, {"F", "i", "r", "e", "f", "o", "x"}</li>
<li>2: {1, 2, 3, 4}, {"F", "i", "r", "e", "o", "x"}</li>
<li>3: [1, 2, 3, 4], ["F", "i", "r", "e", "o", "x"]</li>
<li>4: {1, 1, 2, 3, 4}, {"F", "i", "r", "e", "f", "o", "x"}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Since <code>Set</code> object is a collection of unique values, it won't allow duplicate values in the collection. At the same time, it is case sensitive data structure.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-21-what-is-the-output-of-below-code">21. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-literal">NaN</span> === <span class="hljs-literal">NaN</span>);
</code></pre>
<ul>
<li>1: True</li>
<li>2: False</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

JavaScript follows IEEE 754 spec standards. As per this spec, NaNs are never equal for floating-point numbers.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-22-what-is-the-output-of-below-code">22. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-literal">NaN</span>];
<span class="hljs-built_in">console</span>.log(numbers.indexOf(<span class="hljs-literal">NaN</span>));
</code></pre>
<ul>
<li>1: 4</li>
<li>2: NaN</li>
<li>3: SyntaxError</li>
<li>4: -1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The <code>indexOf</code> uses strict equality operator(===) internally and <code>NaN === NaN</code> evaluates to false. Since indexOf won't be able to find NaN inside an array, it returns -1 always.
But you can use <code>Array.prototype.findIndex</code> method to find out the index of NaN in an array or You can use <code>Array.prototype.includes</code> to check if NaN is present in an array or not.

<code>javascript
let numbers = [1, 2, 3, 4, NaN];
console.log(numbers.findIndex(Number.isNaN)); // 4

console.log(numbers.includes(NaN)); // true</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-23-what-is-the-output-of-below-code">23. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> [a, ...b,] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(a, b);
</code></pre>
<ul>
<li>1: 1, [2, 3, 4, 5]</li>
<li>2: 1, {2, 3, 4, 5}</li>
<li>3: SyntaxError</li>
<li>4: 1, [2, 3, 4]</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

When using rest parameters, trailing commas are not allowed and will throw a SyntaxError.
If you remove the trailing comma then it displays 1st answer

<code>javascript
let [a, ...b] = [1, 2, 3, 4, 5];
console.log(a, b); // 1, [2, 3, 4, 5]</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-25-what-is-the-output-of-below-code">25. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">10</span>;
}
<span class="hljs-built_in">console</span>.log(func());
</code></pre>
<ul>
<li>1: Promise {\: 10}</li>
<li>2: 10</li>
<li>3: SyntaxError</li>
<li>4: Promise {\: 10}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Async functions always return a promise. But even if the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. The above async function is equivalent to below expression,

<code>javascript
function func() {
  return Promise.resolve(10);
}</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-26-what-is-the-output-of-below-code">26. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">await</span> <span class="hljs-number">10</span>;
}
<span class="hljs-built_in">console</span>.log(func());
</code></pre>
<ul>
<li>1: Promise {\: 10}</li>
<li>2: 10</li>
<li>3: SyntaxError</li>
<li>4: Promise {\: undefined}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The await expression returns value 10 with promise resolution and the code after each await expression can be treated as existing in a <code>.then</code> callback. In this case, there is no return expression at the end of the function. Hence, the default return value of <code>undefined</code> is returned as the resolution of the promise. The above async function is equivalent to below expression,

<code>javascript
function func() {
  return Promise.resolve(10).then(() =&gt; undefined);
}</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-27-what-is-the-output-of-below-code">27. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delay</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayedLog</span>(<span class="hljs-params">item</span>) </span>{
  <span class="hljs-keyword">await</span> delay();
  <span class="hljs-built_in">console</span>.log(item);
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processArray</span>(<span class="hljs-params">array</span>) </span>{
  array.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
    <span class="hljs-keyword">await</span> delayedLog(item);
  })
}

processArray([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: 1, 2, 3, 4</li>
<li>3: 4, 4, 4, 4</li>
<li>4: 4, 3, 2, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Even though “processArray” is an async function, the anonymous function that we use for <code>forEach</code> is synchronous. If you use await inside a synchronous function then it throws a syntax error.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-28-what-is-the-output-of-below-code">28. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delay</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">2000</span>));
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayedLog</span>(<span class="hljs-params">item</span>) </span>{
  <span class="hljs-keyword">await</span> delay();
  <span class="hljs-built_in">console</span>.log(item);
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">process</span>(<span class="hljs-params">array</span>) </span>{
  array.forEach(<span class="hljs-keyword">async</span> (item) =&gt; {
    <span class="hljs-keyword">await</span> delayedLog(item);
  });
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Process completed!"</span>);
}
process([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>]);
</code></pre>
<ul>
<li>1: 1 2 3 5 and Process completed!</li>
<li>2: 5 5 5 5 and Process completed!</li>
<li>3: Process completed! and 5 5 5 5</li>
<li>4: Process completed! and 1 2 3 5</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The forEach method will not wait until all items are finished but it just runs the tasks and goes next. Hence, the last statement is displayed first followed by a sequence of promise resolutions.

But you control the array sequence using for..of loop,

<code>javascript
async function processArray(array) {
  for (const item of array) {
    await delayedLog(item);
  }
  console.log("Process completed!");
}</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-29-what-is-the-output-of-below-code">29. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> set = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();
set.add(<span class="hljs-string">"+0"</span>).add(<span class="hljs-string">"-0"</span>).add(<span class="hljs-literal">NaN</span>).add(<span class="hljs-literal">undefined</span>).add(<span class="hljs-literal">NaN</span>);
<span class="hljs-built_in">console</span>.log(set);
</code></pre>
<ul>
<li>1: Set(4) {"+0", "-0", NaN, undefined}</li>
<li>2: Set(3) {"+0", NaN, undefined}</li>
<li>3: Set(5) {"+0", "-0", NaN, undefined, NaN}</li>
<li>4: Set(4) {"+0", NaN, undefined, NaN}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Set has few exceptions from equality check,

1. All NaN values are equal
2. Both +0 and -0 considered as different values

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-30-what-is-the-output-of-below-code">30. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sym1 = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"one"</span>);
<span class="hljs-keyword">const</span> sym2 = <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"one"</span>);

<span class="hljs-keyword">const</span> sym3 = <span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"two"</span>);
<span class="hljs-keyword">const</span> sym4 = <span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"two"</span>);

<span class="hljs-built_in">console</span>.log(sym1 === sym2, sym3 === sym4);
</code></pre>
<ul>
<li>1: true, true</li>
<li>2: true, false</li>
<li>3: false, true</li>
<li>4: false, false</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Symbol follows below conventions,

1. Every symbol value returned from Symbol() is unique irrespective of the optional string.
2. <code>Symbol.for()</code> function creates a symbol in a global symbol registry list. But it doesn't necessarily create a new symbol on every call, it checks first if a symbol with the given key is already present in the registry and returns the symbol if it is found. Otherwise a new symbol created in the registry.

<strong>Note:</strong> The symbol description is just useful for debugging purposes.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-31-what-is-the-output-of-below-code">31. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sym1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">"one"</span>);
<span class="hljs-built_in">console</span>.log(sym1);
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: one</li>
<li>3: Symbol('one')</li>
<li>4: Symbol</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

<code>Symbol</code> is a just a standard function and not an object constructor(unlike other primitives new Boolean, new String and new Number). So if you try to call it with the new operator will result in a TypeError

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-32-what-is-the-output-of-below-code">32. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myNumber = <span class="hljs-number">100</span>;
<span class="hljs-keyword">let</span> myString = <span class="hljs-string">"100"</span>;

<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">typeof</span> myNumber === <span class="hljs-string">"string"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"It is not a string!"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"It is a string!"</span>);
}

<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">typeof</span> myString === <span class="hljs-string">"number"</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"It is not a number!"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"It is a number!"</span>);
}
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: It is not a string!, It is not a number!</li>
<li>3: It is not a string!, It is a number!</li>
<li>4: It is a string!, It is a number!</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The return value of <code>typeof myNumber</code> or <code>typeof myString</code> is always a truthy value (either "number" or "string"). The ! operator operates on either <code>typeof myNumber</code> or <code>typeof myString</code>, converting them to boolean values. Since the value of both <code>!typeof myNumber</code> and <code>!typeof myString</code> is false, the if condition fails, and control goes to else block.

To make the ! operator operate on the equality expression, one needs to add parentheses:

<code>if (!(typeof myNumber === "string"))</code>

Or simply use the inequality operator:

<code>if (typeof myNumber !== "string")</code>

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-33-what-is-the-output-of-below-code">33. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(
  <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">myArray</span>: [<span class="hljs-string">"one"</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{}, <span class="hljs-built_in">Symbol</span>(<span class="hljs-string">""</span>)] })
);
<span class="hljs-built_in">console</span>.log(
  <span class="hljs-built_in">JSON</span>.stringify({ [<span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"one"</span>)]: <span class="hljs-string">"one"</span> }, [<span class="hljs-built_in">Symbol</span>.for(<span class="hljs-string">"one"</span>)])
);
</code></pre>
<ul>
<li>1: {"myArray":['one', undefined, {}, Symbol]}, {}</li>
<li>2: {"myArray":['one', null,null,null]}, {}</li>
<li>3: {"myArray":['one', null,null,null]}, "{ [Symbol.for('one')]: 'one' }, [Symbol.for('one')]"</li>
<li>4: {"myArray":['one', undefined, function(){}, Symbol('')]}, {}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

The symbols has below constraints,

1. The undefined, Functions, and Symbols are not valid JSON values. So those values are either omitted (in an object) or changed to null (in an array). Hence, it returns null values for the value array.
2. All Symbol-keyed properties will be completely ignored. Hence it returns an empty object({}).

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-34-what-is-the-output-of-below-code">34. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span>.target.name);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">A</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>();
  }
}

<span class="hljs-keyword">new</span> A();
<span class="hljs-keyword">new</span> B();
</code></pre>
<ul>
<li>1: A, A</li>
<li>2: A, B</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Using constructors, <code>new.target</code> refers to the constructor (points to the class definition of class which is initialized) that was directly invoked by new. This also applies to the case if the constructor is in a parent class and was delegated from a child constructor.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-35-what-is-the-output-of-below-code">35. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [x, ...y, z] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-built_in">console</span>.log(x, y, z);
</code></pre>
<ul>
<li>1: 1, [2, 3], 4</li>
<li>2: 1, [2, 3, 4], undefined</li>
<li>3: 1, [2], 3</li>
<li>4: SyntaxError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

It throws a syntax error because the rest element should not have a trailing comma. You should always consider using a rest operator as the last element.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-36-what-is-the-output-of-below-code">36. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { <span class="hljs-attr">a</span>: x = <span class="hljs-number">10</span>, <span class="hljs-attr">b</span>: y = <span class="hljs-number">20</span> } = { <span class="hljs-attr">a</span>: <span class="hljs-number">30</span> };

<span class="hljs-built_in">console</span>.log(x);
<span class="hljs-built_in">console</span>.log(y);
</code></pre>
<ul>
<li>1: 30, 20</li>
<li>2: 10, 20</li>
<li>3: 10, undefined</li>
<li>4: 30, undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

The object property follows below rules,

1. The object properties can be retrieved and assigned to a variable with a different name
2. The property assigned a default value when the retrieved value is <code>undefined</code>

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-37-what-is-the-output-of-below-code">37. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">area</span>(<span class="hljs-params">{ length = <span class="hljs-number">10</span>, width = <span class="hljs-number">20</span> }</span>) </span>{
  <span class="hljs-built_in">console</span>.log(length * width);
}

area();
</code></pre>
<ul>
<li>1: 200</li>
<li>2: Error</li>
<li>3: undefined</li>
<li>4: 0</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

If you leave out the right-hand side assignment for the destructuring object, the function will look for at least one argument to be supplied when invoked. Otherwise you will receive an error <code>Error: Cannot read property 'length' of undefined</code> as mentioned above.

You can avoid the error with either of the below changes,

1. <strong>Pass at least an empty object:</strong>

<code>javascript
function area({ length = 10, width = 20 }) {
  console.log(length * width);
}

area({});</code>

2. <strong>Assign default empty object:</strong>

<code>javascript
function area({ length = 10, width = 20 } = {}) {
  console.log(length * width);
}

area();</code>

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-38-what-is-the-output-of-below-code">38. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> props = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Jack"</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Tom"</span> },
];

<span class="hljs-keyword">const</span> [, , { name }] = props;
<span class="hljs-built_in">console</span>.log(name);
</code></pre>
<ul>
<li>1: Tom</li>
<li>2: Error</li>
<li>3: undefined</li>
<li>4: John</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

It is possible to combine Array and Object destructuring. In this case, the third element in the array props accessed first followed by name property in the object.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-39-what-is-the-output-of-below-code">39. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkType</span>(<span class="hljs-params">num = <span class="hljs-number">1</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> num);
}

checkType();
checkType(<span class="hljs-literal">undefined</span>);
checkType(<span class="hljs-string">""</span>);
checkType(<span class="hljs-literal">null</span>);
</code></pre>
<ul>
<li>1: number, undefined, string, object</li>
<li>2: undefined, undefined, string, object</li>
<li>3: number, number, string, object</li>
<li>4: number, number, number, number</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

If the function argument is set implicitly(not passing argument) or explicitly to undefined, the value of the argument is the default parameter. Whereas for other falsy values('' or null), the value of the argument is passed as a parameter.

Hence, the result of function calls categorized as below,

1. The first two function calls logs number type since the type of default value is number
2. The type of '' and null values are string and object type respectively.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-40-what-is-the-output-of-below-code">40. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">item, items = []</span>) </span>{
  items.push(item);
  <span class="hljs-keyword">return</span> items;
}

<span class="hljs-built_in">console</span>.log(add(<span class="hljs-string">"Orange"</span>));
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-string">"Apple"</span>));
</code></pre>
<ul>
<li>1: ['Orange'], ['Orange', 'Apple']</li>
<li>2: ['Orange'], ['Apple']</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Since the default argument is evaluated at call time, a new object is created each time the function is called. So in this case, the new array is created and an element pushed to the default empty array.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-41-what-is-the-output-of-below-code">41. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">greeting, name, message = greeting + <span class="hljs-string">" "</span> + name</span>) </span>{
  <span class="hljs-built_in">console</span>.log([greeting, name, message]);
}

greet(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"John"</span>);
greet(<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"John"</span>, <span class="hljs-string">"Good morning!"</span>);
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: ['Hello', 'John', 'Hello John'], ['Hello', 'John', 'Good morning!']</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Since parameters defined earlier are available to later default parameters, this code snippet doesn't throw any error.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-42-what-is-the-output-of-below-code">42. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outer</span>(<span class="hljs-params">f = inner()</span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inner</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Inner"</span>;
  }
}
outer();
</code></pre>
<ul>
<li>1: ReferenceError</li>
<li>2: Inner</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

The functions and variables declared in the function body cannot be referred from default value parameter initializers. If you still try to access, it throws a run-time ReferenceError(i.e, <code>inner</code> is not defined).

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-43-what-is-the-output-of-below-code">43. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFun</span>(<span class="hljs-params">x, y, ...manyMoreArgs</span>) </span>{
  <span class="hljs-built_in">console</span>.log(manyMoreArgs);
}

myFun(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);
myFun(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
</code></pre>
<ul>
<li>1: [3, 4, 5], undefined</li>
<li>2: SyntaxError</li>
<li>3: [3, 4, 5], []</li>
<li>4: [3, 4, 5], [undefined]</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

The rest parameter is used to hold the remaining parameters of a function and it becomes an empty array if the argument is not provided.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-44-what-is-the-output-of-below-code">44. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">key</span>: <span class="hljs-string">"value"</span> };
<span class="hljs-keyword">const</span> array = [...obj];
<span class="hljs-built_in">console</span>.log(array);
</code></pre>
<ul>
<li>1: ['key', 'value']</li>
<li>2: TypeError</li>
<li>3: []</li>
<li>4: ['key']</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Spread syntax can be applied only to iterable objects. By default, Objects are not iterable, but they become iterable when used in an Array, or with iterating functions such as <code>map(), reduce(), and assign()</code>. If you still try to do it, it still throws <code>TypeError: obj is not iterable</code>.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-45-what-is-the-output-of-below-code">45. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">myGenFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
}
<span class="hljs-keyword">var</span> myGenObj = <span class="hljs-keyword">new</span> myGenFunc();
<span class="hljs-built_in">console</span>.log(myGenObj.next().value);
</code></pre>
<ul>
<li>1: 1</li>
<li>2: undefined</li>
<li>3: SyntaxError</li>
<li>4: TypeError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

Generators are not constructible type. But if you still proceed to do, there will be an error saying "TypeError: myGenFunc is not a constructor"

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-46-what-is-the-output-of-below-code">46. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">yieldAndReturn</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
}

<span class="hljs-keyword">var</span> myGenObj = yieldAndReturn();
<span class="hljs-built_in">console</span>.log(myGenObj.next());
<span class="hljs-built_in">console</span>.log(myGenObj.next());
<span class="hljs-built_in">console</span>.log(myGenObj.next());
</code></pre>
<ul>
<li>1: { value: 1, done: false }, { value: 2, done: true }, { value: undefined, done: true }</li>
<li>2: { value: 1, done: false }, { value: 2, done: false }, { value: undefined, done: true }</li>
<li>3: { value: 1, done: false }, { value: 2, done: true }, { value: 3, done: true }</li>
<li>4: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true }</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

A return statement in a generator function will make the generator finish. If a value is returned, it will be set as the value property of the object and done property to true. When a generator is finished, subsequent next() calls return an object of this form: <code>{value: undefined, done: true}</code>.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-47-what-is-the-output-of-below-code">47. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myGenerator = (<span class="hljs-function"><span class="hljs-keyword">function</span>* (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> <span class="hljs-number">1</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">2</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-number">3</span>;
})();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> myGenerator) {
  <span class="hljs-built_in">console</span>.log(value);
  <span class="hljs-keyword">break</span>;
}

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> myGenerator) {
  <span class="hljs-built_in">console</span>.log(value);
}
</code></pre>
<ul>
<li>1: 1,2,3 and 1,2,3</li>
<li>2: 1,2,3 and 4,5,6</li>
<li>3: 1 and 1</li>
<li>4: 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The generator should not be re-used once the iterator is closed. i.e, Upon exiting a loop(on completion or using break &amp; return), the generator is closed and trying to iterate over it again does not yield any more results. Hence, the second loop doesn't print any value.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-48-what-is-the-output-of-below-code">48. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> num = <span class="hljs-number">0o3</span>8;
<span class="hljs-built_in">console</span>.log(num);
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: 38</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

If you use an invalid number(outside of 0-7 range) in the octal literal, JavaScript will throw a SyntaxError. In ES5, it treats the octal literal as a decimal number.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-49-what-is-the-output-of-below-code">49. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> squareObj = <span class="hljs-keyword">new</span> Square(<span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(squareObj.area);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> </span>{
  <span class="hljs-keyword">constructor</span>(length) {
    <span class="hljs-built_in">this</span>.length = length;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title">area</span>() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.length * <span class="hljs-built_in">this</span>.length;
  }

  <span class="hljs-keyword">set</span> <span class="hljs-title">area</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-built_in">this</span>.area = value;
  }
}
</code></pre>
<ul>
<li>1: 100</li>
<li>2: ReferenceError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Unlike function declarations, class declarations are not hoisted. i.e, First You need to declare your class and then access it, otherwise it will throw a ReferenceError "Uncaught ReferenceError: Square is not defined".

<strong>Note:</strong> Class expressions also applies to the same hoisting restrictions of class declarations.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-50-what-is-the-output-of-below-code">50. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params"></span>) </span>{}

Person.prototype.walk = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
};

Person.run = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
};

<span class="hljs-keyword">let</span> user = <span class="hljs-keyword">new</span> Person();
<span class="hljs-keyword">let</span> walk = user.walk;
<span class="hljs-built_in">console</span>.log(walk());

<span class="hljs-keyword">let</span> run = Person.run;
<span class="hljs-built_in">console</span>.log(run());
</code></pre>
<ul>
<li>1: undefined, undefined</li>
<li>2: Person, Person</li>
<li>3: SyntaxError</li>
<li>4: Window, Window</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

When a regular or prototype method is called without a value for <strong>this</strong>, the methods return an initial this value if the value is not undefined. Otherwise global window object will be returned. In our case, the initial <code>this</code> value is undefined so both methods return window objects.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-51-what-is-the-output-of-below-code">51. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  start() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> vehicle started`</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
  start() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> car started`</span>);
    <span class="hljs-built_in">super</span>.start();
  }
}

<span class="hljs-keyword">const</span> car = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"BMW"</span>);
<span class="hljs-built_in">console</span>.log(car.start());
</code></pre>
<ul>
<li>1: SyntaxError</li>
<li>2: BMW vehicle started, BMW car started</li>
<li>3: BMW car started, BMW vehicle started</li>
<li>4: BMW car started, BMW car started</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

The super keyword is used to call methods of a superclass. Unlike other languages the super invocation doesn't need to be a first statement. i.e, The statements will be executed in the same order of code.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-52-what-is-the-output-of-below-code">52. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> USER = { <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
USER.age = <span class="hljs-number">25</span>;
<span class="hljs-built_in">console</span>.log(USER.age);
</code></pre>
<ul>
<li>1: 30</li>
<li>2: 25</li>
<li>3: Uncaught TypeError</li>
<li>4: SyntaxError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Even though we used constant variables, the content of it is an object and the object's contents (e.g properties) can be altered. Hence, the change is going to be valid in this case.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-53-what-is-the-output-of-below-code">53. What is the output of below code</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"🙂"</span> === <span class="hljs-string">"🙂"</span>);
</code></pre>
<ul>
<li>1: false</li>
<li>2: true</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Emojis are unicodes and the unicode for smile symbol is "U+1F642". The unicode comparison of same emojies is equivalent to string comparison. Hence, the output is always true.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-54-what-is-the-output-of-below-code">54. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-keyword">typeof</span> <span class="hljs-keyword">typeof</span> <span class="hljs-literal">true</span>);
</code></pre>
<ul>
<li>1: string</li>
<li>2: boolean</li>
<li>3: NaN</li>
<li>4: number</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

The typeof operator on any primitive returns a string value. So even if you apply the chain of typeof operators on the return value, it is always string.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-55-what-is-the-output-of-below-code">55. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> zero = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">0</span>);

<span class="hljs-keyword">if</span> (zero) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"If"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Else"</span>);
}
</code></pre>
<ul>
<li>1: If</li>
<li>2: Else</li>
<li>3: NaN</li>
<li>4: SyntaxError</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

1. The type of operator on new Number always returns object. i.e, typeof new Number(0) --&gt; object.
2. Objects are always truthy in if block

Hence the above code block always goes to if section.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-55-what-is-the-output-of-below-code-in-non-strict-mode">55. What is the output of below code in non strict mode?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> msg = <span class="hljs-string">"Good morning!!"</span>;

msg.name = <span class="hljs-string">"John"</span>;

<span class="hljs-built_in">console</span>.log(msg.name);
</code></pre>
<ul>
<li>1: ""</li>
<li>2: Error</li>
<li>3: John</li>
<li>4: Undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

It returns undefined for non-strict mode and returns Error for strict mode. In non-strict mode, the wrapper object is going to be created and get the mentioned property. But the object get disappeared after accessing the property in next line.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-56-what-is-the-output-of-below-code">56. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">10</span>;

(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (count === <span class="hljs-number">10</span>) {
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">11</span>;
    <span class="hljs-built_in">console</span>.log(count);
  }
  <span class="hljs-built_in">console</span>.log(count);
})();
</code></pre>
<ul>
<li>1: 11, 10</li>
<li>2: 11, 11</li>
<li>3: 10, 11</li>
<li>4: 10, 10</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

11 and 10 is logged to the console.

The innerFunc is a closure which captures the count variable from the outerscope. i.e, 10. But the conditional has another local variable <code>count</code> which overwrites the ourter <code>count</code> variable. So the first console.log displays value 11.
Whereas the second console.log logs 10 by capturing the count variable from outerscope.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-57-what-is-the-output-of-below-code">57. What is the output of below code ?</h4>
<ul>
<li>1: console.log(true &amp;&amp; 'hi');</li>
<li>2: console.log(true &amp;&amp; 'hi' &amp;&amp; 1);</li>
<li>3: console.log(true &amp;&amp; '' &amp;&amp; 0);</li>
</ul>
<details><summary><b>Answer</b></summary>

 - 1: hi
 - 2: 1
 - 3: ''

 Reason : The operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

<strong>Note:</strong> Below these values are consider as falsy value

- 1: 0
- 2: ''
- 3: null
- 4: undefined
- 5: NAN

<p></p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-58-what-is-the-output-of-below-code">58. What is the output of below code ?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"1,2,3"</span>;

<span class="hljs-built_in">console</span>.log(arr == str);
</code></pre>
<ul>
<li>1: false</li>
<li>2: Error</li>
<li>3: true</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Arrays have their own implementation of <code>toString</code> method that returns a comma-separated list of elements. So the above code snippet returns true. In order to avoid conversion of array type, we should use === for comparison.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-59-what-is-the-output-of-below-code">59. What is the output of below code?</h4>
<pre><code class="lang-javascript">getMessage();

<span class="hljs-keyword">var</span> getMessage = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Good morning"</span>);
};
</code></pre>
<ul>
<li>1: Good morning</li>
<li>2: getMessage is not a function</li>
<li>3: getMessage is not defined</li>
<li>4: Undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Hoisting will move variables and functions to be the top of scope. Even though getMessage is an arrow function the above function will considered as a variable due to it's variable declaration or assignment. So the variables will have undefined value in memory phase and throws an error '<code>getMessage</code> is not a function' at the code execution phase.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-60-what-is-the-output-of-below-code">60. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> quickPromise = <span class="hljs-built_in">Promise</span>.resolve();

quickPromise.then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"promise finished"</span>));

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"program finished"</span>);
</code></pre>
<ul>
<li>1: program finished</li>
<li>2: Cannot predict the order</li>
<li>3: program finished, promise finished</li>
<li>4: promise finished, program finished</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Even though a promise is resolved immediately, it won't be executed immediately because its <strong>.then/catch/finally</strong> handlers or callbacks(aka task) are pushed into the queue. Whenever the JavaScript engine becomes free from the current program, it pulls a task from the queue and executes it. This is the reason why last statement is printed first before the log of promise handler.

<strong>Note:</strong> We call the above queue as "MicroTask Queue"

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-61-what-is-the-output-of-below-code">61. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>
  .log(<span class="hljs-string">"First line"</span>)
  [(<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>)].forEach(<span class="hljs-function">(<span class="hljs-params">element</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(element));
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Third line"</span>);
</code></pre>
<ul>
<li>1: <code>First line</code>, then print <code>a, b, c</code> in a new line, and finally print <code>Third line</code> as next line</li>
<li>2: <code>First line</code>, then print <code>a, b, c</code> in a first line, and print <code>Third line</code> as next line</li>
<li>3: Missing semi-colon error</li>
<li>4: Cannot read properties of undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

When JavaScript encounters a line break without a semicolon, the JavaScript parser will automatically add a semicolon based on a set of rules called <code>Automatic Semicolon Insertion</code> which determines whether line break as end of statement or not to insert semicolon. But it does not assume a semicolon before square brackets [...]. So the first two lines considered as a single statement as below.

<code>javascript
console
  .log("First line")
  [("a", "b", "c")].forEach((element) =&gt; console.log(element));</code>

Hence, there will be <strong>cannot read properties of undefined</strong> error while applying the array square bracket on log function.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-62-write-a-function-that-returns-a-random-hex-color">62. Write a function that returns a random HEX color</h4>
<details><summary><b>Solution 1 (Iterative generation)</b></summary>
<p>

<code>javascript
const HEX_ALPHABET = [
  "0",
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
];
const HEX_PREFIX = "#";
const HEX_LENGTH = 6;

function generateRandomHex() {
  let randomHex = "";

  for (let i = 0; i &lt; HEX_LENGTH; i++) {
    const randomIndex = Math.floor(Math.random() * HEX_ALPHABET.length);
    randomHex += HEX_ALPHABET[randomIndex];
  }

  return HEX_PREFIX + randomHex;
}</code>

</p>

</details>

<details><summary><b>Solution 2 (One-liner)</b></summary>
<p>

<code>javascript
const HEX_PREFIX = "#";
const HEX_RADIX = 16;
const HEX_LENGTH = 6;

function generateRandomHex() {
  return (
    HEX_PREFIX +
    Math.floor(Math.random() * 0xffffff)
      .toString(HEX_RADIX)
      .padStart(HEX_LENGTH, "0")
  );
}</code>

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-63-what-is-the-output-of-below-code">63. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> <span class="hljs-keyword">of</span> = [<span class="hljs-string">"of"</span>];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> <span class="hljs-keyword">of</span> <span class="hljs-keyword">of</span> <span class="hljs-keyword">of</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">of</span>);
}
</code></pre>
<ul>
<li>1: of</li>
<li>2: SyntaxError: Unexpected token of</li>
<li>3: SyntaxError: Identifier 'of' has already been declared</li>
<li>4: ReferenceError: of is not defined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

In JavaScript, <code>of</code> is not considered as a reserved keyword. So the variable declaration with <code>of</code> is accepted and prints the array value <code>of</code> using for..of loop.

But if you use reserved keyword such as <code>in</code> then there will be a syntax error saying <code>SyntaxError: Unexpected token in</code>,

<code>javascript
var in = ['in'];
for(var in in in) {
  console.log(in[in]);
}</code>

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-64-what-is-the-output-of-below-code">64. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">11</span>, <span class="hljs-number">25</span>, <span class="hljs-number">31</span>, <span class="hljs-number">23</span>, <span class="hljs-number">33</span>, <span class="hljs-number">18</span>, <span class="hljs-number">200</span>];
numbers.sort();
<span class="hljs-built_in">console</span>.log(numbers);
</code></pre>
<ul>
<li>1: [11, 18, 23, 25, 31, 33, 200]</li>
<li>2: [11, 18, 200, 23, 25, 31, 33]</li>
<li>3: [11, 25, 31, 23, 33, 18, 200]</li>
<li>4: Cannot sort numbers</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

By default, the sort method sorts elements alphabetically. This is because elemented converted to strings and strings compared in UTF-16 code units order. Hence, you will see the above numbers not sorted as expected. In order to sort numerically just supply a comparator function which handles numeric sorts.

<code>javascript
const numbers = [11, 25, 31, 23, 33, 18, 200];
numbers.sort((a, b) =&gt; a - b);
console.log(numbers);</code>

<strong>Note:</strong> Sort() method changes the original array.

</p>

</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-65-what-is-the-output-order-of-below-code">65. What is the output order of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1"</span>);
}, <span class="hljs-number">0</span>);
<span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">"hello"</span>).then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"2"</span>));
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"3"</span>);
</code></pre>
<ul>
<li>1: 1, 2, 3</li>
<li>2: 1, 3, 2</li>
<li>3: 3, 1, 2</li>
<li>4: 3, 2, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

When the JavaScript engine parses the above code, the first two statements are asynchronous which will be executed later and third statement is synchronous statement which will be moved to callstack, executed and prints the number 3 in the console. Next, Promise is native in ES6 and it will be moved to Job queue which has high priority than callback queue in the execution order. At last, since setTimeout is part of WebAPI the callback function moved to callback queue and executed. Hence, you will see number 2 printed first followed by 1.

</p></details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-66-what-is-the-output-of-below-code">66. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(name);
<span class="hljs-built_in">console</span>.log(message());
<span class="hljs-keyword">var</span> name = <span class="hljs-string">"John"</span>;
(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">message</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello John: Welcome"</span>);
});
</code></pre>
<ul>
<li>1: John, Hello John: Welcome</li>
<li>2: undefined, Hello John, Welcome</li>
<li>3: Reference error: name is not defined, Reference error: message is not defined</li>
<li>4: undefined, Reference error: message is not defined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

IIFE(Immediately Invoked Function Expression) is just like any other function expression which won't be hoisted. Hence, there will be a reference error for message call.
The behavior would be the same with below function expression of message1,

<code>javascript
console.log(name);
console.log(message());
var name = 'John';
var message = function () {
   console.log('Hello John: Welcome');
});</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-67-what-is-the-output-of-below-code">67. What is the output of below code?</h4>
<pre><code class="lang-javascript">message();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">message</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">message</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Bye"</span>);
}
</code></pre>
<ul>
<li>1: Reference error: message is not defined</li>
<li>2: Hello</li>
<li>3: Bye</li>
<li>4: Compile time error</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

As part of hoisting, initially JavaScript Engine or compiler will store first function in heap memory but later rewrite or replaces with redefined function content.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-68-what-is-the-output-of-below-code">68. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> currentCity = <span class="hljs-string">"NewYork"</span>;

<span class="hljs-keyword">var</span> changeCurrentCity = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Current City:"</span>, currentCity);
  <span class="hljs-keyword">var</span> currentCity = <span class="hljs-string">"Singapore"</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Current City:"</span>, currentCity);
};

changeCurrentCity();
</code></pre>
<ul>
<li>1: NewYork, Singapore</li>
<li>2: NewYork, NewYork</li>
<li>3: undefined, Singapore</li>
<li>4: Singapore, Singapore</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Due to hositing feature, the variables declared with <code>var</code> will have <code>undefined</code> value in the creation phase so the outer variable <code>currentCity</code> will get same <code>undefined</code> value. But after few lines of code JavaScript engine found a new function call(<code>changeCurrentCity()</code>) to update the current city with <code>var</code> re-declaration. Since each function call will create a new execution context, the same variable will have <code>undefined</code> value before the declaration and new value(<code>Singapore</code>) after the declaration. Hence, the value <code>undefined</code> print first followed by new value <code>Singapore</code> in the execution phase.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-69-what-is-the-output-of-below-code-in-an-order">69. What is the output of below code in an order?</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">second</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> message;
  <span class="hljs-built_in">console</span>.log(message);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">first</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> message = <span class="hljs-string">"first"</span>;
  second();
  <span class="hljs-built_in">console</span>.log(message);
}

<span class="hljs-keyword">var</span> message = <span class="hljs-string">"default"</span>;
first();
<span class="hljs-built_in">console</span>.log(message);
</code></pre>
<ul>
<li>1: undefined, first, default</li>
<li>2: default, default, default</li>
<li>3: first, first, default</li>
<li>4: undefined, undefined, undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Each context(global or functional) has it's own variable environment and the callstack of variables in a LIFO order. So you can see the message variable value from second, first functions in an order followed by global context message variable value at the end.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-70-what-is-the-output-of-below-code">70. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> expressionOne = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionOne</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"functionOne"</span>);
};
functionOne();
</code></pre>
<ul>
<li>1: functionOne is not defined</li>
<li>2: functionOne</li>
<li>3: console.log("functionOne")</li>
<li>4: undefined</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

The function call <code>functionOne</code> is not going to be part of scope chain and it has it's own execution context with the enclosed variable environment. i.e, It won't be accessed from global context. Hence, there will be an error while invoking the function as <code>functionOne is not defined</code>.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-71-what-is-the-output-of-below-code">71. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John"</span>,
  eat() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    <span class="hljs-keyword">var</span> eatFruit = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
    };
    eatFruit();
  },
};
user.eat();
</code></pre>
<ul>
<li>1: {name: "John", eat: f}, {name: "John", eat: f}</li>
<li>2: Window {...}, Window {...}</li>
<li>3: {name: "John", eat: f}, undefined</li>
<li>4: {name: "John", eat: f}, Window {...}</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

<code>this</code> keyword is dynamic scoped but not lexically scoped . In other words, it doesn't matter where <code>this</code> has been written but how it has been invoked really matter. In the above code snippet, the <code>user</code> object invokes <code>eat</code> function so <code>this</code> keyword refers to <code>user</code> object but <code>eatFruit</code> has been invoked by <code>eat</code> function and <code>this</code> will have default <code>Window</code> object.

The above pit fall fixed by three ways,

1. In ES6, the arrow function will make <code>this</code> keyword as lexically scoped. Since the surrounding object of <code>this</code> object is <code>user</code> object, the <code>eatFruit</code> function will contain <code>user</code> object for <code>this</code> object.

<code>javascript
const user = {
  name: "John",
  eat() {
    console.log(this);
    var eatFruit = () =&gt; {
      console.log(this);
    };
    eatFruit();
  },
};
user.eat();</code>

The next two solutions have been used before ES6 introduced.

2.  It is possible create a reference of <code>this</code> into a separate variable and use that new variable inplace of <code>this</code> keyword inside <code>eatFruit</code> function. This is a common practice in jQuery and AngularJS before ES6 introduced.

<code>javascript
const user = {
  name: "John",
  eat() {
    console.log(this);
    var self = this;
    var eatFruit = () =&gt; {
      console.log(self);
    };
    eatFruit();
  },
};
user.eat();</code>

3. The <code>eatFruit</code> function can bind explicitly with <code>this</code> keyword where it refers <code>Window</code> object.

<code>javascript
const user = {
  name: "John",
  eat() {
    console.log(this);
    var eatFruit = function () {
      console.log(this);
    };
    return eatFruit.bind(this);
  },
};
user.eat()();</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-72-what-is-the-output-of-below-code">72. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> message = <span class="hljs-string">"Hello World!"</span>;
message[<span class="hljs-number">0</span>] = <span class="hljs-string">"J"</span>;
<span class="hljs-built_in">console</span>.log(message);

<span class="hljs-keyword">let</span> name = <span class="hljs-string">"John"</span>;
name = name + <span class="hljs-string">" Smith"</span>;
<span class="hljs-built_in">console</span>.log(name);
</code></pre>
<ul>
<li>1: Jello World!, John Smith</li>
<li>2: Jello World!, John</li>
<li>3: Hello World!, John Smith</li>
<li>4: Hello World!, John</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

In JavaScript, primitives are immutable i.e. there is no way to change a primitive value once it gets created. So when you try to update the string's first character, there is no change in the string value and prints the same initial value <code>Hello World!</code>. Whereas in the later example, the concatenated value is re-assigned to the same variable which will result into creation of new memory block with the reference pointing to <code>John Smith</code> value and the old memory block value(<code>John</code>) will be garbage collected.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-73-what-is-the-output-of-below-code">73. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user1 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Jacob"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">28</span>,
};

<span class="hljs-keyword">let</span> user2 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Jacob"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">28</span>,
};

<span class="hljs-built_in">console</span>.log(user1 === user2);
</code></pre>
<ul>
<li>1: True</li>
<li>2: False</li>
<li>3: Compile time error</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

In JavaScript, the variables such as objects, arrays and functions comes under pass by reference. When you try to compare two objects with same content, it is going to compare memory address or reference of those variables. These variables always create separate memory blocks hence the comparison is always going to return false value.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-74-what-is-the-output-of-below-code">74. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(message);
  }, <span class="hljs-number">5000</span>);
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">"Hello, Good morning"</span>;
}
greeting();
</code></pre>
<ul>
<li>1: Undefined</li>
<li>2: Reference error:</li>
<li>3: Hello, Good morning</li>
<li>4: null</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

The variable <code>message</code> is still treated as closure(since it has been used in inner function) eventhough it has been declared after setTimeout function. The function with in setTimeout function will be sent to WebAPI and the variable declaration executed with in 5 seconds with the assigned value. Hence, the text declared for the variable will be displayed.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-75-what-is-the-output-of-below-code">75. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> b = <span class="hljs-number">10</span>;
<span class="hljs-built_in">console</span>.log(a === b);
</code></pre>
<ul>
<li>1: False</li>
<li>2: True</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Eventhough both variables <code>a</code> and <code>b</code> refer a number value, the first declaration is based on constructor function and the type of the variable is going to be <code>object</code> type. Whereas the second declaration is primitive assignment with a number and the type is <code>number</code> type. Hence, the equality operator <code>===</code> will output <code>false</code> value.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-76-what-is-the-type-of-below-function">76. What is the type of below function?</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The input arguments are: "</span>, a, b);
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<ul>
<li>1: Pure function</li>
<li>2: Impure function</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

Eventhough the above function returns the same result for the same arguments(input) that are passed in the function, the <code>console.log()</code> statement causes a function to have side effects because it affects the state of an external code. i.e, the <code>console</code> object's state and depends on it to perform the job. Hence, the above function considered as impure function.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-77-what-is-the-output-of-below-code">77. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> promiseOne = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">4000</span>));
<span class="hljs-keyword">const</span> promiseTwo = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(reject, <span class="hljs-number">4000</span>));

<span class="hljs-built_in">Promise</span>.all([promiseOne, promiseTwo]).then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
</code></pre>
<ul>
<li>1: [{status: "fulfilled", value: undefined}, {status: "rejected", reason: undefined}]</li>
<li>2: [{status: "fulfilled", value: undefined}, Uncaught(in promise)]</li>
<li>3: Uncaught (in promise)</li>
<li>4: [Uncaught(in promise), Uncaught(in promise)]</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

The above promises settled at the same time but one of them resolved and other one rejected. When you use <code>.all</code> method on these promises, the result will be short circuted by throwing an error due to rejection in second promise. But If you use <code>.allSettled</code> method then result of both the promises will be returned irrespective of resolved or rejected promise status without throwing any error.

<code>javascript
Promise.allSettled([promiseOne, promiseTwo]).then((data) =&gt; console.log(data));</code>

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-78-what-is-the-output-of-below-code">78. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"try block"</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`An exception is thrown`</span>);
  }, <span class="hljs-number">1000</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error: "</span>, err);
}
</code></pre>
<ul>
<li>1: try block, Error: An exception is thrown</li>
<li>2: Error: An exception is thrown</li>
<li>3: try block, Uncaught Error: Exception is thrown</li>
<li>4: Uncaught Error: Exception is thrown</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

If you put <code>setTimeout</code> and <code>setInterval</code> methods inside the try clause and an exception is thrown, the catch clause will not catch any of them. This is because the try...catch statement works synchronously, and the function in the above code is executed asynchronously after a certain period of time. Hence, you will see runtime exception without catching the error. To resolve this issue, you have to put the try...catch block inside the function as below,

<code>javascript
setTimeout(() =&gt; {
  try {
    console.log("try block");
    throw new Error(`An exception is thrown`);
  } catch (err) {
    console.log("Error: ", err);
  }
}, 1000);</code>

You can use <code>.catch()</code> function in promises to avoid these issues with asynchronous code.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-79-what-is-the-output-of-below-code">79. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">let</span> a = <span class="hljs-number">20</span>;
  <span class="hljs-built_in">console</span>.log(a, <span class="hljs-string">"inside"</span>);
}
<span class="hljs-built_in">console</span>.log(a, <span class="hljs-string">"outside"</span>);
</code></pre>
<ul>
<li>1: 20, "inside" and 20, "outside"</li>
<li>2: 20, "inside" and 10, "outside"</li>
<li>3: 10, "inside" and 10, "outside"</li>
<li>4: 10, "inside" and 20, "outside"</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 2

The variable "a" declared inside "if" has block scope and does not affect the value of the outer "a" variable.

</p>
</details>

<hr />
<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-80-what-is-the-output-of-below-code">80. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">-6</span>, <span class="hljs-number">7</span>];
arr.length = <span class="hljs-number">0</span>;
<span class="hljs-built_in">console</span>.log(arr);
</code></pre>
<ul>
<li>1: 0</li>
<li>2: Undefined</li>
<li>3: null</li>
<li>4: [ ]</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The length of the array 'arr' has been set to 0, so the array becomes empty.

</p>
</details>
---

<strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong>

#### 81. How do you verify two strings are anagrams or not?
An anagram is a word or phrase formed by rearranging all the letters of a different word or phrase exactly once. For example, the anagrams of "eat" word are "tea" and "ate".

You can split each word into characters, followed by sort action and later join them back. After that you can compare those two words to verify whether those two words are anagrams or not.

<code>javascript
function verifyAnagrams(word1, word2) {
  return word1.split("").sort().join("") === word2.split("").sort().join("")
}
console.log(verifyAnagrams("eat", "ate"));</code>

<strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong>

#### 82. What is the output of below code?

<code>javascript
printHello();

printMessage();

function printHello() {
  console.log('Hello')

  function printMessage() {
    console.log("Good day")
  }
}</code>

- 1: Hello, Good day
- 2: Reference Error: printHello is not defined, Reference Error: printMessage is not defined
- 3: Reference Error: printHello is not defined, Good day
- 4: Hello, Reference Error: printMessage is not defined

<details><summary><b>Answer</b></summary>
<p>

##### Answer: 4

The function <code>printHello</code> is hoisted to the top of the global scope and prints "Hello" to the console. Even <code>printMessage</code> function is hoisted, but it is lifted to the local scope(in "printHello") it was declared in. That is the reason you will endup with reference error for second function call.

But if the second function is invoked in the first function itself, there won't be any reference error.

<code>javascript
printHello();

function printHello() {
  printMessage();
  console.log('Hello')

  function printMessage() {
    console.log("Good day")
  }
}</code>

</p>
</details>
---

<strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong>

#### 83. What is the time taken to execute below timeout callback?

<code>javascript
  console.log("Start code");

  setTimeout(function() {
      console.log("Callback code");
  }, 5000);

  console.log("After callback");


  let startTime = new Date().getTime();
  let endTime = startTime;

  while(endTime &lt;= startTime + 10000) {
      endTime = new Date().getTime();
  }

  console.log("End code");</code>

- 1: &gt; 10 sec
- 2: Immediately
- 3: &lt; 10 sec
- 4: &lt;= 5sec

<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

Even though there is a timer of 5 seconds supplied to <code>setTimeout</code> callback, it won't get executed until the main thread is free and finished executing the remaining part of the code. In this example, the remaining code(while loop) takes 10seconds to finish it's execution. In the mean time, the callback will be stored in callback queue upon completion of its 5 seconds timer. After 10 seconds, the callback will be moved to callstack because the callstack is empty by poping out global execution context. 

</p>
</details>

<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-84-what-is-the-output-of-below-code">84. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-string">'wöchentlich'</span>,<span class="hljs-string">'Woche'</span>, <span class="hljs-string">'wäre'</span>, <span class="hljs-string">'Wann'</span>];
<span class="hljs-built_in">console</span>.log(arr.sort());
</code></pre>
<ul>
<li>1: ['wöchentlich','Woche', 'wäre', 'Wann']</li>
<li>2: ['Wann', 'wäre', 'Woche', 'wöchentlich']</li>
<li>3: ['Wann', 'Woche', 'wäre', 'wöchentlich']</li>
<li>4: ['wäre', 'Wann', 'wöchentlich','Woche']</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 3

Javascript has a native method sort that allows sorting an array of elements in-place. It will treat each element as a string and sort it alphabetically. But if you try to sort an array of strings which has non-ASCII characters, you will receive a strange result. This is because characters with an accent have higher character codes. 

In this case, the sort order of an array is ['Wann', 'Woche', 'wäre', 'wöchentlich'].

If you want to sort an array of string values which has non-ASCII characters in an ascending order,  there are two possible options like <strong>localeCompare</strong> and <strong>Intl.Collator</strong> provided by ECMAScript Internationalization API.

<strong>localeCompare:</strong>
<code>javascript
let arr = ['wöchentlich','Woche', 'wäre', 'Wann'];
console.log(arr.sort((a, b) =&gt; a.localeCompare(b))); //['Wann', 'wäre', 'Woche', 'wöchentlich']</code>
<strong>Intl.Collator:</strong>
<code>javascript
let arr = ['wöchentlich','Woche', 'wäre', 'Wann'];
console.log(arr.sort(Intl.Collator().compare)); //['Wann', 'wäre', 'Woche', 'wöchentlich']</code>

</p>
</details>

<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-85-what-is-the-output-of-below-code">85. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params">a, b=<span class="hljs-number">2</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>.length);
}

func(<span class="hljs-literal">undefined</span>);
func();
</code></pre>
<ul>
<li>1: 1, 0</li>
<li>2: 0, 0</li>
<li>3: 0, 1</li>
<li>4: 1, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

If a function is called with <code>undefined</code>, the <code>undefined</code> value is treated as a parameter. But if the function is not passed with any parameters, the <code>arguments</code> object doesn't include any argument eventhough the function has default function parameter. Hence, the function invocation with <code>undefined</code> has one argument and function call without any arguments has 0 arguments.

</p>
</details>

<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h4 id="heading-86-what-is-the-output-of-below-code">86. What is the output of below code?</h4>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params">a, b=<span class="hljs-number">2</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>.length);
}

func(<span class="hljs-literal">undefined</span>);
func();
</code></pre>
<ul>
<li>1: 1, 0</li>
<li>2: 0, 0</li>
<li>3: 0, 1</li>
<li>4: 1, 1</li>
</ul>
<details><summary><b>Answer</b></summary>
<p>

##### Answer: 1

If a function is called with <code>undefined</code>, the <code>undefined</code> value is treated as a parameter. But if the function is not passed with any parameters, the <code>arguments</code> object doesn't include any argument eventhough the function has default function parameter. Hence, the function invocation with <code>undefined</code> has one argument and function call without any arguments has 0 arguments.

</p>
</details>

<p><strong><a class="post-section-overview" href="#table-of-contents">⬆ Back to Top</a></strong></p>
<h2 id="heading-disclaimer">Disclaimer</h2>
<p>The questions provided in this repository are the summary of frequently asked questions across numerous companies. We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus on memorizing all of them. The primary purpose is for you to get a sense of what some companies might ask — do not get discouraged if you don't know the answer to all of them ⁠— that is ok!</p>
<p>Good luck with your interview 😊</p>
<hr />
]]></content:encoded></item><item><title><![CDATA[nodejs Interview Questions Part-3]]></title><description><![CDATA[Node.js follows an event-driven programming paradigm where actions are triggered by events. The core of Node.js, known as the event loop, continuously…]]></description><link>https://articles.tkssharma.com/nodejs-interview-questions-part-3</link><guid isPermaLink="true">https://articles.tkssharma.com/nodejs-interview-questions-part-3</guid><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Thu, 17 Oct 2024 17:09:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729184960942/9c111b42-33ee-4675-879c-c958775443ad.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-event-driven-programming-paradigm-in-nodejs">1. Event-Driven Programming Paradigm in Node.js</h1>
<p>Node.js follows an event-driven programming paradigm where actions are triggered by events. The core of Node.js, known as the event loop, continuously listens for events and executes associated callback functions. This non-blocking architecture enables asynchronous programming, making Node.js highly efficient and scalable.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);  
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> EventEmitter();  

<span class="hljs-comment">// Event listener for 'message' event  </span>
eventEmitter.on(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message received:'</span>, msg);  
});  

<span class="hljs-comment">// Emitting 'message' event  </span>
eventEmitter.emit(<span class="hljs-string">'message'</span>, <span class="hljs-string">'Hello, Node.js!'</span>);
</code></pre>
<h1 id="heading-2-non-blocking-io-in-nodejs">2. Non-Blocking I/O in Node.js</h1>
<p>Node.js utilizes non-blocking I/O operations, allowing multiple tasks to be performed concurrently without waiting for each other to complete. This asynchronous behavior enhances performance and scalability, making Node.js suitable for handling high loads.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);  

<span class="hljs-comment">// Non-blocking file read operation  </span>
fs.readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File content:'</span>, data);  
});
</code></pre>
<h1 id="heading-3-callback-functions-promises-and-asyncawait">3. Callback Functions, Promises, and async/await</h1>
<p>Node.js offers various mechanisms for handling asynchronous operations:</p>
<ul>
<li>Callback functions: Traditional approach, passing a function to be called when the operation completes.</li>
<li>Promises: Representing the eventual completion or failure of an asynchronous operation.</li>
<li>async/await: Syntactic sugar for writing asynchronous code using promises in a synchronous-like manner.</li>
</ul>
<p><strong>Example (Callback):</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{  
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {  
    callback(<span class="hljs-string">'Data fetched'</span>);  
  }, <span class="hljs-number">1000</span>);  
}  

fetchData(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(data);  
});
</code></pre>
<h1 id="heading-4-clustering-in-nodejs">4. Clustering in Node.js</h1>
<p>Clustering in Node.js involves running multiple instances of a Node.js process to take advantage of multi-core systems. It enhances performance and reliability by distributing incoming connections across multiple workers.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>);  
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);  
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).cpus().length;  

<span class="hljs-keyword">if</span> (cluster.isMaster) {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>);  

  <span class="hljs-comment">// Fork workers  </span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numCPUs; i++) {  
    cluster.fork();  
  }  
} <span class="hljs-keyword">else</span> {  
  <span class="hljs-comment">// Workers can share any TCP connection  </span>
  <span class="hljs-comment">// In this case, it's an HTTP server  </span>
  http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
    res.writeHead(<span class="hljs-number">200</span>);  
    res.end(<span class="hljs-string">'Hello, World!'</span>);  
  }).listen(<span class="hljs-number">8000</span>);  

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);  
}
</code></pre>
<h1 id="heading-5-handling-child-processes-in-nodejs">5. Handling Child Processes in Node.js</h1>
<p>Node.js allows spawning child processes to execute system commands or external scripts asynchronously. This is useful for tasks like parallel processing, task delegation, and interacting with system utilities.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'child_process'</span>);  

<span class="hljs-comment">// Executing system command  </span>
exec(<span class="hljs-string">'ls -l'</span>, <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (error) {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">`Error: <span class="hljs-subst">${error.message}</span>`</span>);  
    <span class="hljs-keyword">return</span>;  
  }  
  <span class="hljs-keyword">if</span> (stderr) {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">`stderr: <span class="hljs-subst">${stderr}</span>`</span>);  
    <span class="hljs-keyword">return</span>;  
  }  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`stdout: <span class="hljs-subst">${stdout}</span>`</span>);  
});
</code></pre>
<h1 id="heading-6-avoiding-callback-hell-in-nodejs">6. Avoiding Callback Hell in Node.js</h1>
<p>Callback hell refers to the nested structure of callback functions, leading to unreadable and unmaintainable code. It can be mitigated using techniques like modularization, promises, or async/await.</p>
<p><strong>Example (Promise):</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>).promises;  

fs.readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>)  
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File content:'</span>, data);  
  })  
  .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error reading file:'</span>, err);  
  });
</code></pre>
<h1 id="heading-7-popular-frameworks-and-libraries-in-nodejs">7. Popular Frameworks and Libraries in Node.js</h1>
<p>Node.js ecosystem boasts a plethora of frameworks and libraries catering to various needs:</p>
<ul>
<li>Express.js: A minimalist web framework for building robust web applications and APIs.</li>
<li>Koa.js: A next-generation web framework developed by the creators of Express, emphasizing modularity and async/await.</li>
<li>Socket.io: A library for real-time bidirectional communication between web clients and servers using WebSockets.</li>
<li>Nest.js: A progressive Node.js framework for building efficient, reliable, and scalable server-side applications.</li>
<li><p>Hapi.js: A rich framework for building applications and services, emphasizing configuration over code and enterprise-grade features.</p>
</li>
<li><h1 id="heading-scaling-a-nodejs-application-for-high-traffic-loads">Scaling a Node.js Application for High Traffic Loads</h1>
</li>
</ul>
<p>Scaling a Node.js application involves various strategies to handle high traffic loads efficiently:</p>
<ul>
<li>Horizontal scaling: Adding more instances of the application across multiple servers or containers.</li>
<li>Load balancing: Distributing incoming requests across multiple instances to prevent overload on any single server.</li>
<li>Caching: Implementing caching mechanisms to store frequently accessed data and reduce database load.</li>
<li><p>Asynchronous processing: Offloading time-consuming tasks to background workers or queues to keep the main application responsive.</p>
</li>
<li><h1 id="heading-common-performance-bottlenecks-in-nodejs-applications-and-mitigation">Common Performance Bottlenecks in Node.js Applications and Mitigation</h1>
</li>
</ul>
<p>Common performance bottlenecks in Node.js applications include:</p>
<ul>
<li>Blocking I/O operations: Replace synchronous operations with non-blocking alternatives to prevent event loop blocking.</li>
<li>Memory leaks: Identify and fix memory leaks using tools like heap snapshots and memory profilers.</li>
<li>Inefficient code: Optimize code for performance by minimizing unnecessary computations and improving algorithms.</li>
<li><p>Database queries: Use indexes, batch operations, and caching to optimize database queries and reduce response times.</p>
</li>
<li><h1 id="heading-microservices-architecture-in-nodejs-development">Microservices Architecture in Node.js Development</h1>
</li>
</ul>
<p>Microservices architecture involves breaking down a monolithic application into smaller, independently deployable services, each responsible for a specific functionality. In Node.js development, microservices offer benefits like scalability, resilience, and flexibility. Each microservice can be developed, deployed, and maintained independently, allowing teams to work in parallel and adopt different technologies as per requirements.</p>
<h1 id="heading-11-implementing-authentication-and-authorization-in-a-nodejs-microservices-architecture">11. Implementing Authentication and Authorization in a Node.js Microservices Architecture</h1>
<p>Authentication and authorization in a Node.js microservices architecture can be implemented using various strategies:</p>
<ul>
<li><strong>JWT (JSON Web Tokens)</strong>: Generate and verify tokens to authenticate users across microservices.</li>
<li><strong>Centralized Authentication Service</strong>: Implement a dedicated service for handling authentication and issuing tokens.</li>
<li><strong>API Gateway</strong>: Use an API gateway to handle authentication and route requests to appropriate microservices based on user permissions.</li>
<li><strong>OAuth</strong>: Integrate OAuth providers like Google or Facebook for third-party authentication.</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Middleware for verifying JWT tokens  </span>
<span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);  

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">authenticateToken</span>(<span class="hljs-params">req, res, next</span>) </span>{  
  <span class="hljs-keyword">const</span> token = req.headers[<span class="hljs-string">'authorization'</span>];  
  <span class="hljs-keyword">if</span> (token == <span class="hljs-literal">null</span>) <span class="hljs-keyword">return</span> res.sendStatus(<span class="hljs-number">401</span>);  

  jwt.verify(token, process.env.JWT_SECRET, <span class="hljs-function">(<span class="hljs-params">err, user</span>) =&gt;</span> {  
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> res.sendStatus(<span class="hljs-number">403</span>);  
    req.user = user;  
    next();  
  });  
}
</code></pre>
<h1 id="heading-12-understanding-graphql-and-its-comparison-with-restful-apis-in-nodejs">12. Understanding GraphQL and its Comparison with RESTful APIs in Node.js</h1>
<p>GraphQL is a query language for APIs that enables clients to request only the data they need, providing a more efficient and flexible alternative to traditional RESTful APIs. While RESTful APIs follow a fixed structure of endpoints, GraphQL allows clients to specify their data requirements in a single query.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"># GraphQL query  
query {  
  user(id: <span class="hljs-string">"123"</span>) {  
    name  
    email  
  }  
}
</code></pre>
<h1 id="heading-13-concept-of-websockets-and-their-use-in-nodejs-applications">13. Concept of WebSockets and their Use in Node.js Applications</h1>
<p>WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time communication between clients and servers. In Node.js, libraries like Socket.io simplify WebSocket implementation, facilitating bidirectional communication for features like chat applications and live updates.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Server-side WebSocket setup with Socket.io  </span>
<span class="hljs-keyword">const</span> io = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>)(httpServer);  

io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected'</span>);  

  socket.on(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =&gt;</span> {  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User disconnected'</span>);  
  });  

  socket.on(<span class="hljs-string">'chat message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Message:'</span>, msg);  
    io.emit(<span class="hljs-string">'chat message'</span>, msg);  
  });  
});
</code></pre>
<h1 id="heading-14-implementing-real-time-communication-between-clients-and-servers-in-nodejs">14. Implementing Real-Time Communication between Clients and Servers in Node.js</h1>
<p>Real-time communication between clients and servers in Node.js can be implemented using WebSockets or libraries like Socket.io. Clients and servers exchange messages in real-time, enabling features such as live chat, notifications, and collaborative editing.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Client-side WebSocket setup with Socket.io  </span>
<span class="hljs-keyword">const</span> socket = io();  

socket.on(<span class="hljs-string">'connect'</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connected to server'</span>);  

  socket.on(<span class="hljs-string">'chat message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received message:'</span>, msg);  
    <span class="hljs-comment">// Handle incoming message  </span>
  });  
});  

<span class="hljs-comment">// Send message to server  </span>
socket.emit(<span class="hljs-string">'chat message'</span>, <span class="hljs-string">'Hello, server!'</span>);
</code></pre>
<h1 id="heading-15-best-practices-for-logging-in-a-nodejs-application">15. Best Practices for Logging in a Node.js Application</h1>
<p>Some best practices for logging in a Node.js application include:</p>
<ul>
<li><strong>Use Winston or Bunyan</strong>: Choose a robust logging library like Winston or Bunyan for structured logging.</li>
<li><strong>Level-based Logging</strong>: Log messages at different levels (e.g., debug, info, error) to provide insights into application behavior.</li>
<li><strong>Contextual Logging</strong>: Include relevant metadata (e.g., request ID, user ID) in log messages for easier debugging.</li>
<li><p><strong>Centralized Logging</strong>: Aggregate logs from multiple instances into a central location for analysis and monitoring.</p>
</li>
<li><h1 id="heading-deploying-a-nodejs-application-in-a-containerized-environment-using-docker">Deploying a Node.js Application in a Containerized Environment using Docker</h1>
</li>
</ul>
<p>Deploying a Node.js application in a containerized environment using Docker involves the following steps:</p>
<ol>
<li><strong>Dockerfile</strong>: Create a Dockerfile in the root directory of your Node.js application, specifying the base image, copying application files, and configuring the startup command.</li>
</ol>
<pre><code class="lang-dockerfile"><span class="hljs-keyword">FROM</span> node:<span class="hljs-number">14</span>  

<span class="hljs-keyword">WORKDIR</span><span class="bash"> /usr/src/app  </span>

<span class="hljs-keyword">COPY</span><span class="bash"> package*.json ./  </span>
<span class="hljs-keyword">RUN</span><span class="bash"> npm install  </span>

<span class="hljs-keyword">COPY</span><span class="bash"> . .  </span>

<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">3000</span>  
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"node"</span>, <span class="hljs-string">"index.js"</span>]</span>
</code></pre>
<p><strong>2. Build Docker Image</strong>: Build the Docker image using the Docker CLI.</p>
<p>docker build -t my-node-app .</p>
<p><strong>3. Run Docker Container</strong>: Run the Docker container from the built image.</p>
<p>docker run -p 3000:3000 my-node-app</p>
<p>```</p>
<h1 id="heading-17-handling-long-running-tasks-in-a-nodejs-application-without-blocking-the-event-loop">17. Handling Long-Running Tasks in a Node.js Application without Blocking the Event Loop</h1>
<p>To handle long-running tasks in a Node.js application without blocking the event loop, use techniques like:</p>
<ul>
<li><strong>Child Processes</strong>: Offload heavy tasks to child processes using the <code>child_process</code> module.</li>
<li><strong>Worker Threads</strong>: Leverage Worker Threads API for running CPU-intensive tasks in parallel.</li>
<li><strong>Queues</strong>: Implement a message queue system like RabbitMQ or Redis to process tasks asynchronously.</li>
<li><p><strong>Streams</strong>: Use streams for processing large data sets without loading everything into memory at once.</p>
</li>
<li><h1 id="heading-security-vulnerabilities-in-nodejs-applications-and-mitigation">Security Vulnerabilities in Node.js Applications and Mitigation</h1>
</li>
</ul>
<p>Some security vulnerabilities specific to Node.js applications include:</p>
<ul>
<li><strong>Injection Attacks</strong>: Protect against SQL injection, NoSQL injection, and command injection by using parameterized queries and input validation.</li>
<li><strong>Cross-Site Scripting (XSS)</strong>: Sanitize user input and escape output to prevent XSS attacks.</li>
<li><strong>Cross-Site Request Forgery (CSRF)</strong>: Implement CSRF tokens and ensure that sensitive operations require user authentication.</li>
<li><p><strong>Denial of Service (DoS)</strong>: Implement rate limiting, request validation, and proper error handling to mitigate DoS attacks.</p>
</li>
<li><h1 id="heading-continuous-integration-and-continuous-deployment-cicd-in-nodejs-development">Continuous Integration and Continuous Deployment (CI/CD) in Node.js Development</h1>
</li>
</ul>
<p>Continuous Integration (CI) and Continuous Deployment (CD) automate the process of testing and deploying Node.js applications:</p>
<ul>
<li><strong>CI</strong>: Automatically build and test code changes in a shared repository whenever a new commit is pushed.</li>
<li><strong>CD</strong>: Automatically deploy tested code changes to production or staging environments based on predefined criteria (e.g., passing tests, code review approval).</li>
</ul>
<p>Popular CI/CD tools for Node.js include Jenkins, Travis CI, CircleCI, and GitHub Actions.</p>
<h1 id="heading-20-designing-and-implementing-a-robust-error-handling-strategy-in-a-large-scale-nodejs-application">20. Designing and Implementing a Robust Error Handling Strategy in a Large-Scale Node.js Application</h1>
<p>To design a robust error handling strategy in a large-scale Node.js application:</p>
<ul>
<li><strong>Centralized Error Handling</strong>: Implement a central error handling mechanism to catch and handle errors consistently across the application.</li>
<li><strong>Error Logging</strong>: Log errors with relevant details (e.g., stack trace, request context) for debugging and monitoring purposes.</li>
<li><strong>Graceful Shutdown</strong>: Gracefully handle unhandled exceptions and signals to ensure the application exits cleanly.</li>
<li><strong>Custom Error Classes</strong>: Define custom error classes to represent different types of errors and handle them appropriately.</li>
<li><strong>Retry Mechanisms</strong>: Implement retry mechanisms for transient errors to improve application resilience.</li>
</ul>
<p>These comprehensive guides cover a wide range of topics from beginner to advanced levels, providing valuable insights and practical examples to enhance your Node.js skills and ace your interviews. Be sure to check them out to complete your preparation journey!</p>
]]></content:encoded></item><item><title><![CDATA[Nodejs interview series Part-2]]></title><description><![CDATA[Nodejs interview series Part-2]]></description><link>https://articles.tkssharma.com/nodejs-interview-series-part-2</link><guid isPermaLink="true">https://articles.tkssharma.com/nodejs-interview-series-part-2</guid><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Thu, 17 Oct 2024 16:55:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729184999408/d52001b0-8a65-4117-b436-9f2c25093c60.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-what-is-middleware-in-the-context-of-expressjs-how-is-it-used">1. What is middleware in the context of Express.js? How is it used?</h1>
<p>Middleware in Express.js refers to functions that have access to the request, response, and the next middleware function in the application’s request-response cycle. It is used to perform tasks such as logging, authentication, and error handling.</p>
<p><strong>Example:</strong> Logging Middleware</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Logging middleware  </span>
app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request received:'</span>, req.method, req.url);  
  next(); <span class="hljs-comment">// Pass control to the next middleware  </span>
});  

<span class="hljs-comment">// Route handler  </span>
app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.send(<span class="hljs-string">'Hello, Express!'</span>);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-2-explain-the-concept-of-streams-in-nodejs-when-would-you-use-them">2. Explain the concept of streams in Node.js. When would you use them?</h1>
<p>Streams in Node.js are objects that allow reading or writing data continuously. They are especially useful when working with large amounts of data, as they enable processing data in chunks, reducing memory consumption and improving performance.</p>
<p><strong>Example:</strong> Reading from a Stream</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);  

<span class="hljs-keyword">const</span> stream = fs.createReadStream(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>);  
stream.on(<span class="hljs-string">'data'</span>, <span class="hljs-function"><span class="hljs-params">chunk</span> =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received chunk:'</span>, chunk);  
});  
stream.on(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Stream ended'</span>);  
});
</code></pre>
<h1 id="heading-3-how-does-error-handling-differ-in-synchronous-and-asynchronous-code-in-nodejs">3. How does error handling differ in synchronous and asynchronous code in Node.js?</h1>
<p>In synchronous code, errors are handled using try-catch blocks, where exceptions are caught synchronously. In asynchronous code, errors are typically handled using callback conventions, where the first argument of the callback function represents an error object.</p>
<p><strong>Example:</strong> Synchronous Error Handling</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {  
  <span class="hljs-comment">// Synchronous code that may throw an error  </span>
} <span class="hljs-keyword">catch</span> (error) {  
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error);  
}

**Example:** Asynchronous <span class="hljs-built_in">Error</span> Handling

fs.readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error reading file:'</span>, err);  
    <span class="hljs-keyword">return</span>;  
  }  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File content:'</span>, data);  
});
</code></pre>
<h1 id="heading-4-how-do-you-debug-a-nodejs-application">4. How do you debug a Node.js application?</h1>
<p>Node.js provides built-in debugging support through the Node Inspector tool. Additionally, developers can use console.log statements, the <code>debugger</code> keyword, or third-party debugging tools like Visual Studio Code for debugging Node.js applications.</p>
<p><strong>Example:</strong> Using console.log for Debugging</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> variable = <span class="hljs-string">'test'</span>;  
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Variable:'</span>, variable);
</code></pre>
<h1 id="heading-5-explain-the-concept-of-restful-apis-and-how-they-are-implemented-in-nodejs">5. Explain the concept of RESTful APIs and how they are implemented in Node.js.</h1>
<p>RESTful APIs are web APIs that adhere to the principles of Representational State Transfer (REST). They use standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources. In Node.js, RESTful APIs can be implemented using frameworks like Express.js.</p>
<p><strong>Example:</strong> Creating a RESTful API with Express.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Route handler for GET request to '/users'  </span>
app.get(<span class="hljs-string">'/users'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-comment">// Logic to retrieve users from the database  </span>
  res.json({ <span class="hljs-attr">users</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span> }, { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span> }] });  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-6-what-are-some-security-best-practices-when-developing-a-nodejs-application">6. What are some security best practices when developing a Node.js application?</h1>
<p>When developing Node.js applications, it’s essential to follow security best practices such as validating input data, using parameterized queries to prevent SQL injection, implementing authentication and authorization mechanisms, and regularly updating dependencies to patch security vulnerabilities.</p>
<p><strong>Example:</strong> Input Data Validation</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> Joi = <span class="hljs-built_in">require</span>(<span class="hljs-string">'joi'</span>); <span class="hljs-comment">// Validation library  </span>

<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Middleware for validating request body  </span>
app.use(express.json());  

<span class="hljs-comment">// Route handler for POST request to '/login'  </span>
app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-comment">// Validate request body  </span>
  <span class="hljs-keyword">const</span> schema = Joi.object({  
    <span class="hljs-attr">username</span>: Joi.string().alphanum().min(<span class="hljs-number">3</span>).max(<span class="hljs-number">30</span>).required(),  
    <span class="hljs-attr">password</span>: Joi.string().pattern(<span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(<span class="hljs-string">'^[a-zA-Z0-9]{3,30}$'</span>)).required(),  
  });  
  <span class="hljs-keyword">const</span> { error } = schema.validate(req.body);  
  <span class="hljs-keyword">if</span> (error) {  
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(error.details[<span class="hljs-number">0</span>].message);  
  }  
  <span class="hljs-comment">// Continue with login logic  </span>
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-7-how-do-you-handle-database-operations-in-a-nodejs-application">7. How do you handle database operations in a Node.js application?</h1>
<p>In Node.js applications, database operations are typically performed using database drivers or ORMs (Object-Relational Mappers) such as Sequelize or Mongoose. These libraries provide APIs for connecting to databases, executing queries, and interacting with database models.</p>
<p><strong>Example:</strong> Database Operation with Sequelize</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { Sequelize, DataTypes } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'sequelize'</span>);  

<span class="hljs-comment">// Initialize Sequelize  </span>
<span class="hljs-keyword">const</span> sequelize = <span class="hljs-keyword">new</span> Sequelize(<span class="hljs-string">'sqlite::memory:'</span>);  

<span class="hljs-comment">// Define a model  </span>
<span class="hljs-keyword">const</span> User = sequelize.define(<span class="hljs-string">'User'</span>, {  
  <span class="hljs-attr">username</span>: DataTypes.STRING,  
  <span class="hljs-attr">email</span>: DataTypes.STRING,  
});  

<span class="hljs-comment">// Create a new user  </span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUser</span>(<span class="hljs-params">username, email</span>) </span>{  
  <span class="hljs-keyword">await</span> User.create({ username, email });  
}  

createUser(<span class="hljs-string">'john_doe'</span>, <span class="hljs-string">'john@example.com'</span>);
</code></pre>
<h1 id="heading-8-what-is-the-role-of-the-process-object-in-nodejs-give-examples-of-its-usage">8. What is the role of the process object in Node.js? Give examples of its usage.</h1>
<p>The process object in Node.js provides information and control over the Node.js process. It allows access to environment variables, command-line arguments, and provides methods for exiting the process or listening for signals.</p>
<p><strong>Example:</strong> Accessing Command-Line Arguments</p>
<p>console.log('Arguments:', process.argv);</p>
<h1 id="heading-9-explain-the-difference-between-setimmediate-settimeout-and-processnexttick-in-nodejs">9. Explain the difference between setImmediate(), setTimeout(), and process.nextTick() in Node.js.</h1>
<ul>
<li><code>setImmediate()</code> schedules a callback function to be executed in the next iteration of the event loop.</li>
<li><code>setTimeout()</code> schedules a callback function to be executed after a specified delay.</li>
<li><p><code>process.nextTick()</code> schedules a callback function to be executed immediately after the current operation completes, before the event loop continues.</p>
</li>
<li><h1 id="heading-what-is-session-management-in-expressjs-how-can-it-be-implemented">What is session management in Express.js? How can it be implemented?</h1>
</li>
</ul>
<p>Session management in Express.js involves maintaining user sessions and managing session data across multiple requests. It can be implemented using session middleware like <code>express-session</code> and storing session data in memory, a database, or a session store like Redis.</p>
<p><strong>Example:</strong> Implementing Session Management with express-session</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Session middleware  </span>
app.use(session({  
  <span class="hljs-attr">secret</span>: <span class="hljs-string">'secret-key'</span>,  
  <span class="hljs-attr">resave</span>: <span class="hljs-literal">false</span>,  
  <span class="hljs-attr">saveUninitialized</span>: <span class="hljs-literal">true</span>,  
}));  

<span class="hljs-comment">// Route handler for setting session data  </span>
app.get(<span class="hljs-string">'/set-session'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  req.session.username = <span class="hljs-string">'john_doe'</span>;  
  res.send(<span class="hljs-string">'Session data set'</span>);  
});  

<span class="hljs-comment">// Route handler for getting session data  </span>
app.get(<span class="hljs-string">'/get-session'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-keyword">const</span> username = req.session.username || <span class="hljs-string">'Guest'</span>;  
  res.send(<span class="hljs-string">'Session data: '</span> + username);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-11-how-do-you-handle-file-uploads-in-an-expressjs-application">11. How do you handle file uploads in an Express.js application?</h1>
<p>File uploads in an Express.js application can be handled using middleware like <code>multer</code>. Multer provides easy handling of multipart/form-data, which is typically used for file uploads.</p>
<p><strong>Example:</strong> Handling File Uploads with Multer</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> multer = <span class="hljs-built_in">require</span>(<span class="hljs-string">'multer'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Multer middleware for handling file uploads  </span>
<span class="hljs-keyword">const</span> upload = multer({ <span class="hljs-attr">dest</span>: <span class="hljs-string">'uploads/'</span> });  

<span class="hljs-comment">// Route handler for file upload  </span>
app.post(<span class="hljs-string">'/upload'</span>, upload.single(<span class="hljs-string">'file'</span>), <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-comment">// File uploaded successfully  </span>
  res.send(<span class="hljs-string">'File uploaded'</span>);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-12-what-are-the-differences-between-require-and-import-in-nodejs">12. What are the differences between require() and import in Node.js?</h1>
<p><code>require()</code> is a CommonJS module system function used to import modules in Node.js, while <code>import</code> is an ES6 feature used for importing modules in modern JavaScript environments. Here's an example of <code>require()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

And here’s an example <span class="hljs-keyword">of</span> <span class="hljs-string">`import`</span>:

<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'fs'</span>;
</code></pre>
<h1 id="heading-13-what-is-authentication-how-is-it-implemented-in-nodejs-applications">13. What is authentication? How is it implemented in Node.js applications?</h1>
<p>Authentication is the process of verifying the identity of a user. In Node.js applications, authentication can be implemented using techniques such as username/password authentication, JSON Web Tokens (JWT), OAuth, and session-based authentication. Here’s a basic example of session-based authentication:</p>
<pre><code class="lang-js">app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-comment">// Validate username and password  </span>
  <span class="hljs-keyword">if</span> (req.body.username === <span class="hljs-string">'user'</span> &amp;&amp; req.body.password === <span class="hljs-string">'password'</span>) {  
    <span class="hljs-comment">// Set authenticated session  </span>
    req.session.authenticated = <span class="hljs-literal">true</span>;  
    res.send(<span class="hljs-string">'Login successful'</span>);  
  } <span class="hljs-keyword">else</span> {  
    res.status(<span class="hljs-number">401</span>).send(<span class="hljs-string">'Invalid username or password'</span>);  
  }  
});
</code></pre>
<h1 id="heading-14-explain-the-concept-of-middleware-chaining-in-expressjs">14. Explain the concept of middleware chaining in Express.js.</h1>
<p>Middleware chaining in Express.js involves using multiple middleware functions sequentially in the request-response cycle. Each middleware function can perform its specific task and pass control to the next middleware using the <code>next()</code> function. Here's an example:</p>
<pre><code class="lang-js">app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Middleware 1'</span>);  
  next();  
});  

app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Middleware 2'</span>);  
  next();  
});
</code></pre>
<h1 id="heading-15-how-do-you-handle-cors-cross-origin-resource-sharing-in-a-nodejs-application">15. How do you handle CORS (Cross-Origin Resource Sharing) in a Node.js application?</h1>
<p>CORS in a Node.js application can be handled using middleware like <code>cors</code>. Here's an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>);  

app.use(cors());
</code></pre>
<p>This allows requests from any origin by default. You can also configure CORS options to restrict origins, methods, and headers.</p>
<h1 id="heading-16-what-are-the-advantages-of-using-a-templating-engine-like-ejs-or-handlebars-in-expressjs">16. What are the advantages of using a templating engine like EJS or Handlebars in Express.js?</h1>
<p>Templating engines like EJS or Handlebars allow developers to generate dynamic HTML content on the server-side by embedding JavaScript code into HTML templates. They simplify the process of building dynamic web pages and separating presentation logic from business logic. Here’s an example of using EJS:</p>
<pre><code class="lang-js">app.set(<span class="hljs-string">'view engine'</span>, <span class="hljs-string">'ejs'</span>);
</code></pre>
<h1 id="heading-17-how-do-you-deploy-a-nodejs-application-to-a-production-server">17. How do you deploy a Node.js application to a production server?</h1>
<p>Node.js applications can be deployed to production servers using various deployment strategies such as manual deployment, continuous integration/continuous deployment (CI/CD) pipelines, containerization with Docker, and cloud platforms like AWS, Heroku, or Azure.</p>
<h1 id="heading-18-explain-the-purpose-of-the-expressstatic-middleware-in-expressjs">18. Explain the purpose of the express.static() middleware in Express.js.</h1>
<p>The <code>express.static()</code> middleware in Express.js is used to serve static files such as images, CSS, JavaScript, and other assets from a specified directory. Here's an example:</p>
<pre><code class="lang-js">app.use(express.static(<span class="hljs-string">'public'</span>));
</code></pre>
<p>This serves files from the <code>public</code> directory relative to the application root.</p>
<h1 id="heading-19-what-are-route-parameters-in-expressjs-how-do-you-access-them">19. What are route parameters in Express.js? How do you access them?</h1>
<p>Route parameters in Express.js are placeholders in the route definition that capture values from the URL. They are specified in the route path using colon syntax (<code>:</code>) and can be accessed in route handlers using <code>req.params</code>. Here's an example:</p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/users/:userId'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-keyword">const</span> userId = req.params.userId;  
  <span class="hljs-comment">// Use userId in the route handler  </span>
});
</code></pre>
<h1 id="heading-20-how-do-you-handle-sessions-and-cookies-in-an-expressjs-application">20. How do you handle sessions and cookies in an Express.js application?</h1>
<p>Sessions and cookies in an Express.js application can be handled using middleware like <code>express-session</code> and <code>cookie-parser</code>. Here's an example of setting up sessions:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>);  
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>);  

app.use(cookieParser());  
app.use(session({ <span class="hljs-attr">secret</span>: <span class="hljs-string">'secret-key'</span>, <span class="hljs-attr">resave</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">saveUninitialized</span>: <span class="hljs-literal">true</span> }));
</code></pre>
<h1 id="heading-conclusion">Conclusion:</h1>
<p>Mastering intermediate-level concepts in Node.js is essential for excelling in interviews and building robust applications. In this article, we’ve covered various topics including middleware, streams, error handling, RESTful APIs, security best practices, database operations, and more. Armed with these insights and examples, you’re well-equipped to tackle advanced Node.js interview questions and take your skills to the next level.</p>
<p>Continue your Node.js interview preparation journey with our comprehensive guides:</p>
<p>Stay tuned for more insightful content and happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Nodejs Interview Series Part-1]]></title><description><![CDATA[Nodejs interview series Part-1]]></description><link>https://articles.tkssharma.com/nodejs-interview-series-part-1</link><guid isPermaLink="true">https://articles.tkssharma.com/nodejs-interview-series-part-1</guid><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Thu, 17 Oct 2024 16:53:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729185038378/181469ef-ebab-49bd-850e-4833e3b3898c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-1-what-is-nodejs-explain-its-main-features-and-advantages">1. What is Node.js? Explain its main features and advantages.</h1>
<p>Node.js is a server-side JavaScript runtime built on Chrome’s V8 JavaScript engine. Its main features include:</p>
<ul>
<li><strong>Asynchronous and Event-Driven:</strong> Node.js uses non-blocking, event-driven I/O, making it lightweight and efficient.</li>
<li><strong>Single-threaded:</strong> Utilizes a single-threaded event loop to handle multiple concurrent connections.</li>
<li><strong>Cross-platform:</strong> Runs on various operating systems, including Windows, macOS, and Linux.</li>
<li><strong>Vast Ecosystem:</strong> Supported by a rich ecosystem of packages and modules available via npm.</li>
</ul>
<p><strong>Example:</strong> Hello World in Node.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, Node.js!'</span>);
</code></pre>
<h1 id="heading-2-how-does-nodejs-differ-from-traditional-server-side-platforms-like-apache-or-nginx">2. How does Node.js differ from traditional server-side platforms like Apache or Nginx?</h1>
<p>Unlike traditional platforms, Node.js follows an asynchronous, non-blocking I/O model. While Apache or Nginx rely on a multi-threaded approach, Node.js uses a single-threaded event loop, making it highly scalable and suitable for real-time applications.</p>
<h1 id="heading-3-what-is-npm-how-is-it-used-in-nodejs-development">3. What is npm? How is it used in Node.js development?</h1>
<p>npm (Node Package Manager) is the default package manager for Node.js, used for installing, managing, and sharing JavaScript packages. It simplifies dependency management and facilitates package discovery and installation.</p>
<p><strong>Example:</strong> Installing Express.js using npm</p>
<p>npm install express</p>
<h1 id="heading-4-what-is-the-purpose-of-the-packagejson-file-in-a-nodejs-project">4. What is the purpose of the package.json file in a Node.js project?</h1>
<p>The package.json file serves as a manifest for Node.js projects, containing metadata such as project name, version, dependencies, and scripts. It facilitates project initialization, dependency installation, and script execution.</p>
<p><strong>Example:</strong> Sample package.json</p>
<pre><code class="lang-json">{  
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-node-app"</span>,  
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,  
  <span class="hljs-attr">"dependencies"</span>: {  
    <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.17.1"</span>  
  },  
  <span class="hljs-attr">"scripts"</span>: {  
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node index.js"</span>  
  }  
}
</code></pre>
<h1 id="heading-5-describe-the-role-of-modules-in-nodejs-how-are-they-created-and-used">5. Describe the role of modules in Node.js. How are they created and used?</h1>
<p>Modules in Node.js are encapsulated blocks of code that can be reused across multiple files or projects. They promote code organization, modularity, and reusability. Modules are created using the <code>module.exports</code> or <code>exports</code> objects and imported using the <code>require</code> function.</p>
<p><strong>Example:</strong> Creating and Using a Module</p>
<pre><code class="lang-js"><span class="hljs-comment">// math.js  </span>
<span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;  
<span class="hljs-keyword">const</span> subtract = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b;  

<span class="hljs-built_in">module</span>.exports = { add, subtract };

<span class="hljs-comment">// index.js  </span>
<span class="hljs-keyword">const</span> math = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./math'</span>);  

<span class="hljs-built_in">console</span>.log(math.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 8  </span>
<span class="hljs-built_in">console</span>.log(math.subtract(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 2</span>
</code></pre>
<h1 id="heading-6-what-is-the-purpose-of-the-dirname-and-filename-variables-in-nodejs">6. What is the purpose of the <strong>dirname and </strong>filename variables in Node.js?</h1>
<p><code>__dirname</code> and <code>__filename</code> are special variables in Node.js that provide the directory name and filename of the currently executing script, respectively. They are useful for resolving file paths and determining the location of the executing script.</p>
<p><strong>Example:</strong> Using <strong>dirname and </strong>filename</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(__dirname); <span class="hljs-comment">// Output: /path/to/current/directory  </span>
<span class="hljs-built_in">console</span>.log(__filename); <span class="hljs-comment">// Output: /path/to/current/file.js</span>
</code></pre>
<h1 id="heading-7-how-do-you-install-external-dependencies-in-a-nodejs-project-using-npm">7. How do you install external dependencies in a Node.js project using npm?</h1>
<p>npm simplifies dependency management in Node.js projects. To install external dependencies, use the <code>npm install</code> command followed by the package name.</p>
<p><strong>Example:</strong> Installing External Dependency</p>
<p>npm install express</p>
<h1 id="heading-8-explain-the-concept-of-callback-functions-in-nodejs-provide-an-example">8. Explain the concept of callback functions in Node.js. Provide an example.</h1>
<p>In Node.js, callback functions are functions passed as arguments to other functions and are executed asynchronously once the operation completes. They are commonly used for handling asynchronous tasks such as I/O operations and event handling.</p>
<p><strong>Example:</strong> Asynchronous File Read using Callbacks</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);  

fs.readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error reading file:'</span>, err);  
    <span class="hljs-keyword">return</span>;  
  }  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File content:'</span>, data);  
});
</code></pre>
<h1 id="heading-9-what-is-the-nodejs-event-loop-how-does-it-work">9. What is the Node.js event loop? How does it work?</h1>
<p>The Node.js event loop is a single-threaded mechanism responsible for handling I/O operations, callbacks, and asynchronous tasks. It continuously loops, waiting for events to occur, executing callbacks, and processing asynchronous tasks without blocking the main thread.</p>
<h1 id="heading-10-how-can-you-handle-errors-in-nodejs-applications">10. How can you handle errors in Node.js applications?</h1>
<p>Node.js provides various error-handling mechanisms, including try-catch blocks, error events, and callback conventions. Handling errors effectively involves identifying potential error sources, implementing appropriate error-handling strategies, and providing meaningful error messages.</p>
<p><strong>Example:</strong> Handling Errors with try-catch</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {  
  <span class="hljs-comment">// Code that may throw an error  </span>
} <span class="hljs-keyword">catch</span> (error) {  
  <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'An error occurred:'</span>, error);  
}
</code></pre>
<h1 id="heading-11-what-is-asynchronous-programming-in-nodejs-why-is-it-important">11. What is asynchronous programming in Node.js? Why is it important?</h1>
<p>Asynchronous programming in Node.js allows multiple tasks to be executed concurrently without blocking the event loop. It enhances application performance and responsiveness, particularly in I/O-bound operations, by leveraging non-blocking I/O and callback mechanisms.</p>
<h1 id="heading-12-how-do-you-read-and-write-files-in-nodejs">12. How do you read and write files in Node.js?</h1>
<p>Node.js provides built-in modules like fs (File System) for reading and writing files asynchronously or synchronously. Asynchronous file operations are preferred for non-blocking I/O, while synchronous operations are suitable for blocking scenarios.</p>
<p><strong>Example:</strong> Asynchronous File Write</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);  

<span class="hljs-keyword">const</span> content = <span class="hljs-string">'Hello, Node.js!'</span>;  
fs.writeFile(<span class="hljs-string">'example.txt'</span>, content, <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) {  
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error writing to file:'</span>, err);  
    <span class="hljs-keyword">return</span>;  
  }  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File written successfully.'</span>);  
});
</code></pre>
<h1 id="heading-13-what-is-expressjs-how-does-it-simplify-building-web-applications-with-nodejs">13. What is Express.js? How does it simplify building web applications with Node.js?</h1>
<p>Express.js is a minimal and flexible web application framework for Node.js, designed for building web and API applications. It simplifies common web development tasks such as routing, middleware integration, and request handling, enabling rapid development of scalable and robust applications.</p>
<p><strong>Example:</strong> Creating a Simple Express Server</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> app = express();  

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.send(<span class="hljs-string">'Hello, Express!'</span>);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-14-explain-the-concept-of-middleware-in-expressjs">14. Explain the concept of middleware in Express.js.</h1>
<p>Middleware in Express.js are functions that have access to the request, response, and next middleware function in the application’s request-response cycle. They can perform tasks such as logging, authentication, and error handling, enhancing the functionality of the application.</p>
<p><strong>Example:</strong> Custom Middleware for Logging</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Custom middleware function for logging  </span>
<span class="hljs-keyword">const</span> logger = <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Request received:'</span>, req.method, req.url);  
  next(); <span class="hljs-comment">// Pass control to the next middleware function  </span>
};  

app.use(logger);  

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.send(<span class="hljs-string">'Hello, Express!'</span>);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-15-what-is-routing-in-expressjs-how-is-it-implemented">15. What is routing in Express.js? How is it implemented?</h1>
<p>Routing in Express.js refers to the process of defining routes that map HTTP requests to handler functions. It allows developers to define multiple endpoints and handle different HTTP methods (GET, POST, PUT, DELETE) for those endpoints.</p>
<p><strong>Example:</strong> Basic Route Handling in Express.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Route handler for GET request to '/'  </span>
app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.send(<span class="hljs-string">'Hello, Express!'</span>);  
});  

<span class="hljs-comment">// Route handler for POST request to '/users'  </span>
app.post(<span class="hljs-string">'/users'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.send(<span class="hljs-string">'User created successfully'</span>);  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-16-how-do-you-create-a-simple-http-server-in-nodejs">16. How do you create a simple HTTP server in Node.js?</h1>
<p>Node.js provides the <code>http</code> module for creating HTTP servers. By leveraging the <code>http.createServer()</code> method, developers can create a basic HTTP server that listens for incoming requests and handles them accordingly.</p>
<p><strong>Example:</strong> Creating a Simple HTTP Server</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);  

<span class="hljs-keyword">const</span> server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>});  
  res.end(<span class="hljs-string">'Hello, world!n'</span>);  
});  

server.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running at http://localhost:3000/'</span>);  
});
</code></pre>
<h1 id="heading-17-describe-the-role-of-the-require-function-in-nodejs">17. Describe the role of the require function in Node.js.</h1>
<p>The <code>require</code> function in Node.js is used to import modules or files in a Node.js application. It loads the module and returns its <code>exports</code> object, allowing developers to access its functionality and variables.</p>
<p><strong>Example:</strong> Using require to Import Modules</p>
<pre><code class="lang-js"><span class="hljs-comment">// Importing the 'fs' module  </span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);  

<span class="hljs-comment">// Using the 'fs' module to read a file  </span>
fs.readFile(<span class="hljs-string">'example.txt'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File content:'</span>, data);  
});
</code></pre>
<h1 id="heading-18-what-are-global-objects-in-nodejs-give-examples">18. What are global objects in Node.js? Give examples.</h1>
<p>Global objects in Node.js are objects available in all modules without the need for importing. Examples include <code>console</code> for logging, <code>process</code> for accessing environment variables and command-line arguments, and <code>Buffer</code> for handling binary data.</p>
<p><strong>Example:</strong> Using the console Object</p>
<p>console.log('Hello, Node.js!');</p>
<h1 id="heading-19-how-do-you-handle-form-data-in-an-expressjs-application">19. How do you handle form data in an Express.js application?</h1>
<p>In an Express.js application, form data can be handled using middleware such as <code>body-parser</code> to parse incoming request bodies. This middleware extracts form data from <code>POST</code> requests and makes it accessible via <code>req.body</code>.</p>
<p><strong>Example:</strong> Handling Form Data with body-parser Middleware</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);  
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>);  
<span class="hljs-keyword">const</span> app = express();  

<span class="hljs-comment">// Middleware for parsing form data  </span>
app.use(bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> }));  

<span class="hljs-comment">// Route handler for POST request to '/submit'  </span>
app.post(<span class="hljs-string">'/submit'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
  <span class="hljs-keyword">const</span> formData = req.body;  
  res.send(<span class="hljs-string">'Form data received: '</span> + <span class="hljs-built_in">JSON</span>.stringify(formData));  
});  

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>);  
});
</code></pre>
<h1 id="heading-20-what-is-the-role-of-environment-variables-in-nodejs-development">20. What is the role of environment variables in Node.js development?</h1>
<p>Environment variables in Node.js are dynamic variables used to configure and customize application behavior based on the environment. They provide a convenient way to store sensitive information like database credentials or API keys without hardcoding them into the codebase.</p>
<p><strong>Example:</strong> Accessing Environment Variables</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;  
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${port}</span>`</span>);
</code></pre>
<p>By mastering these fundamental concepts and examples, you’re well on your way to becoming proficient in Node.js development. Stay tuned for the next part of our guide, where we’ll delve into intermediate-level topics and practical examples to further enhance your Node.js skills.</p>
]]></content:encoded></item><item><title><![CDATA[Nodejs crack backend Jobs]]></title><description><![CDATA[Node.js is an open-source server side runtime environment built on Chrome\'s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous)…]]></description><link>https://articles.tkssharma.com/nodejs-crack-backend-jobs</link><guid isPermaLink="true">https://articles.tkssharma.com/nodejs-crack-backend-jobs</guid><category><![CDATA[crack interview]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[jobs]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Fri, 11 Oct 2024 14:26:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728656783227/03ad078b-e321-4f9c-a2ae-dfefa26ffca2.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-nodejs-interview-questions">Node.js Interview Questions</h1>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#-1-introduction">Introduction</a></li>
<li><a class="post-section-overview" href="#-2-nodejs-setup">Node.js Setup</a></li>
<li><a class="post-section-overview" href="#-3-nodejs-data-types">Node.js Data Types</a></li>
<li><a class="post-section-overview" href="#-4-nodejs-architecture">Node.js Architecture</a></li>
<li><a class="post-section-overview" href="#-5-nodejs-events">Node.js Events</a></li>
<li><a class="post-section-overview" href="#-6-nodejs-file-system">Node.js File System</a></li>
<li><a class="post-section-overview" href="#-7-nodejs-streams">Node.js Streams</a></li>
<li><a class="post-section-overview" href="#-8-nodejs-multithreading">Node.js Multithreading</a></li>
<li><a class="post-section-overview" href="#-9-nodejs-web-module">Node.js Web Module</a></li>
<li><a class="post-section-overview" href="#-10-nodejs-middleware">Node.js Middleware</a></li>
<li><a class="post-section-overview" href="#-11-nodejs-restful-api">Node.js RESTFul API</a></li>
<li><a class="post-section-overview" href="#-12-nodejs-routing">Node.js Routing</a></li>
<li><a class="post-section-overview" href="#-13-nodejs-caching">Node.js Caching</a></li>
<li><a class="post-section-overview" href="#-14-nodejs-error-handling">Node.js Error Handling</a></li>
<li><a class="post-section-overview" href="#-15-nodejs-logging">Node.js Logging</a></li>
<li><a class="post-section-overview" href="#-16-nodejs-internationalization">Node.js Internationalization</a></li>
<li><a class="post-section-overview" href="#-17-nodejs-testing">Node.js Testing</a></li>
<li><a class="post-section-overview" href="#-18-nodejs-miscellaneous">Node.js Miscellaneous</a></li>
</ul>
<p><br /></p>
<h2 id="heading-1-introduction"># 1. INTRODUCTION</h2>
<p><br /></p>
<h2 id="heading-q-what-is-nodejs">Q. What is Node.js?</h2>
<p>Node.js is an open-source server side runtime environment built on Chrome\'s V8 JavaScript engine. It provides an event driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-nodejs-process-model">Q. What is Node.js Process Model?</h2>
<p>Node.js runs in a single process and the application code runs in a single thread and thereby needs less resources than other platforms.</p>
<p>All the user requests to your web application will be handled by a single thread and all the I/O work or long running job is performed asynchronously for a particular request. So, this single thread doesn\'t have to wait for the request to complete and is free to handle the next request. When asynchronous I/O work completes then it processes the request further and sends the response.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-key-features-of-nodejs">Q. What are the key features of Node.js?</h2>
<ul>
<li><p><strong>Asynchronous and Event driven</strong> – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.</p>
</li>
<li><p><strong>Fast in Code execution</strong> – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.</p>
</li>
<li><p><strong>Single Threaded but Highly Scalable</strong> – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.</p>
</li>
<li><p><strong>Node.js library uses JavaScript</strong> – This is another important aspect of Node.js from the developer\'s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.</p>
</li>
<li><p><strong>There is an Active and vibrant community for the Node.js framework</strong> – The active community always keeps the framework updated with the latest trends in the web development.</p>
</li>
<li><p><strong>No Buffering</strong> – Node.js applications never buffer any data. They simply output the data in chunks.</p>
</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-how-does-nodejs-work">Q. Explain how does Node.js work?</h2>
<p>A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.</p>
<p>Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn\'t have to wait if the processing is not complete.</p>
<p>While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-2-nodejs-setup"># 2. NODE.JS SETUP</h2>
<p><br /></p>
<h2 id="heading-q-how-to-create-a-simple-server-in-nodejs-that-returns-hello-world">Q. How to create a simple server in Node.js that returns Hello World?</h2>
<p><strong>Step 01</strong>: Create a project directory</p>
<pre><code class="lang-js">mkdir myapp
cd myapp
</code></pre>
<p><strong>Step 02</strong>: Initialize project and link it to npm</p>
<pre><code class="lang-js">npm init
</code></pre>
<p>This creates a <code>package.json</code> file in your myapp folder. The file contains references for all npm packages you have downloaded to your project. The command will prompt you to enter a number of things.
You can enter your way through all of them EXCEPT this one:</p>
<pre><code class="lang-js">entry point: (index.js)
</code></pre>
<p>Rename this to:</p>
<pre><code class="lang-js">app.js
</code></pre>
<p><strong>Step 03</strong>: Install Express in the myapp directory</p>
<pre><code class="lang-js">npm install express --save
</code></pre>
<p><strong>Step 04</strong>: app.js</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Express.js
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'Hello World!'</span>);
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'App listening on port 3000!'</span>);
});
</code></pre>
<p><strong>Step 05</strong>: Run the app</p>
<pre><code class="lang-bah">node app.js
</code></pre>
<p><strong>⚝ <a target="_blank" href="https://codesandbox.io/s/hello-world-in-nodejs-ue3cs3">Try this example on CodeSandbox</a></strong></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-the-concept-of-url-module-in-nodejs">Q. Explain the concept of URL module in Node.js?</h2>
<p>The URL module in Node.js splits up a web address into readable parts. Use <code>require()</code> to include the module. Then parse an address with the <code>url.parse()</code> method, and it will return a URL object with each part of the address as properties.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * URL Module in Node.js
 */</span>
<span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'url'</span>);
<span class="hljs-keyword">const</span> adr = <span class="hljs-string">'http://localhost:8080/default.htm?year=2022&amp;month=september'</span>;
<span class="hljs-keyword">const</span> q = url.parse(adr, <span class="hljs-literal">true</span>);

<span class="hljs-built_in">console</span>.log(q.host); <span class="hljs-comment">// localhost:8080</span>
<span class="hljs-built_in">console</span>.log(q.pathname); <span class="hljs-comment">// "/default.htm"</span>
<span class="hljs-built_in">console</span>.log(q.search); <span class="hljs-comment">// "?year=2022&amp;month=september"</span>

<span class="hljs-keyword">const</span> qdata = q.query; <span class="hljs-comment">// { year: 2022, month: 'september' }</span>
<span class="hljs-built_in">console</span>.log(qdata.month); <span class="hljs-comment">// "september"</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-3-nodejs-data-types"># 3. NODE.JS DATA TYPES</h2>
<p><br /></p>
<h2 id="heading-q-what-are-the-data-types-in-nodejs">Q. What are the data types in Node.js?</h2>
<p>Just like JS, there are two categories of data types in Node: Primitives and Objects.</p>
<p><strong>1. Primitives:</strong></p>
<ul>
<li>String</li>
<li>Number</li>
<li>BigInt</li>
<li>Boolean</li>
<li>Undefined</li>
<li>Null</li>
<li>Symbol</li>
</ul>
<p><strong>2. Objects:</strong></p>
<ul>
<li>Function</li>
<li>Array</li>
<li>Buffer</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-string-data-type-in-nodejs">Q. Explain String data type in Node.js?</h2>
<p>Strings in Node.js are sequences of unicode characters. Strings can be wrapped in a single or double quotation marks.
Javascript provide many functions to operate on string, like indexOf(), split(), substr(), length.</p>
<p><strong>String functions:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Function</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>charAt()</td><td>It is useful to find a specific character present in a string.</td></tr>
<tr>
<td>Concat()</td><td>It is useful to concat more than one string.</td></tr>
<tr>
<td>indexOf()</td><td>It is useful to get the index of a specified character or a part of the string.</td></tr>
<tr>
<td>Match()</td><td>It is useful to match multiple strings.</td></tr>
<tr>
<td>Split()</td><td>It is useful to split the string and return an array of string.</td></tr>
<tr>
<td>Join()</td><td>It is useful to join the array of strings and those are separated by comma (,) operator.</td></tr>
</tbody>
</table>
</div><p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/** 
 * String Data Type
 */</span>
<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">'World'</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Concat Using (+) :"</span> , (str1 + <span class="hljs-string">' '</span> + str2));
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Concat Using Function :"</span> , (str1.concat(str2)));
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-number-data-type-in-nodejs">Q. Explain Number data type in Node.js?</h2>
<p>The number data type in Node.js is 64 bits floating point number both positive and negative. The parseInt() and parseFloat() functions are used to convert to number, if it fails to convert into a number then it returns <code>NaN</code>.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Number Data Type
 */</span>
<span class="hljs-comment">// Example 01:</span>
<span class="hljs-keyword">const</span> num1 = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> num2 = <span class="hljs-number">20</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`sum: <span class="hljs-subst">${num1 + num2}</span>`</span>); 

<span class="hljs-comment">// Example 02:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">parseInt</span>(<span class="hljs-string">"32"</span>));  <span class="hljs-comment">// 32</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">parseFloat</span>(<span class="hljs-string">"8.24"</span>)); <span class="hljs-comment">// 8.24</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">parseInt</span>(<span class="hljs-string">"234.12345"</span>)); <span class="hljs-comment">// 234</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">parseFloat</span>(<span class="hljs-string">"10"</span>)); <span class="hljs-comment">// 10</span>

<span class="hljs-comment">// Example 03:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">isFinite</span>(<span class="hljs-number">10</span>/<span class="hljs-number">5</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">isFinite</span>(<span class="hljs-number">10</span>/<span class="hljs-number">0</span>)); <span class="hljs-comment">// false</span>

<span class="hljs-comment">// Example 04:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span> / <span class="hljs-number">0</span>); <span class="hljs-comment">// Infinity</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">-5</span> / <span class="hljs-number">0</span>); <span class="hljs-comment">// -Infinity</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-bigint-data-type-in-nodejs">Q. Explain BigInt data type in Node.js?</h2>
<p>A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending <strong>n</strong> to the end of an integer literal, or by calling the BigInt() function ( without the new operator ) and giving it an integer value or string value.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * BigInt Data Type
 */</span>
<span class="hljs-keyword">const</span> maxSafeInteger = <span class="hljs-number">99n</span>; <span class="hljs-comment">// This is a BigInt</span>
<span class="hljs-keyword">const</span> num2 = BigInt(<span class="hljs-string">'99'</span>); <span class="hljs-comment">// This is equivalent</span>
<span class="hljs-keyword">const</span> num3 = BigInt(<span class="hljs-number">99</span>); <span class="hljs-comment">// Also works</span>

<span class="hljs-keyword">typeof</span> <span class="hljs-number">1n</span> === <span class="hljs-string">'bigint'</span>           <span class="hljs-comment">// true</span>
<span class="hljs-keyword">typeof</span> BigInt(<span class="hljs-string">'1'</span>) === <span class="hljs-string">'bigint'</span>  <span class="hljs-comment">// true</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-boolean-data-type-in-nodejs">Q. Explain Boolean data type in Node.js?</h2>
<p>Boolean data type is a data type that has one of two possible values, either true or false. In programming, it is used in logical representation or to control program structure.</p>
<p>The boolean() function is used to convert any data type to a boolean value. According to the rules, false, 0, NaN, null, undefined, empty string evaluate to false and other values evaluates to true.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Boolean Data Type
 */</span>
<span class="hljs-comment">// Example 01:</span>
<span class="hljs-keyword">const</span> isValid = <span class="hljs-literal">true</span>; 
<span class="hljs-built_in">console</span>.log(isValid); <span class="hljs-comment">// true </span>

<span class="hljs-comment">// Example 02:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">true</span>); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> &amp;&amp; <span class="hljs-literal">false</span>); <span class="hljs-comment">// false </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">true</span> || <span class="hljs-literal">false</span>); <span class="hljs-comment">// true </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-literal">false</span> || <span class="hljs-literal">false</span>); <span class="hljs-comment">// false </span>
<span class="hljs-built_in">console</span>.log(!<span class="hljs-literal">true</span>); <span class="hljs-comment">// false </span>
<span class="hljs-built_in">console</span>.log(!<span class="hljs-literal">false</span>); <span class="hljs-comment">// true</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-undefined-and-null-data-type-in-nodejs">Q. Explain <code>Undefined</code> and <code>Null</code> data type in Node.js?</h2>
<p>In node.js, if a variable is defined without assigning any value, then that will take <strong>undefined</strong> as value. If we assign a null value to the variable, then the value of the variable becomes <strong>null</strong>.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * NULL and UNDEFINED Data Type
 */</span>
<span class="hljs-keyword">let</span> x;
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// undefined</span>

<span class="hljs-keyword">let</span> y = <span class="hljs-literal">null</span>;
<span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// null</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-symbol-data-type-in-nodejs">Q. Explain Symbol data type in Node.js?</h2>
<p>Symbol is an immutable primitive value that is unique. It\'s a very peculiar data type. Once you create a symbol, its value is kept private and for internal use.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Symbol Data Type
 */</span>
<span class="hljs-keyword">const</span> NAME = <span class="hljs-built_in">Symbol</span>()
<span class="hljs-keyword">const</span> person = {
  [NAME]: <span class="hljs-string">'Ritika Bhavsar'</span>
}

person[NAME] <span class="hljs-comment">// 'Ritika Bhavsar'</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-function-in-nodejs">Q. Explain function in Node.js?</h2>
<p>Functions are first class citizens in Node\'s JavaScript, similar to the browser\'s JavaScript. A function can have attributes and properties also. It can be treated like a class in JavaScript.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Function in Node.js
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Messsage</span>(<span class="hljs-params">name</span>) </span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello "</span>+name);
}

Messsage(<span class="hljs-string">"World"</span>); <span class="hljs-comment">// Hello World</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-buffer-data-type-in-nodejs">Q. Explain Buffer data type in Node.js?</h2>
<p>Node.js includes an additional data type called Buffer ( not available in browser\'s JavaScript ). Buffer is mainly used to store binary data, while reading from a file or receiving packets over the network.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Buffer Data Type
 */</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-keyword">new</span> Buffer(<span class="hljs-number">10000</span>);
<span class="hljs-keyword">let</span> str = <span class="hljs-string">"----------"</span>;

b.write(str); 
<span class="hljs-built_in">console</span>.log( str.length ); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log( b.length ); <span class="hljs-comment">// 10000</span>
</code></pre>
<p><em>Note: Buffer() is deprecated due to security and usability issues.</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-4-nodejs-architecture"># 4. NODE.JS ARCHITECTURE</h2>
<p><br /></p>
<h2 id="heading-q-how-does-nodejs-works">Q. How does Node.js works?</h2>
<p>Node.js is completely event-driven. Basically the server consists of one thread processing one event after another.</p>
<p>A new request coming in is one kind of event. The server starts processing it and when there is a blocking IO operation, it does not wait until it completes and instead registers a callback function. The server then immediately starts to process another event ( maybe another request ). When the IO operation is finished, that is another kind of event, and the server will process it ( i.e. continue working on the request ) by executing the callback as soon as it has time.</p>
<p>Node.js Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node.js Processing model mainly based on Javascript Event based model with Javascript callback mechanism.  </p>
<p>
  <img src="assets/event-loop.png" alt="Node Architecture" />
</p>

<p><strong>Single Threaded Event Loop Model Processing Steps:</strong></p>
<ul>
<li>Clients Send request to Web Server.</li>
<li>Node.js Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.</li>
<li>Node.js Web Server receives those requests and places them into a Queue. It is known as <strong>Event Queue</strong>.</li>
<li>Node.js Web Server internally has a Component, known as <strong>Event Loop</strong>. Why it got this name is that it uses indefinite loop to receive requests and process them.</li>
<li>Event Loop uses Single Thread only. It is main heart of Node.js Platform Processing Model.</li>
<li>Event Loop checks any Client Request is placed in Event Queue. If no, then wait for incoming requests for indefinitely.</li>
<li>If yes, then pick up one Client Request from Event Queue<ul>
<li>Starts process that Client Request</li>
<li>If that Client Request Does Not requires any Blocking IO Operations, then process everything, prepare response and send it back to client.</li>
<li>If that Client Request requires some Blocking IO Operations like interacting with Database, File System, External Services then it will follow different approach<ul>
<li>Checks Threads availability from Internal Thread Pool</li>
<li>Picks up one Thread and assign this Client Request to that thread.</li>
<li>That Thread is responsible for taking that request, process it, perform Blocking IO operations, prepare response and send it back to the Event Loop</li>
<li>Event Loop in turn, sends that Response to the respective Client.</li>
</ul>
</li>
</ul>
</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-core-modules-of-nodejs">Q. What are the core modules of Node.js?</h2>
<p>Node.js has a set of core modules that are part of the platform and come with the Node.js installation. These modules can be loaded into the program by using the require function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'module_name'</span>);
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

http.createServer(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>});
  res.write(<span class="hljs-string">'Welcome to Node.js!'</span>);
  res.end();
}).listen(<span class="hljs-number">3000</span>);
</code></pre>
<p>The following table lists some of the important core modules in Node.js.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Core Module</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>assert</td><td>provides a set of assertion functions useful for testing</td></tr>
<tr>
<td>console</td><td>provides a simple debugging console</td></tr>
<tr>
<td>crypto</td><td>provides cryptographic functionality</td></tr>
<tr>
<td>http</td><td>http module includes classes, methods and events to create Node.js http server.</td></tr>
<tr>
<td>url</td><td>url module includes methods for URL resolution and parsing.</td></tr>
<tr>
<td>querystring</td><td>querystring module includes methods to deal with query string.</td></tr>
<tr>
<td>path</td><td>path module includes methods to deal with file paths.</td></tr>
<tr>
<td>fs</td><td>fs module includes classes, methods, and events to work with file I/O.</td></tr>
<tr>
<td>util</td><td>util module includes utility functions useful for programmers.</td></tr>
</tbody>
</table>
</div><div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-do-you-understand-by-reactor-pattern-in-nodejs">Q. What do you understand by Reactor Pattern in Node.js?</h2>
<p><strong>Reactor Pattern</strong> is used to avoid the blocking of the Input/Output operations. It provides us with a handler that is associated with I/O operations. When the I/O requests are to be generated, they get submitted to a demultiplexer, which handles concurrency in avoiding the blocking of the I/O mode and collects the requests in form of an event and queues those events.</p>
<p><strong>There are two ways in which I/O operations are performed:</strong></p>
<p><strong>1. Blocking I/O:</strong> Application will make a function call and pause its execution at a point until the data is received. It is called as "Synchronous".</p>
<p><strong>2. Non-Blocking I/O:</strong> Application will make a function call, and, without waiting for the results it continues its execution. It is called as "Asynchronous".</p>
<p>
  <img src="assets/reactor-pattern.jpg" alt="Reactor Pattern" />
</p>

<p><strong>Reactor Pattern comprises of:</strong></p>
<p><strong>1. Resources:</strong> They are shared by multiple applications for I/O operations, generally slower in executions.</p>
<p><strong>2. Synchronous Event De-multiplexer/Event Notifier:</strong> This uses Event Loop for blocking on all resources. When a set of I/O operations completes, the Event De-multiplexer pushes the new events into the Event Queue.</p>
<p><strong>3. Event Loop and Event Queue:</strong> Event Queue queues up the new events that occurred along with its event-handler, pair.</p>
<p><strong>4. Request Handler/Application:</strong> This is, generally, the application that provides the handler to be executed for registered events on resources.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-global-objects-of-nodejs">Q. What are the global objects of node.js?</h2>
<p>Node.js Global Objects are the objects that are available in all modules. Global Objects are built-in objects that are part of the JavaScript and can be used directly in the application without importing any particular module.</p>
<p>These objects are modules, functions, strings and object itself as explained below.</p>
<p><strong>1. global:</strong></p>
<p>It is a global namespace. Defining a variable within this namespace makes it globally accessible.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> myvar;
</code></pre>
<p><strong>2. process:</strong></p>
<p>It is an inbuilt global object that is an instance of EventEmitter used to get information on current process. It can also be accessed using require() explicitly.</p>
<p><strong>3. console:</strong></p>
<p>It is an inbuilt global object used to print to stdout and stderr.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World"</span>); <span class="hljs-comment">// Hello World</span>
</code></pre>
<p><strong>4. setTimeout(), clearTimeout(), setInterval(), clearInterval():</strong></p>
<p>The built-in timer functions are globals</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printHello</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log( <span class="hljs-string">"Hello, World!"</span>);
}

<span class="hljs-comment">// Now call above function after 2 seconds</span>
<span class="hljs-keyword">var</span> timeoutObj = <span class="hljs-built_in">setTimeout</span>(printHello, <span class="hljs-number">2000</span>);
</code></pre>
<p><strong>5. __dirname:</strong></p>
<p>It is a string. It specifies the name of the directory that currently contains the code.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(__dirname);
</code></pre>
<p><strong>6. __filename:</strong></p>
<p>It specifies the filename of the code being executed. This is the resolved absolute path of this code file. The value inside a module is the path to that module file.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(__filename);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-chrome-v8-engine">Q. What is chrome v8 engine?</h2>
<p>V8 is a C++ based open-source JavaScript engine developed by Google. It was originally designed for Google Chrome and Chromium-based browsers ( such as Brave ) in 2008, but it was later utilized to create Node.js for server-side coding.</p>
<p>V8 is the JavaScript engine i.e. it parses and executes JavaScript code. The DOM, and the other Web Platform APIs ( they all makeup runtime environment ) are provided by the browser.</p>
<p>V8 is known to be a JavaScript engine because it takes JavaScript code and executes it while browsing in Chrome. It provides a runtime environment for the execution of JavaScript code. The best part is that the JavaScript engine is completely independent of the browser in which it runs.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-why-is-libuv-needed-in-node-js">Q. Why is LIBUV needed in Node JS?</h2>
<p><strong>libuv</strong> is a C library originally written for Node.js to abstract non-blocking I/O operations. It provide the below features</p>
<ul>
<li>It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network.</li>
<li>It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications.</li>
<li>It provides mechanisms to handle file system, DNS, network, child processes, pipes, signal handling, polling and streaming</li>
<li>It also includes a thread pool for offloading work for some things that can\'t be done asynchronously at the operating system level.</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-v8-compiles-javascript-code">Q. How V8 compiles JavaScript code?</h2>
<p>Compilation is the process of converting human-readable code to machine code. There are two ways to compile the code</p>
<ul>
<li><strong>Using an Interpreter</strong>: The interpreter scans the code line by line and converts it into byte code.</li>
<li><strong>Using a Compiler</strong>: The Compiler scans the entire document and compiles it into highly optimized byte code.</li>
</ul>
<p>The V8 engine uses both a compiler and an interpreter and follows <strong>just-in-time (JIT)</strong> compilation to speed up the execution. JIT compiling works by compiling small portions of code that are just about to be executed. This prevents long compilation time and the code being compiles is only that which is highly likely to run.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-5-nodejs-events"># 5. NODE.JS EVENTS</h2>
<p><br /></p>
<h2 id="heading-q-what-is-eventemitter-in-nodejs">Q. What is EventEmitter in Node.js?</h2>
<p>The EventEmitter is a class that facilitates communication/interaction between objects in Node.js. The EventEmitter class can be used to create and handle custom events.</p>
<p>EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node\'s built-in modules inherit from EventEmitter including prominent frameworks like Express.js. An emitter object basically has two main features:</p>
<ul>
<li>Emitting name events.</li>
<li>Registering and unregistering listener functions.</li>
</ul>
<p><strong>Example 01:</strong> Create an event emitter instance and register a couple of callbacks</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callbacks Events
 */</span>
<span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listenerOne</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'First Listener Executed'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listenerTwo</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Second Listener Executed'</span>);
}

eventEmitter.on(<span class="hljs-string">'listenerOne'</span>, listenerOne); <span class="hljs-comment">// Register for listenerOne</span>
eventEmitter.on(<span class="hljs-string">'listenerOne'</span>, listenerTwo); <span class="hljs-comment">// Register for listenerOne</span>

<span class="hljs-comment">// When the event "listenerOne" is emitted, both the above callbacks should be invoked.</span>
eventEmitter.emit(<span class="hljs-string">'listenerOne'</span>);

<span class="hljs-comment">// Output</span>
First Listener Executed
Second Listener Executed
</code></pre>
<p><strong>Example 02:</strong> Registering for the event to be fired only one time using <strong>once</strong>.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Emit Events Once
 */</span>
<span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listenerOnce</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'listenerOnce fired once'</span>);
}

eventEmitter.once(<span class="hljs-string">'listenerOne'</span>, listenerOnce); <span class="hljs-comment">// Register listenerOnce</span>
eventEmitter.emit(<span class="hljs-string">'listenerOne'</span>);

<span class="hljs-comment">// Output</span>
listenerOnce fired once
</code></pre>
<p><strong>Example 03:</strong> Registering for the event with callback parameters</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callback Events with Parameters
 */</span>
<span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">listener</span>(<span class="hljs-params">code, msg</span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`status <span class="hljs-subst">${code}</span> and <span class="hljs-subst">${msg}</span>`</span>);
}

eventEmitter.on(<span class="hljs-string">'status'</span>, listener); <span class="hljs-comment">// Register listener</span>
eventEmitter.emit(<span class="hljs-string">'status'</span>, <span class="hljs-number">200</span>, <span class="hljs-string">'ok'</span>);

<span class="hljs-comment">// Output</span>
status <span class="hljs-number">200</span> and ok
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-the-event-loop-works-in-nodejs">Q. How the Event Loop Works in Node.js?</h2>
<p>The <strong>event loop</strong> allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by offloading operations to the system kernel whenever possible.</p>
<p>Node.js is a single-threaded application, but it can support <strong>concurrency</strong> via the concept of <strong>event</strong> and <strong>callbacks</strong>. Every API of Node.js is asynchronous and being single-threaded, they use <strong>async function calls</strong> to maintain concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event-listener function to execute.</p>
<p><strong>Features of Event Loop:</strong></p>
<ul>
<li>Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.</li>
<li>The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.</li>
<li>The event loop allows us to use callbacks and promises.</li>
<li>The event loop executes the tasks starting from the oldest first.</li>
</ul>
<p>
  <img src="assets/nodejs-event-loop.png" alt="Event Loop" />
</p>

<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Event loop in Node.js
 */</span>
<span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();

<span class="hljs-comment">// Create an event handler as follows</span>
<span class="hljs-keyword">const</span> connectHandler = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">connected</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'connection succesful.'</span>);
   eventEmitter.emit(<span class="hljs-string">'data_received'</span>);
}

<span class="hljs-comment">// Bind the connection event with the handler</span>
eventEmitter.on(<span class="hljs-string">'connection'</span>, connectHandler);

<span class="hljs-comment">// Bind the data_received event with the anonymous function</span>
eventEmitter.on(<span class="hljs-string">'data_received'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'data received succesfully.'</span>);
});

<span class="hljs-comment">// Fire the connection event </span>
eventEmitter.emit(<span class="hljs-string">'connection'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Program Ended."</span>);

<span class="hljs-comment">// Output</span>
Connection succesful.
Data received succesfully.
Program Ended.
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-the-difference-between-processnexttick-and-setimmediate">Q. What is the difference between process.nextTick() and setImmediate()?</h2>
<p><strong>1. process.nextTick():</strong></p>
<p>The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.</p>
<p><strong>2. setImmdeiate():</strong></p>
<p>The setImmediate() method is used to execute a function right after the current event loop finishes. It is callback function is placed in the check phase of the next event queue.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * setImmediate() and process.nextTick()
 */</span>
setImmediate(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1st Immediate"</span>);
});

setImmediate(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"2nd Immediate"</span>);
});

process.nextTick(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"1st Process"</span>);
});

process.nextTick(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"2nd Process"</span>);
});

<span class="hljs-comment">// First event queue ends here</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Program Started"</span>);

<span class="hljs-comment">// Output</span>
Program Started
<span class="hljs-number">1</span>st Process
<span class="hljs-number">2n</span>d Process
<span class="hljs-number">1</span>st Immediate
<span class="hljs-number">2n</span>d Immediate
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-callback-function-in-nodejs">Q. What is callback function in Node.js?</h2>
<p>A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime.</p>
<p>Callback is called when task get completed and is asynchronous equivalent for a function. Using Callback concept, Node.js can process a large number of requests without waiting for any function to return the result which makes Node.js highly scalable.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callback Function
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myAsync</span>(<span class="hljs-params">a, b, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    callback(a + b);
  }, <span class="hljs-number">100</span>);
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Before Asynchronous Call"</span>);

myAsync(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sum: "</span> + result);
});
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"After Asynchronous Call"</span>);

<span class="hljs-comment">// Output</span>
Before Asynchronous Call
After Asynchronous Call
<span class="hljs-attr">Sum</span>: <span class="hljs-number">30</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-difference-between-events-and-callbacks">Q. What are the difference between Events and Callbacks?</h2>
<p><strong>1. Events:</strong></p>
<p>Node.js <strong>events</strong> module which emits named events that can cause corresponding functions or callbacks to be called. Functions ( callbacks ) listen or subscribe to a particular event to occur and when that event triggers, all the callbacks subscribed to that event are fired one by one in order to which they were registered.</p>
<p>All objects that emit events are instances of the <strong>EventEmitter</strong> class. The event can be emitted or listen to an event with the help of EventEmitter</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Events Module
 */</span>
<span class="hljs-keyword">const</span> event = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);  
<span class="hljs-keyword">const</span> eventEmitter = <span class="hljs-keyword">new</span> event.EventEmitter();  

<span class="hljs-comment">// add listener function for Sum event  </span>
eventEmitter.on(<span class="hljs-string">'Sum'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">num1, num2</span>) </span>{  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Total: '</span> + (num1 + num2));  
});  

<span class="hljs-comment">// call event  </span>
eventEmitter.emit(<span class="hljs-string">'Sum'</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>);

<span class="hljs-comment">// Output</span>
Total: <span class="hljs-number">30</span>
</code></pre>
<p><strong>2. Callbacks:</strong></p>
<p>A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callbacks
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Total: '</span> + number);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculator</span>(<span class="hljs-params">num1, num2, callback</span>) </span>{
  <span class="hljs-keyword">let</span> total = num1 + num2;
  callback(total);
}

calculator(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, sum);

<span class="hljs-comment">// Output</span>
Total: <span class="hljs-number">30</span>
</code></pre>
<p>Callback functions are called when an asynchronous function returns its result, whereas event handling works on the <strong>observer pattern</strong>. The functions that listen to events act as Observers. Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-built events available through events module and EventEmitter class which are used to bind events and event-listeners</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-an-error-first-callback">Q. What is an error-first callback?</h2>
<p>The pattern used across all the asynchronous methods in Node.js is called <em>Error-first Callback</em>. Here is an example:</p>
<pre><code class="lang-js">fs.readFile( <span class="hljs-string">"file.json"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"> err, data </span>) </span>{
  <span class="hljs-keyword">if</span> ( err ) {
    <span class="hljs-built_in">console</span>.error( err );
  }
  <span class="hljs-built_in">console</span>.log( data );
});
</code></pre>
<p>Any asynchronous method expects one of the arguments to be a callback. The full callback argument list depends on the caller method, but the first argument is always an error object or null. When we go for the asynchronous method, an exception thrown during function execution cannot be detected in a try/catch statement. The event happens after the JavaScript engine leaves the try block. </p>
<p>In the preceding example, if any exception is thrown during the reading of the file, it lands on the callback function as the first and mandatory parameter.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-callback-hell-in-nodejs">Q. What is callback hell in Node.js?</h2>
<p>The callback hell contains complex nested callbacks. Here, every callback takes an argument that is a result of the previous callbacks. In this way, the code structure looks like a pyramid, making it difficult to read and maintain. Also, if there is an error in one function, then all other functions get affected.</p>
<p>An asynchronous function is one where some external activity must complete before a result can be processed; it is "asynchronous" in the sense that there is an unpredictable amount of time before a result becomes available. Such functions require a callback function to handle errors and process the result.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callback Hell
 */</span>
getData(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a</span>)</span>{
    getMoreData(a, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">b</span>)</span>{
        getMoreData(b, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">c</span>)</span>{ 
            getMoreData(c, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d</span>)</span>{ 
                getMoreData(d, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>)</span>{ 
                    ...
                });
            });
        });
    });
});
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-avoid-callback-hell-in-nodejs">Q. How to avoid callback hell in Node.js?</h2>
<p><strong>1. Managing callbacks using Async.js:</strong>  </p>
<p><code>Async</code> is a really powerful npm module for managing asynchronous nature of JavaScript. Along with Node.js, it also works for JavaScript written for browsers.</p>
<p>Async provides lots of powerful utilities to work with asynchronous processes under different scenarios.</p>
<pre><code class="lang-js">npm install --save <span class="hljs-keyword">async</span>
</code></pre>
<p><strong>2. Managing callbacks hell using promises:</strong>  </p>
<p>Promises are alternative to callbacks while dealing with asynchronous code. Promises return the value of the result or an error exception. The core of the promises is the <code>.then()</code> function, which waits for the promise object to be returned.</p>
<p>The <code>.then()</code> function takes two optional functions as arguments and depending on the state of the promise only one will ever be called. The first function is called when the promise if fulfilled (A successful result). The second function is called when the promise is rejected.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Promises
 */</span>
<span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    resolve(<span class="hljs-string">"Successful!"</span>);
  }, <span class="hljs-number">300</span>);
});
</code></pre>
<p><strong>3. Using Async Await:</strong>  </p>
<p>Async await makes asynchronous code look like it\'s synchronous. This has only been possible because of the reintroduction of promises into node.js. Async-Await only works with functions that return a promise.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Async Await
 */</span>
<span class="hljs-keyword">const</span> getrandomnumber = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>)=&gt;</span>{
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            resolve(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">20</span>));
        }, <span class="hljs-number">1000</span>);
    });
}

<span class="hljs-keyword">const</span> addRandomNumber = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> sum = <span class="hljs-keyword">await</span> getrandomnumber() + <span class="hljs-keyword">await</span> getrandomnumber();
    <span class="hljs-built_in">console</span>.log(sum);
}

addRandomNumber();
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-typically-the-first-argument-passed-to-a-callback-handler">Q. What is typically the first argument passed to a callback handler?</h2>
<p>The first parameter of the callback is the <strong>error</strong> value. If the function hits an error, then they typically call the <strong>callback</strong> with the first parameter being an Error object.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Callback Handler
 */</span>
<span class="hljs-keyword">const</span> Division = <span class="hljs-function">(<span class="hljs-params">numerator, denominator, callback</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (denominator === <span class="hljs-number">0</span>) {
      callback(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Divide by zero error!'</span>));
    } <span class="hljs-keyword">else</span> {
      callback(<span class="hljs-literal">null</span>, numerator / denominator);
    }
};

<span class="hljs-comment">// Function Call</span>
Division(<span class="hljs-number">5</span>, <span class="hljs-number">0</span>, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.log(err.message);
  }
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Result: <span class="hljs-subst">${result}</span>`</span>);
});
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-timing-features-of-nodejs">Q. What are the timing features of Node.js?</h2>
<p>The Timers module in Node.js contains functions that execute code after a set period of time. Timers do not need to be imported via require(), since all the methods are available globally to emulate the browser JavaScript API.</p>
<p>Some of the functions provided in this module are</p>
<p><strong>1. setTimeout():</strong></p>
<p>This function schedules code execution after the assigned amount of time ( in milliseconds ). Only after the timeout has occurred, the code will be executed. This method returns an ID that can be used in <strong>clearTimeout()</strong> method.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(callback, delay, args )
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printMessage</span>(<span class="hljs-params">arg</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${arg}</span>`</span>);
}

<span class="hljs-built_in">setTimeout</span>(printMessage, <span class="hljs-number">1000</span>, <span class="hljs-string">'Display this Message after 1 seconds!'</span>);
</code></pre>
<p><strong>2. setImmediate():</strong></p>
<p>The setImmediate() method executes the code at the end of the current event loop cycle. The function passed in the setImmediate() argument is a function that will be executed in the next iteration of the event loop.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-js">setImmediate(callback, args)
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Setting timeout for the function</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setTimeout() function running...'</span>);
}, <span class="hljs-number">500</span>);

<span class="hljs-comment">// Running this function immediately before any other</span>
setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setImmediate() function running...'</span>);
});

<span class="hljs-comment">// Directly printing the statement</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Normal statement in the event loop'</span>);

<span class="hljs-comment">// Output</span>
<span class="hljs-comment">// Normal statement in the event loop</span>
<span class="hljs-comment">// setImmediate() function running...</span>
<span class="hljs-comment">// setTimeout() function running...</span>
</code></pre>
<p><strong>3. setInterval():</strong></p>
<p>The setInterval() method executes the code after the specified interval. The function is executed multiple times after the interval has passed. The function will keep on calling until the process is stopped externally or using code after specified time period. The clearInterval() method can be used to prevent the function from running.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">setInterval</span>(callback, delay, args)
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">setInterval</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Display this Message intervals of 1 seconds!'</span>);
}, <span class="hljs-number">1000</span>);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-6-nodejs-file-system"># 6. NODE.JS FILE SYSTEM</h2>
<p><br /></p>
<h2 id="heading-q-how-nodejs-read-the-content-of-a-file">Q. How Node.js read the content of a file?</h2>
<p>The "normal" way in Node.js is probably to read in the content of a file in a non-blocking, asynchronous way. That is, to tell Node to read in the file, and then to get a callback when the file-reading has been finished. That would allow us to hand several requests in parallel.</p>
<p>Common use for the File System module:</p>
<ul>
<li>Read files</li>
<li>Create files</li>
<li>Update files</li>
<li>Delete files</li>
<li>Rename files  </li>
</ul>
<p><strong>Read Files</strong><br />index.html</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Header<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>My paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * read_file.js
 */</span>
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
http.createServer(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  fs.readFile(<span class="hljs-string">'index.html'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
    res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>});
    res.write(data);
    res.end();
  });
}).listen(<span class="hljs-number">8080</span>);
</code></pre>
<p>Initiate read_file.js:</p>
<pre><code class="lang-js">node read_file.js
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-7-nodejs-streams"># 7. NODE.JS STREAMS</h2>
<p><br /></p>
<h2 id="heading-q-how-many-types-of-streams-are-present-in-nodejs">Q. How many types of streams are present in node.js?</h2>
<p>Streams are objects that let you read data from a source or write data to a destination in continuous fashion.
There are four types of streams</p>
<ul>
<li><strong>Readable</strong> − Stream which is used for read operation.</li>
<li><strong>Writable</strong> − Stream which is used for write operation.</li>
<li><strong>Duplex</strong> − Stream which can be used for both read and write operation.</li>
<li><strong>Transform</strong> − A type of duplex stream where the output is computed based on input.  </li>
</ul>
<p>Each type of Stream is an EventEmitter instance and throws several events at different instance of times.  </p>
<p><strong>Example:</strong></p>
<ul>
<li><strong>data</strong> − This event is fired when there is data is available to read.</li>
<li><strong>end</strong> − This event is fired when there is no more data to read.</li>
<li><strong>error</strong> − This event is fired when there is any error receiving or writing data.</li>
<li><strong>finish</strong> − This event is fired when all the data has been flushed to underlying system. </li>
</ul>
<p><strong>Reading from a Stream:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-string">''</span>;

<span class="hljs-comment">// Create a readable stream</span>
<span class="hljs-keyword">const</span> readerStream = fs.createReadStream(<span class="hljs-string">'input.txt'</span>);

<span class="hljs-comment">// Set the encoding to be utf8. </span>
readerStream.setEncoding(<span class="hljs-string">'UTF8'</span>);

<span class="hljs-comment">// Handle stream events --&gt; data, end, and error</span>
readerStream.on(<span class="hljs-string">'data'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">chunk</span>) </span>{
   data += chunk;
});

readerStream.on(<span class="hljs-string">'end'</span>,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(data);
});

readerStream.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
   <span class="hljs-built_in">console</span>.log(err.stack);
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Program Ended"</span>);
</code></pre>
<p><strong>Writing to a Stream:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-string">'Simply Easy Learning'</span>;

<span class="hljs-comment">// Create a writable stream</span>
<span class="hljs-keyword">const</span> writerStream = fs.createWriteStream(<span class="hljs-string">'output.txt'</span>);

<span class="hljs-comment">// Write the data to stream with encoding to be utf8</span>
writerStream.write(data,<span class="hljs-string">'UTF8'</span>);

<span class="hljs-comment">// Mark the end of file</span>
writerStream.end();

<span class="hljs-comment">// Handle stream events --&gt; finish, and error</span>
writerStream.on(<span class="hljs-string">'finish'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Write completed."</span>);
});

writerStream.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
   <span class="hljs-built_in">console</span>.log(err.stack);
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Program Ended"</span>);
</code></pre>
<p><strong>Piping the Streams:</strong></p>
<p>Piping is a mechanism where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream. There is no limit on piping operations.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);

<span class="hljs-comment">// Create a readable stream</span>
<span class="hljs-keyword">const</span> readerStream = fs.createReadStream(<span class="hljs-string">'input.txt'</span>);

<span class="hljs-comment">// Create a writable stream</span>
<span class="hljs-keyword">const</span> writerStream = fs.createWriteStream(<span class="hljs-string">'output.txt'</span>);

<span class="hljs-comment">// Pipe the read and write operations</span>
<span class="hljs-comment">// read input.txt and write data to output.txt</span>
readerStream.pipe(writerStream);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Program Ended"</span>);
</code></pre>
<p><strong>Chaining the Streams:</strong></p>
<p>Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.  </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'zlib'</span>);

<span class="hljs-comment">// Compress the file input.txt to input.txt.gz</span>
fs.createReadStream(<span class="hljs-string">'input.txt'</span>)
   .pipe(zlib.createGzip())
   .pipe(fs.createWriteStream(<span class="hljs-string">'input.txt.gz'</span>));

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"File Compressed."</span>);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-8-nodejs-multithreading"># 8. NODE.JS MULTITHREADING</h2>
<p><br /></p>
<h2 id="heading-q-is-nodejs-entirely-based-on-a-single-thread">Q. Is Node.js entirely based on a single-thread?</h2>
<p>Yes, it is true that Node.js processes all requests on a single thread. But it is just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.</p>
<p>Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.</p>
<p>To explain it practically, let\'s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-does-nodejs-handle-child-threads">Q. How does Node.js handle child threads?</h2>
<p>Node.js is a single threaded language which in background uses multiple threads to execute asynchronous code.
Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by Node.js run-time.</p>
<ul>
<li>Nodejs Primary application runs in an event loop, which is in a single thread.</li>
<li>Background I/O is running in a thread pool that is only accessible to C/C++ or other compiled/native modules and mostly transparent to the JS.</li>
<li>Node v11/12 now has experimental worker_threads, which is another option.</li>
<li>Node.js does support forking multiple processes ( which are executed on different cores ).</li>
<li>It is important to know that state is not shared between master and forked process.</li>
<li>We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-does-nodejs-support-multi-processor-platforms-and-does-it-fully-utilize-all-processor-resources">Q. How does Node.js support multi-processor platforms, and does it fully utilize all processor resources?</h2>
<p>Since Node.js is by default a single thread application, it will run on a single processor core and will not take full advantage of multiple core resources. However, Node.js provides support for deployment on multiple-core systems, to take greater advantage of the hardware. The Cluster module is one of the core Node.js modules and it allows running multiple Node.js worker processes that will share the same port.</p>
<p>The cluster module helps to spawn new processes on the operating system. Each process works independently, so you cannot use shared state between child processes. Each process communicates with the main process by IPC and pass server handles back and forth.</p>
<p>Cluster supports two types of load distribution:</p>
<ul>
<li>The main process listens on a port, accepts new connection and assigns it to a child process in a round robin fashion.</li>
<li>The main process assigns the port to a child process and child process itself listen the port.</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-since-node-is-a-single-threaded-process-how-to-make-use-of-all-cpus">Q. Since node is a single threaded process, how to make use of all CPUs?</h2>
<p>Node.js is a single threaded language which in background uses multiple threads to execute asynchronous code.
Node.js is non-blocking which means that all functions ( callbacks ) are delegated to the event loop and they are ( or can be ) executed by different threads. That is handled by Node.js run-time.</p>
<ul>
<li>Node.js does support forking multiple processes ( which are executed on different cores ).</li>
<li>It is important to know that state is not shared between master and forked process.</li>
<li>We can pass messages to forked process ( which is different script ) and to master process from forked process with function send.</li>
</ul>
<p>A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load. The cluster module allows easy creation of child processes that all share server ports.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).cpus().length;

<span class="hljs-keyword">if</span> (cluster.isMaster) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>);

  <span class="hljs-comment">// Fork workers.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numCPUs; i++) {
    cluster.fork();
  }

  cluster.on(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
  });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Workers can share any TCP connection</span>
  <span class="hljs-comment">// In this case it is an HTTP server</span>
  http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.writeHead(<span class="hljs-number">200</span>);
    res.end(<span class="hljs-string">'hello world\n'</span>);
  }).listen(<span class="hljs-number">8000</span>);

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}
</code></pre>
<p>Running Node.js will now share port 8000 between the workers:</p>
<pre><code class="lang-js">$ node server.js
Master <span class="hljs-number">3596</span> is running
Worker <span class="hljs-number">4324</span> started
Worker <span class="hljs-number">4520</span> started
Worker <span class="hljs-number">6056</span> started
Worker <span class="hljs-number">5644</span> started
</code></pre>
<p>The worker processes are spawned using the <code>child_process.fork()</code> method, so that they can communicate with the parent via IPC and pass server handles back and forth.</p>
<p>The cluster module supports two methods of distributing incoming connections.</p>
<p>The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process.</p>
<p>The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-if-nodejs-is-single-threaded-then-how-it-handles-concurrency">Q. If Node.js is single threaded then how it handles concurrency?</h2>
<p>Node js despite being single-threaded is the asynchronous nature that makes it possible to handle concurrency and perform multiple I/O operations at the same time. Node js uses an event loop to maintain concurrency and perform non-blocking I/O operations.</p>
<p>As soon as Node js starts, it initializes an event loop. The event loop works on a queue (which is called an event queue) and performs tasks in FIFO (First In First Out) order. It executes a task only when there is no ongoing task in the call stack. The call stack works in LIFO(Last In First Out) order. The event loop continuously checks the call stack to check if there is any task that needs to be run. Now whenever the event loop finds any function, it adds it to the stack and runs in order.  </p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Concurrency
 */</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Two times the number <span class="hljs-subst">${n}</span> is `</span> + add(n, n));
}

print(<span class="hljs-number">5</span>);
</code></pre>
<p>Here, the function <strong>print(5)</strong> will be invoked and will push into the call stack. When the function is called, it starts consoling the statement inside it but before consoling the whole statement it encounters another function add(n,n) and suspends its current execution, and pushes the add function into the top of the call stack.</p>
<p>Now the function will return the addition <strong>a+b</strong> and then popped out from the stack and now the previously suspended function will start running and will log the output to console and then this function too will get pop from the stack and now the stack is empty. So this is how a call stack works.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-kill-child-processes-that-spawn-their-own-child-processes-in-nodejs">Q. How to kill child processes that spawn their own child processes in Node.js?</h2>
<p>If a child process in Node.js spawn their own child processes, kill() method will not kill the child process\'s own child processes. For example, if I start a process that starts it\'s own child processes via child_process module, killing that child process will not make my program to quit.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> spawn = <span class="hljs-built_in">require</span>(<span class="hljs-string">'child_process'</span>).spawn;
<span class="hljs-keyword">const</span> child = spawn(<span class="hljs-string">'my-command'</span>);

child.kill();
</code></pre>
<p>The program above will not quit if <code>my-command</code> spins up some more processes.</p>
<p><strong>PID range hack:</strong></p>
<p>We can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new group of processes. Then using process.kill(-pid) method on main process we can kill all processes that are in the same group of a child process with the same pid group. In my case, I only have one processes in this group.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> spawn = <span class="hljs-built_in">require</span>(<span class="hljs-string">'child_process'</span>).spawn;
<span class="hljs-keyword">const</span> child = spawn(<span class="hljs-string">'my-command'</span>, {<span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>});

process.kill(-child.pid);
</code></pre>
<p>Please note - before pid. This converts a pid to a group of pids for process kill() method.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-synchronize-data-between-multiple-clients-on-nodejs-server">Q. How to synchronize data between multiple clients on node.js server?</h2>
<p><em>ToDo</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-9-nodejs-web-module"># 9. NODE.JS WEB MODULE</h2>
<p><br /></p>
<h2 id="heading-q-how-to-use-json-web-token-jwt-for-authentication-in-nodejs">Q. How to use JSON Web Token (JWT) for authentication in Node.js?</h2>
<p>JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.</p>
<p>There are some advantages of using JWT for authorization:</p>
<ul>
<li>Purely stateless. No additional server or infra required to store session information.</li>
<li>It can be easily shared among services.</li>
</ul>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-js">jwt.sign(payload, secretOrPrivateKey, [options, callback])
</code></pre>
<ul>
<li><strong>Header</strong> - Consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512)</li>
<li><strong>Payload</strong> - Contains the claims that provide information about a user who has been authenticated along with other information such as token expiration time.</li>
<li><strong>Signature</strong> - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret</li>
</ul>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install jsonwebtoken bcryptjs --save
</code></pre>
<p><strong>Example</strong>:</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * AuthController.js
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> router = express.Router();
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'body-parser'</span>);
<span class="hljs-keyword">const</span> User = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../user/User'</span>);

<span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);
<span class="hljs-keyword">const</span> bcrypt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'bcryptjs'</span>);
<span class="hljs-keyword">const</span> config = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../config'</span>);


router.use(bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> }));
router.use(bodyParser.json());

router.post(<span class="hljs-string">'/register'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{

  <span class="hljs-keyword">let</span> hashedPassword = bcrypt.hashSync(req.body.password, <span class="hljs-number">8</span>);

  User.create({
    <span class="hljs-attr">name</span> : req.body.name,
    <span class="hljs-attr">email</span> : req.body.email,
    <span class="hljs-attr">password</span> : hashedPassword
  },
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, user</span>) </span>{
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">500</span>).send(<span class="hljs-string">"There was a problem registering the user."</span>)
    <span class="hljs-comment">// create a token</span>
    <span class="hljs-keyword">let</span> token = jwt.sign({ <span class="hljs-attr">id</span>: user._id }, config.secret, {
      <span class="hljs-attr">expiresIn</span>: <span class="hljs-number">86400</span> <span class="hljs-comment">// expires in 24 hours</span>
    });
    res.status(<span class="hljs-number">200</span>).send({ <span class="hljs-attr">auth</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">token</span>: token });
  });
});
</code></pre>
<p><strong>config.js:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * config.js
 */</span>
<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-string">'secret'</span>: <span class="hljs-string">'supersecret'</span>
};
</code></pre>
<p>The <code>jwt.sign()</code> method takes a payload and the secret key defined in <code>config.js</code> as parameters. It creates a unique string of characters representing the payload. In our case, the payload is an object containing only the id of the user.</p>
<p><strong>Reference:</strong></p>
<ul>
<li><em><a target="_blank" href="https://www.npmjs.com/package/jsonwebtoken">https://www.npmjs.com/package/jsonwebtoken</a></em></li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-build-a-microservices-architecture-with-nodejs">Q. How to build a microservices architecture with Node.js?</h2>
<p>Microservices are a style of <strong>Service Oriented Architecture (SOA)</strong> where the app is structured on an assembly of interconnected services. With microservices, the application architecture is built with lightweight protocols. The services are finely seeded in the architecture. Microservices disintegrate the app into smaller services and enable improved modularity.</p>
<p>
  <img src="assets/monolithic-and-microservices-architecture.jpg" alt="Microservices" />
</p>

<p>There are few things worth emphasizing about the superiority of microservices, and distributed systems generally, over monolithic architecture:</p>
<ul>
<li><strong>Modularity</strong> — responsibility for specific operations is assigned to separate pieces of the application</li>
<li><strong>Uniformity</strong> — microservices interfaces (API endpoints) consist of a base URI identifying a data object and standard HTTP methods (GET, POST, PUT, PATCH and DELETE) used to manipulate the object</li>
<li><strong>Robustness</strong> — component failures cause only the absence or reduction of a specific unit of functionality</li>
<li><strong>Maintainability</strong> — system components can be modified and deployed independently</li>
<li><strong>Scalability</strong> — instances of a service can be added or removed to respond to changes in demand.</li>
<li><strong>Availability</strong> — new features can be added to the system while maintaining 100% availability.</li>
<li><strong>Testability</strong> — new solutions can be tested directly in the production environment by implementing them for  restricted segments of users to see how they behave in real life.</li>
</ul>
<p><strong>Example:</strong> Creating Microservices with Node.js</p>
<p><strong>Step 01:</strong> Creating a Server to Accept Requests</p>
<p>This file is creating our server and assigns routes to process all requests.</p>
<pre><code class="lang-js"><span class="hljs-comment">//  server.js</span>

<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>;

<span class="hljs-keyword">const</span> routes = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./api/routes'</span>);
routes(app);
app.listen(port, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server started on port: '</span> + port);
});
</code></pre>
<p><strong>Step 02:</strong> Defining the routes</p>
<p>The next step is to define the routes for the microservices and then assign each to a target in the controller. We have two endpoints. One endpoint called "about" that returns information about the application. And a "distance" endpoint that includes two path parameters, both Zip Codes of the Lego store. This endpoint returns the distance, in miles, between these two Zip Codes.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./controller'</span>);

<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">app</span>) </span>{
   app.route(<span class="hljs-string">'/about'</span>)
       .get(controller.about);
   app.route(<span class="hljs-string">'/distance/:zipcode1/:zipcode2'</span>)
       .get(controller.getDistance);
};
</code></pre>
<p><strong>Step 03:</strong> Adding Controller Logic</p>
<p>Within the controller file, we are going to create a controller object with two properties. Those properties are the functions to handle the requests we defined in the routes module.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> properties = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../package.json'</span>)
<span class="hljs-keyword">const</span> distance = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../service/distance'</span>);

<span class="hljs-keyword">const</span> controllers = {
   <span class="hljs-attr">about</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
       <span class="hljs-keyword">let</span> aboutInfo = {
           <span class="hljs-attr">name</span>: properties.name,
           <span class="hljs-attr">version</span>: properties.version
       }
       res.json(aboutInfo);
   },
   <span class="hljs-attr">getDistance</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
           distance.find(req, res, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, dist</span>) </span>{
               <span class="hljs-keyword">if</span> (err)
                   res.send(err);
               res.json(dist);
           });
       },
};

<span class="hljs-built_in">module</span>.exports = controllers;
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-microservices-communicate-with-each-other-in-nodejs">Q. How microservices communicate with each other in Node.js?</h2>
<p><em>ToDo</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-10-nodejs-middleware"># 10. NODE.JS MIDDLEWARE</h2>
<p><br /></p>
<h2 id="heading-q-what-are-the-middleware-functions-in-nodejs">Q. What are the middleware functions in Node.js?</h2>
<p>Middleware functions are functions that have access to the <strong>request object (req)</strong>, the <strong>response object (res)</strong>, and the <code>next</code> function in the application\'s request-response cycle.</p>
<p>Middleware functions can perform the following tasks:</p>
<ul>
<li>Execute any code.</li>
<li>Make changes to the request and the response objects.</li>
<li>End the request-response cycle.</li>
<li>Call the next middleware in the stack.</li>
</ul>
<p>If the current middleware function does not end the request-response cycle, it must call <code>next()</code> to pass control to the next middleware function. Otherwise, the request will be left hanging.</p>
<p>The following figure shows the elements of a middleware function call:</p>
<p>
  <img src="assets/express-mw.png" alt="Middleware functions" />
</p>

<p>Middleware functions that return a Promise will call <code>next(value)</code> when they reject or throw an error. <code>next</code> will be called with either the rejected value or the thrown Error.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-the-use-of-next-in-nodejs">Q. Explain the use of next in Node.js?</h2>
<p>The <strong>next</strong> is a function in the Express router which executes the middleware succeeding the current middleware.</p>
<p><strong>Example:</strong></p>
<p>To load the middleware function, call <code>app.use()</code>, specifying the middleware function. For example, the following code loads the <strong>myLogger</strong> middleware function before the route to the root path (/).</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * myLogger
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-keyword">const</span> myLogger = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"LOGGED"</span>);
  next();
};

app.use(myLogger);

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">"Hello World!"</span>);
});

app.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p><strong>⚝ <a target="_blank" href="https://codesandbox.io/s/next-function-nq042s">Try this example on CodeSandbox</a></strong></p>
<p><em>Note: The <code>next()</code> function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The <code>next()</code> function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-why-to-use-expressjs">Q. Why to use Express.js?</h2>
<p>Express.js is a Node.js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application.</p>
<p><strong>Features of Express.js:</strong></p>
<ul>
<li><strong>Fast Server-Side Development:</strong> The features of node js help express saving a lot of time.</li>
<li><strong>Middleware:</strong> Middleware is a request handler that has access to the application\'s request-response cycle.</li>
<li><strong>Routing:</strong> It refers to how an application\'s endpoint\'s URLs respond to client requests.</li>
<li><strong>Templating:</strong> It provides templating engines to build dynamic content on the web pages by creating HTML templates on the server.</li>
<li><strong>Debugging:</strong> Express makes it easier as it identifies the exact part where bugs are.</li>
</ul>
<p>The Express.js framework makes it very easy to develop an application which can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Simple server using Express.js
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> app = express();

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">"Hello World!"</span>);
});

<span class="hljs-keyword">const</span> server = app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{});
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-why-should-you-separate-express-app-and-server">Q. Why should you separate Express 'app' and 'server'?</h2>
<p>Keeping the API declaration separated from the network related configuration (port, protocol, etc) allows testing the API in-process, without performing network calls, with all the benefits that it brings to the table: fast testing execution and getting coverage metrics of the code. It also allows deploying the same API under flexible and different network conditions.</p>
<p>API declaration, should reside in app.js:</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * app.js
 */</span>
<span class="hljs-keyword">const</span> app = express();

app.use(bodyParser.json());
app.use(<span class="hljs-string">"/api/events"</span>, events.API);
app.use(<span class="hljs-string">"/api/forms"</span>, forms);
</code></pre>
<p>Server network declaration</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * server.js
 */</span>
<span class="hljs-keyword">const</span> app = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../app'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);


<span class="hljs-comment">// Get port from environment and store in Express.</span>
<span class="hljs-keyword">const</span> port = normalizePort(process.env.PORT || <span class="hljs-string">'3000'</span>);
app.set(<span class="hljs-string">'port'</span>, port);


<span class="hljs-comment">// Create HTTP server.</span>
<span class="hljs-keyword">const</span> server = http.createServer(app);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-some-of-the-most-popular-packages-of-nodejs">Q. What are some of the most popular packages of Node.js?</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Package</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>Async</td><td>Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript</td></tr>
<tr>
<td>Browserify</td><td>Browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <code>&lt;script&gt;</code> tag</td></tr>
<tr>
<td>Bower</td><td>Bower is a package manager for the web It works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you\'re looking for</td></tr>
<tr>
<td>Csv</td><td>csv module has four sub modules which provides CSV generation, parsing, transformation and serialization for Node.js</td></tr>
<tr>
<td>Debug</td><td>Debug is a tiny node.js debugging utility modelled after node core\'s debugging technique</td></tr>
<tr>
<td>Express</td><td>Express is a fast, un-opinionated, minimalist web framework. It provides small, robust tooling for HTTP servers, making it a great solution for single page applications, web sites, hybrids, or public HTTP APIs</td></tr>
<tr>
<td>Grunt</td><td>is a JavaScript Task Runner that facilitates creating new projects and makes performing repetitive but necessary tasks such as linting, unit testing, concatenating and minifying files (among other things) trivial</td></tr>
<tr>
<td>Gulp</td><td>is a streaming build system that helps you automate painful or time-consuming tasks in your development workflow</td></tr>
<tr>
<td>Hapi</td><td>is a streaming build system that helps you automate painful or time-consuming tasks in your development workflow</td></tr>
<tr>
<td>Http-server</td><td>is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it\'s simple and hackable enough to be used for testing, local development, and learning</td></tr>
<tr>
<td>Inquirer</td><td>A collection of common interactive command line user interfaces</td></tr>
<tr>
<td>Jquery</td><td>jQuery is a fast, small, and feature-rich JavaScript library</td></tr>
<tr>
<td>Jshint</td><td>Static analysis tool to detect errors and potential problems in JavaScript code and to enforce your team\'s coding conventions</td></tr>
<tr>
<td>Koa</td><td>Koa is web app framework. It is an expressive HTTP middleware for node.js to make web applications and APIs more enjoyable to write</td></tr>
<tr>
<td>Lodash</td><td>The lodash library exported as a node module. Lodash is a modern JavaScript utility library delivering modularity, performance, &amp; extras</td></tr>
<tr>
<td>Less</td><td>The less library exported as a node module</td></tr>
<tr>
<td>Moment</td><td>A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates</td></tr>
<tr>
<td>Mongoose</td><td>It is a MongoDB object modeling tool designed to work in an asynchronous environment</td></tr>
<tr>
<td>MongoDB</td><td>The official MongoDB driver for Node.js. It provides a high-level API on top of mongodb-core that is meant for end users</td></tr>
<tr>
<td>Npm</td><td>is package manager for javascript</td></tr>
<tr>
<td>Nodemon</td><td>It is a simple monitor script for use during development of a node.js app, It will watch the files in the directory in which nodemon was started, and if any files change, nodemon will automatically restart your node application</td></tr>
<tr>
<td>Nodemailer</td><td>This module enables e-mail sending from a Node.js applications</td></tr>
<tr>
<td>Optimist</td><td>is a node.js library for option parsing with an argv hash</td></tr>
<tr>
<td>Phantomjs</td><td>An NPM installer for PhantomJS, headless webkit with JS API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG</td></tr>
<tr>
<td>Passport</td><td>A simple, unobtrusive authentication middleware for Node.js. Passport uses the strategies to authenticate requests. Strategies can range from verifying username and password credentials or authentication using OAuth or OpenID</td></tr>
<tr>
<td>Q</td><td>Q is a library for promises. A promise is an object that represents the return value or the thrown exception that the function may eventually provide</td></tr>
<tr>
<td>Request</td><td>Request is Simplified HTTP request client make it possible to make http calls. It supports HTTPS and follows redirects by default</td></tr>
<tr>
<td>Socket.io</td><td>Its a node.js realtime framework server</td></tr>
<tr>
<td>Sails</td><td>Sails is a API-driven framework for building realtime apps, using MVC conventions (based on Express and Socket.io)</td></tr>
<tr>
<td>Through</td><td>It enables simplified stream construction. It is easy way to create a stream that is both readable and writable</td></tr>
<tr>
<td>Underscore</td><td>Underscore.js is a utility-belt library for JavaScript that provides support for the usual functional suspects (each, map, reduce, filter...) without extending any core JavaScript objects</td></tr>
<tr>
<td>Validator</td><td>A nodejs module for a library of string validators and sanitizers</td></tr>
<tr>
<td>Winston</td><td>A multi-transport async logging library for Node.js</td></tr>
<tr>
<td>Ws</td><td>A simple to use, blazing fast and thoroughly tested websocket client, server and console for node.js</td></tr>
<tr>
<td>Xml2js</td><td>A Simple XML to JavaScript object converter</td></tr>
<tr>
<td>Yo</td><td>A CLI tool for running Yeoman generators</td></tr>
<tr>
<td>Zmq</td><td>Bindings for node.js and io.js to ZeroMQ. It is a high-performance asynchronous messaging library, aimed at use in distributed or concurrent applications</td></tr>
</tbody>
</table>
</div><div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-can-you-make-sure-your-dependencies-are-safe">Q. How can you make sure your dependencies are safe?</h2>
<p>The only option is to automate the update / security audit of your dependencies. For that there are free and paid options:</p>
<ol>
<li>npm outdated</li>
<li>Trace by RisingStack</li>
<li>NSP</li>
<li>GreenKeeper</li>
<li>Snyk</li>
<li>npm audit</li>
<li>npm audit fix</li>
</ol>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-the-security-mechanisms-available-in-nodejs">Q. What are the security mechanisms available in Node.js?</h2>
<p><strong>1. Helmet module:</strong></p>
<p><a target="_blank" href="https://www.npmjs.com/package/helmet">Helmet</a> helps to secure your Express applications by setting various HTTP headers, like:</p>
<ul>
<li>X-Frame-Options to mitigates clickjacking attacks,</li>
<li>Strict-Transport-Security to keep your users on HTTPS,</li>
<li>X-XSS-Protection to prevent reflected XSS attacks,</li>
<li>X-DNS-Prefetch-Control to disable browsers DNS prefetching.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Helmet
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> helmet = <span class="hljs-built_in">require</span>(<span class="hljs-string">'helmet'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(helmet())
</code></pre>
<p><strong>2. JOI module:</strong></p>
<p>Validating user input is one of the most important things to do when it comes to the security of your application. Failing to do it correctly can open up your application and users to a wide range of attacks, including command injection, SQL injection or stored cross-site scripting.</p>
<p>To validate user input, one of the best libraries you can pick is joi. <a target="_blank" href="https://www.npmjs.com/package/joi">Joi</a> is an object schema description language and validator for JavaScript objects.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Joi
 */</span>
<span class="hljs-keyword">const</span> Joi = <span class="hljs-built_in">require</span>(<span class="hljs-string">'joi'</span>);

<span class="hljs-keyword">const</span> schema = Joi.object().keys({
    <span class="hljs-attr">username</span>: Joi.string().alphanum().min(<span class="hljs-number">3</span>).max(<span class="hljs-number">30</span>).required(),
    <span class="hljs-attr">password</span>: Joi.string().regex(<span class="hljs-regexp">/^[a-zA-Z0-9]{3,30}$/</span>),
    <span class="hljs-attr">access_token</span>: [Joi.string(), Joi.number()],
    <span class="hljs-attr">birthyear</span>: Joi.number().integer().min(<span class="hljs-number">1900</span>).max(<span class="hljs-number">2013</span>),
    <span class="hljs-attr">email</span>: Joi.string().email()
}).with(<span class="hljs-string">'username'</span>, <span class="hljs-string">'birthyear'</span>).without(<span class="hljs-string">'password'</span>, <span class="hljs-string">'access_token'</span>)

<span class="hljs-comment">// Return result</span>
<span class="hljs-keyword">const</span> result = Joi.validate({
    <span class="hljs-attr">username</span>: <span class="hljs-string">'abc'</span>,
    <span class="hljs-attr">birthyear</span>: <span class="hljs-number">1994</span>
}, schema)
<span class="hljs-comment">// result.error === null -&gt; valid</span>
</code></pre>
<p><strong>3. Regular Expressions:</strong></p>
<p>Regular Expressions are a great way to manipulate texts and get the parts that you need from them. However, there is an attack vector called Regular Expression Denial of Service attack, which exposes the fact that most Regular Expression implementations may reach extreme situations for specially crafted input, that cause them to work extremely slowly.</p>
<p>The Regular Expressions that can do such a thing are commonly referred as Evil Regexes. These expressions contain:
<em>grouping with repetition,
</em>inside the repeated group:
    <em>repetition, or
    </em>alternation with overlapping  </p>
<p>Examples of Evil Regular Expressions patterns:</p>
<pre><code class="lang-js">(a+)+
([a-zA-Z]+)*
(a|aa)+
</code></pre>
<p><strong>4. Security.txt:</strong></p>
<p>Security.txt defines a standard to help organizations define the process for security researchers to securely disclose security vulnerabilities.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> securityTxt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-security.txt'</span>)

<span class="hljs-keyword">const</span> app = express()

app.get(<span class="hljs-string">'/security.txt'</span>, securityTxt({
  <span class="hljs-comment">// your security address</span>
  <span class="hljs-attr">contact</span>: <span class="hljs-string">'email@example.com'</span>,
  <span class="hljs-comment">// your pgp key</span>
  <span class="hljs-attr">encryption</span>: <span class="hljs-string">'encryption'</span>,
  <span class="hljs-comment">// if you have a hall of fame for securty resourcers, include the link here</span>
  <span class="hljs-attr">acknowledgements</span>: <span class="hljs-string">'http://acknowledgements.example.com'</span>
}))
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-npm-in-nodejs">Q. What is npm in Node.js?</h2>
<p>NPM stands for Node Package Manager. It provides following two main functionalities.</p>
<ul>
<li>It works as an Online repository for node.js packages/modules which are present at .</li>
<li>It works as Command line utility to install packages, do version management and dependency management of Node.js packages.
NPM comes bundled along with Node.js installable. We can verify its version using the following command-</li>
</ul>
<pre><code class="lang-js">npm --version
</code></pre>
<p>NPM helps to install any Node.js module using the following command.</p>
<pre><code class="lang-js">npm install &lt;Module Name&gt;
</code></pre>
<p>For example, following is the command to install a famous Node.js web framework module called express-</p>
<pre><code class="lang-js">npm install express
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-why-npm-shrinkwrap-is-useful">Q. Why npm shrinkwrap is useful?</h2>
<p>NPM shrinkwrap lets you lock down the ver­sions of installed pack­ages and their descen­dant pack­ages. It helps you use same package versions on all environments (development, staging, production) and also improve download and installation speed.</p>
<p>After installing packages using npm install or npm install <code>&lt;package-name&gt;</code> and updating your <strong>node_modules</strong> folder, you should run</p>
<pre><code class="lang-js">npm shrinkwrap
</code></pre>
<p>It should create new <strong>npm-shrinkwrap.json</strong> file with information about all packages you use. Next time, when someone calls <strong>npm install</strong>, it will install packages from <strong>npm-shrinkwrap.json</strong> and you will have the same environment on all machines.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-handle-file-upload-in-nodejs">Q. How to handle file upload in Node.js?</h2>
<p>File can be uploaded to the server using Multer module. Multer is a Node.js middleware which is used for handling multipart/form-data, which is mostly used library for uploading files.</p>
<p><strong>1. Installing the dependencies:</strong></p>
<pre><code class="lang-js">npm install express body-parser multer --save
</code></pre>
<p><strong>2. server.js:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * File Upload in Node.js
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);
<span class="hljs-keyword">const</span> multer = <span class="hljs-built_in">require</span>(<span class="hljs-string">"multer"</span>);
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// for text/number data transfer between clientg and server</span>
app.use(bodyParser());

<span class="hljs-keyword">const</span> storage = multer.diskStorage({
  <span class="hljs-attr">destination</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, file, callback</span>) </span>{
    callback(<span class="hljs-literal">null</span>, <span class="hljs-string">"./uploads"</span>);
  },
  <span class="hljs-attr">filename</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, file, callback</span>) </span>{
    callback(<span class="hljs-literal">null</span>, file.fieldname + <span class="hljs-string">"-"</span> + <span class="hljs-built_in">Date</span>.now());
  },
});

<span class="hljs-keyword">const</span> upload = multer({ <span class="hljs-attr">storage</span>: storage }).single(<span class="hljs-string">"userPhoto"</span>);

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.sendFile(__dirname + <span class="hljs-string">"/index.html"</span>);
});

<span class="hljs-comment">// POST: upload for single file upload</span>
app.post(<span class="hljs-string">"/api/photo"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  upload(req, res, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-keyword">return</span> res.end(<span class="hljs-string">"Error uploading file."</span>);
    }
    res.end(<span class="hljs-string">"File is uploaded"</span>);
  });
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Listening on port 3000"</span>);
});
</code></pre>
<p><strong>3. index.html:</strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Multer-File-Upload<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>MULTER File Upload | Single File Upload<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 

    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">id</span> = <span class="hljs-string">"uploadForm"</span>
         <span class="hljs-attr">enctype</span> = <span class="hljs-string">"multipart/form-data"</span>
         <span class="hljs-attr">action</span> = <span class="hljs-string">"/api/photo"</span>
         <span class="hljs-attr">method</span> = <span class="hljs-string">"post"</span>
    &gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"userPhoto"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Upload Image"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"submit"</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-the-terms-body-parser-cookie-parser-morgan-nodemon-pm2-serve-favicon-cors-dotenv-fs-extra-moment-in-expressjs">Q. Explain the terms body-parser, cookie-parser, morgan, nodemon, pm2, serve-favicon, cors, dotenv, fs-extra, moment in Express.js?</h2>
<p><strong>1. body-parser:</strong></p>
<p><code>body-parser</code> extract the entire body portion of an incoming request stream and exposes it on <code>req.body</code>. The body-parser module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST request.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js">npm install body-parser
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * body-parser
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>);
<span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-comment">// create application/json parser</span>
<span class="hljs-keyword">const</span> jsonParser = bodyParser.json();

<span class="hljs-comment">// create application/x-www-form-urlencoded parser</span>
<span class="hljs-keyword">const</span> urlencodedParser = bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> });

<span class="hljs-comment">// POST /login gets urlencoded bodies</span>
app.post(<span class="hljs-string">"/login"</span>, urlencodedParser, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">"welcome, "</span> + req.body.username);
});

<span class="hljs-comment">// POST /api/users gets JSON bodies</span>
app.post(<span class="hljs-string">"/api/users"</span>, jsonParser, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-comment">// create user in req.body</span>
});
</code></pre>
<p><strong>2. cookie-parser:</strong></p>
<p>A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using.</p>
<p>The <code>cookie-parser</code> middleware\'s cookieParser function takes a <code>secret</code> string or array of strings as the first argument and an <code>options</code> object as the second argument.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install cookie-parser
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * cookie-parser
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>)

<span class="hljs-keyword">const</span> app = express()
app.use(cookieParser())

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-comment">// Cookies that have not been signed</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Cookies: '</span>, req.cookies)

  <span class="hljs-comment">// Cookies that have been signed</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Signed Cookies: '</span>, req.signedCookies)
})

app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p><strong>3. morgan:</strong></p>
<p>HTTP request logger middleware for node.js.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install morgan
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Writing logs to a file
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>)
<span class="hljs-keyword">const</span> morgan = <span class="hljs-built_in">require</span>(<span class="hljs-string">'morgan'</span>)
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>)

<span class="hljs-keyword">const</span> app = express()

<span class="hljs-comment">// create a write stream (in append mode)</span>
<span class="hljs-keyword">const</span> accessLogStream = fs.createWriteStream(path.join(__dirname, <span class="hljs-string">'access.log'</span>), { <span class="hljs-attr">flags</span>: <span class="hljs-string">'a'</span> })

<span class="hljs-comment">// setup the logger</span>
app.use(morgan(<span class="hljs-string">'combined'</span>, { <span class="hljs-attr">stream</span>: accessLogStream }))

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'hello, world!'</span>)
})
</code></pre>
<p><strong>4. nodemon:</strong></p>
<p>Nodemon is a utility that will monitor for any changes in source and automatically restart your server.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install -g nodemon
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// ...</span>
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"nodemon server.js"</span>
  },
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p><strong>5. pm2:</strong></p>
<p><strong>P</strong>(rocess) <strong>M</strong>(anager) <strong>2</strong> (pm2) is a production process manager for Node.js applications with a built-in load balancer. It allows to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install pm2 -g
</code></pre>
<p><strong>Start an application:</strong></p>
<pre><code class="lang-js">pm2 start app.js
</code></pre>
<p><strong>Reference:</strong></p>
<ul>
<li><em><a target="_blank" href="https://pm2.keymetrics.io/docs/usage/quick-start/">https://pm2.keymetrics.io/docs/usage/quick-start/</a></em></li>
</ul>
<p><strong>6. serve-favicon:</strong></p>
<p>Node.js middleware for serving a favicon. It create new middleware to serve a favicon from the given path to a favicon file. <strong>path</strong> may also be a Buffer of the icon to serve.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install serve-favicon
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * serve-favicon
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> favicon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'serve-favicon'</span>)
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>)

<span class="hljs-keyword">const</span> app = express()
app.use(favicon(path.join(__dirname, <span class="hljs-string">'public'</span>, <span class="hljs-string">'favicon.ico'</span>)))

<span class="hljs-comment">// Add your routes here, etc.</span>

app.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p><strong>7. cors:</strong></p>
<p><strong>C</strong>ross-<strong>O</strong>rigin <strong>R</strong>esource <strong>S</strong>haring (CORS) headers allow apps running in the browser to make requests to servers on different domains (also known as origins). CORS headers are set on the server side - the HTTP server is responsible for indicating that a given HTTP request can be cross-origin.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install cors
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Enable CORS for a Single Route
 */</span>
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>)
<span class="hljs-keyword">const</span> app = express()

app.get(<span class="hljs-string">'/products/:id'</span>, cors(), <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{
  res.json({<span class="hljs-attr">msg</span>: <span class="hljs-string">'This is CORS-enabled for a Single Route'</span>})
})

app.listen(<span class="hljs-number">8080</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'CORS-enabled web server listening on port 80'</span>)
})
</code></pre>
<p><strong>8. dotenv:</strong></p>
<p>When a NodeJs application runs, it injects a global variable called <code>process.env</code> which contains information about the state of environment in which the application is running. The <code>dotenv</code> loads environment variables stored in the <code>.env</code> file into <code>process.env</code>.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install dotenv
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// .env</span>

DB_HOST=localhost
DB_USER=admin
DB_PASS=root
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * config.js
 */</span>
<span class="hljs-keyword">const</span> db = <span class="hljs-built_in">require</span>(<span class="hljs-string">'db'</span>)

db.connect({
  <span class="hljs-attr">host</span>: process.env.DB_HOST,
  <span class="hljs-attr">username</span>: process.env.DB_USER,
  <span class="hljs-attr">password</span>: process.env.DB_PASS
})
</code></pre>
<p><strong>9. fs-extra:</strong></p>
<p><code>fs-extra</code> contains methods that aren\'t included in the vanilla Node.js fs package. Such as recursive <code>mkdir</code>, <code>copy</code>, and <code>remove</code>. It also uses graceful-fs to prevent <code>EMFILE</code> errors.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install fs-extra
</code></pre>
<p><strong>Usage:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * fs-extra
 */</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs-extra'</span>)

<span class="hljs-comment">// Async with callbacks:</span>
fs.copy(<span class="hljs-string">'/tmp/myfile'</span>, <span class="hljs-string">'/tmp/mynewfile'</span>, <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'success!'</span>)
})
</code></pre>
<p><strong>10. moment:</strong></p>
<p>A JavaScript date library for parsing, validating, manipulating, and formatting dates.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install moment --save
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Format Dates</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">'moment'</span>);

moment().format(<span class="hljs-string">'MMMM Do YYYY, h:mm:ss a'</span>); <span class="hljs-comment">// October 24th 2022, 3:15:22 pm</span>
moment().format(<span class="hljs-string">'dddd'</span>);                    <span class="hljs-comment">// Saturday</span>
moment().format(<span class="hljs-string">"MMM Do YY"</span>);               <span class="hljs-comment">// Oct 24th 22</span>
</code></pre>
<ul>
<li>Relative Time</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">'moment'</span>);

moment(<span class="hljs-string">"20111031"</span>, <span class="hljs-string">"YYYYMMDD"</span>).fromNow(); <span class="hljs-comment">// 9 years ago</span>
moment(<span class="hljs-string">"20120620"</span>, <span class="hljs-string">"YYYYMMDD"</span>).fromNow(); <span class="hljs-comment">// 8 years ago</span>
moment().startOf(<span class="hljs-string">'day'</span>).fromNow();        <span class="hljs-comment">// 15 hours ago</span>
</code></pre>
<ul>
<li>Calendar Time</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">'moment'</span>);

moment().subtract(<span class="hljs-number">10</span>, <span class="hljs-string">'days'</span>).calendar(); <span class="hljs-comment">// 10/14/2022</span>
moment().subtract(<span class="hljs-number">6</span>, <span class="hljs-string">'days'</span>).calendar();  <span class="hljs-comment">// Last Sunday at 3:18 PM</span>
moment().subtract(<span class="hljs-number">3</span>, <span class="hljs-string">'days'</span>).calendar();  <span class="hljs-comment">// Last Wednesday at 3:18 PM</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-11-nodejs-restful-api"># 11. NODE.JS RESTFUL API</h2>
<p><br /></p>
<h2 id="heading-q-explain-restful-web-services-in-nodejs">Q. Explain RESTful Web Services in Node.js?</h2>
<p>REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol.
It is an architectural style as well as an approach for communications purposes that is often used in various web services development. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol.</p>
<p><strong>HTTP methods:</strong></p>
<ul>
<li><code>GET</code> − Provides read-only access to a resource.</li>
<li><code>PUT</code> − Updates an existing resource or creates a new resource.</li>
<li><code>DELETE</code> − Removes a resource.</li>
<li><code>POST</code> − Creates a new resource.</li>
<li><code>PATCH</code>− Update/modify a resource</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-json"><span class="hljs-comment">// users.json</span>
{
   <span class="hljs-attr">"user1"</span> : {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">"name"</span> : <span class="hljs-string">"Ehsan Philip"</span>,
      <span class="hljs-attr">"age"</span> : <span class="hljs-number">24</span>
   },

   <span class="hljs-attr">"user2"</span> : {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
      <span class="hljs-attr">"name"</span> : <span class="hljs-string">"Karim Jimenez"</span>,
      <span class="hljs-attr">"age"</span> : <span class="hljs-number">22</span>
   },

   <span class="hljs-attr">"user3"</span> : {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
      <span class="hljs-attr">"name"</span> : <span class="hljs-string">"Giacomo Weir"</span>,
      <span class="hljs-attr">"age"</span> : <span class="hljs-number">18</span>
   }
}
</code></pre>
<p><strong>List Users</strong> ( <code>GET</code> method)</p>
<p>Let\'s implement our first RESTful API listUsers using the following code in a server.js file −</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);

app.get(<span class="hljs-string">'/listUsers'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
   fs.readFile( __dirname + <span class="hljs-string">"/"</span> + <span class="hljs-string">"users.json"</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, data</span>) </span>{
      <span class="hljs-built_in">console</span>.log( data );
      res.end( data );
   });
})

<span class="hljs-keyword">const</span> server = app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> host = server.address().address
   <span class="hljs-keyword">const</span> port = server.address().port
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"App listening at http://%s:%s"</span>, host, port)
});
</code></pre>
<p><strong>Add User</strong> ( <code>POST</code> method )</p>
<p>Following API will show you how to add new user in the list. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);

<span class="hljs-keyword">const</span> user = {
   <span class="hljs-string">"user4"</span> : {
      <span class="hljs-string">"id"</span>: <span class="hljs-number">4</span>,
      <span class="hljs-string">"name"</span> : <span class="hljs-string">"Spencer Amos"</span>,
      <span class="hljs-string">"age"</span> : <span class="hljs-number">28</span>
   }
}

app.post(<span class="hljs-string">'/addUser'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
   <span class="hljs-comment">// First read existing users.</span>
   fs.readFile( __dirname + <span class="hljs-string">"/"</span> + <span class="hljs-string">"users.json"</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, data</span>) </span>{
      data = <span class="hljs-built_in">JSON</span>.parse( data );
      data[<span class="hljs-string">"user4"</span>] = user[<span class="hljs-string">"user4"</span>];
      <span class="hljs-built_in">console</span>.log( data );
      res.end( <span class="hljs-built_in">JSON</span>.stringify(data));
   });
})

<span class="hljs-keyword">const</span> server = app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> host = server.address().address
   <span class="hljs-keyword">const</span> port = server.address().port
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"App listening at http://%s:%s"</span>, host, port)
})
</code></pre>
<p><strong>Delete User:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);

<span class="hljs-keyword">const</span> id = <span class="hljs-number">2</span>;

app.delete(<span class="hljs-string">'/deleteUser'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
   <span class="hljs-comment">// First read existing users.</span>
   fs.readFile( __dirname + <span class="hljs-string">"/"</span> + <span class="hljs-string">"users.json"</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, data</span>) </span>{
      data = <span class="hljs-built_in">JSON</span>.parse( data );
      <span class="hljs-keyword">delete</span> data[<span class="hljs-string">"user"</span> + <span class="hljs-number">2</span>];
      <span class="hljs-built_in">console</span>.log( data );
      res.end( <span class="hljs-built_in">JSON</span>.stringify(data));
   });
})

<span class="hljs-keyword">const</span> server = app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> host = server.address().address
   <span class="hljs-keyword">const</span> port = server.address().port
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"App listening at http://%s:%s"</span>, host, port)
})
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-the-difference-between-reqparams-and-reqquery">Q. What is the difference between req.params and req.query?</h2>
<p>The <strong>req.params</strong> are a part of a path in URL and they\'re also known as URL variables. for example, if you have the route <strong>/books/:id</strong>, then the <strong>id</strong> property will be available as <strong>req.params.id</strong>. req.params default value is an empty object {}.</p>
<p>A <strong>req.query</strong> is a part of a URL that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML form. A query is the last part of URL</p>
<p><strong>Example 01:</strong> req.params</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * req.params
 */</span>

<span class="hljs-comment">// GET  http://localhost:3000/employees/10</span>

app.get(<span class="hljs-string">'/employees/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(req.params.id); <span class="hljs-comment">// 10</span>
})
</code></pre>
<p><strong>Example 02:</strong> req.query</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * req.query
 */</span>

<span class="hljs-comment">// GET  http://localhost:3000/employees?page=20</span>

app.get(<span class="hljs-string">'/employees'</span>, <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(req.query.page) <span class="hljs-comment">// 20</span>
})
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-make-post-request-in-nodejs">Q. How to make post request in Node.js?</h2>
<p>Following code snippet can be used to make a Post Request in Node.js.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * POST Request
 */</span>
<span class="hljs-keyword">const</span> request = <span class="hljs-built_in">require</span>(<span class="hljs-string">"request"</span>);

request.post(<span class="hljs-string">"http://localhost:3000/action"</span>,  { <span class="hljs-attr">form</span>: { <span class="hljs-attr">key</span>: <span class="hljs-string">"value"</span> } },
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error, response, body</span>) </span>{
    <span class="hljs-keyword">if</span> (!error &amp;&amp; response.statusCode === <span class="hljs-number">200</span>) {
      <span class="hljs-built_in">console</span>.log(body);
    }
  }
);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-promises-in-nodejs">Q. What are Promises in Node.js?</h2>
<p>It allows to associate handlers to an asynchronous action\'s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.</p>
<p>Promises in node.js promised to do some work and then had separate callbacks that would be executed for success and failure as well as handling timeouts. Another way to think of promises in node.js was that they were emitters that could emit only two events: success and error.The cool thing about promises is you can combine them into dependency chains (do Promise C only when Promise A and Promise B complete).</p>
<p>The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:</p>
<ul>
<li>pending - The initial state of a promise.</li>
<li>fulfilled - The state of a promise representing a successful operation.</li>
<li>rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).  </li>
</ul>
<p><strong>Creating a Promise:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myPromise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>)</span>{
   ....
})
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-can-you-secure-your-http-cookies-against-xss-attacks">Q. How can you secure your HTTP cookies against XSS attacks?</h2>
<p><strong>1.</strong> When the web server sets cookies, it can provide some additional attributes to make sure the cookies won\'t be accessible by using malicious JavaScript. One such attribute is HttpOnly.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Set</span>-Cookie: [name]=[value]; HttpOnly
</code></pre>
<p>HttpOnly makes sure the cookies will be submitted only to the domain they originated from.</p>
<p><strong>2.</strong> The "Secure" attribute can make sure the cookies are sent over secured channel only.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Set</span>-Cookie: [name]=[value]; Secure
</code></pre>
<p><strong>3.</strong> The web server can use X-XSS-Protection response header to make sure pages do not load when they detect reflected cross-site scripting (XSS) attacks.</p>
<pre><code class="lang-js">X-XSS-Protection: <span class="hljs-number">1</span>; mode=block
</code></pre>
<p><strong>4.</strong> The web server can use HTTP Content-Security-Policy response header to control what resources a user agent is allowed to load for a certain page. It can help to prevent various types of attacks like Cross Site Scripting (XSS) and data injection attacks.</p>
<pre><code class="lang-js">Content-Security-Policy: <span class="hljs-keyword">default</span>-src <span class="hljs-string">'self'</span> *.http:<span class="hljs-comment">//sometrustedwebsite.com</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-make-an-http-post-request-using-nodejs">Q. How to make an HTTP POST request using Node.js?</h2>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'https'</span>)


<span class="hljs-keyword">const</span> obj = {
    <span class="hljs-string">"userId"</span>:<span class="hljs-number">1</span>,
    <span class="hljs-string">"id"</span>:<span class="hljs-number">1</span>,
    <span class="hljs-string">"title"</span>:<span class="hljs-string">"whatever"</span>,
    <span class="hljs-string">"completed"</span>:<span class="hljs-literal">false</span>
}

<span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.stringify(obj)

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'jsonplaceholder.typicode.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/todos'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    <span class="hljs-string">'Content-Length'</span>: data.length
  }
}

<span class="hljs-keyword">const</span> req = https.request(options, <span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`statusCode: <span class="hljs-subst">${res.statusCode}</span>`</span>)

  res.on(<span class="hljs-string">'data'</span>, <span class="hljs-function"><span class="hljs-params">d</span> =&gt;</span> {
    process.stdout.write(d)
  })
})

req.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.error(error)
})

req.write(data)
req.end()
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-asynchronous-programming-in-nodejs">Q. What is asynchronous programming in Node.js?</h2>
<p>Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed). There are numerous benefits to using it, such as improved application performance and enhanced responsiveness.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-the-difference-between-asynchronous-and-non-blocking">Q. What is the difference between Asynchronous and Non-blocking?</h2>
<p><strong>1. Asynchronous:</strong></p>
<p>The architecture of asynchronous explains that the message sent will not give the reply on immediate basis just like we send the mail but do not get the reply on an immediate basis. It does not have any dependency or order. Hence improving the system efficiency and performance. The server stores the information and when the action is done it will be notified.</p>
<p><strong>2. Non-Blocking:</strong></p>
<p>Nonblocking immediately responses with whatever data available. Moreover, it does not block any execution and keeps on running as per the requests. If an answer could not be retrieved then in those cases API returns immediately with an error. Nonblocking is mostly used with I/O(input/output). Node.js is itself based on nonblocking I/O model. There are few ways of communication that a nonblocking I/O has completed. The callback function is to be called when the operation is completed. Nonblocking call uses the help of javascript which provides a callback function.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-nodejs-prevents-blocking-code">Q. How node.js prevents blocking code?</h2>
<p><strong>Blocking vs Non-blocking:</strong></p>
<p><strong>Blocking</strong> is when the execution of additional JavaScript in the Node.js process must wait until a non-JavaScript operation completes. This happens because the event loop is unable to continue running JavaScript while a <strong>blocking</strong> operation is occurring.</p>
<p>Synchronous methods in the Node.js standard library that use <strong>libuv</strong> are the most commonly used blocking operations. Native modules may also have blocking methods. Blocking methods execute <code>synchronously</code> and non-blocking methods execute <code>asynchronously</code>.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Blocking</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> data = fs.readFileSync(<span class="hljs-string">'/file.md'</span>); <span class="hljs-comment">// blocks here until file is read</span>
<span class="hljs-built_in">console</span>.log(data);
moreWork(); <span class="hljs-comment">// will run after console.log</span>

<span class="hljs-comment">// Non-blocking</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
fs.readFile(<span class="hljs-string">'/file.md'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-built_in">console</span>.log(data);
});
moreWork(); <span class="hljs-comment">// will run before console.log</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-name-the-types-of-api-functions-in-nodejs">Q. Name the types of API functions in Node.js?</h2>
<p>There are two types of API functions in Node.js:</p>
<ul>
<li>Asynchronous, Non-blocking functions</li>
<li>Synchronous, Blocking functions</li>
</ul>
<p><strong>1. Blocking functions:</strong></p>
<p>In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> data = fs.readFileSync(<span class="hljs-string">'/file.md'</span>); <span class="hljs-comment">// blocks here until file is read</span>
<span class="hljs-built_in">console</span>.log(data);
<span class="hljs-comment">// moreWork(); will run after console.log</span>
</code></pre>
<p>The second line of code blocks the execution of additional JavaScript until the entire file is read. moreWork () will only be called after Console.log</p>
<p><strong>2. Non-blocking functions:</strong></p>
<p>In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
fs.readFile(<span class="hljs-string">'/file.md'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-built_in">console</span>.log(data);
});
<span class="hljs-comment">// moreWork(); will run before console.log</span>
</code></pre>
<p>Since <code>fs.readFile()</code> is non-blocking, moreWork() does not have to wait for the file read to complete before being called. This allows for higher throughput.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-difference-between-put-and-patch">Q. What is difference between put and patch?</h2>
<p>PUT and PATCH are HTTP verbs and they both relate to updating a resource. The main difference between PUT and PATCH requests are in the way the server processes the enclosed entity to modify the resource identified by the Request-URI.</p>
<p>In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced.</p>
<p>With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.</p>
<p>Also, another difference is that when you want to update a resource with PUT request, you have to send the full payload as the request whereas with PATCH, you only send the parameters which you want to update.</p>
<p>The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.</p>
<ul>
<li><code>POST</code> - create</li>
<li><code>GET</code>  - read  </li>
<li><code>PUT</code>  - update</li>
<li><code>DELETE</code> - delete</li>
</ul>
<p><strong>PATCH</strong>: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-list-types-of-http-requests-supported-by-nodejs">Q. List types of Http requests supported by Node.js?</h2>
<p>The HTTP core module is a key module to Node.js networking.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>)
</code></pre>
<p><strong>http.METHODS</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>).METHODS
[ <span class="hljs-string">'ACL'</span>,
  <span class="hljs-string">'BIND'</span>,
  <span class="hljs-string">'CHECKOUT'</span>,
  <span class="hljs-string">'CONNECT'</span>,
  <span class="hljs-string">'COPY'</span>,
  <span class="hljs-string">'DELETE'</span>,
  <span class="hljs-string">'GET'</span>,
  <span class="hljs-string">'HEAD'</span>,
  <span class="hljs-string">'LINK'</span>,
  <span class="hljs-string">'LOCK'</span>,
  <span class="hljs-string">'M-SEARCH'</span>,
  <span class="hljs-string">'MERGE'</span>,
  <span class="hljs-string">'MKACTIVITY'</span>,
  <span class="hljs-string">'MKCALENDAR'</span>,
  <span class="hljs-string">'MKCOL'</span>,
  <span class="hljs-string">'MOVE'</span>,
  <span class="hljs-string">'NOTIFY'</span>,
  <span class="hljs-string">'OPTIONS'</span>,
  <span class="hljs-string">'PATCH'</span>,
  <span class="hljs-string">'POST'</span>,
  <span class="hljs-string">'PROPFIND'</span>,
  <span class="hljs-string">'PROPPATCH'</span>,
  <span class="hljs-string">'PURGE'</span>,
  <span class="hljs-string">'PUT'</span>,
  <span class="hljs-string">'REBIND'</span>,
  <span class="hljs-string">'REPORT'</span>,
  <span class="hljs-string">'SEARCH'</span>,
  <span class="hljs-string">'SUBSCRIBE'</span>,
  <span class="hljs-string">'TRACE'</span>,
  <span class="hljs-string">'UNBIND'</span>,
  <span class="hljs-string">'UNLINK'</span>,
  <span class="hljs-string">'UNLOCK'</span>,
  <span class="hljs-string">'UNSUBSCRIBE'</span> ]
</code></pre>
<p><strong>http.STATUS_CODES</strong></p>
<pre><code class="lang-js">  <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>).STATUS_CODES
{ <span class="hljs-string">'100'</span>: <span class="hljs-string">'Continue'</span>,
  <span class="hljs-string">'101'</span>: <span class="hljs-string">'Switching Protocols'</span>,
  <span class="hljs-string">'102'</span>: <span class="hljs-string">'Processing'</span>,
  <span class="hljs-string">'200'</span>: <span class="hljs-string">'OK'</span>,
  <span class="hljs-string">'201'</span>: <span class="hljs-string">'Created'</span>,
  <span class="hljs-string">'202'</span>: <span class="hljs-string">'Accepted'</span>,
  <span class="hljs-string">'203'</span>: <span class="hljs-string">'Non-Authoritative Information'</span>,
  <span class="hljs-string">'204'</span>: <span class="hljs-string">'No Content'</span>,
  <span class="hljs-string">'205'</span>: <span class="hljs-string">'Reset Content'</span>,
  <span class="hljs-string">'206'</span>: <span class="hljs-string">'Partial Content'</span>,
  <span class="hljs-string">'207'</span>: <span class="hljs-string">'Multi-Status'</span>,
  <span class="hljs-string">'208'</span>: <span class="hljs-string">'Already Reported'</span>,
  <span class="hljs-string">'226'</span>: <span class="hljs-string">'IM Used'</span>,
  <span class="hljs-string">'300'</span>: <span class="hljs-string">'Multiple Choices'</span>,
  <span class="hljs-string">'301'</span>: <span class="hljs-string">'Moved Permanently'</span>,
  <span class="hljs-string">'302'</span>: <span class="hljs-string">'Found'</span>,
  <span class="hljs-string">'303'</span>: <span class="hljs-string">'See Other'</span>,
  <span class="hljs-string">'304'</span>: <span class="hljs-string">'Not Modified'</span>,
  <span class="hljs-string">'305'</span>: <span class="hljs-string">'Use Proxy'</span>,
  <span class="hljs-string">'307'</span>: <span class="hljs-string">'Temporary Redirect'</span>,
  <span class="hljs-string">'308'</span>: <span class="hljs-string">'Permanent Redirect'</span>,
  <span class="hljs-string">'400'</span>: <span class="hljs-string">'Bad Request'</span>,
  <span class="hljs-string">'401'</span>: <span class="hljs-string">'Unauthorized'</span>,
  <span class="hljs-string">'402'</span>: <span class="hljs-string">'Payment Required'</span>,
  <span class="hljs-string">'403'</span>: <span class="hljs-string">'Forbidden'</span>,
  <span class="hljs-string">'404'</span>: <span class="hljs-string">'Not Found'</span>,
  <span class="hljs-string">'405'</span>: <span class="hljs-string">'Method Not Allowed'</span>,
  <span class="hljs-string">'406'</span>: <span class="hljs-string">'Not Acceptable'</span>,
  <span class="hljs-string">'407'</span>: <span class="hljs-string">'Proxy Authentication Required'</span>,
  <span class="hljs-string">'408'</span>: <span class="hljs-string">'Request Timeout'</span>,
  <span class="hljs-string">'409'</span>: <span class="hljs-string">'Conflict'</span>,
  <span class="hljs-string">'410'</span>: <span class="hljs-string">'Gone'</span>,
  <span class="hljs-string">'411'</span>: <span class="hljs-string">'Length Required'</span>,
  <span class="hljs-string">'412'</span>: <span class="hljs-string">'Precondition Failed'</span>,
  <span class="hljs-string">'413'</span>: <span class="hljs-string">'Payload Too Large'</span>,
  <span class="hljs-string">'414'</span>: <span class="hljs-string">'URI Too Long'</span>,
  <span class="hljs-string">'415'</span>: <span class="hljs-string">'Unsupported Media Type'</span>,
  <span class="hljs-string">'416'</span>: <span class="hljs-string">'Range Not Satisfiable'</span>,
  <span class="hljs-string">'417'</span>: <span class="hljs-string">'Expectation Failed'</span>,
  <span class="hljs-string">'418'</span>: <span class="hljs-string">'I\'m a teapot'</span>,
  <span class="hljs-string">'421'</span>: <span class="hljs-string">'Misdirected Request'</span>,
  <span class="hljs-string">'422'</span>: <span class="hljs-string">'Unprocessable Entity'</span>,
  <span class="hljs-string">'423'</span>: <span class="hljs-string">'Locked'</span>,
  <span class="hljs-string">'424'</span>: <span class="hljs-string">'Failed Dependency'</span>,
  <span class="hljs-string">'425'</span>: <span class="hljs-string">'Unordered Collection'</span>,
  <span class="hljs-string">'426'</span>: <span class="hljs-string">'Upgrade Required'</span>,
  <span class="hljs-string">'428'</span>: <span class="hljs-string">'Precondition Required'</span>,
  <span class="hljs-string">'429'</span>: <span class="hljs-string">'Too Many Requests'</span>,
  <span class="hljs-string">'431'</span>: <span class="hljs-string">'Request Header Fields Too Large'</span>,
  <span class="hljs-string">'451'</span>: <span class="hljs-string">'Unavailable For Legal Reasons'</span>,
  <span class="hljs-string">'500'</span>: <span class="hljs-string">'Internal Server Error'</span>,
  <span class="hljs-string">'501'</span>: <span class="hljs-string">'Not Implemented'</span>,
  <span class="hljs-string">'502'</span>: <span class="hljs-string">'Bad Gateway'</span>,
  <span class="hljs-string">'503'</span>: <span class="hljs-string">'Service Unavailable'</span>,
  <span class="hljs-string">'504'</span>: <span class="hljs-string">'Gateway Timeout'</span>,
  <span class="hljs-string">'505'</span>: <span class="hljs-string">'HTTP Version Not Supported'</span>,
  <span class="hljs-string">'506'</span>: <span class="hljs-string">'Variant Also Negotiates'</span>,
  <span class="hljs-string">'507'</span>: <span class="hljs-string">'Insufficient Storage'</span>,
  <span class="hljs-string">'508'</span>: <span class="hljs-string">'Loop Detected'</span>,
  <span class="hljs-string">'509'</span>: <span class="hljs-string">'Bandwidth Limit Exceeded'</span>,
  <span class="hljs-string">'510'</span>: <span class="hljs-string">'Not Extended'</span>,
  <span class="hljs-string">'511'</span>: <span class="hljs-string">'Network Authentication Required'</span> }
</code></pre>
<p><strong>Making HTTP Requests</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> request = <span class="hljs-built_in">require</span>(<span class="hljs-string">'request'</span>);

request(<span class="hljs-string">'https://nodejs.org/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, res, body</span>) </span>{
    <span class="hljs-built_in">console</span>.log(body);
});
</code></pre>
<p>The first argument to request can either be a URL string, or an object of options. Here are some of the more common options you\'ll encounter in your applications:</p>
<ul>
<li><strong>url</strong>: The destination URL of the HTTP request</li>
<li><strong>method</strong>: The HTTP method to be used (GET, POST, DELETE, etc)</li>
<li><strong>headers</strong>: An object of HTTP headers (key-value) to be set in the request</li>
<li><strong>form</strong>: An object containing key-value form data</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> request = <span class="hljs-built_in">require</span>(<span class="hljs-string">'request'</span>);

<span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">url</span>: <span class="hljs-string">'https://nodejs.org/file.json'</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
    <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Accept'</span>: <span class="hljs-string">'application/json'</span>,
        <span class="hljs-string">'Accept-Charset'</span>: <span class="hljs-string">'utf-8'</span>,
        <span class="hljs-string">'User-Agent'</span>: <span class="hljs-string">'my-reddit-client'</span>
    }
};

request(options, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, res, body</span>) </span>{
    <span class="hljs-keyword">let</span> json = <span class="hljs-built_in">JSON</span>.parse(body);
    <span class="hljs-built_in">console</span>.log(json);
});
</code></pre>
<p>Using the options object, this request uses the GET method to retrieve JSON data directly from Reddit, which is returned as a string in the body field. From here, you can use <code>JSON.parse</code> and use the data as a normal JavaScript object.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-difference-between-promises-and-async-await-in-nodejs">Q. What is difference between promises and async-await in Node.js?</h2>
<p><strong>1. Promises:</strong></p>
<p>A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed. This way, other operations can keep running without interruption.</p>
<p><strong>States of Promises:</strong></p>
<ul>
<li><code>Pending</code>: Initial State, before the Promise succeeds or fails.</li>
<li><code>Resolved</code>: Completed Promise</li>
<li><code>Rejected</code>: Failed Promise, throw an error</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logFetch</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">return</span> fetch(url)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(response);
    })
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'fetch failed'</span>, err);
    });
}
</code></pre>
<p><strong>2. Async-Await:</strong></p>
<p><code>Await</code> is basically syntactic sugar for <strong>Promises</strong>. It makes asynchronous code look more like synchronous/procedural code, which is easier for humans to understand.</p>
<p>Putting the keyword <code>async</code> before a function tells the function to return a Promise. If the code returns something that is not a <code>Promise</code>, then JavaScript automatically wraps it into a resolved promise with that value. The <code>await</code> keyword simply makes JavaScript wait until that <code>Promise</code> settles and then returns its result.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logFetch</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
    <span class="hljs-built_in">console</span>.log(response);
  }
  <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'fetch failed'</span>, err);
  }
}
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-mention-the-steps-by-which-you-can-async-in-nodejs">Q. Mention the steps by which you can async in Node.js?</h2>
<p>ES 2017 introduced Asynchronous functions. Async functions are essentially a cleaner way to work with asynchronous code in JavaScript. </p>
<p><strong>1. Async/Await:</strong></p>
<ul>
<li>The newest way to write asynchronous code in JavaScript.</li>
<li>It is non blocking (just like promises and callbacks).</li>
<li>Async/Await was created to simplify the process of working with and writing chained promises.</li>
<li>Async functions return a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.  </li>
</ul>
<p>Syntax</p>
<pre><code class="lang-js"><span class="hljs-comment">// Normal Function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">x,y</span>)</span>{
  <span class="hljs-keyword">return</span> x + y;
}
<span class="hljs-comment">// Async Function</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">x,y</span>)</span>{
  <span class="hljs-keyword">return</span> x + y;
}
</code></pre>
<p><strong>2. Await:</strong></p>
<p>Async functions can make use of the await expression. This will pause the async function and wait for the Promise to resolve prior to moving on.  </p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doubleAfter2Seconds</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      resolve(x * <span class="hljs-number">2</span>);
    }, <span class="hljs-number">2000</span>);
  });
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addAsync</span>(<span class="hljs-params">x</span>) </span>{
  <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">10</span>);
  <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">20</span>);
  <span class="hljs-keyword">const</span> c = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">30</span>);
  <span class="hljs-keyword">return</span> x + a + b + c;
}


addAsync(<span class="hljs-number">10</span>).then(<span class="hljs-function">(<span class="hljs-params">sum</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(sum);
});
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-use-q-promise-in-nodejs">Q. How to use Q promise in Node.js?</h2>
<p>A promise is an object that represents the return value or the thrown exception that the function may eventually provide. A promise can also be used as a proxy for a remote object to overcome latency.</p>
<p>Promise is relatively an easy implementation for asynchronous operation. The promise object returned from the function represents an operation which is not completed yet, but it guarantees to the caller of the operation that the operation will be completed in future.</p>
<p>Promise has the following states:</p>
<ul>
<li><strong>Pending</strong> - asynchronous operation is not yet completed.</li>
<li><strong>Fulfilled</strong> - asynchronous operation is completed successfully.</li>
<li><strong>Rejected</strong> - asynchronous operation is terminated with an error.</li>
<li><strong>Settled</strong> - asynchronous operation is either fulfilled or rejected.</li>
<li><strong>Callback</strong> - function is executed if the promise is executed with value.</li>
<li><strong>Errback</strong> - function is executed if the promise is rejected.</li>
</ul>
<p><strong>Moving to Promises from Callback</strong></p>
<p>On the first pass, promises can mitigate the <strong>Pyramid of Doom</strong>: the situation where code marches to the right faster than it marches forward.</p>
<pre><code class="lang-js">step1(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value1</span>) </span>{
    step2(value1, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value2</span>) </span>{
        step3(value2, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value3</span>) </span>{
            step4(value3, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">value4</span>) </span>{
                <span class="hljs-comment">// Do something with value4</span>
            });
        });
    });
});
</code></pre>
<p>With a promise library, it can flatten the pyramid.</p>
<pre><code class="lang-js">Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">value4</span>) </span>{
    <span class="hljs-comment">// Do something with value4</span>
})
.catch(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) </span>{
    <span class="hljs-comment">// Handle any error from all above steps</span>
})
.done();
</code></pre>
<p><strong>Reference:</strong></p>
<ul>
<li><em><a target="_blank" href="https://www.npmjs.com/package/q">https://www.npmjs.com/package/q</a></em></li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-are-async-functions-in-node">Q. What are async functions in Node?</h2>
<h4 id="heading-q-how-do-you-convert-an-existing-callback-api-to-promises">Q. How do you convert an existing callback API to promises?</h4>
<p><em>ToDo</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-12-nodejs-routing"># 12. NODE.JS ROUTING</h2>
<p><br /></p>
<h2 id="heading-q-how-does-routing-work-in-nodejs">Q. How does routing work in Node.js?</h2>
<p>Routing defines the way in which the client requests are handled by the application endpoints. We define routing using methods of the Express app object that correspond to HTTP methods; for example, <code>app.get()</code> to handle <code>GET</code> requests and <code>app.post</code> to handle <code>POST</code> requests, <code>app.all()</code> to handle all HTTP methods and <code>app.use()</code> to specify middleware as the callback function.</p>
<p>These routing methods "listens" for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.</p>
<p><em>Syntax</em>:</p>
<pre><code class="lang-js">app.METHOD(PATH, HANDLER)
</code></pre>
<p>Where:</p>
<ul>
<li>app is an instance of express.</li>
<li>METHOD is an <code>HTTP request method</code>.</li>
<li>PATH is a path on the server.</li>
<li>HANDLER is the function executed when the route is matched.</li>
</ul>
<p><strong>a) Route methods:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// GET method route</span>
app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'GET request'</span>)
})

<span class="hljs-comment">// POST method route</span>
app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'POST request'</span>)
})

<span class="hljs-comment">// ALL method route</span>
app.all(<span class="hljs-string">'/secret'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Accessing the secret section ...'</span>)
  next() <span class="hljs-comment">// pass control to the next handler</span>
})
</code></pre>
<p><strong>b) Route paths:</strong></p>
<p>Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.</p>
<p>The characters <code>?</code>, <code>+</code>, <code>*</code>, and <code>()</code> are subsets of their regular expression counterparts. The hyphen <code>(-)</code> and the dot <code>(.)</code> are interpreted literally by string-based paths.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// This route path will match requests to /about.</span>
app.get(<span class="hljs-string">'/about'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'about'</span>)
})


<span class="hljs-comment">// This route path will match acd and abcd.</span>
app.get(<span class="hljs-string">'/ab?cd'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'ab?cd'</span>)
})


<span class="hljs-comment">// This route path will match butterfly and dragonfly</span>
app.get(<span class="hljs-regexp">/.*fly$/</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'/.*fly$/'</span>)
})
</code></pre>
<p><strong>c) Route parameters:</strong></p>
<p>Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the <code>req.params</code> object, with the name of the route parameter specified in the path as their respective keys.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js">app.get(<span class="hljs-string">'/users/:userId'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(req.params)
})
</code></pre>
<p><strong>Response methods:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Method</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>res.download()</code></td><td>Prompt a file to be downloaded.</td></tr>
<tr>
<td><code>res.end()</code></td><td>End the response process.</td></tr>
<tr>
<td><code>res.json()</code></td><td>Send a JSON response.</td></tr>
<tr>
<td><code>res.jsonp()</code></td><td>Send a JSON response with JSONP support.</td></tr>
<tr>
<td><code>res.redirect()</code></td><td>Redirect a request.</td></tr>
<tr>
<td><code>res.render()</code></td><td>Render a view template.</td></tr>
<tr>
<td><code>res.send()</code></td><td>Send a response of various types.</td></tr>
<tr>
<td><code>res.sendFile()</code></td><td>Send a file as an octet stream.</td></tr>
<tr>
<td><code>res.sendStatus()</code></td><td>Set the response status code and send its string representation as the response body.</td></tr>
</tbody>
</table>
</div><p><strong>d) Router method:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> router = express.Router()

<span class="hljs-comment">// middleware that is specific to this router</span>
router.use(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">timeLog</span> (<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Time: '</span>, <span class="hljs-built_in">Date</span>.now())
  next()
})

<span class="hljs-comment">// define the home page route</span>
router.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'Birds home page'</span>)
})

<span class="hljs-comment">// define the about route</span>
router.get(<span class="hljs-string">'/about'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
  res.send(<span class="hljs-string">'About birds'</span>)
})

<span class="hljs-built_in">module</span>.exports = router
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-13-nodejs-caching"># 13. NODE.JS CACHING</h2>
<p><br /></p>
<h2 id="heading-14-nodejs-error-handling"># 14. NODE.JS ERROR HANDLING</h2>
<p><br /></p>
<h2 id="heading-q-what-is-the-preferred-method-of-resolving-unhandled-exceptions-in-nodejs">Q. What is the preferred method of resolving unhandled exceptions in Node.js?</h2>
<p>Unhandled exceptions in Node.js can be caught at the Process level by attaching a handler for uncaughtException event.</p>
<pre><code class="lang-js">process.on(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Caught exception: '</span> + err);
});
</code></pre>
<p>Process is a global object that provides information about the current Node.js process. Process is a listener function that is always listening to events.</p>
<p>Few events are :</p>
<ol>
<li>Exit</li>
<li>disconnect</li>
<li>unhandledException</li>
<li>rejectionHandled</li>
</ol>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h4 id="heading-q-explain-error-handling-approaches-in-nodejs">Q. Explain Error Handling approaches in Node.js?</h4>
<h4 id="heading-q-how-would-you-handle-errors-for-async-code-in-nodejs">Q. How would you handle errors for async code in Node.js?</h4>
<h4 id="heading-q-how-to-solve-process-out-of-memory-exception-in-nodejs">Q. How to solve "Process out of Memory Exception" in Node.js?</h4>
<h4 id="heading-q-what-are-the-types-of-memory-leaks-in-nodejs">Q. What are the types of memory leaks in node.js</h4>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-15-nodejs-logging"># 15. NODE.JS LOGGING</h2>
<p><br /></p>
<h2 id="heading-q-how-to-debug-an-application-in-nodejs">Q. How to debug an application in Node.js?</h2>
<p><strong>1. node-inspector:</strong></p>
<pre><code class="lang-js">npm install -g node-inspector
</code></pre>
<p>Run</p>
<pre><code class="lang-js">node-debug app.js
</code></pre>
<p><strong>2. Debugging:</strong></p>
<ul>
<li>Debugger</li>
<li>Node Inspector</li>
<li>Visual Studio Code</li>
<li>Cloud9</li>
<li>Brackets</li>
</ul>
<p><strong>3. Profiling:</strong></p>
<pre><code class="lang-js"><span class="hljs-number">1.</span> node --prof ./app.js
<span class="hljs-number">2.</span> node --prof-process ./the-generated-log-file
</code></pre>
<p><strong>4. Heapdumps:</strong></p>
<ul>
<li>node-heapdump with Chrome Developer Tools</li>
</ul>
<p><strong>5. Tracing:</strong></p>
<ul>
<li>Interactive Stack Traces with TraceGL</li>
</ul>
<p><strong>6. Logging:</strong></p>
<p>Libraries that output debugging information</p>
<ul>
<li>Caterpillar</li>
<li>Tracer</li>
<li>scribbles</li>
</ul>
<p>Libraries that enhance stack trace information  </p>
<ul>
<li>Longjohn</li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-16-nodejs-internationalization"># 16. NODE.JS INTERNATIONALIZATION</h2>
<p><br /></p>
<h4 id="heading-q-how-to-use-locale-i18n-in-nodejs">Q. How to use locale (i18n) in Node.js?</h4>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-17-nodejs-testing"># 17. NODE.JS TESTING</h2>
<p><br /></p>
<h2 id="heading-q-what-is-a-stub">Q. What is a stub?</h2>
<p>Stubbing and verification for node.js tests. Enables you to validate and override behaviour of nested pieces of code such as methods, require() and npm modules or even instances of classes. This library is inspired on node-gently, MockJS and mock-require.  </p>
<p><strong>Features of Stub:</strong>  </p>
<ul>
<li>Produces simple, lightweight Objects capable of extending down their tree</li>
<li>Compatible with Nodejs</li>
<li>Easily extendable directly or through an ExtensionManager</li>
<li>Comes with predefined, usable extensions</li>
</ul>
<p>Stubs are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.</p>
<p>A use-case can be a file read, when you do not want to read an actual file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">const</span> readFileStub = sinon.stub(fs, <span class="hljs-string">'readFile'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">path, cb</span>) </span>{  
  <span class="hljs-keyword">return</span> cb(<span class="hljs-literal">null</span>, <span class="hljs-string">'filecontent'</span>);
});

expect(readFileStub).to.be.called;  
readFileStub.restore();
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-a-test-pyramid">Q. What is a test pyramid?</h2>
<p>The "Test Pyramid" is a metaphor that tells us to group software tests into buckets of different granularity. It also gives an idea of how many tests we should have in each of these groups. It shows which kinds of tests you should be looking for in the different levels of the pyramid and gives practical examples on how these can be implemented.</p>
<p>
  <img src="assets/testPyramid.png" alt="Test Pyramid" />
</p>

<p>Mike Cohn\'s original test pyramid consists of three layers that your test suite should consist of (bottom to top):</p>
<ol>
<li>Unit Tests</li>
<li>Service Tests</li>
<li>User Interface Tests</li>
</ol>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-use-joi-module-for-schema-validation-in-nodejs">Q. How to use Joi module for schema validation in Node.js?</h2>
<p>Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Joi = <span class="hljs-built_in">require</span>(<span class="hljs-string">"joi"</span>);

<span class="hljs-comment">// User-defined function to validate the user</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validateUser</span>(<span class="hljs-params">user</span>) </span>{

  <span class="hljs-keyword">const</span> JoiSchema = Joi.object({

    <span class="hljs-attr">username</span>: Joi.string().min(<span class="hljs-number">5</span>).max(<span class="hljs-number">30</span>).required(),

    <span class="hljs-attr">email</span>: Joi.string().email().min(<span class="hljs-number">5</span>).max(<span class="hljs-number">50</span>).optional(),

    <span class="hljs-attr">date_of_birth</span>: Joi.date().optional(),

    <span class="hljs-attr">account_status</span>: Joi.string()
      .valid(<span class="hljs-string">"activated"</span>)
      .valid(<span class="hljs-string">"unactivated"</span>)
      .optional(),
  }).options({ <span class="hljs-attr">abortEarly</span>: <span class="hljs-literal">false</span> });

  <span class="hljs-keyword">return</span> JoiSchema.validate(user);
}

<span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">username</span>: <span class="hljs-string">"Deepak Lucky"</span>,
  <span class="hljs-attr">email</span>: <span class="hljs-string">"deepak.lucky@gmail.com"</span>,
  <span class="hljs-attr">date_of_birth</span>: <span class="hljs-string">"2000-07-07"</span>,
  <span class="hljs-attr">account_status</span>: <span class="hljs-string">"activated"</span>,
};

<span class="hljs-keyword">let</span> response = validateUser(user);

<span class="hljs-keyword">if</span> (response.error) {
  <span class="hljs-built_in">console</span>.log(response.error.details);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Validated Data"</span>);
}
</code></pre>
<p><strong>⚝ <a target="_blank" href="https://codesandbox.io/s/schema-validation-using-joi-s2nhzs">Try this example on CodeSandbox</a></strong></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-18-nodejs-miscellaneous"># 18. NODE.JS MISCELLANEOUS</h2>
<p><br /></p>
<h2 id="heading-q-what-is-crypto-in-nodejs">Q. What is crypto in Node.js?</h2>
<p>The Node.js Crypto module supports cryptography. It provides cryptographic functionality that includes a set of wrappers for open SSL\'s hash HMAC, cipher, decipher, sign and verify functions.</p>
<ul>
<li><strong>Hash</strong>: A hash is a fixed-length string of bits i.e. procedurally and deterministically generated from some arbitrary block of source data.</li>
<li><p><strong>HMAC</strong>: HMAC stands for Hash-based Message Authentication Code. It is a process for applying a hash algorithm to both data and a secret key that results in a single final hash.</p>
</li>
<li><p>Encryption Example using Hash and HMAC</p>
</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);  
<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'abcdefg'</span>;  
<span class="hljs-keyword">const</span> hash = crypto.createHmac(<span class="hljs-string">'sha256'</span>, secret)  
                   .update(<span class="hljs-string">'Welcome to Node.js'</span>)  
                   .digest(<span class="hljs-string">'hex'</span>);  
<span class="hljs-built_in">console</span>.log(hash);
</code></pre>
<ul>
<li>Encryption example using Cipher</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);  
<span class="hljs-keyword">const</span> cipher = crypto.createCipher(<span class="hljs-string">'aes192'</span>, <span class="hljs-string">'a password'</span>);  

<span class="hljs-keyword">const</span> encrypted = cipher.update(<span class="hljs-string">'Hello Node.js'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'hex'</span>);  
encrypted += cipher.final(<span class="hljs-string">'hex'</span>);  

<span class="hljs-built_in">console</span>.log(encrypted);
</code></pre>
<ul>
<li>Decryption example using Decipher</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);  
<span class="hljs-keyword">const</span> decipher = crypto.createDecipher(<span class="hljs-string">'aes192'</span>, <span class="hljs-string">'a password'</span>);  

<span class="hljs-keyword">const</span> encrypted = <span class="hljs-string">'4ce3b761d58398aed30d5af898a0656a3174d9c7d7502e781e83cf6b9fb836d5'</span>;  
<span class="hljs-keyword">const</span> decrypted = decipher.update(encrypted, <span class="hljs-string">'hex'</span>, <span class="hljs-string">'utf8'</span>);  
decrypted += decipher.final(<span class="hljs-string">'utf8'</span>);  

<span class="hljs-built_in">console</span>.log(decrypted);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-execute-an-external-program-from-within-nodejs">Q. How to execute an external program from within Node.js?</h2>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'child_process'</span>);

exec(<span class="hljs-string">'"/path/to/test file/test.sh" arg1 arg2'</span>);

exec(<span class="hljs-string">'echo "The \\$HOME variable is $HOME"'</span>);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-repl">Q. What is REPL?</h2>
<p>REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL environment when it is installed. System interacts with the user through outputs of commands/expressions used. It is useful in writing and debugging the codes. The work of REPL can be understood from its full form:</p>
<ul>
<li><strong>Read</strong>: It reads the inputs from users and parses it into JavaScript data structure. It is then stored to memory.</li>
<li><strong>Eval</strong>: The parsed JavaScript data structure is evaluated for the results.</li>
<li><strong>Print</strong>: The result is printed after the evaluation.</li>
<li><strong>Loop</strong>: Loops the input command. To come out of NODE REPL, press ctrl+c twice</li>
</ul>
<p>Simple Expression</p>
<pre><code class="lang-js">$ node
&gt; <span class="hljs-number">10</span> + <span class="hljs-number">20</span>
<span class="hljs-number">30</span>
&gt; <span class="hljs-number">10</span> + ( <span class="hljs-number">20</span> * <span class="hljs-number">30</span> ) - <span class="hljs-number">40</span>
<span class="hljs-number">570</span>
&gt;
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-does-the-runtime-environment-mean-in-nodejs">Q. What does the runtime environment mean in Node.js?</h2>
<p>The Node.js runtime is the software stack responsible for installing your web service\'s code and its dependencies and running your service.</p>
<p>The Node.js runtime for App Engine in the standard environment is declared in the <code>app.yaml</code> file:</p>
<pre><code class="lang-js">runtime: nodejs10
</code></pre>
<p>The runtime environment is literally just the environment your application is running in. This can be used to describe both the hardware and the software that is running your application. How much RAM, what version of node, what operating system, how much CPU cores, can all be referenced when talking about a runtime environment.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-explain-usage-of-nodeenv">Q. Explain usage of NODE_ENV?</h2>
<p>NODE_ENV is an environment variable made popular by the express web server framework. When a node application is run, it can check the value of the environment variable and do different things based on the value.</p>
<p>For example, when we work on a project and there are production and development environments. We don\'t need to use caching in the development env. So we set</p>
<pre><code class="lang-js"> NODE_ENV=development
</code></pre>
<p>and use the code below</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (process.env.NODE_ENV === <span class="hljs-string">'development'</span>)
    useCaching = <span class="hljs-literal">false</span>;
</code></pre>
<p>Upon that, if the project runs on production it will use caching.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-assert-works-in-nodejs">Q. How assert works in Node.js?</h2>
<p>The assert module provides a way of testing expressions. If the expression evaluates to 0, or false, an assertion failure is being caused, and the program is terminated.</p>
<p>This module was built to be used internally by Node.js.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Sample usage</span>

<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'assert'</span>);
assert(<span class="hljs-number">50</span> &gt; <span class="hljs-number">70</span>, <span class="hljs-string">"50 is less than 70."</span>);
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-the-use-of-dns-module-in-nodejs">Q. What is the use of DNS module in Node.js?</h2>
<p>DNS is a node module used to do name resolution facility which is provided by the operating system as well as used to do an actual DNS lookup. No need for memorising IP addresses – DNS servers provide a nifty solution of converting domain or subdomain names to IP addresses. This module provides an asynchronous network wrapper and can be imported using the following syntax.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dns'</span>);
</code></pre>
<p><strong>Example:</strong> <code>dns.lookup()</code> function  </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dns'</span>);  
dns.lookup(<span class="hljs-string">'www.google.com'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses, family</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'addresses:'</span>, addresses);  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'family:'</span>,family);  
});
</code></pre>
<p><strong>Example:</strong> <code>resolve4()</code> and <code>reverse()</code> functions</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dns'</span>);  
dns.resolve4(<span class="hljs-string">'www.google.com'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =&gt;</span> {  
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`addresses: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(addresses)}</span>`</span>);  
  addresses.forEach(<span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> {  
    dns.reverse(a, <span class="hljs-function">(<span class="hljs-params">err, hostnames</span>) =&gt;</span> {  
      <span class="hljs-keyword">if</span> (err) {  
        <span class="hljs-keyword">throw</span> err;  
      }  
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`reverse for <span class="hljs-subst">${a}</span>: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(hostnames)}</span>`</span>);  
    });  
  });  
});
</code></pre>
<p><strong>Example:</strong> Print the localhost name using <code>lookupService()</code> function</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'dns'</span>);  
dns.lookupService(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>, <span class="hljs-function">(<span class="hljs-params">err, hostname, service</span>) =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(hostname, service);  
    <span class="hljs-comment">// Prints: localhost  </span>
});
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-what-is-jit-and-how-is-it-related-to-nodejs">Q. What is JIT and how is it related to Node.js?</h2>
<p>Node.js has depended on the V8 JavaScript engine to provide code execution in the language. The V8 is a JavaScript engine built at the google development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side (node.js) JavaScript applications. A central piece of the V8 engine that allows it to execute JavaScript at high speed is the JIT (Just In Time) compiler. This is a dynamic compiler that can optimize code during runtime. When V8 was first built the JIT Compiler was dubbed FullCodegen. Then, the V8 team implemented Crankshaft, which included many performance optimizations that FullCodegen did not implement.</p>
<p>The <code>V8</code> was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn\'t produce bytecode or any intermediate code.</p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-access-cache-data-in-nodejs">Q. How to access cache data in Node.js ?</h2>
<p><em>ToDo</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-implement-caching-in-nodejs-using-redis">Q. How to implement caching in Node.js using Redis?</h2>
<p><em>ToDo</em></p>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-implement-memcached-in-nodejs">Q. How to implement Memcached in Node.js?</h2>
<p><strong>Memcached</strong> is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read. Memcached is free and open-source software, licensed under the Revised BSD licence. Memcached runs on Unix-like operating systems (at least LINUX and OS X) and on Microsoft windows.</p>
<p>We can store data to memcached server in key pair format. So whenever any request come from the app can be matched with memcached server without any query from mysql/Nosql server. This increases the performance of the application.</p>
<p><strong>Installation:</strong></p>
<pre><code class="lang-js">npm install memcached
</code></pre>
<p><strong>Setting up the client:</strong></p>
<p>The constructor of the memcached client take 2 different arguments server locations and options. Syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Memcached = <span class="hljs-built_in">require</span>(<span class="hljs-string">'memcached'</span>);
<span class="hljs-keyword">const</span> memcached = <span class="hljs-keyword">new</span> Memcached(Server locations, options);
</code></pre>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * Memcached
 */</span>
<span class="hljs-keyword">const</span> Memcached = <span class="hljs-built_in">require</span>(<span class="hljs-string">'memcached'</span>);
<span class="hljs-comment">// all global configurations should be applied to the .config object of the Client.</span>
Memcached.config.poolSize = <span class="hljs-number">25</span>;

<span class="hljs-keyword">const</span> memcached = <span class="hljs-keyword">new</span> Memcached(<span class="hljs-string">'localhost:11211'</span>, { <span class="hljs-attr">retries</span>:<span class="hljs-number">10</span>, <span class="hljs-attr">retry</span>:<span class="hljs-number">10000</span>, <span class="hljs-attr">remove</span>:<span class="hljs-literal">true</span>, <span class="hljs-attr">failOverServers</span>:[<span class="hljs-string">'192.168.0.103:11211'</span>]});
</code></pre>
<p><br /></p>
<p><strong>Reference:</strong></p>
<ul>
<li><em><a target="_blank" href="https://www.npmjs.com/package/memcached">https://www.npmjs.com/package/memcached</a></em></li>
</ul>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h2 id="heading-q-how-to-generate-and-verify-checksum-of-the-given-string-in-nodejs">Q. How to generate and verify checksum of the given string in Nodejs</h2>
<p>The <strong>checksum</strong> (aka <strong>hash sum</strong>) calculation is a one-way process of mapping an extensive data set of variable length (e.g., message, file), to a smaller data set of a fixed length (hash). The length depends on a hashing algorithm.</p>
<p>For the checksum generation, we can use node <code>crypto()</code> module. The module uses <code>createHash(algorithm)</code> to create a checksum (hash) generator. The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);

<span class="hljs-comment">// To get a list of all available hash algorithms</span>
crypto.getHashes() <span class="hljs-comment">// [ 'md5', 'sha1', 'sha3-256', ... ]</span>


<span class="hljs-comment">// Create hash of SHA1 type</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-string">"MY_SECRET_KEY"</span>;


<span class="hljs-comment">// 'digest' is the output of hash function containing  </span>
<span class="hljs-comment">// only hexadecimal digits</span>
hashPwd = crypto.createHash(<span class="hljs-string">'sha1'</span>).update(key).digest(<span class="hljs-string">'hex'</span>);

<span class="hljs-built_in">console</span>.log(hashPwd); <span class="hljs-comment">//ef5225a03e4f9cc953ab3c4dd41f5c4db7dc2e5b</span>
</code></pre>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>

<h4 id="heading-q-what-are-the-use-cases-for-the-nodejs-vm-core-module">Q. What are the use cases for the Node.js "vm" core module?</h4>
<h4 id="heading-q-explain-the-concept-of-domain-in-nodejs">Q. Explain the concept of Domain in Node.js?</h4>
<h4 id="heading-q-what-is-node-api-n-api">Q. What is Node-API (N-API)?</h4>
<h4 id="heading-q-how-to-implement-a-sleep-function">Q. How to implement a Sleep function?</h4>
<h4 id="heading-q-how-does-the-cluster-load-balance-work-in-nodejs">Q. How does the cluster load balance work in node.js?</h4>
<h4 id="heading-q-what-is-daemon-process-how-to-implement-it-in-nodejs">Q. What is daemon process? how to implement it in node.js?</h4>
<h4 id="heading-q-how-would-you-scale-node-application">Q. How would you scale Node application?</h4>
<h4 id="heading-q-how-does-the-cluster-module-work-what-is-the-difference-between-it-and-a-load-balancer">Q. How does the cluster module work? What is the difference between it and a load balancer?</h4>
<h4 id="heading-q-why-do-we-need-c-addons-in-nodejs">Q. Why do we need C++ Addons in Node.js?</h4>
<div>
    <b><a href="#table-of-contents">↥ back to top</a></b>
</div>]]></content:encoded></item><item><title><![CDATA[Backend Interview Questions and Answers related to Node JS]]></title><description><![CDATA[Click :star: if you like the project. Pull Request are highly appreciated. Node JS Express JS MongoDB and Mongoose Database Engineering Golang Node.js is…]]></description><link>https://articles.tkssharma.com/backend-interview-questions-and-answers-related-to-node-js</link><guid isPermaLink="true">https://articles.tkssharma.com/backend-interview-questions-and-answers-related-to-node-js</guid><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><category><![CDATA[interview questions]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Fri, 11 Oct 2024 14:23:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728656591885/0cd2112c-7a0c-4c1b-b766-745c7c9b951c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-backend-interview-questions-and-answers-related-to-node-js">Backend Interview Questions and Answers related to Node JS</h1>
<blockquote>
<p>Click :star:   if you like the project. Pull Request are highly appreciated.<br />
<a class="post-section-overview" href="#table-of-contents---node-js">Node JS</a><br />
<a class="post-section-overview" href="#table-of-contents---express-js">Express JS</a><br />
<a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose">MongoDB and Mongoose</a><br />
<a class="post-section-overview" href="#table-of-contents---database-engineering">Database Engineering</a><br />
<a class="post-section-overview" href="#table-of-contents---golang">Golang</a><br /></p>
</blockquote>
<h3 id="heading-table-of-contents-node-js">Table of Contents - Node JS</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td></td><td><strong>Node JS</strong></td></tr>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-is-nodejs">What is NodeJS?</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#how-can-you-avoid-callback-hells">How can you avoid callback hells?</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#when-are-background-or-worker-processes-useful">When are background or worker processes useful?</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#why-is-nodejs-single-threaded">Why is NodeJS Single threaded?</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#name-the-types-of-api-functions-in-node">Name the types of API functions in Node?</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#explain-chaining-in-nodejs">Explain chaining in Nodejs?</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-are-streams-in-nodejs-explain-the-different-types-of-streams-present-in-nodejs">What are streams in Nodejs Explain the different types of streams present in Nodejs?</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#what-is-package-json">What is package json?</a></td><td></td><td></td><td>9</td><td><a class="post-section-overview" href="#explain-the-purpose-of-module-exports">Explain the purpose of module exports?</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#list-down-the-major-security-implementations-within-nodejs">List down the major security implementations within Node.js?</a></td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#explain-the-concept-of-url-module">Explain the concept of URL module?</a></td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#explain-the-concept-of-middleware-in-nodejs">Explain the concept of middleware in Nodejs?</a></td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#explain-libuv">Explain libuv?</a></td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#list-down-the-two-arguments-that-async-queue-takes-as-input">List down the two arguments that async queue takes as input?</a></td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#differentiate-between-spawn-and-fork-methods-in-nodejs">Differentiate between spawn and fork methods in Nodejs?</a></td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#explain-the-purpose-of-expressjs-package">Explain the purpose of ExpressJS package?</a></td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#explain-the-usage-of-a-buffer-class-in-nodejs">Explain the usage of a buffer class in Nodejs?</a></td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#how-does-nodejs-handle-the-child-threads">How does Nodejs handle the child threads?</a></td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#explain-stream-in-nodejs-along-with-its-various-types">Explain stream in Nodejs along with its various types?</a></td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#describe-the-exit-codes-of-nodejs">Describe the exit codes of Nodejs?</a></td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#is-cryptography-supported-in-nodejs">Is cryptography supported in Nodejs?</a></td></tr>
<tr>
<td>22</td><td><a class="post-section-overview" href="#explain-the-reason-as-to-why-express-app-and-server-folder-must-be-kept-separate">Explain the reason as to why Express app and server folder must be kept separate?</a></td></tr>
<tr>
<td>23</td><td><a class="post-section-overview" href="#what-is-the-role-of-asset-module-in-nodejs">What is the role of asset module in nodejs?</a></td></tr>
<tr>
<td>24</td><td><a class="post-section-overview" href="#what-is-the-role-of-async_hooks-module-in-nodejs">What is the role of async_hooks module in nodejs?</a></td></tr>
<tr>
<td>25</td><td><a class="post-section-overview" href="#what-are-buffer-objects-in-nodejs">What are buffer objects in nodejs?</a></td></tr>
<tr>
<td>26</td><td><a class="post-section-overview" href="#what-are-the-different-ways-of-implementing-addons-in-nodejs">What are the different ways of implementing Addons in NodeJS?</a></td></tr>
<tr>
<td>27</td><td><a class="post-section-overview" href="#how-can-we-spawn-the-child-process-asynchronously-without-blocking-the-nodejs-event-loop">How can we spawn the child process asynchronously without blocking the Nodejs event loop?</a></td></tr>
<tr>
<td>28</td><td><a class="post-section-overview" href="#how-can-we-take-advantage-of-multi-core-system-in-nodejs-as-nodejs-works-on-single-thread">How can we take advantage of multi-core system in Nodejs as nodejs works on single thread?</a></td></tr>
<tr>
<td>29</td><td><a class="post-section-overview" href="#what-is-the-datatype-of-console">What is the datatype of console?</a></td></tr>
<tr>
<td>30</td><td><a class="post-section-overview" href="#which-are-the-different-console-methods-available">Which are the different console methods available?</a></td></tr>
<tr>
<td>31</td><td><a class="post-section-overview" href="#can-node-js-perform-cryptographic-functions">Can node js perform cryptographic functions?</a></td></tr>
<tr>
<td>32</td><td><a class="post-section-overview" href="#how-can-we-read-or-write-files-in-node-js">How can we read or write files in node js?</a></td></tr>
<tr>
<td>33</td><td><a class="post-section-overview" href="#which-are-the-global-objects-in-node-js">Which are the global objects in Node JS?</a></td></tr>
<tr>
<td>34</td><td><a class="post-section-overview" href="#how-can-we-perform-asynchronous-network-api-in-node-js">How can we perform asynchronous network API in Node JS?</a></td></tr>
<tr>
<td>35</td><td><a class="post-section-overview" href="#what-are-the-utilities-of-os-module-in-nodejs">What are the utilities of OS module in NodeJS?</a></td></tr>
<tr>
<td>36</td><td><a class="post-section-overview" href="#which-are-the-areas-where-it-is-suitable-to-use-nodejs">Which are the areas where it is suitable to use NodeJS?</a></td></tr>
<tr>
<td>37</td><td><a class="post-section-overview" href="#which-are-the-areas-where-it-is-not-suitable-to-use-nodejs">Which are the areas where it is not suitable to use NodeJS?</a></td></tr>
<tr>
<td>38</td><td><a class="post-section-overview" href="#what-are-the-key-features-of-nodejs">What Are The Key Features Of NodeJs?</a></td></tr>
<tr>
<td>39</td><td><a class="post-section-overview" href="#explain-repl-in-nodejs">Explain REPL In NodeJs?</a></td></tr>
<tr>
<td>40</td><td><a class="post-section-overview" href="#can-you-write-crud-operations-in-node-js-without-using-frameworks">Can you write CRUD operations in Node js without using frameworks?</a></td></tr>
<tr>
<td>41</td><td><a class="post-section-overview" href="#can-you-create-http-server-in-nodejs-explain-the-code-used-for-it">Can You Create HTTP Server In Nodejs Explain The Code Used For It?</a></td></tr>
<tr>
<td>42</td><td><a class="post-section-overview" href="#what-is-the-difference-between-nodejs-ajax-and-jquery">What Is The Difference Between Nodejs AJAX And JQuery?</a></td></tr>
<tr>
<td>43</td><td><a class="post-section-overview" href="#what-is-eventemitter-in-nodejs">What Is EventEmitter In NodeJs? </a></td></tr>
<tr>
<td>44</td><td><a class="post-section-overview" href="#what-is-a-child_process-module-in-nodejs">What Is A Child_process Module In NodeJs? </a></td></tr>
</tbody>
</table>
</div><h2 id="heading-node-js">Node Js</h2>
<ol>
<li><h3 id="heading-what-is-nodejs">What is NodeJS?</h3>
<p>Node.js is an open-source, cross-platform, <strong>JavaScript runtime environment that executes JavaScript code outside of a browser</strong>. Node JS was created by <a target="_blank" href="https://github.com/ry">Ryan Dahl</a>, Ryan Dahl is a software engineer and the original developer of the Node.js JavaScript runtime.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="2">
<li><h3 id="heading-how-can-you-avoid-callback-hells">How can you avoid callback hells?</h3>
<p>There are lots of ways to solve the issue of callback hells: <br /> 1.modularization: break callbacks into independent functions, <br /> 2.use a control flow library, like async. <br /> 3.use generators with Promises, <br /> 4.use async/await (note that it is only available in the latest v7 release and not in the LTS version</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="3">
<li><h3 id="heading-when-are-background-or-worker-processes-useful">When are background or worker processes useful?</h3>
<p>Worker processes are extremely useful if you'd like to do data processing in the background, like sending out emails or processing images.
<br />
There are lots of options for this like RabbitMQ or Kafka.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="4">
<li><h3 id="heading-why-is-nodejs-single-threaded">Why is NodeJS Single threaded?</h3>
<p>Node.js is single-threaded for async processing. By doing async processing on a single-thread under typical web loads, more performance and scalability can be achieved as opposed to the typical thread-based implementation.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="5">
<li><h3 id="heading-name-the-types-of-api-functions-in-node">Name the types of API functions in Node?</h3>
<p>There are two types of functions in Node.js. <br />
1.Blocking functions - In a blocking operation, all other code is blocked from executing until an I/O event that is being waited on occurs. Blocking functions execute synchronously. <br />2.Non-blocking functions - In a non-blocking operation, multiple I/O calls can be performed without the execution of the program being halted. Non-blocking functions execute asynchronously.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="6">
<li><h3 id="heading-explain-chaining-in-nodejs">Explain chaining in Nodejs?</h3>
<p>Chaining is a mechanism whereby the output of one stream is connected to another stream creating a chain of multiple stream operations.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="7">
<li><h3 id="heading-what-are-streams-in-nodejs-explain-the-different-types-of-streams-present-in-nodejs">What are streams in Nodejs Explain the different types of streams present in Nodejs?</h3>
<p>Streams are objects that allow the reading of data from the source and writing of data to the destination as a continuous process.<br />
There are four types of streams.<br />
 to facilitate the reading operation.<br />
 to facilitate the writing operation.<br />
 to facilitate both read and write operations.<br />
 is a form of Duplex stream that performs computations based on the available input.<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="8">
<li><h3 id="heading-what-is-package-json">What is package json?</h3>
<p>The package.json file in Node.js is the heart of the entire application. It is basically the manifest file that contains the metadata of the project where we define the properties of a package.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="9">
<li><h3 id="heading-explain-the-purpose-of-module-exports">Explain the purpose of module exports?</h3>
<p>A module in Node.js is used to encapsulate all the related codes into a single unit of code which can be interpreted by shifting all related functions into a single file</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="10">
<li><h3 id="heading-list-down-the-major-security-implementations-within-nodejs">List down the major security implementations within Nodejs?</h3>
<p>Major security implementations in Node.js are:Authentications,Error Handling</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="11">
<li><h3 id="heading-explain-the-concept-of-url-module">Explain the concept of URL module?</h3>
<p>The URL module splits up a web address into readable parts</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="12">
<li><h3 id="heading-explain-the-concept-of-middleware-in-nodejs">Explain the concept of middleware in Nodejs?</h3>
<p>In general, middleware is a function receives the Request and Response objects. In other words, in an application’s request-response cycle these functions have access to various request &amp; response objects along with the next function of the cycle,The next function of middleware is represented with the help of a variable, usually named next. Most commonly performed tasks by the middleware functions are <br /></p>
<p>Execute any type of code<br />
Update or modify the request and the response objects<br />
Finish the request-response cycle<br />
Invoke the next middleware in the stack</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="13">
<li><h3 id="heading-explain-libuv">Explain libuv?</h3>
<p>Libuv is a multi-platform support library of Node.js which majorly is used for asynchronous I/O. It was primarily developed for Node.js, with time it is popularly practiced with other systems like as Luvit, pyuv, Julia, etc. Libuv is basically an abstraction around libev/ IOCP depending on the platform, providing users an API based on libev. A few of the important features of libuv are: <br /></p>
<p>Full-featured event loop backed<br />
File system events<br />
Asynchronous file &amp; file system operations<br />
Asynchronous TCP &amp; UDP sockets<br />
Child processes</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="14">
<li><h3 id="heading-list-down-the-two-arguments-that-asyncqueue-takes-as-input">List down the two arguments that async.queue takes as input?</h3>
<p>Below are the two arguments that async.queue takes as input - Task Function &amp; Concurrency Value</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="15">
<li><h3 id="heading-differentiate-between-spawn-and-fork-methods-in-nodejs">Differentiate between spawn and fork methods in Nodejs?</h3>
<p>In Node.js, the spawn() is used to launch a new process with the provided set of commands. This method doesn’t create a new V8 instance and just one copy of the node module is active on the processor. When your child process returns a large amount of data to the Node you can invoke this method.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="16">
<li><h3 id="heading-explain-the-purpose-of-expressjs-package">Explain the purpose of ExpressJS package?</h3>
<p>Express.js is a framework built on top of Node.js that facilitates the management of the flow of data between server and routes in the server-side applications. It is a lightweight and flexible framework that provides a wide range of features required for the web as well as mobile application development. Express.js is developed on the middleware module of Node.js called connect. The connect module further makes use of http module to communicate with Node.js. Thus, if you are working with any of the connect based middleware modules, then you can easily integrate with Express.js.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="17">
<li><h3 id="heading-explain-the-usage-of-a-buffer-class-in-nodejs">Explain the usage of a buffer class in Nodejs?</h3>
<p>Buffer class in Node.js is used for storing the raw data in a similar manner of an array of integers. But it corresponds to a raw memory allocation that is located outside the V8 heap. It is a global class that is easily accessible can be accessed in an application without importing a buffer module. Buffer class is used because pure JavaScript is not compatible with binary data. So, when dealing with TCP streams or the file system, it’s necessary to handle octet streams.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="18">
<li><h3 id="heading-how-does-nodejs-handle-the-child-threads">How does Nodejs handle the child threads?</h3>
<p>In general, Node.js is a single threaded process and doesn’t expose the child threads or thread management methods. But you can still make use of the child threads using spawn() for some specific asynchronous I/O tasks which execute in the background and don’t usually execute any JS code or hinder with the main event loop in the application. If you still want to use the threading concept in your application you have to include a module called ChildProcess explicitly.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="19">
<li><h3 id="heading-explain-stream-in-nodejs-along-with-its-various-types">Explain stream in Nodejs along with its various types?</h3>
<p>Streams in Node.js are the collection of data similar to arrays and strings. They are objects using which you can read data from a source or write data to a destination in a continuous manner. It might not be available at once and need not to have fit in the memory. These streams are especially useful for reading and processing a large set of data. In Node.js, there are four fundamental types of streams:<br />
Readable: Used for reading large chunks of data from the source.<br />
Writeable: Use for writing large chunks of data to the destination.<br />
Duplex: Used for both the functions; read and write.<br />
Transform: It is a duplex stream that is used for modifying the data.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="20">
<li><h3 id="heading-describe-the-exit-codes-of-nodejs">Describe the exit codes of Nodejs?</h3>
<p>In Node.js, exit codes are a set of specific codes which are used for finishing a specific process. These processes can include the global object as well. Below are some of the exit codes used in Node.js:<br />
<em>Uncaught fatal exception<br />
</em>Unused<br />
<em>Fatal Error<br />
</em>Internal Exception handler Run-time failure<br />
*Internal JavaScript Evaluation Failure<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="21">
<li><h3 id="heading-is-cryptography-supported-in-nodejs">Is cryptography supported in Nodejs?</h3>
<p>Yes, Node.js does support cryptography through a module called Crypto. This module provides various cryptographic functionalities like cipher, decipher, sign and verify functions, a set of wrappers for open SSL’s hash HMAC etc.<br /></p>
<pre><code><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span><span class="hljs-string">'crypto'</span>);
<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'akerude'</span>;
<span class="hljs-keyword">const</span> hash = crypto.createHmac(<span class="hljs-string">'swaEdu'</span>, secret).update(<span class="hljs-string">'Welcome to Edureka'</span>).digest(<span class="hljs-string">'hex'</span>);
<span class="hljs-built_in">console</span>.log(hash);
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="22">
<li><h3 id="heading-explain-the-reason-as-to-why-express-app-and-server-folder-must-be-kept-separate">Explain the reason as to why Express app and server folder must be kept separate?</h3>
<p>Express ‘app’ and ‘server’ must be kept separate as by doing this, you will be separating the API declaration from the network related configuration which benefits in the below listed ways:<br />
<em>It allows testing the API in-process without having to perform the network calls<br />
</em>Faster testing execution<br />
<em>Getting wider coverage metrics of the code<br />
</em>Allows deploying the same API under flexible and different network conditions<br />
*Better separation of concerns and cleaner code</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="23">
<li><h3 id="heading-what-is-the-role-of-asset-module-in-nodejs">What is the role of asset module in nodejs?</h3>
<p>The assert module provides a set of assertion functions for verifying invariants</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="24">
<li><h3 id="heading-what-is-the-role-of-asynchooks-module-in-nodejs">What is the role of async_hooks module in nodejs?</h3>
<p>The async_hooks module provides an API to track asynchronous resources. It can be accessed using:</p>
<pre><code><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="25">
<li><h3 id="heading-what-are-buffer-objects-in-nodejs">What are buffer objects in nodejs?</h3>
<p>In Node.js, Buffer objects are used to represent binary data in the form of a sequence of bytes. Many Node.js APIs, for example streams and file system operations, support Buffers, as interactions with the operating system or other processes generally always happen in terms of binary data</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="26">
<li><h3 id="heading-what-are-the-different-ways-of-implementing-addons-in-nodejs">What are the different ways of implementing Addons in NodeJS?</h3>
<p>There are three options for implementing Addons: <br />N-API<br /> nan direct use of internal V8 <br />  libuv <br /> Node.js libraries</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="27">
<li><h3 id="heading-how-can-we-spawn-the-child-process-asynchronously-without-blocking-the-nodejs-event-loop">How can we spawn the child process asynchronously without     blocking the Nodejs event loop?</h3>
<p><strong>child_process.spawn()</strong> method spawns the child process asynchronously, without blocking the Node.js event loop,The child_process. <br /><strong>spawnSync()</strong>  function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="28">
<li><h3 id="heading-how-can-we-take-advantage-of-multi-core-system-in-nodejs-as-nodejs-works-on-single-thread">How can we take advantage of multi-core system in Nodejs as nodejs works on single thread?</h3>
<p>We can use node js cluster to use multicores in the hardware,The cluster module allows easy creation of child processes that all share server ports<br /></p>
<pre><code><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cluster'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>).cpus().length;

<span class="hljs-keyword">if</span> (cluster.isMaster) {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>);

<span class="hljs-comment">// Fork workers.</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numCPUs; i++) {
cluster.fork();
}

cluster.on(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
    });
} 
<span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Workers can share any TCP connection</span>
    <span class="hljs-comment">// In this case it is an HTTP server</span>
http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
res.writeHead(<span class="hljs-number">200</span>);
res.end(<span class="hljs-string">'hello world\n'</span>);
}).listen(<span class="hljs-number">8000</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}

<span class="hljs-comment">//Running Node.js will now share port 8000 between the workers:</span>

$ node server.js
Master <span class="hljs-number">3596</span> is running
Worker <span class="hljs-number">4324</span> started
Worker <span class="hljs-number">4520</span> started
Worker <span class="hljs-number">6056</span> started
Worker <span class="hljs-number">5644</span> started
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="29">
<li><h3 id="heading-what-is-the-datatype-of-console">What is the datatype of console?</h3>
<p>The datatype of console is an <strong>object</strong></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="30">
<li><h3 id="heading-which-are-the-different-console-methods-available">Which are the different console methods available?</h3>
<p>There are around 21 inbuilt console methods , we can also built our own prototypes using new Console constructor function<br />
here are a few popular one's<br />
1.<strong>console.clear()</strong> will clear only the output in the current terminal viewport for the Node.js binary.<br />
2.<strong>console.error([data][, ...args])</strong> Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution<br />
3.<strong>console.table(tabularData[, properties])</strong>  a table with the columns of the properties of tabularData (or use properties) and rows of tabularData and log it.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="31">
<li><h3 id="heading-can-node-js-perform-cryptographic-functions">Can node js perform cryptographic functions?</h3>
<p>Yes,The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.<br /></p>
<p>Use require('crypto') to access this module.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="32">
<li><h3 id="heading-how-can-we-read-or-write-files-in-node-js">How can we read or write files in node js?</h3>
<p>The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.
To use this module:<br /></p>
<p>const fs = require('fs');<br /><br />There are a few methods like 
<br />fs.readFile(file, data[, options], callback)
<br />fs.writeFile(file, data[, options], callback)</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="33">
<li><h3 id="heading-which-are-the-global-objects-in-node-js">Which are the global objects in Node JS?</h3>
<p><strong>dirname<br />
</strong>filename<br />
clearImmediate(immediateObject)<br />
clearInterval(intervalObject)<br />
clearTimeout(timeoutObject)<br />
console<br />
exports<br />
global<br />
module<br />
process<br />
queueMicrotask(callback)<br />
require()<br />
setImmediate(callback[, ...args])<br />
setInterval(callback, delay[, ...args])<br />
setTimeout(callback, delay[, ...args])<br />
TextDecoder<br />
TextEncoder<br />
URL<br />
URLSearchParams<br />
WebAssembly<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="34">
<li><h3 id="heading-how-can-we-perform-asynchronous-network-api-in-node-js">How can we perform asynchronous network API in Node JS?</h3>
<p>The net module provides an asynchronous network API for creating stream-based TCP or IPC servers (net.createServer()) and clients (net.createConnection()).</p>
<p>It can be accessed using:
<br /></p>
<p>const net = require('net');</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="35">
<li><h3 id="heading-what-are-the-utilities-of-os-module-in-nodejs">What are the utilities of OS module in NodeJS?</h3>
<p>The os module provides operating system-related utility methods and properties. It can be accessed using:<br /></p>
<p>const os = require('os');.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="36">
<li><h3 id="heading-which-are-the-areas-where-it-is-suitable-to-use-nodejs">Which are the areas where it is suitable to use NodeJS?</h3>
</li>
</ol>
<p>    I/O bound Applications<br />
    Data Streaming Applications<br />
    Data Intensive Real-time Applications (DIRT)<br />
    JSON APIs based Applications<br />
    Single Page Applications<br />
.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="37">
<li><h3 id="heading-which-are-the-areas-where-it-is-not-suitable-to-use-nodejs">Which are the areas where it is not suitable to use NodeJS?</h3>
<p>it’s not suitable for heavy applications involving more of CPU usage</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="38">
<li><h3 id="heading-what-are-the-key-features-of-nodejs">What Are The Key Features Of NodeJs?</h3>
</li>
</ol>
<p>    <strong>Asynchronous event driven IO</strong> helps concurrent request handling – All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.<br />
    <strong>Fast in Code execution</strong> – Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.<br />
    <strong>Single Threaded but Highly Scalable</strong> – Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.<br />
    <strong>Node.js library uses JavaScript</strong> – This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.<br />
    <strong>There is an Active and vibrant community for the Node.js</strong> framework – The active community always keeps the framework updated with the latest trends in the web development.<br />
    <strong>No Buffering</strong> – Node.js applications never buffer any data. They simply output the data in chunks.<br />
.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="39">
<li><h3 id="heading-explain-repl-in-nodejs">Explain REPL In NodeJs?</h3>
</li>
</ol>
<p>    The REPL stands for “Read Eval Print Loop”. It is a simple program that accepts the commands, evaluates them, and finally prints the results. REPL provides an environment similar to that of Unix/Linux shell or a window console, in which we can enter the command and the system, in turn, responds with the output. REPL performs the following tasks.<br /></p>
<p>    <strong>READ</strong> - It Reads the input from the user, parses it into JavaScript data structure and then stores it in the memory.<br />
    <strong>EVAL</strong> - It Executes the data structure.<br />
    <strong>PRINT</strong> - It Prints the result obtained after evaluating the command.<br />
    <strong>LOOP</strong> - It Loops the above command until the user presses Ctrl+C two times.<br /></p>
<p>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong>?</p>
<ol start="40">
<li><h3 id="heading-can-you-write-crud-operations-in-node-js-without-using-frameworks">Can you write CRUD operations in Node js without using frameworks?</h3>
</li>
</ol>
<p>    Yes,we can use inbuilt http library for that , here is a simple code for the same:</p>
<pre><code>    <span class="hljs-keyword">var</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);<span class="hljs-comment">//create a server object:</span>
    http.createServer(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{
    res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>}); <span class="hljs-comment">// http headervar     url = req.url;</span>
    <span class="hljs-keyword">if</span>(url ===<span class="hljs-string">'/about'</span>){
        res.write(<span class="hljs-string">'&lt;h1&gt;about us page&lt;h1&gt;'</span>); <span class="hljs-comment">//write a response</span>
        res.end(); <span class="hljs-comment">//end the response</span>
    }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(url ===<span class="hljs-string">'/contact'</span>){
        res.write(<span class="hljs-string">'&lt;h1&gt;contact us page&lt;h1&gt;'</span>); <span class="hljs-comment">//write a response</span>
        res.end(); <span class="hljs-comment">//end the response</span>
    }<span class="hljs-keyword">else</span>{
        res.write(<span class="hljs-string">'&lt;h1&gt;Hello World!&lt;h1&gt;'</span>); <span class="hljs-comment">//write a response</span>
        res.end(); <span class="hljs-comment">//end the response</span>
    }}).listen(<span class="hljs-number">3000</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"server start at port 3000"</span>); <span class="hljs-comment">//the server object listens on port 3000</span>
    });
</code></pre><p>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="42">
<li><h3 id="heading-what-is-the-difference-between-nodejs-ajax-and-jquery">What Is The Difference Between Nodejs AJAX And JQuery?</h3>
</li>
</ol>
<p>    The one common trait between Node.js, AJAX, and jQuery is that all of them are the advanced implementation of JavaScript. However, they serve completely different purposes.<br /></p>
<p>    <strong>Node.Js</strong> :<br /></p>
<p>    It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.<br /></p>
<p>    <strong>AJAX</strong> (Aka Asynchronous Javascript And XML) :<br /></p>
<p>    It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.<br /></p>
<p>    <strong>JQuery</strong> :<br /></p>
<p>    It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.<br /></p>
<p>.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="43">
<li><h3 id="heading-what-is-eventemitter-in-nodejs">What Is EventEmitter In NodeJs?</h3>
</li>
</ol>
<p>    Events module in Node.js allows us to create and handle custom events. The Event module contains “EventEmitter” class which can be used to raise and handle custom events. It is accessible via the following code.<br /></p>
<pre><code>    <span class="hljs-comment">// Import events module</span>
    <span class="hljs-keyword">var</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);

    <span class="hljs-comment">// Create an eventEmitter object</span>
    <span class="hljs-keyword">var</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();
</code></pre><p>    <br />
    When an EventEmitter instance encounters an error, it emits an “error” event. When a new listener gets added, it fires a “newListener” event and when a listener gets removed, it fires a “removeListener” event.</p>
<p>    EventEmitter provides multiple properties like “on” and “emit”. The “on” property is used to bind a function to the event and “emit” is used to fire an event.
.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<ol start="44">
<li><h3 id="heading-what-is-a-childprocess-module-in-nodejs">What Is A Child_process Module In NodeJs?</h3>
</li>
</ol>
<p>    Node.js supports the creation of child processes to help in parallel processing along with the event-driven model.<br /></p>
<p>    The Child processes always have three streams , child.stdout, and child.stderr. The  stream of the parent process shares the streams of the child process.<br /></p>
<p>    Node.js provides a  module which supports following three methods to create a child process.<br /></p>
<p>        <strong>exec</strong> –  method runs a command in a shell/console and buffers the output.
        <strong>spawn</strong> –  launches a new process with a given command.
        <strong>fork</strong> –  is a special case of the spawn() method to create child processes.
    .</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---node-js"> Back to Top ⬆ </a></strong></p>
<h3 id="heading-table-of-contents-express-js">Table of Contents - Express JS</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td></td><td><strong>Express JS</strong></td></tr>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-is-expressjs">What is ExpressJS?</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-are-some-of-the-salient-features-of-express">What are some of the salient features of express?</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#explain-with-an-example-a-working-of-a-simple-express-app">Explain with an example a working of a simple express app?</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#mention-few-properties-of-request-parameter-in-express">Mention few properties of request parameter in express?</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#how-to-get-the-name-parameters-in-express">How to get the name parameters in express?</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#how-to-retrieve-the-get-query-string-parameters-using-express">How to retrieve the get query string parameters using express? ?</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#how-to-send-a-response-back-using-express">How to send a response back using express?</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#how-to-set-http-response-status-using-express">How to set http response status using express?</a></td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#what-are-the-different-http-status-codes">What are the different http status codes?</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#mention-few-properties-of-request-parameter-in-express">Mention few properties of request parameter in express?</a></td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#how-can-you-change-http-header-value-of-a-response">How can you change http header value of a response?</a></td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#how-to-redirect-to-other-pages-server-side">How to redirect to other pages server-side?</a></td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#how-does-routing-work-in-express">How does routing work in express?</a></td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#what-are-the-tasks-that-a-middleware-can-do">What are the tasks that a middleware can do?</a></td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#what-are-the-different-types-of-middleware">What are the different types of middleware?</a></td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#how-to-serve-static-assests-from-express">How to serve static assests from express? </a></td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#how-to-provide-file-download-using-express">How to provide file download using express?</a></td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#how-to-use-the-response-cookie-()-method-to-manipulate-your-cookies">How to use the Response.cookie() method to manipulate your cookies?</a></td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#how-to-manage-sessions-using-express">How to manage sessions using express?</a></td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#how-to-provide-file-download-using-express">How to provide file download using express?</a></td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#how-to-allow-cors-in-expressjs--explain-with-an-example">How To Allow Cors In Expressjs  Explain With An Example?</a></td></tr>
</tbody>
</table>
</div><h2 id="heading-express-js">Express Js</h2>
<ol>
<li><h3 id="heading-what-is-expressjs">What is ExpressJS?</h3>
<p>Fast, unopinionated, minimalist web framework for Node.js,Express is a project of the Node.js Foundation.it is open source and click <a target="_blank" href="https://github.com/expressjs/express/">here</a> to view,it is mainly used for  building networking services (web applications) and applications,it is builds on top of node js features to provide easy to use functionality that satisfy the needs for building web applications.it has lots of pre-built packages and also many framework are built on top of it like <br />
<strong>Feathers</strong>: Build prototypes in minutes and production ready real-time apps in days<br />
<strong>NestJs</strong>: A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications on top of TypeScript &amp; JavaScript (ES6, ES7, ES8)<br />
<strong>Sails</strong>: MVC framework for Node.js for building practical, production-ready apps.<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="2">
<li><h3 id="heading-what-are-some-of-the-salient-features-of-express">What are some of the salient features of express?</h3>
</li>
</ol>
<p>    <strong>Middlewares</strong>: Set up middlewares in order to respond to HTTP/RESTful Requests.<br />
    <strong>Routing</strong>: It is possible to defines a routing table in order to perform different HTTP operations.<br />
    <strong>Templates</strong>: Dynamically renders HTML Pages based on passing arguments to templates.<br />
    <strong>High Performance</strong>: Express prepare a thin layer, therefore, the performance is adequate.<br />
    <strong>Database Support</strong>: Express supports RDBMS as well as NoSQL databases.<br />
    <strong>MVC Support</strong>: Organize the web application into an MVC architecture.
    <strong>Manages everything from routes</strong> to rendering view and preforming HTTP request.<br /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="3">
<li><h3 id="heading-explain-with-an-example-a-working-of-a-simple-express-app">Explain with an example a working of a simple express app?</h3>
<p> I have given you the code, you explain , don't expect me to do all the stuff</p>
<pre><code> <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
 <span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>
 <span class="hljs-keyword">const</span> app = express()
 app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
   res.send(<span class="hljs-string">'Hello World!'</span>)
 })
 app.listen(port, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{ 
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'listening on port'</span>,port)
 })
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="4">
<li><h3 id="heading-mention-few-properties-of-request-parameter-in-express">Mention few properties of request parameter in express?</h3>
<p> here is a list of few req methods needed for you to knows
 <img src="/img/express_req_methods.png" alt="req methods" /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="5">
<li><h3 id="heading-how-to-get-the-name-parameters-in-express">How to get the name parameters in express?</h3>
<p> This property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /user/:name, then the “name” property is available as req.params.name. This object defaults to {}.</p>
<pre><code> <span class="hljs-comment">// GET /user/tj</span>
 req.params.name
 <span class="hljs-comment">// =&gt; "tj"</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="6">
<li><h3 id="heading-how-to-retrieve-the-get-query-string-parameters-using-express">How to retrieve the get query string parameters using express?</h3>
<p> The query string is the part that comes after the URL path, and starts with a question mark ?.</p>
<pre><code> ?height=<span class="hljs-number">6</span>&amp;weight=<span class="hljs-number">60</span>
 <span class="hljs-comment">//req.query.height - 6</span>
 <span class="hljs-comment">//req.query.weight - 60</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="7">
<li><h3 id="heading-how-to-send-a-response-back-using-express">How to send a response back using express?</h3>
<p> we can use any one of these commands</p>
<pre><code> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
     res.send(<span class="hljs-string">'Hello World!'</span>)
 }
 <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
     res.end(<span class="hljs-string">'Hello World!'</span>)
 }
 <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{
     res.json({<span class="hljs-attr">title</span>:<span class="hljs-string">'Hello World!'</span>})
 }
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="8">
<li><h3 id="heading-how-to-set-http-response-status-using-express">How to set http response status using express?</h3>
<p> we can either use <strong>res.status()</strong> or <strong>res.sendStatus()</strong></p>
<pre><code> res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'File not found'</span>)

 <span class="hljs-comment">//if sendStatus we no need to write send method , i will pre send a few inbuilt messages upon using that</span>

 res.sendStatus(<span class="hljs-number">200</span>)
 <span class="hljs-comment">// === res.status(200).send('OK')</span>

 res.sendStatus(<span class="hljs-number">403</span>)
 <span class="hljs-comment">// === res.status(403).send('Forbidden')</span>

 res.sendStatus(<span class="hljs-number">404</span>)
 <span class="hljs-comment">// === res.status(404).send('Not Found')</span>

 res.sendStatus(<span class="hljs-number">500</span>)
 <span class="hljs-comment">// === res.status(500).send('Internal Server Error')</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="9">
<li><h3 id="heading-what-are-the-different-http-status-codes">What are the different http status codes?</h3>
<p> | Code | Message |    Description                   |
 | ---- | ------- |    ------------------------------|
 |    100|Continue|Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request|
 |101|Switching Protocols|The server switches protocol|
 |200 |OK|The request is OK.|
 |201 |Created|The request is complete, and a new resource is created |
 |202 |Accepted|The request is accepted for processing, but the processing is not complete|
 |203 |Non-authoritative Information|The information in the entity header is from a local or third-party copy, not from the original server.|
 |204 |No Content|A status code and a header are given in the response but there is no entity-body in the reply|
 |205 |Reset Content|The browser should clear the form used for this transaction for additional input|
 |206 |Partial Content|The server is returning partial data of the size requested. Used in response to a request specifying a Range header. The server must specify the range included in the response with the Content-Range header|
 |300 |Multiple Choices|A link list. The user can select a link and go to that location. Maximum five addresses|
 |301 |Moved Permanently|The requested page has moved to a new url |
 |302 |Found|The requested page has moved temporarily to a new url|
 |303  |See Other|The requested page can be found under a different url|
 |304  |Not Modified|This is the response code to an If-Modified-Since or If-None-Match header, where the URL has not been modified since the specified date|
 |305  |Use Proxy|The requested URL must be accessed through the proxy mentioned in the Location header|
 |306  |Unused|This code was used in a previous version. It is no longer used, but the code is reserved|
 |307  |Temporary Redirect|The requested page has moved temporarily to a new url|
 |400  |Bad Request|The server did not understand the request|
 |401  | Unauthorized|The requested page needs a username and a password|
 |402  | Payment Required|You can not use this code yet.|
 |403  |Forbidden|Access is forbidden to the requested page.|
 |404  |Not Found|The server can not find the requested page.|
 |405  |Method Not Allowed|The method specified in the request is not allowed|
 |406  |Not Acceptable|The server can only generate a response that is not accepted by the client|
 |407  | Proxy Authentication Required|You must authenticate with a proxy server before this request can be served|
 |408  |Request Timeout|The request took longer than the server was prepared to wait|
 |409  |Conflict|The request could not be completed because of a conflict|
 |410  |Gone|The requested page is no longer available|
 |411  |Length Required|The "Content-Length" is not defined. The server will not accept the request without it .|
 |412  |Precondition Failed|The pre condition given in the request evaluated to false by the server|
 |413  | Request Entity Too Large|The server will not accept the request, because the request entity is too large.|
 |414  |Request-url Too Long|The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information|
 |415  |Unsupported Media Type|The server will not accept the request, because the mediatype is not supported |
 |416  |Requested Range Not Satisfiable|The requested byte range is not available and is out of bounds|
 |417  |Expectation Failed|The expectation given in an Expect request-header field could not be met by this server.|
 |500  |Internal Server Error|The request was not completed. The server met an unexpected condition.|
 |501  | Not Implemented|The request was not completed. The server did not support the functionality required.|
 |502  | Bad Gateway|The request was not completed. The server received an invalid response from the upstream server.|
 |503  |Service Unavailable|The request was not completed. The server is temporarily overloading or down.|
 |504  |Gateway Timeout|The gateway has timed out.|
 |505  |HTTP Version Not Supported|The server does not support the "http protocol" version|</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="10">
<li><h3 id="heading-mention-few-properties-of-request-parameter-in-express-1">Mention few properties of request parameter in express?</h3>
<p>You can access all the HTTP headers using the Request.headers property:</p>
<pre><code>app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
<span class="hljs-built_in">console</span>.log(req.headers)
})

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
req.header(<span class="hljs-string">'User-Agent'</span>)
})
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="11">
<li><h3 id="heading-how-can-you-change-http-header-value-of-a-response">How can you change http header value of a response?</h3>
<p>You can change any HTTP header value using Response.set():</p>
<pre><code>res.set(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>)
res.type(<span class="hljs-string">'json'</span>)
<span class="hljs-comment">// =&gt; 'application/json'</span>

res.type(<span class="hljs-string">'application/json'</span>)
<span class="hljs-comment">// =&gt; 'application/json'</span>

res.type(<span class="hljs-string">'png'</span>)
<span class="hljs-comment">// =&gt; image/png:</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="12">
<li><h3 id="heading-how-to-redirect-to-other-pages-server-side">How to redirect to other pages server-side?</h3>
<p>Redirects are common in Web Development. You can create a redirect using the Response.redirect() method:<br /></p>
<pre><code>res.redirect(<span class="hljs-string">'/go-there'</span>)
<span class="hljs-comment">//it can be either a url or a path of file</span>
res.redirect(<span class="hljs-number">301</span>, <span class="hljs-string">'/go-there'</span>)
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="13">
<li><h3 id="heading-how-does-routing-work-in-express">How does routing work in express?</h3>
<p>Routing is the process of determining what should happen when a URL is called, or also which parts of the application should handle a specific incoming request.<br /></p>
<p>In the Hello World example we used this code<br /></p>
<pre><code>app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res</span>) </span>{ 
 <span class="hljs-comment">/* */</span> 
})
<span class="hljs-comment">//This creates a route that maps accessing the root domain URL / using the HTTP GET method to the response we want to provide.</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="14">
<li><h3 id="heading-what-are-the-tasks-that-a-middleware-can-do">What are the tasks that a middleware can do?</h3>
<p>Middleware functions can perform the following tasks:<br /></p>
<p>Execute any code.<br />
Make changes to the request and the response objects.<br />
End the request-response cycle.<br />
Call the next middleware function in the stack.<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="15">
<li><h3 id="heading-what-are-the-different-types-of-middleware">What are the different types of middleware?</h3>
<p>An Express application can use the following types of middleware:<br /></p>
</li>
</ol>
<p>    Application-level middleware<br />
    Router-level middleware<br />
    Error-handling middleware<br />
    Built-in middleware<br />
    Third-party middleware</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="16">
<li><h3 id="heading-how-to-serve-static-assests-from-express">How to serve static assests from express?</h3>
<p>It’s common to have images, CSS and more in a public subfolder, and expose them to the root level:</p>
</li>
</ol>
<pre><code>    <span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
    <span class="hljs-keyword">const</span> app = express()

    app.use(express.static(<span class="hljs-string">'public'</span>))

    app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server ready'</span>))
</code></pre><p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="17">
<li><h3 id="heading-how-to-provide-file-download-using-express">How to provide file download using express?</h3>
<p>Express provides a handy method to transfer a file as attachment: Response.download().<br /></p>
<p>Once a user hits a route that sends a file using this method, browsers will prompt the user for download.<br /></p>
<p>The Response.download() method allows you to send a file attached to the request, and the browser instead of showing it in the page, it will save it to disk.<br /></p>
<pre><code>app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.download(<span class="hljs-string">'./file.pdf'</span>))
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="18">
<li><h3 id="heading-how-to-use-the-responsecookie-method-to-manipulate-your-cookies">How to use the Response.cookie() method to manipulate your cookies?</h3>
<p>Cookies are small pieces of data sent from a website and are stored in user's web browser while user is browsing that website. Every time the user loads that website back, the browser sends that stored data back to website or server, to distinguish user's previous     activity.</p>
</li>
</ol>
<pre><code>    res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Adam'</span>)

    This method accepts a third parameter which contains various options:
    res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Adam'</span>, { <span class="hljs-attr">domain</span>: <span class="hljs-string">'.bangalore.com'</span>, <span class="hljs-attr">path</span>: <span class="hljs-string">'/administrator'</span>, <span class="hljs-attr">secure</span>: <span class="hljs-literal">true</span> })

    res.cookie(<span class="hljs-string">'username'</span>, <span class="hljs-string">'Adam'</span>, { <span class="hljs-attr">expires</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Date</span>.now() + <span class="hljs-number">900000</span>), <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span> })

    <span class="hljs-comment">//clear cookie</span>
    res.clearCookie(<span class="hljs-string">'username'</span>)
</code></pre><p>    The most useful parameters you can set are:
    | Value | Description |
    | ----- | ----------- |
    | domain | the cookie domain name|
    |expires|set the cookie expiration date. If missing, or 0, the cookie is a session cookie|
    |httpOnly|set the cookie to be accessible only by the web server. See HttpOnly|
    |maxAge|set the expiry time relative to the current time, expressed in milliseconds|
    |path|the cookie path. Defaults to /|
    |secure|Marks the cookie HTTPS only|
    |signed|     set the cookie to be signed|
    |sameSite|Value of SameSite|</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="19">
<li><h3 id="heading-how-to-manage-sessions-using-express">How to manage sessions using express?</h3>
<p>We’ll use the express-session module, which is maintained by the Express team.When implemented, every user of you API or website will be assigned a unique session, and this allows you to store the userstate.as by default Express requests are sequential and no request can be linked to each other. There is no way to know if this request comes from a client that already performed a request previously.</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> session = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express-session'</span>)

<span class="hljs-keyword">const</span> app = express()
app.use(session(
<span class="hljs-string">'secret'</span>: <span class="hljs-string">'343ji43j4n3jn4jk3n'</span>
))
</code></pre><p>All solutions store the session id in a cookie, and keep the data server-side. The client will receive the session id in a cookie, and will send it along with every HTTP request.</p>
<p>We’ll reference that server-side to associate the session id with the data stored locally.</p>
<p>Memory is the default, it requires no special setup on your part, it’s the simplest thing but it’s meant only for development purposes.</p>
<p>The best choice is a memory cache like Redis, for which you need to setup its own infrastructure.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="20">
<li><h3 id="heading-how-to-process-forms-using-express">How to process forms using Express?</h3>
<p>The form data will be sent in the POST request body.</p>
<p>To extract it, you will use the express.urlencoded() middleware, provided by Express:</p>
<pre><code><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
<span class="hljs-keyword">const</span> app = express()

app.use(express.urlencoded())
</code></pre><p>Now you need to create a POST endpoint on the /submit-form route, and any data will be available on Request.body:</p>
<pre><code>app.post(<span class="hljs-string">'/submit-form'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
<span class="hljs-keyword">const</span> username = req.body.username
<span class="hljs-comment">//...</span>
res.end()
})
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<ol start="21">
<li><h3 id="heading-how-to-allow-cors-in-expressjs-explain-with-an-example">How To Allow Cors In Expressjs  Explain With An Example?</h3>
</li>
</ol>
<p>    In order to allow CORS in Express.js,  add the following code in server.js:</p>
<pre><code>    app.all(<span class="hljs-string">'*'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res, next</span>) </span>{
    res.set(<span class="hljs-string">'Access-Control-Allow-Origin'</span>, <span class="hljs-string">'*'</span>);
    res.set(<span class="hljs-string">'Access-Control-Allow-Methods'</span>, <span class="hljs-string">'GET, POST, DELETE, PUT'</span>);
    res.set(<span class="hljs-string">'Access-Control-Allow-Headers'</span>, <span class="hljs-string">'X-Requested-With, Content-Type'</span>);
    <span class="hljs-keyword">if</span> (<span class="hljs-string">'OPTIONS'</span> == req.method) <span class="hljs-keyword">return</span> res.send(<span class="hljs-number">200</span>);
    next();
    });
</code></pre><p>    or you can install a package called cors ,CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.<a target="_blank" href="https://www.npmjs.com/package/cors">link</a></p>
<pre><code>    <span class="hljs-keyword">var</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)
    <span class="hljs-keyword">var</span> cors = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cors'</span>)
    <span class="hljs-keyword">var</span> app = express()

    app.use(cors())
</code></pre><p><strong><a class="post-section-overview" href="#table-of-contents---express-js"> Back to Top ⬆ </a></strong></p>
<h3 id="heading-table-of-contents-mongodb-and-mongoose">Table of Contents - MongoDB and Mongoose</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td></td><td><strong>MongoDB and Mongoose</strong></td></tr>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-is-mongodb">What is MongoDB?</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-are-the-difference-between-nosql-and-sql">What are the difference between NoSQL and SQL</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#how-to-establish-mongodb-database-connection-in-a-node-application">How to establish MongoDB database connection in a node application?</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#what-are-virtual-property-in-mongoose">What are virtual property in mongoose</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#how-can-we-add-or-create-our-own-instance-methods-in-mongoose">How can we add or create our own instance methods in mongoose</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#how-can-we-add-or-create-our-own-static-methods-in-mongoose">How can we add or create our own static methods in mongoose</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-are-the-mongoose-middlewares">What are the mongoose middlewares?</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#how-to-query-data-using-mongoose">How to query data using mongoose?</a></td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#what-is-population-in-mongoose">What is Population in mongoose</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#what-is-datamasking">What is Datamasking?</a></td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#what-is-hashing-and-explain-how-it-works">What is hashing and explain how it works?</a></td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#what-are-salts-and-why-are-they-so-important">What are salts and why are they so important?</a></td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#what-are-pepper-and-why-are-they-so-important">What are pepper and why are they so important?</a></td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#what-are-jwt">What are JWT?</a></td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#what-are-different-authentication-methods">What are different authentication methods?</a></td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#what-are-disadvantages-of-using-session-based-authentication">What are disadvantages of using session based authentication?</a></td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#what-are-disadvantages-of-using-jwt-based-authentication">What are disadvantages of using jwt based authentication?</a></td></tr>
</tbody>
</table>
</div><ol>
<li><h3 id="heading-what-is-mongodb">What is MongoDB?</h3>
<p>MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability.Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema.<br />
MongoDB is written in C++<br /></p>
<p>MongoDB is known to be used by the City of Chicago, Codecademy, Google Search, Foursquare, IBM, Orange S.A., The Gap, Inc., Uber, Coinbase, Sega, Barclays, HSBC, eBay, Cisco, Bosch and Urban Outfitters</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="2">
<li><h3 id="heading-what-are-the-difference-between-nosql-and-sql">What are the difference between NoSQL and SQL?</h3>
<p>| Parameter | SQL | NOSQL |
| --------- | --- | ----- |
|Definition |SQL databases are primarily called RDBMS or Relational Databases |NoSQL databases are primarily called as Non-relational or distributed database |
|Query Language|Structured query language (SQL) |No declarative query language |
|Type |    SQL databases are table based databases |NoSQL databases can be document based, key-value pairs, graph databases |
|Schema |SQL databases have a predefined schema |NoSQL databases use dynamic schema for unstructured data. |
|Ability to scale |SQL databases are vertically scalable |NoSQL databases are horizontally scalable |
|Examples|Oracle, Postgres, and MS-SQL. |    MongoDB, Redis, Neo4j, Cassandra, Hbase.|
|Best suited for |An ideal choice for the complex query intensive environment. |It is not good fit complex queries. |
|Hierarchical data storage |SQL databases are not suitable for hierarchical data storage.|More suitable for the hierarchical data store as it supports key-value pair method |
|Variations|    One type with minor variations|Many different types which include key-value stores, document databases, and graph databases|
|Consistency |It should be configured for strong consistency. |It depends on DBMS as some offers strong consistency like MongoDB, whereas others offer only offers eventual consistency, like Cassandra. |
|Hardware|Specialized DB hardware (Oracle Exadata, etc.)|Commodity hardware |
|Network |Highly available network (Infiniband, Fabric Path, etc.) |Commodity network (Ethernet, etc.) |
|Best features |Cross-platform support, Secure and free |Easy to use, High performance, and Flexible tool. |
|Top Companies Using |Hootsuite, CircleCI, Gauges |Airbnb, Uber, Kickstarter |
|ACID vs. BASE Mode|ACID( Atomicity, Consistency, Isolation, and Durability) is a standard for RDBMS |Base ( Basically Available, Soft state, Eventually Consistent) is a model of many NoSQL systems |
|Average salary|₹ 5,58,704 per year|₹ 6,04,959 per year|</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="3">
<li><h3 id="heading-how-to-establish-mongodb-database-connection-in-a-node-application">How to establish MongoDB database connection in a node application?</h3>
<p> <strong>Database Connection</strong>
 Create a file ./config/database.js under the project root.</p>
<p> Database Connection</p>
<p> Next, we will add code that connects to the database.</p>
<p> in database.js file </p>
<pre><code> <span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);
 <span class="hljs-keyword">const</span> server = <span class="hljs-string">'127.0.0.1:27017'</span>; <span class="hljs-comment">// REPLACE WITH YOUR DB SERVER</span>
 <span class="hljs-keyword">const</span> database = <span class="hljs-string">'fcc-Mail'</span>;      <span class="hljs-comment">// REPLACE WITH YOUR DB NAME</span>

  mongoose.connect(<span class="hljs-string">`mongodb://<span class="hljs-subst">${server}</span>/<span class="hljs-subst">${database}</span>`</span>)
    .then(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Database connection successful'</span>)
    })
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Database connection error'</span>)
    })

 <span class="hljs-built_in">module</span>.exports = { mongoose }
</code></pre><p> <strong>MongoDB Atlas</strong>
 sign up to mongosb atlas and it will help you make a connection by url, having a secret key and password</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="4">
<li><h3 id="heading-what-are-virtual-property-in-mongoose">What are virtual property in mongoose?</h3>
<p>A virtual property is not persisted to the database. We can add it to our schema as a helper to get and set values.but it wont store in database</p>
<pre><code> userSchema.virtual(<span class="hljs-string">'fullName'</span>).get(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">' '</span> + <span class="hljs-built_in">this</span>.lastName
 })

 userSchema.virtual(<span class="hljs-string">'fullName'</span>).set(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{
 <span class="hljs-keyword">let</span> str = name.split(<span class="hljs-string">' '</span>)

 <span class="hljs-built_in">this</span>.firstName = str[<span class="hljs-number">0</span>]
 <span class="hljs-built_in">this</span>.lastName = str[<span class="hljs-number">1</span>]
 })

 <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User()
 user.fullName = <span class="hljs-string">'Thomas Anderson'</span>
 <span class="hljs-built_in">console</span>.log(user.toJSON())  <span class="hljs-comment">// Output model fields as JSON</span>
 <span class="hljs-built_in">console</span>.log()
 <span class="hljs-built_in">console</span>.log(user.fullName)  <span class="hljs-comment">// Output the full name</span>
 <span class="hljs-comment">//The code above will output the following:</span>

 { <span class="hljs-attr">_id</span>: <span class="hljs-number">5</span>a7a4248550ebb9fafd898cf,
     <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Thomas'</span>,
     <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Anderson'</span> }
 <span class="hljs-comment">//Thomas Anderson</span>
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="5">
<li><h3 id="heading-how-can-we-add-or-create-our-own-instance-methods-in-mongoose">How can we add or create our own instance methods in mongoose?</h3>
<p>We can create custom helper methods on the schema and access them via the model instance. These methods will have access to the model object and they can be used quite creatively</p>
<pre><code> userSchema.methods.details = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.username + <span class="hljs-string">' - '</span> +  <span class="hljs-built_in">this</span>.email
 }
 <span class="hljs-comment">//This method will be accessible via a model instance:</span>
 <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">new</span> User({
 <span class="hljs-attr">username</span>: <span class="hljs-string">'user2'</span>,
 <span class="hljs-attr">email</span>: <span class="hljs-string">'user2@gmail.com'</span>
 })
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="6">
<li><h3 id="heading-how-can-we-add-or-create-our-own-static-methods-in-mongoose">How can we add or create our own static methods in mongoose?</h3>
<p>Similar to instance methods, we can create static methods on the schema. Let’s create a method to retrieve all users in the database:</p>
<pre><code>userSchema.statics.getUsers = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
 <span class="hljs-built_in">this</span>.find(<span class="hljs-function">(<span class="hljs-params">err, docs</span>) =&gt;</span> {
   <span class="hljs-keyword">if</span>(err) {
     <span class="hljs-built_in">console</span>.error(err)
     <span class="hljs-keyword">return</span> reject(err)
   }
   resolve(docs)
         })
     })
 }
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="7">
<li><h3 id="heading-what-are-the-mongoose-middlewares">What are the mongoose middlewares?</h3>
<p>Middleware are functions that run at specific stages of a pipeline. Mongoose supports middleware for the following operations:<br /></p>
<p> Aggregate<br />
 Document<br />
 Model<br />
 Query<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="8">
<li><h3 id="heading-how-to-query-data-using-mongoose">How to query data using mongoose?</h3>
<p>Mongoose has a very rich API that handles many complex operations supported by MongoDB. Consider a query where we can incrementally build query components.<br /></p>
<p> In this example, we are going to:<br /></p>
<p> Find all users<br />
 Skip the first 100 records<br />
 Limit the results to 10 records<br />
 Sort the results by the firstName field<br />
 Select the firstName<br />
 Execute that query<br /></p>
<pre><code> User.find()                   <span class="hljs-comment">// find all users</span>
      .skip(<span class="hljs-number">100</span>)                <span class="hljs-comment">// skip the first 100 items</span>
      .limit(<span class="hljs-number">10</span>)                <span class="hljs-comment">// limit to 10 items</span>
      .sort({<span class="hljs-attr">firstName</span>: <span class="hljs-number">1</span>}      <span class="hljs-comment">// sort ascending by firstName</span>
      .select({<span class="hljs-attr">firstName</span>: <span class="hljs-literal">true</span>} <span class="hljs-comment">// select firstName only</span>
      .exec()                   <span class="hljs-comment">// execute the query</span>
      .then(<span class="hljs-function"><span class="hljs-params">docs</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.log(docs)
       })
      .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
         <span class="hljs-built_in">console</span>.error(err)
       })
</code></pre></li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="9">
<li><h3 id="heading-what-is-population-in-mongoose">What is Population in mongoose?</h3>
<p>Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="10">
<li><h3 id="heading-what-is-datamasking">What is Datamasking?</h3>
<p>Data masking is a method of creating a structurally similar but inauthentic version of an organization's data that can be used for purposes such as software testing and user training. The purpose is to protect the actual data while having a functional substitute for occasions when the real data is not required.<br />
you can simply use <strong>$project</strong> to hide the mobile field<br />
Or perhaps you have an extra field in your document to indicate whether the information is public or not, i.e. given documents<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="11">
<li><h3 id="heading-what-is-hashing-and-explain-how-it-works">What is hashing and explain how it works?</h3>
<p>Hashing is the process of converting an input of any length into a fixed size string of text, using a mathematical function.
<img src="https://miro.medium.com/max/4000/0*Zkd2fcKuVGirbNpl.png" alt="hashing" />
When the user provides a input it will be converted to a value of fixed length by a hashing function and the resulting value will be called as hashed text, and it should be always unique for different value</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="12">
<li><h3 id="heading-what-are-salts-and-why-are-they-so-important">What are salts and why are they so important?</h3>
<p>It's a unique value that can be added to the end of the password to create a different hash value. This adds a layer of security to the hashing process<br />
They are so important as they prevent <strong>brute force attacks</strong>(Trying all possible combintaion of password) and also against <strong>rainbow table</strong>(a table containing all common hashed text and their respective passwords)<br /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="13">
<li><h3 id="heading-what-are-pepper-and-why-are-they-so-important">What are pepper and why are they so important?</h3>
<p>A pepper is a secret added to an input such as a password prior to being hashed with a cryptographic hash function<br />
A pepper performs a comparable role to a salt, but while a salt is not secret (merely unique) and can be stored alongside the hashed output<br /> A pepper is secret and must not be stored with the output. The hash and salt are usually stored in a database, but a pepper must be stored separately (e.g. in a configuration file) to prevent it from being obtained by the attacker in case of a database breach. <br /> Where the salt only has to be long enough to be unique, a pepper has to be secure to remain secret (at least 112 bits is recommended by NIST), otherwise an attacker only needs one known entry to crack the pepper.<br /> Finally, the pepper must be generated anew for every application it is deployed in, otherwise a breach of one application would result in lowered security of another application.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="14">
<li><h3 id="heading-what-are-jwt">What are JWT?</h3>
<p>JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object<br />
some scenarios where JSON Web Tokens are useful:<br />
<strong>Authorization</strong>: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.<br /></p>
<p><strong>Information Exchange</strong>: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.<br /></p>
<p><img src="https://research.securitum.com/wp-content/uploads/sites/2/2019/10/jwt_ng1_en.png" alt="jwt" /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="15">
<li><h3 id="heading-what-are-different-authentication-methods">What are different authentication methods?</h3>
</li>
</ol>
<p>    Use <strong>API keys</strong> if you expect developers to build internal applications that don’t need to access more than a single user’s data.<br />
    Use <strong>OAuth</strong> access tokens if you want users to easily provide authorization to applications without needing to share private data or dig through developer documentation.<br />
    Use <strong>session cookies</strong>, here server is responsible for creating a session for the particular user when the user log's in, after that the id of the session is stored in a cookie on the user browser. For every request sent by the user, the cookie will be sent too, where the server can compare the session id from the cookie with the session information stored on the server so the user identity is verified.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="16">
<li><h3 id="heading-what-are-disadvantages-of-using-session-based-authentication">What are disadvantages of using session based authentication?</h3>
</li>
</ol>
<p>   <strong>Compromised Secret Key</strong> : The best and the worst thing about JWT is that it relies on just one Key. Consider that the Key is leaked by a careless or a rogue developer/administrator, the whole system is compromised!<br />
  <strong>Cannot manage client from the server</strong><br /><strong>Cannot push Messages to clients</strong> <br /><strong>Crypto-algo can be deprecated</strong><br /><strong>Data Overhead</strong> : The size of the JWT token will be more than that of a normal Session token<br />Complicated to understand: JWT uses cryptographic Signature algorithms to verify the data and get the user-id from the token. Understanding the Signing Algo in itself requires basics of cryptography. <br /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<ol start="17">
<li><h3 id="heading-what-are-disadvantages-of-using-jwt-based-authentication">What are disadvantages of using jwt based authentication?</h3>
</li>
</ol>
<p>   <strong>Session based authentication</strong>:<br /> Because the sessions are stored in the server’s memory, scaling becomes an issue when there is a huge number of users using the system at once.<br />Cookies normally work on a single domain or subdomains and they are normally disabled by browser if they work cross-domain (3rd party cookies). It poses issues when APIs are served from a different domain to mobile and web devices.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---mongodb-and-mongoose"> Back to Top ⬆ </a></strong></p>
<h3 id="heading-table-of-contents-golang">Table of Contents - Golang</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td></td><td><strong>Golang</strong></td></tr>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-is-golang">What is Golang?</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-are-the-pros-and-cons-of-golang">What are the pros and cons of Golang?</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#what-kind-of-projects-are-suitable-to-be-built-in-golang">What kind of projects are suitable to be built in Golang?</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#is-golang-an-object-oriented-language">Is Golang an object oriented language?</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#what-are-the-data-types-in-golang">What are the data types in Golang?</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#can-you-return-multiple-values-from-a-function">Can you return multiple values from a function?</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-is-a-gopath">What is a GOPATH?</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#what-are-goroutines">What are Goroutines?</a></td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#what-is-nil-in-go">What is nil in Go?</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#what-is-the-difference-between-array-and-slice-in-go">What is the difference between array and slice in Go?</a></td></tr>
<tr>
<td>11</td><td><a class="post-section-overview" href="#how-does-a-go-compiler-work">How does a go compiler work?</a></td></tr>
<tr>
<td>12</td><td><a class="post-section-overview" href="#what-is-an-interface-and-why-do-you-use-it">What is an Interface and Why do you use it?</a></td></tr>
<tr>
<td>13</td><td><a class="post-section-overview" href="#what-are-concurrency-and-parralism-and-what-is-the-difference-between-both">What are concurrency and parralism and what is the difference between both?</a></td></tr>
<tr>
<td>14</td><td><a class="post-section-overview" href="#what-are-the-difference-between-goroutines-and-threads">What are the difference between goroutines and threads?</a></td></tr>
<tr>
<td>15</td><td><a class="post-section-overview" href="#what-are-channels-for">What are channels for?</a></td></tr>
<tr>
<td>16</td><td><a class="post-section-overview" href="#can-you-do-something-in-goroutines-using-channels">Can you do something in goroutines using channels?</a></td></tr>
<tr>
<td>17</td><td><a class="post-section-overview" href="#what-is-a-closure">What is a Closure?</a></td></tr>
<tr>
<td>18</td><td><a class="post-section-overview" href="#what-are-runtime--and-runtime-packages">What are runtime  and runtime packages?</a></td></tr>
<tr>
<td>19</td><td><a class="post-section-overview" href="#how-can-you-get-how-many-cores-your-computer-has">How can you get how many cores your computer has?</a></td></tr>
<tr>
<td>20</td><td><a class="post-section-overview" href="#how-would-you-tell-a-goroutine-to-use-less-core-than-what-you-have">How would you tell a goroutine to use less core than what you have?</a></td></tr>
<tr>
<td>21</td><td><a class="post-section-overview" href="#how-would-you-determine-the-type-of-a-variable-and-which-package-to-use-for-it">How would you determine the type of a variable and Which package to use for it?</a></td></tr>
<tr>
<td>22</td><td><a class="post-section-overview" href="#what-all-types-can-map-store">What all types can map store?</a></td></tr>
<tr>
<td>23</td><td><a class="post-section-overview" href="#what-are-microservices">What are microservices?</a></td></tr>
<tr>
<td>24</td><td><a class="post-section-overview" href="#why-are-there-no-classes-in-go">Why are there no classes in Go?</a></td></tr>
<tr>
<td>25</td><td><a class="post-section-overview" href="#difference-between-compile-time-and-runtime">Difference between Compile time and runtime?</a></td></tr>
<tr>
<td>26</td><td><a class="post-section-overview" href="#how-to-generate-a-true-random-number-in-golang">How to generate a true random number in golang?</a></td></tr>
<tr>
<td>27</td><td><a class="post-section-overview" href="#why-are-goroutines-light-weight">Why are goroutines light-weight?</a></td></tr>
<tr>
<td>28</td><td><a class="post-section-overview" href="#if-capacity-is-not-defined-in-slice,-what-would-the-capacity-be">If capacity is not defined in slice, what would the capacity be?</a></td></tr>
<tr>
<td>29</td><td><a class="post-section-overview" href="#what-is-the-easiest-way-to-check-if-a-slice-is-empty">What is the easiest way to check if a slice is empty?</a></td></tr>
<tr>
<td>30</td><td><a class="post-section-overview" href="#what-is-an-advantage-of-go-evaluating-implicit-types-at-compile-time">What is an advantage of Go evaluating implicit types at compile time?</a></td></tr>
</tbody>
</table>
</div><ol>
<li><h3 id="heading-what-is-golang">What is Golang?</h3>
</li>
</ol>
<p>   Golang is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Golang was designed at Google in 2007 to improve programming productivity in an era of multicore, networked machines and large codebases.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong></p>
<ol start="2">
<li><h3 id="heading-what-are-the-pros-and-cons-of-golang">What are the pros and cons of Golang?</h3>
<p> <strong>Pros:</strong></p>
<ul>
<li>Ease of use</li>
<li>A Smart Standard library</li>
<li>Strong security built-in</li>
<li>Garbage collected language.</li>
<li>Minimalism &amp; Readability</li>
<li>Concurrency</li>
</ul>
</li>
</ol>
<p>    <strong>Cons:</strong></p>
<ul>
<li>No generics</li>
<li>Error-handling boilerplate &amp; lack of compile-time checks unhandled errors</li>
<li>Shortage of high-level parallelism and concurrency features</li>
</ul>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong></p>
<ol start="3">
<li><h3 id="heading-what-kind-of-projects-are-suitable-to-be-built-in-golang">What kind of projects are suitable to be built in Golang?</h3>
<ul>
<li>Cloud services </li>
<li>Media platforms</li>
<li>Broadcast providers</li>
<li>Projects with microservice architecture</li>
</ul>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong></p>
</li>
<li><h3 id="heading-is-golang-an-object-oriented-language">Is Golang an object oriented language?</h3>
<p> Golang has types and methods and allows an object-oriented style of programming, there is no type hierarchy.Golang has some properties of object oriented programming like Encapsulation , Composition , but it doesn't have inheritance , classes , function overloading .</p>
</li>
</ol>
<p>  <strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong></p>
<ol start="5">
<li><h3 id="heading-what-are-the-data-types-in-golang">What are the data types in Golang?</h3>
<ol>
<li><strong>Basic type</strong>: Numbers, strings, and booleans .</li>
<li><strong>Aggregate type</strong>: Array and structs .</li>
<li><strong>Reference type</strong>: Pointers, slices, maps, functions, and channels .</li>
<li><strong>Interface type</strong></li>
</ol>
</li>
</ol>
<p>  <strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong></p>
<ol start="6">
<li><h3 id="heading-can-you-return-multiple-values-from-a-function">Can you return multiple values from a function?</h3>
<p> Yes. A Go function can return multiple values, each separated by commas in the return statement.</p>
<pre><code class="lang-go">     <span class="hljs-keyword">package</span> main

     <span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

     <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">foo</span><span class="hljs-params">()</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>)</span></span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"foo"</span>, <span class="hljs-string">"ball"</span>
     }

     <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
        fmt.Println(foo())
     }
</code></pre>
</li>
</ol>
<p>  <strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>    </p>
<ol start="7">
<li><h3 id="heading-what-is-a-gopath">What is a GOPATH?</h3>
</li>
</ol>
<p>    The GOPATH environment variable specifies the location of your workspace. It defaults to a directory named go inside your home directory    <br /><br />    The command go env GOPATH prints the effective current GOPATH; it prints the default location if the environment variable is unset.          </p>
<p>  <strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
<ol start="8">
<li><h3 id="heading-what-are-goroutines">What are Goroutines?</h3>
<p> Goroutines are incredibly lightweight “threads” managed by the go runtime. They enable us to create asynchronous parallel programs that can execute some tasks far quicker than if they were written in a sequential manner.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-is-nil-in-go">What is nil in Go?</h3>
<p> nil is a predeclared identifier in Go that represents zero values for pointers, interfaces, channels, maps, slices and function types.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-is-the-difference-between-array-and-slice-in-go">What is the difference between array and slice in Go ?</h3>
<ul>
<li><strong>ARRAY</strong> : An array is a fixed collection of data. The emphasis here is on fixed, because once you set the length of an array, it cannot be changed.<br /></li>
</ul>
<pre><code class="lang-go">arr := [<span class="hljs-number">4</span>]<span class="hljs-keyword">int</span>{<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>}
</code></pre>
<ul>
<li><strong>SLICE</strong> : Slices are much more flexible, powerful, and convenient than arrays. Unlike arrays, slices can be resized using the built-in append function .</li>
</ul>
<pre><code class="lang-go">slicee := <span class="hljs-built_in">make</span>([]Type, length, capacity)
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-how-does-a-go-compiler-work">How does a go compiler work?</h3>
<p>A Go compiler goes through the following steps , they are in brief , if we go in detail then you will need a complete book to understand each module, for interview purpose , I have attached a hand written note , I will generate a digital form soon </p>
<p><img src="/img/go_compiler.jpeg" alt="go compiler" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
</ol>
<ol start="12">
<li><h3 id="heading-what-is-an-interface-and-why-do-you-use-it">What is an Interface and Why do you use it?</h3>
<p>The interface is a collection of methods as well as it is a custom type.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

    <span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

    <span class="hljs-comment">// Creating an interface</span>
    <span class="hljs-keyword">type</span> tank <span class="hljs-keyword">interface</span> {

        <span class="hljs-comment">// Methods</span>
        Tarea() <span class="hljs-keyword">float64</span>
        Volume() <span class="hljs-keyword">float64</span>
    }

    <span class="hljs-keyword">type</span> myvalue <span class="hljs-keyword">struct</span> {
        radius <span class="hljs-keyword">float64</span>
        height <span class="hljs-keyword">float64</span>
    }

    <span class="hljs-comment">// Implementing methods of</span>
    <span class="hljs-comment">// the tank interface</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(m myvalue)</span> <span class="hljs-title">Tarea</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {

        <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>*m.radius*m.height +
            <span class="hljs-number">2</span>*<span class="hljs-number">3.14</span>*m.radius*m.radius
    }

    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(m myvalue)</span> <span class="hljs-title">Volume</span><span class="hljs-params">()</span> <span class="hljs-title">float64</span></span> {

        <span class="hljs-keyword">return</span> <span class="hljs-number">3.14</span> * m.radius * m.radius * m.height
    }

    <span class="hljs-comment">// Main Method</span>
    <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

        <span class="hljs-comment">// Accessing elements of</span>
        <span class="hljs-comment">// the tank interface</span>
        <span class="hljs-keyword">var</span> t tank
        t = myvalue{<span class="hljs-number">10</span>, <span class="hljs-number">14</span>}
        fmt.Println(<span class="hljs-string">"Area of tank :"</span>, t.Tarea())
        fmt.Println(<span class="hljs-string">"Volume of tank:"</span>, t.Volume())
    }
</code></pre>
<p>Interfaces can make code clearer, shorter, more readable, and they can provide a good API between packages, or clients (users) and servers (providers).</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
</ol>
<ol start="13">
<li><h3 id="heading-what-are-concurrency-and-parralism-and-what-is-the-difference-between-both">What are concurrency and parralism and what is the difference between both?</h3>
<p><strong>Concurrency</strong> :<br />Defination 1 : Dealing with multiple things at once. <br />
Defination 2 : A Composition of independently executing processes(Example: suppose there are two tasks A and B , the way this work is A task done 70% meanwhile it has to wait for something , so it picks up task B and try to complete if suppose B task has to wait at 60% , for something then it picks up A task them completes it and comes back to B )    </p>
<p><strong>Parralism</strong> : 
Defination 1 : Parallelism is about doing lots of things at once. <br />
Defination 2 : It is the simultaneous execution of (possibly related) computations. (Example: suppose there are two tasks A and B , it takes both tasks and try to complete both together )</p>
<p><img src="/img/cocurrency_parllel.jpg" alt="cocurrency_parllel" /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-are-the-difference-between-goroutines-and-threads">What are the difference between goroutines and threads?</h3>
<p><strong>Threads</strong> : A thread is just a sequence of instructions that can be executed independently by a processor. Threads  use a lot of memory due to their large stack and requires call to OS for resources (such as memory) which is slow. so doesn’t always guarantee a better performance than processes in this multi-core processor world.</p>
<p><strong>Goroutines</strong>:Goroutines exists only in the virtual space of go runtime and not in the OS. and A goroutine is created with initial only 2KB of stack size. Each function in go already has a check if more stack is needed or not and the stack can be copied to another region in memory with twice the original size. This makes goroutine very light on resources.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-are-channels-for">What are channels for?</h3>
<p>Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>    </p>
</li>
<li><h3 id="heading-can-you-do-something-in-goroutines-using-channels">Can you do something in goroutines using channels?</h3>
<ul>
<li>Channels are goroutine-safe and can store and pass values between goroutines</li>
<li>Channels provide FIFO semantics.</li>
<li>Channels cause goroutines to block and unblock, which we just learned about. </li>
</ul>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-is-a-closure">What is a Closure?</h3>
<p>   A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables.<br /></p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-what-are-runtime-and-runtime-packages">What are runtime  and runtime packages?</h3>
<p>The runtime library implements garbage collection, concurrency, stack management, and other critical features of the Go language. The Package runtime contains operations that interact with Go's runtime system, such as functions to control goroutines.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-how-can-you-get-how-many-cores-your-computer-has">How can you get how many cores your computer has?</h3>
<p>With the help of runtime package</p>
<pre><code class="lang-go">   <span class="hljs-keyword">package</span> main

   <span class="hljs-keyword">import</span> (  
        <span class="hljs-string">"fmt"</span>
        <span class="hljs-string">"runtime"</span>
          )

      <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
      fmt.Println(runtime.NumCPU())
      }
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-how-would-you-tell-a-goroutine-to-use-less-core-than-what-you-have">How would you tell a goroutine to use less core than what you have?</h3>
<p>  We can restrict the number of goroutines running at the same time , like below</p>
<pre><code class="lang-go">    <span class="hljs-keyword">package</span> main

    <span class="hljs-keyword">import</span> (
      <span class="hljs-string">"flag"</span>
      <span class="hljs-string">"fmt"</span>
      <span class="hljs-string">"time"</span>
      <span class="hljs-string">"sync"</span>
  ) 

  <span class="hljs-comment">// Fake a long and difficult work.</span>
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">DoWork</span><span class="hljs-params">()</span></span> {
      time.Sleep(<span class="hljs-number">500</span> * time.Millisecond)
  }

  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
      maxNbConcurrentGoroutines := flag.Int(<span class="hljs-string">"maxNbConcurrentGoroutines"</span>, <span class="hljs-number">2</span>, <span class="hljs-string">"the number of goroutines that are allowed to run concurrently"</span>)
      nbJobs := flag.Int(<span class="hljs-string">"nbJobs"</span>, <span class="hljs-number">5</span>, <span class="hljs-string">"the number of jobs that we need to do"</span>)
      flag.Parse()

      concurrentGoroutines := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{}, *maxNbConcurrentGoroutines)

      <span class="hljs-keyword">var</span> wg sync.WaitGroup

      <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; *nbJobs; i++ {
          wg.Add(<span class="hljs-number">1</span>)
          <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-keyword">int</span>)</span></span> {
              <span class="hljs-keyword">defer</span> wg.Done()
              concurrentGoroutines &lt;- <span class="hljs-keyword">struct</span>{}{}
              fmt.Println(<span class="hljs-string">"doing"</span>, i)
              DoWork()
              fmt.Println(<span class="hljs-string">"finished"</span>, i)
              &lt;-concurrentGoroutines
          }(i)
      }
      wg.Wait()
  }
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>   </p>
</li>
<li><h3 id="heading-how-would-you-determine-the-type-of-a-variable-and-which-package-to-use-for-it">How would you determine the type of a variable and Which package to use for it?</h3>
<p>There are three different ways to find type of variable in Golang<br /></p>
<ul>
<li><p><strong>reflect.TypeOf Function</strong>: Using the golang inbuilt package reflect we can find the Type of variable</p>
<p>   ```go
       package main</p>
</li>
</ul>
</li>
</ol>
<p>                import (
                    "fmt"
                    "reflect"
                )</p>
<p>                func main(){
                var string_type =  "Hello Go";
                var complex_type =  complex(9, 15);</p>
<p>                 fmt.Println("string_type", reflect.TypeOf(string_type))
                 fmt.Println("complex_type = ", reflect.TypeOf(complex_type))
                }</p>
<pre><code>        * **reflect.ValueOf.Kind() <span class="hljs-built_in">Function</span>** : Using the golang inbuilt package reflect we can find the Type <span class="hljs-keyword">of</span> variable

             <span class="hljs-string">``</span><span class="hljs-string">`go
                package main


                import (
                    "fmt"
                    "reflect"
                )

                func main(){
                var string_type =  "Hello Go";
                var complex_type =  complex(9, 15);

                 fmt.Println("string_type", reflect.ValueOf(string_type).Kind())
                 fmt.Println("complex_type = ", reflect.TypeOf(complex_type).Kind())
                }</span>
</code></pre><ul>
<li><p><strong>%T with Printf</strong> : You can use Printf also to find value of variable</p>
<p>  ```go
      package main</p>
</li>
</ul>
<p>                import (
                    "fmt"
                    "reflect"
                )</p>
<p>                func main(){
                var string_type =  "Hello Go";
                var complex_type =  complex(9, 15);</p>
<p>                 fmt.Printf("string_type=%T\n", string_type)
                 fmt.Printf("complex_type =%T\n", complex_type)
                }</p>
<pre><code>
      **[ Back to Top ⬆ ](#table-<span class="hljs-keyword">of</span>-contents---golang)**   




  <span class="hljs-number">22.</span> ### What all types can map store?
      **Value** - The Value type <span class="hljs-keyword">of</span> a mpa can be anything, including another map &lt;br/&gt;
      **Key** - The key type <span class="hljs-keyword">of</span> <span class="hljs-built_in">Map</span> can only be values that can be compared i.e - boolean, numeric, string, pointer, channel, and interface types, and structs or arrays , that excludes - slices, maps, and functions 

      **[ Back to Top ⬆ ](#table-<span class="hljs-keyword">of</span>-contents---golang)**   

  <span class="hljs-number">23.</span> ### What are microservices?
      Microservices is an architectural style that structures an application <span class="hljs-keyword">as</span> a collection <span class="hljs-keyword">of</span> services that are
        * Highly maintainable and testable
        * Loosely coupled
        * Independently deployable
        * Organized around business capabilities
        * Owned by a small team &lt;br/&gt;

      **[ Back to Top ⬆ ](#table-<span class="hljs-keyword">of</span>-contents---golang)**   

  <span class="hljs-number">24.</span> ### Why are there no classes <span class="hljs-keyword">in</span> Go ?

      Go doesn<span class="hljs-string">'t require an explicit class definition as Java, C++, C#, etc do.  Instead, a "class" is implicitly defined by providing a set of "methods" which operate on a common type.  The type may be a struct or any other user-defined type.  For example:

      ```go
      type Integer int;
        func (i *Integer) String() string {
            return strconv.itoa(i)
        }</span>
</code></pre><p>      is analogous to below code in java:<br /></p>
<pre><code class="lang-java">      <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Integer</span> </span>{
            <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> i;
            <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> Integer.toString(i); }
        }
</code></pre>
<p>  <strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
<ol start="25">
<li><h3 id="heading-difference-between-compile-time-and-runtime">Difference between Compile time and runtime?</h3>
<p><strong>Compile-time</strong> is the time at which the source code is converted into an executable code <br />
<strong>Run time</strong> is the time at which the executable code is started running.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
</ol>
<ol start="26">
<li><h3 id="heading-how-to-generate-a-true-random-number-in-golang">How to generate a true random number in golang?</h3>
<p>The default number generator is deterministic, so it’ll produce the same sequence of numbers each time by default , so you need to seed it with different number you can do it with nano seconds like below <br /></p>
<pre><code class="lang-go">   <span class="hljs-keyword">package</span> main
  <span class="hljs-keyword">import</span> (
      <span class="hljs-string">"fmt"</span>
      <span class="hljs-string">"math/rand"</span>
       <span class="hljs-string">"time"</span>
      )
  <span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
  s1 := rand.NewSource(time.Now().UnixNano())
  r1 := rand.New(s1)
   fmt.Print(r1.Intn(<span class="hljs-number">100</span>))
   }
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
</ol>
<ol start="27">
<li><h3 id="heading-why-are-goroutines-light-weight">Why are goroutines light-weight?</h3>
<p>A goroutine is created with initial only 2KB of stack size. Each function in go already has a check if more stack is needed or not and the stack can be copied to another region in memory with twice the original size. This makes goroutine very light</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
<li><h3 id="heading-if-capacity-is-not-defined-in-slice-what-would-the-capacity-be">If capacity is not defined in slice, what would the capacity be?</h3>
<p>It would be set by default to length of the slice </p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
<li><h3 id="heading-what-is-the-easiest-way-to-check-if-a-slice-is-empty">What is the easiest way to check if a slice is empty?</h3>
<p> You can use the length (len(slice)) property to find if the slice is empty</p>
<pre><code class="lang-go">  <span class="hljs-keyword">if</span>(<span class="hljs-built_in">len</span>(slice_data)==<span class="hljs-number">0</span>){
  fmt.Println(<span class="hljs-string">"Empty slice"</span>)
  }
</code></pre>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
<li><h3 id="heading-what-is-an-advantage-of-go-evaluating-implicit-types-at-compile-time">What is an advantage of Go evaluating implicit types at compile time?</h3>
<p>Types can be implicitly inferred from expressions and don’t need to be explicitly specified.The special handling of interfaces and the implicit typing makes Go feel very lightweight and dynamic.</p>
<p><strong><a class="post-section-overview" href="#table-of-contents---golang"> Back to Top ⬆ </a></strong>  </p>
</li>
</ol>
<h3 id="heading-table-of-contents-database-engineering">Table of Contents - Database Engineering</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>No.</td><td>Questions</td></tr>
</thead>
<tbody>
<tr>
<td></td><td><strong>Database Engineering</strong></td></tr>
<tr>
<td>1</td><td><a class="post-section-overview" href="#what-is-acid-model-in-database">What is ACID Model in Database?</a></td></tr>
<tr>
<td>2</td><td><a class="post-section-overview" href="#what-does-acid-acronym-mean">What does ACID acronym mean?</a></td></tr>
<tr>
<td>3</td><td><a class="post-section-overview" href="#explain-in-brief-the-acid-model">Explain in brief the ACID Model?</a></td></tr>
<tr>
<td>4</td><td><a class="post-section-overview" href="#what-are-the-read-phenomena-in-isolation">What are the read phenomena in Isolation?</a></td></tr>
<tr>
<td>5</td><td><a class="post-section-overview" href="#what-are-the-four-isolation-levels">What are the four Isolation levels?</a></td></tr>
<tr>
<td>6</td><td><a class="post-section-overview" href="#which-isolation-levels-can-prevent-problems-that-occur-in-read-phenomena">Which isolation levels can prevent problems that occur in read phenomena?</a></td></tr>
<tr>
<td>7</td><td><a class="post-section-overview" href="#what-does-eventually-consistent-mean">What does Eventually Consistent Mean?</a></td></tr>
<tr>
<td>8</td><td><a class="post-section-overview" href="#what-is-indexing-in-sql">What is indexing in SQL?</a></td></tr>
<tr>
<td>9</td><td><a class="post-section-overview" href="#how-does-sql-create-an-index">How does SQL create an Index?</a></td></tr>
<tr>
<td>10</td><td><a class="post-section-overview" href="#what-is-difference-between-index-scan-and-index-only-scan">What is difference between index scan and index only scan?</a></td></tr>
</tbody>
</table>
</div><ol>
<li><h3 id="heading-what-is-acid-model-in-database">What is ACID Model in Database?</h3>
<p> The ACID database transaction model ensures that a performed transaction is always consistent. This makes it a good fit for businesses which deal with online transaction processing (e.g: finance institutions) or online analytical processing (e.g: data warehousing). These organizations need database systems which can handle many small simultaneous transactions. There must be zero tolerance for invalid states</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
<ol start="2">
<li><h3 id="heading-what-does-acid-acronym-mean">What does ACID acronym mean?</h3>
<ul>
<li>A - Atomicity</li>
<li>C - Consistency</li>
<li>I - Isolation</li>
<li>D - Durability</li>
</ul>
</li>
<li><h3 id="heading-explain-in-brief-the-acid-model">Explain in brief the ACID Model?</h3>
<ul>
<li><strong>Atomicity</strong>: Each transaction is either properly carried out or the process halts and the database reverts back to the state before the transaction started. This ensures that all data in the database is valid .<br /></li>
<li><strong>Consistency</strong>: The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database , also a DB should have Atomicity and Isolation for this property.<br /></li>
<li><strong>Isolation</strong>: Any reads or writes performed on the database should not be impacted by other reads and writes of separate transactions occurring on the same database.<br /></li>
<li><strong>Durability</strong>: The database should be durable enough to hold all its latest updates even if the system fails or restarts .</li>
</ul>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
<ol start="4">
<li><h3 id="heading-what-are-the-read-phenomena-in-isolation">What are the read phenomena in Isolation?</h3>
<ul>
<li><strong>Dirty Read</strong>:A Dirty read is the situation when a transaction reads a data that has not yet been committed .<br /></li>
<li><strong>Non Repeatable read</strong>: Non Repeatable read occurs when a transaction reads same row twice, and get a different value each time.<br /></li>
<li><strong>Phantom Read</strong>:  Phantom Read occurs when two same queries are executed, but the rows retrieved by the two, are differen i.e a new row might have been inserted or deleted</li>
</ul>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
<ol start="5">
<li><h3 id="heading-what-are-the-four-isolation-levels">What are the four Isolation levels?</h3>
<ul>
<li><p><strong>Read Uncommitted</strong> – Read Uncommitted is the lowest isolation level. In this level, one transaction may read not yet committed changes made by other transaction</p>
</li>
<li><p><strong>Read Committed</strong> – This isolation level guarantees that any data read is committed at the moment it is read. Thus it does not allows dirty read. The transaction holds a read or write lock on the current row, and thus prevent other transactions from reading, updating or deleting it.</p>
</li>
<li><p><strong>Repeatable Read</strong> - This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on all rows it inserts, updates, or deletes. Since other transaction cannot read, update or delete these rows, consequently it avoids non-repeatable read.</p>
</li>
<li><p><strong>Serializable</strong> - Transactions are serialized , occur one by one</p>
</li>
</ul>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
</li>
<li><h3 id="heading-which-isolation-levels-can-prevent-problems-that-occur-in-read-phenomena">Which isolation levels can prevent problems that occur in read phenomena?</h3>
<p> Refer Image for a comparison  </p>
<p>  <img src="/img/acid.png" alt="isolation" /></p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
<ol start="7">
<li><h3 id="heading-what-does-eventually-consistent-mean">What does Eventually Consistent Mean ?</h3>
<p> <strong>Eventual Consistency</strong> concept is that while a database may have some inconsistencies at any point in time, it will eventually become consistent when all updates cease i.e eventually all nodes will receive the latest consistent updates.</p>
</li>
</ol>
<p><strong><a class="post-section-overview" href="#table-of-contents---database-engineering"> Back to Top ⬆ </a></strong></p>
]]></content:encoded></item><item><title><![CDATA[Nodejs Interview Prep]]></title><description><![CDATA[Node.js is an open-source, cross-platform JavaScript runtime environment that executes code outside of a web browser. It is built on V8, the same…]]></description><link>https://articles.tkssharma.com/nodejs-interview-prep</link><guid isPermaLink="true">https://articles.tkssharma.com/nodejs-interview-prep</guid><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Fri, 11 Oct 2024 14:20:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728656393844/39b820e0-8b70-43a8-acae-764efa508b38.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-100-must-know-nodejs-interview-questions">100 Must-Know Node.js Interview Questions</h1>
<h2 id="heading-1-what-is-nodejs-and-why-is-it-used">1. What is Node.js and why is it used?</h2>
<p><strong>Node.js</strong> is an open-source, cross-platform JavaScript runtime environment that executes code outside of a web browser. It is built on V8, the same JavaScript engine within Chrome, and optimized for high performance. This environment, coupled with an event-driven, non-blocking I/O framework, is tailored for server-side web development and more.</p>
<h3 id="heading-key-features">Key Features</h3>
<ul>
<li><strong>Asynchronous &amp; Non-Blocking</strong>: Ideal for handling a myriad of concurrent connections with efficiency.</li>
<li><strong>V8 Engine</strong>: Powered by Google's V8, Node.js boasts top-tier JavaScript execution.</li>
<li><strong>Libuv Library</strong>: Ensures consistent performance across platforms and assists in managing I/O operations.</li>
<li><strong>NPM</strong>: A vast package ecosystem simplifies module management and deployment.</li>
<li><strong>Full-Stack JavaScript</strong>: Allows for unified server and client-side code in JavaScript.</li>
</ul>
<h3 id="heading-use-cases">Use Cases</h3>
<ul>
<li><strong>Data Streaming</strong>: Suited for real-time streaming of audio, video, and lightweight data.</li>
<li><strong>API Servers</strong>: Ideal for building fast, scalable, and data-intensive applications.</li>
<li><strong>Microservices</strong>: Its module-oriented design facilitates the development of decoupled, independently scalable services.</li>
<li><strong>Single Page Applications</strong>: Often used with frameworks like Angular, React, or Vue to craft robust, server-side backends.</li>
<li><strong>Chat Applications</strong>: Its real-time capabilities are advantageous in building instant messaging systems.</li>
<li><strong>Internet of Things (IoT)</strong>: Provides a lightweight environment for running applications on constrained devices like Raspberry Pi.</li>
</ul>
<h3 id="heading-why-nodejs">Why Node.js?</h3>
<ul>
<li><strong>Unified Language</strong>: Utilizing JavaScript both on the frontend and backend brings coherence to development efforts, potentially reducing debugging time and enabling shared libraries.</li>
<li><strong>NPM Ecosystem</strong>: The NPM repository offers myriad open-source packages, empowering rapid development and feature expansion.</li>
<li><strong>Rapid Prototyping</strong>: Express, a minimalist web framework for Node.js, and NPM's wealth of modules expedite early application development and testing.</li>
<li><strong>Scalability</strong>: Cluster modules, load balancers, and Microservice Architecture aid in linear, on-demand scaling for both simple and intricate applications.</li>
<li><strong>Real-Time Power</strong>: With built-in WebSockets and event-based architecture, Node.js excels in constructing real-time applications such as multiplayer games, stock trading platforms, and chat applications.</li>
<li><strong>Open Source</strong>: Being an open-source technology, Node.js continuously benefits from community contributions, updates, and enhanced packages.
<br /></li>
</ul>
<h2 id="heading-2-how-does-nodejs-handle-child-threads">2. How does Node.js handle child threads?</h2>
<p><strong>Node.js</strong> employs event-driven architecture and non-blocking I/O for efficiency.</p>
<p>While Node.js <strong>operates off a single main thread</strong>, it can harness the full power of multi-core systems by launching child threads for specific tasks, such as file compression or image processing.</p>
<h3 id="heading-thread-pool-and-worker-threads">Thread Pool and Worker Threads</h3>
<p>To manage these child threads, Node.js uses a combination of:</p>
<ul>
<li>A <strong>thread pool</strong>, powered by the libuv library.</li>
<li><strong>Worker threads</strong> for dedicated, offloaded computation.</li>
</ul>
<h3 id="heading-nodejs-event-loop">Node.js Event Loop</h3>
<p>When a task in Node.js is designated to operate on a child thread, the main event loop hands it over to the thread pool. This setup allows Node.js to <strong>stay responsive to incoming requests</strong>, benefiting from asynchronous I/O.</p>
<p>The main event loop regains control once the task on the child thread is completed, and results are ready.</p>
<h3 id="heading-advantages">Advantages</h3>
<ul>
<li><strong>Boosted Efficiency</strong>: Offloading certain tasks to worker threads prevents I/O or computation-heavy jobs from blocking the event loop.</li>
<li><strong>Convenient Multi-Threading</strong>: Node.js enables multi-threading without the complexities of managing threads directly.</li>
</ul>
<h3 id="heading-code-example-basic-multi-threading-task">Code Example: Basic Multi-Threading Task</h3>
<p>Here is the JavaScript code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import the built-in 'worker_threads' module</span>
<span class="hljs-keyword">const</span> { Worker, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);

<span class="hljs-comment">// Check if it's the main module</span>
<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-comment">// Create a new child worker</span>
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> Worker(__filename);

  <span class="hljs-comment">// Listen for messages from the worker</span>
  worker.on(<span class="hljs-string">'message'</span>, <span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received:'</span>, message));

  <span class="hljs-comment">// Send a message to the worker</span>
  worker.postMessage(<span class="hljs-string">'Hello from the main thread!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Listen for messages from the main thread</span>
  parentPort.on(<span class="hljs-string">'message'</span>, <span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received in the worker:'</span>, message);
    <span class="hljs-comment">// Send a message back to the main thread</span>
    parentPort.postMessage(<span class="hljs-string">'Hello from the worker thread!'</span>);
  });
}
</code></pre>
<p><br /></p>
<h2 id="heading-3-describe-the-event-driven-programming-in-nodejs">3. Describe the event-driven programming in Node.js.</h2>
<p><strong>Event-driven programming,</strong> a hallmark of Node.js, uses an <strong>event, listener,</strong> and <strong>emitter</strong> architecture to handle asynchronous tasks. This design centers around events and how they trigger actions in the attached listeners.</p>
<h3 id="heading-core-components">Core Components</h3>
<ul>
<li><p><strong>Event Emitter</strong>: Acts as the event registry and dispatcher, letting objects register interest in particular events and emit these events when they occur.</p>
</li>
<li><p><strong>Event Handler (Listener)</strong>: Associates with a particular event through registration. These callback functions will be asynchronously carried out when a matching event is emitted.</p>
</li>
</ul>
<h4 id="heading-code-example-event-emitter-and-handlers">Code Example: Event Emitter and Handlers</h4>
<p>Here is the Node.js code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { EventEmitter } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

emitter.on(<span class="hljs-string">'event-name'</span>, <span class="hljs-function">(<span class="hljs-params">eventArgs</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Event-name was emitted with arguments: <span class="hljs-subst">${eventArgs}</span>`</span>);
});

emitter.emit(<span class="hljs-string">'event-name'</span>, <span class="hljs-string">'Some Payload'</span>);
</code></pre>
<p>In this code, when <code>emit</code> is called, the <code>on</code> method's callback is executed asynchronously.</p>
<h3 id="heading-event-loop-mechanism-in-nodejs">Event Loop Mechanism in Node.js</h3>
<ul>
<li><p><strong>Call Stack</strong>: Maintains the call order of the functions and methods being executed.</p>
</li>
<li><p><strong>Node APIs</strong> and <strong>Callbacks Queue</strong>: Handle I/O tasks and timers.</p>
</li>
<li><p><strong>Event Loop</strong>: Constantly watches the execution stack and checks whether it's clear to execute pending tasks from the Callback Queue.</p>
</li>
</ul>
<h3 id="heading-practical-applications-in-nodejs">Practical Applications in Node.js</h3>
<ul>
<li><p><strong>HTTP Server</strong>: Listens for and serves requests.</p>
</li>
<li><p><strong>File System Operations</strong>: Execute I/O tasks.</p>
</li>
<li><p><strong>Database Operations</strong>: Such as data retrieval.
<br /></p>
</li>
</ul>
<h2 id="heading-4-what-is-the-event-loop-in-nodejs">4. What is the event loop in Node.js?</h2>
<p>The <strong>event loop</strong> is a fundamental concept in Node.js for managing asynchronous operations. Its efficiency is a key reason behind Node.js's high performance.</p>
<h3 id="heading-how-does-the-event-loop-work">How Does the Event Loop Work?</h3>
<ol>
<li><p><strong>Initialization</strong>: When Node.js starts, it initializes the <strong>event loop</strong> to watch for I/O operations and other asynchronous tasks.</p>
</li>
<li><p><strong>Queueing</strong>: Any task or I/O operation is added to a <strong>queue</strong>, which can be either the <code>microtask queue</code> or the <code>macrotask/Callback queue</code>.</p>
</li>
<li><p><strong>Polling</strong>: The event loop iteratively checks for tasks in the queue while also <strong>waiting</strong> for I/O and timers.</p>
</li>
<li><p><strong>Execution Phases</strong>: When the event loop detects tasks in the queue, it executes them in specific phases, ensuring order efficiency.</p>
</li>
</ol>
<h3 id="heading-task-scheduler-zones-microtask-and-callback-queue">Task Scheduler Zones: microtask and Callback Queue</h3>
<ul>
<li><strong>Microtask Queue</strong>: This is a highly prioritized queue, usually acting over tasks in the <strong>Callback Queue</strong>. Useful for tasks that require immediate attention.</li>
<li><strong>Callback Queue (Macrotask Queue)</strong>: Also known as the 'Task Queue,' it manages events and I/O operations.</li>
</ul>
<h3 id="heading-event-loop-phases">Event Loop Phases</h3>
<ul>
<li><strong>Timers</strong>: Manages timer events for scheduled tasks.</li>
<li><strong>Pending callbacks</strong>: Handles system events such as I/O, which are typically queued by the kernel.</li>
<li><strong>Idle / prepare</strong>: Ensures internal actions are managed before I/O events handling.</li>
<li><strong>Poll</strong>: Retrieves New I/O events.</li>
<li><strong>Check</strong>: Executes 'setImmediate' functions.</li>
<li><strong>Close</strong>: Handles close events, such as 'socket.close'.</li>
</ul>
<h3 id="heading-task-scheduling-microtasks-and-macrotasks">Task Scheduling: microtasks and macrotasks</h3>
<ul>
<li><strong>Microtasks (process.nextTick and Promises)</strong>: Executed after each task.</li>
<li><strong>Macrotasks</strong>: Executed after the poll phase when the event loop is not behind any file I/O or scheduled time. This includes timers, setImmediate, and I/O events.</li>
</ul>
<h3 id="heading-code-example-timers-and-task-queues">Code Example: Timers and Task Queues</h3>
<p>Here is the JavaScript code:</p>
<p><strong>Node.js</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Code Example</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Start'</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {  
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Set Timeout - 1'</span>);

  <span class="hljs-built_in">Promise</span>.resolve().then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Promise - 1'</span>);
  }).then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Promise - 2'</span>);
  });

}, <span class="hljs-number">0</span>);

setImmediate(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Set Immediate'</span>);
});

process.nextTick(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Next Tick'</span>);
  <span class="hljs-comment">// It's like an infinite loop point for microtask queue</span>
  process.nextTick(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Next Tick - nested'</span>));
});

fs.readFile(file, <span class="hljs-string">'utf-8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'File Read'</span>);
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'End'</span>);
</code></pre>
<p><br /></p>
<h2 id="heading-5-what-is-the-difference-between-nodejs-and-traditional-web-server-technologies">5. What is the difference between Node.js and traditional web server technologies?</h2>
<p><strong>Node.js</strong> revolutionized server-side development with its non-blocking, event-driven architecture. Let's look at how it differs from traditional web servers and how it leverages a <strong>Single Input-Output (I/O)</strong> model.</p>
<h3 id="heading-key-distinctions">Key Distinctions</h3>
<h4 id="heading-multi-threading-traditional-servers-vs-event-loop-nodejs">Multi-threading (Traditional Servers) vs. Event Loop (Node.js)</h4>
<ul>
<li><strong>Traditional Servers</strong>: Employ multi-threading. Each client request spawns a new thread, requiring resources even when idle.</li>
<li><strong>Node.js</strong>: Utilizes a single-thread with non-blocking, asynchronous functions for I/O tasks. This makes it exceptionally suitable for scenarios like real-time updates and microservices.</li>
</ul>
<h4 id="heading-blocking-vs-non-blocking-io">Blocking vs. Non-blocking I/O</h4>
<ul>
<li><strong>Traditional Servers</strong>: Primarily rely on blocking I/O, meaning that the server waits for each I/O operation to finish before moving on to the next task.</li>
<li><strong>Node.js</strong>: Leverages non-blocking I/O, allowing the server to continue handling other tasks while waiting for I/O operations. Callbacks, Promises, and async/await support this approach.</li>
</ul>
<h4 id="heading-language-consistency">Language Consistency</h4>
<ul>
<li><strong>Traditional Servers</strong>: Often pair with languages like Java, C#, or PHP for server-side logic. Front-end developers might need to be proficient in both the server language and client-side technologies like JavaScript.</li>
<li><strong>Node.js</strong>: Employs JavaScript both client-side and server-side, fostering full-stack developer coherence and code reusability.</li>
</ul>
<h4 id="heading-code-execution">Code Execution</h4>
<ul>
<li><strong>Traditional Servers</strong>: Generally compile and execute code. Alterations might necessitate recompilation and possible downtime.</li>
<li><strong>Node.js</strong>: Facilitates a "write, save, and run" approach, without the need for recompilation.</li>
</ul>
<h4 id="heading-package-management">Package Management</h4>
<ul>
<li><strong>Traditional Servers</strong>: Rely on package managers like Maven or NuGet, with each language typically having its own package dependency system.</li>
<li><strong>Node.js</strong>: Centralizes dependency management via npm, simplifying the sharing and integration of libraries.</li>
</ul>
<h4 id="heading-deployment">Deployment</h4>
<ul>
<li><strong>Traditional Servers</strong>: Often necessitate coordination with systems, database administrators, and IT teams for deployment.</li>
<li><strong>Node.js</strong>: Offers flexible, straightforward deployments. It's especially suited for cloud-native applications.</li>
</ul>
<h3 id="heading-use-cases-1">Use Cases</h3>
<ul>
<li><strong>Traditional Servers</strong>: Ideal for enterprise systems, legacy applications, or when extensive computational tasks are required.</li>
<li><strong>Node.js</strong>: Well-suited for data-intensive, real-time applications like collaborative tools, gaming, or social media platforms. Its lightweight, scalable nature also complements cloud deployments.
<br /></li>
</ul>
<h2 id="heading-6-explain-what-non-blocking-means-in-nodejs">6. Explain what "non-blocking" means in Node.js.</h2>
<p><strong>Node.js leverages non-blocking I/O</strong> to handle multiple operations without waiting for each to complete separately.</p>
<p>This particular I/O model, coupled with the event-driven paradigm of Node.js, is key to its high performance and scalability, making it <strong>ideal</strong> for tasks such as data streaming, background tasks, and concurrent operations.</p>
<h3 id="heading-non-blocking-io">Non-Blocking I/O</h3>
<p>With non-blocking I/O, an application <strong>doesn't halt</strong> or wait for a resource to become available. Instead, it goes on executing other tasks that don't depend on that resource.</p>
<p>For instance, if a file operation is in progress, Node.js doesn't pause the entire application until the file is read or written. This allows for a more responsive and efficient system, especially when handling multiple, concurrent I/O operations.</p>
<h3 id="heading-event-loop">Event Loop</h3>
<p>Node.js constantly monitors tasks and I/O operations. When a task or operation is ready, it triggers an event. This mechanism is referred to as the <strong>event loop</strong>.</p>
<p>When an event fires, a corresponding event handler or callback function is executed.</p>
<h3 id="heading-concurrency-without-threads">Concurrency Without Threads</h3>
<p>Traditionally, concurrency can be achieved in languages that support multithreading (e.g., Java). However, managing and coordinating multiple threads can be challenging and is a common source of bugs.</p>
<p>Node.js, on the other hand, provides a simplified yet effective concurrency model using non-blocking I/O and the event loop. It achieves parallelism through mechanisms such as <strong>callbacks</strong>, <strong>Promises</strong>, and <strong>async/await</strong>.</p>
<p>By not using threads, Node.js eliminates many of the complexities associated with traditional multithreaded architectures, making it easier to <strong>develop</strong> and <strong>maintain</strong> applications, particularly those requiring high concurrency.</p>
<h3 id="heading-code-example-file-io">Code Example: File I/O</h3>
<p>Here is the JavaScript code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// Perform non-blocking file read operation</span>
fs.readFile(<span class="hljs-string">'path/to/file'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    <span class="hljs-built_in">console</span>.log(data);
});

<span class="hljs-comment">// Other non-blocking operations continue without waiting for file read</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This message is displayed immediately.'</span>);
</code></pre>
<p>In this example, the file read operation is non-blocking. Node.js does not halt the thread of execution to wait for the file read to complete. Instead, the supplied callback function is invoked when the read operation finishes.
<br /></p>
<h2 id="heading-7-how-do-you-update-nodejs-to-the-latest-version">7. How do you update Node.js to the latest version?</h2>
<p>Regular updates ensure that your <strong>Node.js</strong> setup is secure, efficient, and equipped with the latest features. Here's how to keep it up-to-date.</p>
<h3 id="heading-using-package-managers">Using Package Managers</h3>
<ul>
<li><p><strong>NPM</strong>: Run the following commands to find and install the latest stable version of Node.js:</p>
<pre><code class="lang-shell">npm cache clean -f
</code></pre>
<pre><code class="lang-shell">npm install -g n
</code></pre>
</li>
<li><p><strong>Yarn</strong>: Execute the following command that fetches the latest version and updates Node.js in your system:</p>
<pre><code class="lang-shell">yarn global add n
</code></pre>
</li>
</ul>
<h3 id="heading-using-the-official-installer">Using the Official Installer</h3>
<p>You can use the official installer to upgrade to the latest stable version.</p>
<h3 id="heading-version-management-tools">Version Management Tools</h3>
<p>Tools like <strong>nvm</strong> (Node Version Manager), <strong>n</strong> (Node Version Manager) and <strong>nvs</strong> (Node Version Switcher) can be convenient for managing multiple Node.js versions and performing updates.</p>
<h3 id="heading-windows-via-scoop">Windows via Scoop</h3>
<p>On Windows, <strong>Scoop</strong> simplifies the task of updating:</p>
<pre><code class="lang-shell">scoop update nodejs-lts
</code></pre>
<h3 id="heading-check-the-updated-version">Check the Updated Version</h3>
<p>Verify that the update was successful by checking the version number:</p>
<pre><code class="lang-shell">node -v
</code></pre>
<p><br /></p>
<h2 id="heading-8-what-is-npm-and-what-is-it-used-for">8. What is "npm" and what is it used for?</h2>
<p><strong>npm (Node Package Manager)</strong> is a powerful and highly popular package manager that is focused on the Node.js environment. Its primary purpose is to simplify the installation, management, and sharing of libraries or tools written in Node.js.</p>
<p>npm is more than just a package manager: It's also a thriving ecosystem, offering a plethora of ready-to-use modules and tools, thereby making the development workflow for Node.js even more efficient.</p>
<h3 id="heading-key-functions">Key Functions</h3>
<ul>
<li><p><strong>Package Installation</strong>: npm makes it easy to install and specify dependencies for Node.js applications. Developers can simply define required packages in a <code>package.json</code> file, and npm resolves and installs all dependencies.</p>
</li>
<li><p><strong>Dependency Management</strong>: npm establishes a tiered dependency system, effectively managing the versions and interdependencies of various packages.</p>
</li>
<li><p><strong>Registry Access</strong>: It acts as a central repository for Node.js packages, where developers can host, discover, and access modules.</p>
</li>
<li><p><strong>Version Control</strong>: npm enables version control to ensure consistent and predictable package installations. It supports features such as semantic versioning and lock files.</p>
</li>
<li><p><strong>Lifecycle Scripts</strong>: It allows developers to define custom scripts for tasks like application start or build, making it convenient to execute routine operations.</p>
</li>
<li><p><strong>Packaging and Publication</strong>: Developers can use npm to bundle their applications and publish them, ready for use by others.</p>
</li>
</ul>
<h3 id="heading-npm-client-and-registry">npm Client and Registry</h3>
<ul>
<li><p>The <strong>npm client</strong> is the command-line tool that developers interact with locally. It provides a set of commands to manage a project's packages, scripts, and configuration.</p>
</li>
<li><p>The <strong>npm registry</strong> is a global, central database of published Node.js packages. It's where modules and libraries are made available to the Node.js community. The official, public registry is managed by npm, Inc.</p>
</li>
</ul>
<h3 id="heading-npm-vs-yarn">npm vs yarn</h3>
<ul>
<li><strong>yarn</strong> is another popular package manager, introduced by Facebook. Like npm, it's designed for Node.js and excels in areas like performance and determinism. However, both npm and yarn are continuously evolving, and their differences are becoming more nuanced.</li>
</ul>
<h3 id="heading-famous-commands">Famous Commands</h3>
<ul>
<li><strong>install</strong>: This command downloads and installs the specified packages and their dependencies.</li>
<li><strong>init</strong>: This command initializes a <code>package.json</code> file for the project.</li>
<li><strong>start</strong>: This command typically begins the execution of a Node.js application, as specified in the <code>scripts</code> section of <code>package.json</code>.</li>
<li><strong>publish</strong>: This command is used to publish the package to the npm registry.</li>
</ul>
<h3 id="heading-npm-scripts">npm Scripts</h3>
<p>One of the key features of npm is the ability to define scripts in the <code>package.json</code> file, executing them with the <code>npm run</code> command. This allows for automation of tasks such as testing, building, and starting the application.</p>
<p>These scripts have access to a variety of built-in and environment-specific variables, helping you to customize the script's behavior.</p>
<p>For example:</p>
<p>In <code>package.json</code>:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node server.js"</span>
  }
}
</code></pre>
<p>You can then execute:</p>
<pre><code class="lang-sh">npm start
</code></pre>
<p>to start the server.</p>
<h3 id="heading-npm-web-interface">npm Web Interface</h3>
<p>While most developers interact with npm via the command line, it also offers a web interface called <code>npmjs.com</code>. The website allows users to search for packages, view documentation, and explore related modules. It is also where developers publish and manage their packages.
<br /></p>
<h2 id="heading-9-how-do-you-manage-packages-in-a-nodejs-project">9. How do you manage packages in a Node.js project?</h2>
<p><strong>Node.js</strong> utilizes <strong>npm</strong> (Node Package Manager) or yarn for <strong>package management</strong>.</p>
<h3 id="heading-npm-vs-yarn-1">npm vs. Yarn</h3>
<p>Both tools create a <code>node_modules</code> folder, but they have subtle differences:</p>
<ul>
<li><strong>Yarn's</strong> <code>yarn.lock</code> provides deterministic package versions, while npm uses <code>package-lock.json</code>.</li>
<li>npm uses <code>npm install</code> while Yarn uses <code>yarn add</code> to install a package.</li>
</ul>
<p>Yarn also has advanced features like parallel package installations and a lockfile ensuring consistent installations across machines.</p>
<h3 id="heading-core-npm-commands">Core npm Commands</h3>
<ul>
<li><strong>npm init</strong>: Initializes a new project and creates a <code>package.json</code> file.</li>
<li><strong>npm install [package] (-D)</strong>: Installs a package and updates the <code>package.json</code> file. The <code>-D</code> flag indicates a devDependency.</li>
<li><strong>npm update [package]</strong>: Updates installed packages to their latest versions.</li>
</ul>
<h4 id="heading-using-npm-scripts">Using npm Scripts</h4>
<p>The <code>package.json</code> can include custom scripts for tasks like testing, building, and deployment, opening up the terminal from the current project directory and running <code>npm run SCRIPT_NAME</code>.</p>
<h4 id="heading-cli-examples">CLI Examples</h4>
<ul>
<li><strong>Install lodash</strong>: <code>npm install lodash</code></li>
<li><strong>Install express and save as a devDependency</strong>: <code>npm install express --save-dev</code></li>
<li><strong>Update all packages</strong>: <code>npm update</code>
<br /></li>
</ul>
<h2 id="heading-10-what-is-a-packagejson-file">10. What is a package.json file?</h2>
<p>The <strong>package.json</strong> file in Node.js projects contains valuable information, such as project metadata and dependencies. This file is essential for managing project modules, scripts, and version control and helps ensure the consistency and stability of your project.</p>
<h3 id="heading-key-elements">Key Elements</h3>
<p>The <code>package.json</code> file consists of several essential sections:</p>
<ol>
<li><p><strong>Name and Version</strong>: Required elements that identify the project and its version.</p>
</li>
<li><p><strong>Dependencies</strong>: Separated into <code>dependencies</code>, <code>devDependencies</code>, and <code>optionalDependencies</code> which list package dependencies needed for development, production, or as optional features, respectively.</p>
</li>
<li><p><strong>Scripts</strong>: Encompasses a series of custom commands, managed by npm or yarn, that can be executed to perform various tasks.</p>
</li>
<li><p><strong>Git Repository Information</strong>: Optional but helpful for version control.</p>
</li>
<li><p><strong>Project Metadata</strong>: Such as the description and the author-related details.</p>
</li>
<li><p><strong>Peer Dependencies</strong>: A list of dependencies that must be installed alongside the module but are not bundled with it.</p>
</li>
<li><p><strong>Private/Public Status</strong>: Indicates whether the package is publicly available.</p>
</li>
</ol>
<h3 id="heading-creating-packagejson">Creating <code>package.json</code></h3>
<p>You can <strong>generate</strong> the initial <code>package.json</code> file by running <code>npm init</code> or <code>yarn init</code> in the project directory. This command will guide you through a set of interactive prompts to configure your project.</p>
<h3 id="heading-managing-dependencies">Managing Dependencies</h3>
<h4 id="heading-adding-packages">Adding Packages</h4>
<p>To add a package to your project, use <code>npm install package-name</code> or <code>yarn add package-name</code>. This will also automatically update your <code>package.json</code> file.</p>
<h4 id="heading-removing-packages">Removing Packages</h4>
<p>Remove a package from the project and update the <code>package.json</code> file by running <code>npm uninstall package-name</code> or <code>yarn remove package-name</code>.</p>
<h3 id="heading-scripts">Scripts</h3>
<p>The <code>scripts</code> section allows you to define <strong>task shortcuts</strong>. Each entry is a command or group of sub-commands that can be invoked via <code>npm run</code> or <code>yarn run</code>.</p>
<p>For example, the following <code>scripts</code> section would enable the executing of <code>babel src -d lib</code> by running <code>npm run build</code>.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"babel src -d lib"</span>
  }
}
</code></pre>
<h3 id="heading-using-packagejson-in-cicd-pipelines">Using <code>package.json</code> in CI/CD Pipelines</h3>
<p>When using services like Travis CI, the <code>package.json</code> file is crucial for both setting the project environment and defining any required test steps and deployment commands.</p>
<p>For instance, you might use the <code>scripts</code> section to specify the test command:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"mocha"</span>
  }
}
</code></pre>
<p>During the Travis CI build, you can run <code>npm test</code> to execute Mocha tests as per the <code>package.json</code> configuration.</p>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><p><strong>Regular Updates</strong>: Keep your dependencies up to date, especially any security patches or bug fixes.</p>
</li>
<li><p><strong>Conservative Versioning</strong>: Use <code>^</code> for minor upgrades and <code>~</code> for patch upgrades to maximize stability and compatibility.</p>
</li>
<li><p><strong>Try out 'npm' &amp; 'yarn'</strong>: Both are reliable package managers, so pick one that best suits your workflow.
<br /></p>
</li>
</ul>
<h2 id="heading-11-describe-some-of-the-core-modules-of-nodejs">11. Describe some of the core modules of Node.js.</h2>
<p><strong>Node.js</strong> offers a host of inbuilt modules that cover diverse functionalities, ranging from file system handling to HTTP server management. These modules expedite development and allow for more streamlined application building.</p>
<h3 id="heading-core-modules-overview">Core Modules Overview</h3>
<h4 id="heading-major-categories">Major Categories</h4>
<ul>
<li><strong>Basic/System Control</strong>: Modules optimized for system interaction, diagnostics, and error handling.</li>
<li><strong>File System Handling</strong>: Offers a range of file operations.</li>
<li><strong>Networking</strong>: Specialized for data communication over various network protocols.</li>
<li><strong>Utility Modules</strong>: Miscellaneous tools for data analysis, task scheduling, etc.</li>
</ul>
<h3 id="heading-key-modules">Key Modules</h3>
<h4 id="heading-basicsystem-control">Basic/System Control</h4>
<ul>
<li><strong><code>os</code></strong>: Provides system-related utility functions. Example: <code>os.freemem()</code>, <code>os.totalmem()</code>.</li>
<li><strong><code>util</code></strong>: General utility functions primarily used for debugging. Example: <code>util.inspect()</code>.</li>
</ul>
<h4 id="heading-file-system-handling">File System Handling</h4>
<ul>
<li><strong><code>fs</code></strong>: Offers extensive file system capabilities. Commonly used methods include <code>fs.readFile()</code> and <code>fs.writeFile()</code>.</li>
</ul>
<h4 id="heading-networking">Networking</h4>
<ul>
<li><strong><code>http</code>/<code>https</code></strong>: Implements web server and client. Example: <code>http.createServer()</code>.</li>
<li><strong><code>net</code></strong>: Facilitates low-level networking tasks. Example: <code>net.createServer()</code>.</li>
<li><strong><code>dgram</code></strong>: Delivers UDP Datagram Socket support for messaging.</li>
</ul>
<h4 id="heading-utility-modules">Utility Modules</h4>
<ul>
<li><strong><code>crypto</code></strong>: Encompasses cryptographic operations. Common methods include <code>crypto.createHash()</code> and <code>crypto.createHmac()</code>.</li>
<li><strong><code>zlib</code></strong>: Offers data compression capabilities integrated with various modules like <code>http</code>.</li>
<li><strong><code>stream</code></strong>: Facilitates event-based data stream processing.</li>
</ul>
<h4 id="heading-others">Others</h4>
<ul>
<li><strong><code>path</code></strong>: Aids in file path string manipulation.</li>
<li><strong><code>url</code></strong>: Parses and formats URL strings, especially beneficial in web applications and server operations.</li>
</ul>
<h3 id="heading-code-example-using-core-modules">Code Example: Using Core Modules</h3>
<p>Here is the node.js code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
<span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'url'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'zlib'</span>);

<span class="hljs-comment">// Module: os</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Free memory:'</span>, os.freemem());
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Total memory:'</span>, os.totalmem());

<span class="hljs-comment">// Module: fs</span>
fs.readFile(<span class="hljs-string">'input.txt'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-built_in">console</span>.log(data);
});

<span class="hljs-comment">// Module: http</span>
http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> reqPath = url.parse(req.url).pathname;
  <span class="hljs-keyword">const</span> file = path.join(__dirname, reqPath);

  <span class="hljs-keyword">const</span> readStream = fs.createReadStream(file);
  readStream.pipe(zlib.createGzip()).pipe(res);
}).listen(<span class="hljs-number">8080</span>);
</code></pre>
<p><br /></p>
<h2 id="heading-12-how-do-you-create-a-simple-server-in-nodejs-using-the-http-module">12. How do you create a simple server in Node.js using the HTTP module?</h2>
<p>Let's look at how to create a simple server in Node.js using the built-in <code>http</code> module.</p>
<h3 id="heading-server-setup">Server Setup</h3>
<p>First, a few steps are necessary.</p>
<ol>
<li><p><strong>Import the Module</strong>: Use <code>require</code> to load the <code>http</code> module.</p>
</li>
<li><p><strong>Define Callback Function</strong>: For each request, the server will execute a specific callback function. This function takes two parameters:</p>
<ul>
<li><code>request</code>: Represents the HTTP request, from which you can extract any necessary data.</li>
<li><code>response</code>: Use this parameter to define what the server sends back to the client.</li>
</ul>
</li>
<li><p><strong>Server Initialization</strong>: Use the <code>http.createServer</code> method to set up the server and define the callback function.</p>
</li>
<li><p><strong>Listen on a Port</strong>: Use the <code>.listen</code> method to specify the port the server should "listen" on, waiting for incoming requests.</p>
</li>
</ol>
<h3 id="heading-code-example-server-setup">Code Example: Server Setup</h3>
<p>Here is the Node.js code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import the http module</span>
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-comment">// Define the callback function</span>
<span class="hljs-keyword">const</span> requestListener = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.writeHead(<span class="hljs-number">200</span>);
  res.end(<span class="hljs-string">'Hello, World!'</span>);
};

<span class="hljs-comment">// Server initialization</span>
<span class="hljs-keyword">const</span> server = http.createServer(requestListener);

<span class="hljs-comment">// Listen on port 8080</span>
server.listen(<span class="hljs-number">8080</span>);
</code></pre>
<h3 id="heading-request-handler">Request Handler</h3>
<p>The <strong>Request listener</strong> is the main entry to the server. This callback function handles the incoming client request and sends a response back to the client.</p>
<p>The <a target="_blank" href="https://nodejs.org/api/http.html#http_class_http_incomingmessage"><code>req</code></a> object represents the HTTP request that the server receives. It provides all the details about the request, such as the request URL, request headers, request method, and more.</p>
<p>The <code>res</code> object is the server's response to the client. You can use methods on this object, like <code>res.write()</code> and <code>res.end()</code>, to send data back to the client. In most cases, you'll use <code>res.end()</code> to send a response.</p>
<h3 id="heading-code-example-request-listener-with-more-capabilities">Code Example: Request Listener with More Capabilities</h3>
<p>Here is the Node.js code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> requestListener = <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span>(req.url === <span class="hljs-string">'/profile'</span>) {
    res.writeHead(<span class="hljs-number">200</span>);
    res.end(<span class="hljs-string">'Welcome to your profile!'</span>);
  } <span class="hljs-keyword">else</span> {
    res.writeHead(<span class="hljs-number">200</span>);
    res.end(<span class="hljs-string">'Hello, World!'</span>);
  }
};
</code></pre>
<p>In this example, we're checking the request URL. If it's <code>/profile</code>, the server will respond with a "Welcome!" message; otherwise, it will respond with "Hello, World!".</p>
<p>This server is basic yet powerful. With this foundational understanding, you can extend the server's behavior in numerous ways, such as by serving dynamic content or handling different HTTP methods like <code>POST</code> and <code>PUT</code>.
<br /></p>
<h2 id="heading-13-explain-the-purpose-of-the-file-system-fs-module">13. Explain the purpose of the File System (fs) module.</h2>
<p>The <strong>File System (fs)</strong> module in Node.js facilitates file operations such as reading, writing, and manipulation. It's a core module, meaning it's available without needing 3rd-party installations.</p>
<h3 id="heading-key-methods-of-the-fs-module">Key Methods of the <code>fs</code> Module</h3>
<ul>
<li><strong>Asynchronous Methods</strong>: Ideal for non-blocking file I/O operations. Their function names end with <code>File</code>.</li>
<li><strong>Synchronous Methods</strong>: Best suited for simpler scripts and robustness is needed.</li>
<li><strong>File Names</strong>: As a convention, file and folder names in the Node.js <code>fs</code> module that correspond to methods end with <code>Sync</code> to indicate synchronous operations (e.g., <code>renameSync</code>).</li>
</ul>
<h3 id="heading-the-synchronous-approach">The Synchronous Approach</h3>
<p>Though the synchronous file methods can make scripting simpler, their use should be limited in web servers as they can block the event loop, reducing scalability and performance.</p>
<p>Synchronous operations in Node's <code>fs</code> module are best avoided in server-side applications that must manage many connections.</p>
<h3 id="heading-supported-operations">Supported Operations</h3>
<p>The <code>fs</code> module covers a wide array of file-handling tasks, including:</p>
<ul>
<li><strong>I/O Operations</strong>: Read or write files using streams or high-level functions.</li>
<li><strong>File Metadata</strong>: Obtain attributes such as size or timestamps.</li>
<li><strong>Directories</strong>: Manage folders and the files within them, including sync and async variants for listing.</li>
<li><strong>File Types</strong>: Distinguish between files and directories.</li>
<li><strong>Links</strong>: Create and manage hard or symbolic links.</li>
<li><strong>Permissions and Ownership</strong>: Integrate with operating systems' security systems.</li>
</ul>
<h3 id="heading-code-example-file-reading">Code Example: File Reading</h3>
<p>Here is the Node.js code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-comment">// Asynchronous read</span>
fs.readFile(<span class="hljs-string">'input.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err);
  }
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Asynchronous read: '</span> + data.toString());
});

<span class="hljs-comment">// Synchronous read</span>
<span class="hljs-keyword">const</span> data = fs.readFileSync(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Synchronous read: '</span> + data.toString());
</code></pre>
<p>In the above code, both asynchronous and synchronous methods are demonstrated for file reading.</p>
<h3 id="heading-considerations-for-the-web">Considerations for the Web</h3>
<p>When working with HTTP connections or in web applications, the <strong>synchronous methods may block other requests</strong>. Always favor their asynchronous counterparts, especially in web applications.
<br /></p>
<h2 id="heading-14-what-is-the-buffer-class-in-nodejs">14. What is the Buffer class in Node.js?</h2>
<p>In <strong>Node.js</strong>, the <code>Buffer</code> class is a core module that provides a way to <strong>read</strong>, <strong>manipulate</strong>, and <strong>allocate</strong> binary data, which primarily represents a sequence of bytes (octets).</p>
<h3 id="heading-key-features-1">Key Features</h3>
<ul>
<li><p><strong>Backbone of I/O Operations</strong>: Buffers serve as the primary data structure for handling I/O in Node.js, acting as a transient container for data being read from or written to streams and files.</p>
</li>
<li><p><strong>Raw Binary Data</strong>: Buffers are used for handling raw binary data, which is particularly useful for tasks like cryptography, network protocols, and WebGL operations.</p>
</li>
<li><p><strong>Unmodifiable Size</strong>: Buffers are fixed in size after allocation. To resize a buffer, you'd need to create a new buffer with the necessary size and optionally copy over the original data.</p>
</li>
<li><p><strong>Shared Memory</strong>: Buffers provide a mechanism for sharing memory between Node.js instances or between Node.js and C++ Addons, offering enhanced performance in certain scenarios.</p>
</li>
</ul>
<h3 id="heading-common-use-cases">Common Use Cases</h3>
<ul>
<li><p><strong>File and Network Operations</strong>: Buffers are leveraged for reading and writing data from files, sockets, and other sources/sinks.</p>
</li>
<li><p><strong>Data Conversion</strong>: For example, converting text to binary data or vice versa using character encodings such as UTF-8.</p>
</li>
<li><p><strong>Binary Calculations</strong>: Buffers make binary manipulations more manageable, such as computing checksums or parsing binary file formats.</p>
</li>
</ul>
<h3 id="heading-code-example-buffer-use">Code Example: Buffer Use</h3>
<p>Here is the JavaScript code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> bufTemp = Buffer.from(<span class="hljs-string">'Hey!'</span>);
<span class="hljs-built_in">console</span>.log(bufTemp.toString()); <span class="hljs-comment">// Output: Hey!</span>

<span class="hljs-keyword">let</span> bufAlloc = Buffer.alloc(<span class="hljs-number">5</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-built_in">console</span>.log(bufAlloc.toString()); <span class="hljs-comment">// Output: aaaaa</span>

bufAlloc.write(<span class="hljs-string">'Hello'</span>);
<span class="hljs-built_in">console</span>.log(bufAlloc.toString()); <span class="hljs-comment">// Output: Hello</span>

<span class="hljs-keyword">let</span> bufSlice = bufAlloc.slice(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);  <span class="hljs-comment">// Slice the buffer</span>
<span class="hljs-built_in">console</span>.log(bufSlice.toString());  <span class="hljs-comment">// Output: Hel</span>
</code></pre>
<p><br /></p>
<h2 id="heading-15-what-are-streams-in-nodejs-and-what-types-are-available">15. What are streams in Node.js and what types are available?</h2>
<p><strong>Node.js</strong> utilizes <strong>streams</strong> for efficient handling of input/output data, offering two main varieties: readable and writable.</p>
<h3 id="heading-categories-of-streams">Categories of Streams</h3>
<ol>
<li><p><strong>Standard Streams</strong>: Represent standard input, output, and error. These are instances of Readable or Writable streams.</p>
</li>
<li><p><strong>Duplex Streams</strong>: Facilitate both reading and writing. They can be connected to processes or handling pipelines.</p>
</li>
<li><p><strong>Transform Streams</strong>: A special type that acts as an intermediary, modifying the data as it passes through.</p>
</li>
</ol>
<h3 id="heading-practical-implementations">Practical Implementations</h3>
<ul>
<li><p><strong>HTTP Transactions</strong>: HTTP clients use readable and writable streams for sending requests and receiving responses. HTTP servers also apply these streams for similar actions in the opposite direction.</p>
</li>
<li><p><strong>File System</strong>: Reading and writing files in Node.js utilizes these streams. For instance, the <code>fs.createReadStream()</code> method generates a readable stream whereas <code>fs.createWriteStream()</code> creates a writable one.</p>
</li>
</ul>
<h3 id="heading-workflows">Workflows</h3>
<ol>
<li><p><strong>Standard I/O Streams</strong>: These support interactivity between a program and its running environment. For example, stdout (a writable stream) can be used to display information, and stdin (a readable stream) can capture user input.</p>
</li>
<li><p><strong>File Operations</strong>: Streams are beneficial when working with large files. This is because they streamline the process by breaking it down into smaller, manageable chunks, thereby conserving memory.</p>
</li>
<li><p><strong>Server Operations</strong>: Streams facilitate data transfer for operations such as network requests, database communications, and more.</p>
</li>
<li><p><strong>Pipelines</strong>: Streams can be easily combined using <code>pipe()</code> to create powerful, efficient operations called pipelines. For instance, to compress a file and then write it to disk, you can pipe a readable stream to a transform stream and then to a writable stream. This arrangement neatly dictates the flow of data.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Can you Crack Nodejs Interviews]]></title><description><![CDATA[Answer: All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data…]]></description><link>https://articles.tkssharma.com/can-you-crack-nodejs-interviews</link><guid isPermaLink="true">https://articles.tkssharma.com/can-you-crack-nodejs-interviews</guid><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Fri, 11 Oct 2024 02:12:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728612717844/767647b7-a4a1-44e2-8df4-d52ad25cd938.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-interview-questions">Interview Questions</h1>
<h2 id="heading-nodejs">Node.js</h2>
<h3 id="heading-q1-what-do-you-mean-by-asynchronous-api">Q1: What do you mean by Asynchronous API? ☆☆</h3>
<p><strong>Answer:</strong>
All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q2-what-are-the-benefits-of-using-nodejs">Q2: What are the benefits of using Node.js? ☆☆</h3>
<p><strong>Answer:</strong>
Following are main benefits of using Node.js</p>
<ul>
<li><strong>Aynchronous and Event Driven</strong> - All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.</li>
<li><strong>Very Fast</strong> - Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.</li>
<li><strong>Single Threaded but highly Scalable</strong> - Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server.</li>
<li><strong>No Buffering</strong> - Node.js applications never buffer any data. These applications simply output the data in chunks.</li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q3-is-node-a-single-threaded-application">Q3: Is Node a single threaded application? ☆☆</h3>
<p><strong>Answer:</strong>
Yes! Node uses a single threaded model with event looping.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q4-what-is-global-installation-of-dependencies">Q4: What is global installation of dependencies? ☆☆</h3>
<p><strong>Answer:</strong>
Globally installed packages/dependencies are stored in <strong></strong>/npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q5-what-is-an-error-first-callback">Q5: What is an error-first callback? ☆☆</h3>
<p><strong>Answer:</strong>
<em>Error-first callbacks</em> are used to pass errors and data. The first argument is always an error object that the programmer has to check if something went wrong. Additional arguments are used to pass data.</p>
<pre><code class="lang-js">fs.readFile(filePath, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, data</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-comment">//handle the error</span>
  }
  <span class="hljs-comment">// use the data object</span>
});
</code></pre>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q6-whats-the-difference-between-operational-and-programmer-errors">Q6: What's the difference between operational and programmer errors? ☆☆</h3>
<p><strong>Answer:</strong>
Operation errors are not bugs, but problems with the system, like <em>request timeout</em> or <em>hardware failure</em>. On the other hand programmer errors are actual bugs.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q7-what-is-the-difference-between-nodejs-ajax-and-jquery">Q7: What is the difference between Nodejs, AJAX, and jQuery? ☆☆</h3>
<p><strong>Answer:</strong>
The one common trait between Node.js, AJAX, and jQuery is that all of them are the advanced implementation of JavaScript. However, they serve completely different purposes.</p>
<ul>
<li><p>Node.js –It is a server-side platform for developing client-server applications. For example, if we’ve to build an online employee management system, then we won’t do it using client-side JS. But the Node.js can certainly do it as it runs on a server similar to Apache, Django not in a browser.</p>
</li>
<li><p>AJAX (aka Asynchronous Javascript and XML) –It is a client-side scripting technique, primarily designed for rendering the contents of a page without refreshing it. There are a no. of large companies utilizing AJAX such as Facebook and Stack Overflow to display dynamic content.</p>
</li>
<li><p>jQuery –It is a famous JavaScript module which complements AJAX, DOM traversal, looping and so on. This library provides many useful functions to help in JavaScript development. However, it’s not mandatory to use it but as it also manages cross-browser compatibility, so can help you produce highly maintainable web applications.</p>
</li>
</ul>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q8-how-to-make-post-request-in-nodejs">Q8: How to make Post request in Node.js? ☆☆</h3>
<p><strong>Answer:</strong>
Following code snippet can be used to make a Post Request in Node.js.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> request = <span class="hljs-built_in">require</span>(<span class="hljs-string">'request'</span>);
request.post(<span class="hljs-string">'http://www.example.com/action'</span>, {
  <span class="hljs-attr">form</span>: {
    <span class="hljs-attr">key</span>: <span class="hljs-string">'value'</span>
  }
}, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">error, response, body</span>) </span>{
  <span class="hljs-keyword">if</span> (!error &amp;&amp; response.statusCode == <span class="hljs-number">200</span>) {
    <span class="hljs-built_in">console</span>.log(body)
  }
});
</code></pre>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q9-what-are-the-key-features-of-nodejs">Q9: What are the key features of Node.js? ☆☆</h3>
<p><strong>Answer:</strong>
Let’s look at some of the key features of Node.js.</p>
<ul>
<li><strong>Asynchronous event driven IO helps concurrent request handling –</strong> All APIs of Node.js are asynchronous. This feature means that if a Node receives a request for some Input/Output operation, it will execute that operation in the background and continue with the processing of other requests. Thus it will not wait for the response from the previous requests.</li>
<li><strong>Fast in Code execution –</strong> Node.js uses the V8 JavaScript Runtime engine, the one which is used by Google Chrome. Node has a wrapper over the JavaScript engine which makes the runtime engine much faster and hence processing of requests within Node.js also become faster.</li>
<li><strong>Single Threaded but Highly Scalable –</strong> Node.js uses a single thread model for event looping. The response from these events may or may not reach the server immediately. However, this does not block other operations. Thus making Node.js highly scalable. Traditional servers create limited threads to handle requests while Node.js creates a single thread that provides service to much larger numbers of such requests.</li>
<li><strong>Node.js library uses JavaScript –</strong> This is another important aspect of Node.js from the developer’s point of view. The majority of developers are already well-versed in JavaScript. Hence, development in Node.js becomes easier for a developer who knows JavaScript.</li>
<li><strong>There is an Active and vibrant community for the Node.js framework –</strong> The active community always keeps the framework updated with the latest trends in the web development.</li>
<li><strong>No Buffering –</strong> Node.js applications never buffer any data. They simply output the data in chunks.</li>
</ul>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q10-what-is-control-flow-function">Q10: What is control flow function?   ☆☆</h3>
<p><strong>Answer:</strong>
It is a generic piece of code which runs in between several asynchronous function calls is known as control flow function.</p>
<p><strong>Source:</strong> <em>lazyquestion.com</em></p>
<h3 id="heading-q11-what-are-event-listeners">Q11: What are Event Listeners?   ☆☆</h3>
<p><strong>Answer:</strong>
<strong>Event Listeners</strong> are similar to call back functions but are associated with some event. For example when a server listens to http request on a given port a event will be generated and to specify http server has received and will invoke corresponding event listener. Basically, Event listener's are also call backs for a corresponding event.</p>
<p>Node.js has built in event's and built in event listeners. Node.js also provides functionality to create Custom events and Custom Event listeners.</p>
<p><strong>Source:</strong> <em>lazyquestion.com</em></p>
<h3 id="heading-q12-if-nodejs-is-single-threaded-then-how-it-handles-concurrency">Q12: If Node.js is single threaded then how it handles concurrency? ☆☆</h3>
<p><strong>Answer:</strong>
Node provides a single thread to programmers so that code can be written easily and without bottleneck. Node internally uses multiple POSIX threads for various I/O operations such as File, DNS, Network calls etc.</p>
<p>When Node gets I/O request it creates or uses a thread to perform that I/O operation and once the operation is done, it pushes the result to the event queue. On each such event, event loop runs and checks the queue and if the execution stack of Node is empty then it adds the queue result to execution stack.</p>
<p>This is how Node manages concurrency.</p>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q13-what-is-callback-hell">Q13: What is Callback Hell? ☆☆</h3>
<p><strong>Answer:</strong>
The asynchronous function requires callbacks as a return parameter. When multiple asynchronous functions are chained together then callback hell situation comes up. </p>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q14-could-we-run-an-external-process-with-nodejs">Q14: Could we run an external process with Node.js? ☆☆</h3>
<p><strong>Answer:</strong>
Yes. <em>Child process module</em> enables us to access operating system functionaries or other apps. Scalability is baked into Node and child processes are the key factors to scale our application. You can use child process to run system commands, read large files without blocking event loop,  decompose the application into various “nodes” (That’s why it’s called Node).</p>
<p>Child process module has following three major ways to create child processes –</p>
<ul>
<li>spawn  - child_process.spawn launches a new process with a given command.</li>
<li>exec  - child_process.exec method runs a command in a shell/console and buffers the output.</li>
<li>fork - The child_process.fork method is a special case of the spawn() to create child processes.</li>
</ul>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q15-list-out-the-differences-between-angularjs-and-nodejs">Q15:  List out the differences between AngularJS and NodeJS? ☆☆</h3>
<p><strong>Answer:</strong>
AngularJS is a web application development framework. It’s a JavaScript and it is different from other web app frameworks written in JavaScript like jQuery. NodeJS is a runtime environment used for building server-side applications while AngularJS is a JavaScript framework mainly useful in building/developing client-side part of applications which run inside a web browser.</p>
<p><strong>Source:</strong> <em>a4academics.com</em></p>
<h3 id="heading-q16-how-you-can-monitor-a-file-for-modifications-in-nodejs">Q16:  How you can monitor a file for modifications in Node.js ? ☆☆</h3>
<p><strong>Answer:</strong>
We can take advantage of File System <code>watch()</code> function which watches the changes of the file.</p>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q17-what-are-the-core-modules-of-nodejs">Q17: What are the core modules of Node,js? ☆☆</h3>
<p><strong>Answer:</strong></p>
<ul>
<li>EventEmitter</li>
<li>Stream</li>
<li>FS</li>
<li>Net</li>
<li>Global Objects</li>
</ul>
<p><strong>Source:</strong> <em>github.com/jimuyouyou</em></p>
<h3 id="heading-q18-what-is-v8">Q18: What is V8? ☆☆</h3>
<p><strong>Answer:</strong>
The V8 library provides Node.js with a JavaScript engine (a program that converts Javascript code into lower level or machine code that microprocessors can understand), which Node.js controls via the V8 C++ API. V8 is maintained by Google, for use in Chrome.</p>
<p>The Chrome V8 engine :</p>
<ul>
<li>The V8 engine is written in C++ and used in Chrome and Nodejs.</li>
<li>It implements ECMAScript as specified in ECMA-262.</li>
<li>The V8 engine can run standalone we can embed it with our own C++ program.</li>
</ul>
<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q19-what-is-libuv">Q19: What is libuv? ☆☆</h3>
<p><strong>Answer:</strong>
<strong>libuv</strong> is a C library that is used to abstract non-blocking I/O operations to a consistent interface across all supported platforms. It provides mechanisms to handle file system, DNS, network, child processes, pipes, signal handling, polling and streaming. It also includes a thread pool for offloading work for some things that can't be done asynchronously at the operating system level.</p>
<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q20-what-is-the-difference-between-returning-a-callback-and-just-calling-a-callback">Q20: What is the difference between returning a callback and just calling a callback? ☆☆</h3>
<p><strong>Answer:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">return</span> callback();
<span class="hljs-comment">//some more lines of code; -  won't be executed</span>

callback();
<span class="hljs-comment">//some more lines of code; - will be executed</span>
</code></pre>
<p>Of course returning will help the context calling async function get the value returned by callback.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">do2</span>(<span class="hljs-params">callback</span>) </span>{
    log.trace(<span class="hljs-string">'Execute function: do2'</span>);
    <span class="hljs-keyword">return</span> callback(<span class="hljs-string">'do2 callback param'</span>);
}

<span class="hljs-keyword">var</span> do2Result = do2(<span class="hljs-function">(<span class="hljs-params">param</span>) =&gt;</span> {
    log.trace(<span class="hljs-string">`print <span class="hljs-subst">${param}</span>`</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-string">`return from callback(<span class="hljs-subst">${param}</span>)`</span>; <span class="hljs-comment">// we could use that return</span>
});

log.trace(<span class="hljs-string">`print <span class="hljs-subst">${do2Result}</span>`</span>);
</code></pre>
<p>Output:</p>
<pre><code class="lang-sh">C:\Work\Node&gt;node --use-strict main.js
[0] Execute <span class="hljs-keyword">function</span>: do2
[0] <span class="hljs-built_in">print</span> do2 callback param
[0] <span class="hljs-built_in">print</span> <span class="hljs-built_in">return</span> from callback(do2 callback param)
</code></pre>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q21-what-is-repl-in-context-of-node">Q21: What is REPL in context of Node? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>REPL</strong> stands for Read Eval Print Loop and it represents a computer environment like a window console or unix/linux shell where a command is entered and system responds with an output. Node.js or Node comes bundled with a REPL environment. It performs the following desired tasks.</p>
<ul>
<li><strong>Read</strong> - Reads user's input, parse the input into JavaScript data-structure and stores in memory.</li>
<li><strong>Eval</strong> - Takes and evaluates the data structure</li>
<li><strong>Print</strong> - Prints the result</li>
<li><strong>Loop</strong> - Loops the above command until user press ctrl-c twice.</li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q22-what-is-callback">Q22: What is Callback? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Callback</strong> is an asynchronous equivalent for a function. A callback function is called at the completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is such a way that they supports callbacks. </p>
<p>For example, a function to read a file may start reading file and return the control to execution environment immediately so that next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as parameter. So there is no blocking or wait for File I/O. </p>
<p>This makes Node.js highly scalable, as it can process high number of request without waiting for any function to return result.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q23-what-is-a-blocking-code">Q23: What is a blocking code? ☆☆☆</h3>
<p><strong>Answer:</strong>
If application has to wait for some I/O operation in order to complete its execution any further then the code responsible for waiting is known as blocking code.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q24-how-node-prevents-blocking-code">Q24: How Node prevents blocking code? ☆☆☆</h3>
<p><strong>Answer:</strong>
By providing callback function. Callback function gets called whenever corresponding event triggered.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q25-what-is-event-loop">Q25: What is Event Loop? ☆☆☆</h3>
<p><strong>Answer:</strong>
Node.js is a single threaded application but it support concurrency via concept of event and callbacks. As every API of Node js are asynchronous and being a single thread, it uses async function calls to maintain the concurrency. Node uses observer pattern. Node thread keeps an event loop and whenever any task get completed, it fires the corresponding event which signals the event listener function to get executed.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q26-what-is-event-emmitter">Q26: What is Event Emmitter? ☆☆☆</h3>
<p><strong>Answer:</strong>
All objects that emit events are members of EventEmitter class. These objects expose an <code>eventEmitter.on()</code> function that allows one or more functions to be attached to named events emitted by the object.</p>
<p>When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{}

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> MyEmitter();
myEmitter.on(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'an event occurred!'</span>);
});
myEmitter.emit(<span class="hljs-string">'event'</span>);
</code></pre>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q27-what-is-purpose-of-buffer-class-in-node">Q27: What is purpose of Buffer class in Node? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Buffer</strong> class is a global class and can be accessed in application without importing buffer module. A Buffer is a kind of an array of integers and corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q28-what-is-difference-between-synchronous-and-asynchronous-method-of-fs-module">Q28: What is difference between synchronous and asynchronous method of fs module? ☆☆☆</h3>
<p><strong>Answer:</strong></p>
<p>Every method in <code>fs</code> module has synchronous as well as asynchronous form. Asynchronous methods takes a last parameter as completion function callback and first parameter of the callback function is error. It is preferred to use asynchronous method instead of synchronous method as former never block the program execution where the latter one does.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q29-what-are-streams">Q29: What are streams? ☆☆☆</h3>
<p><strong>Answer:</strong>
Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams.</p>
<ul>
<li><strong>Readable</strong> - Stream which is used for read operation.</li>
<li><strong>Writable</strong> - Stream which is used for write operation.</li>
<li><strong>Duplex</strong> - Stream which can be used for both read and write operation.</li>
<li><strong>Transform</strong> - A type of duplex stream where the output is computed based on input.</li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q30-what-is-chaining-in-node">Q30: What is Chaining in Node? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Chanining</strong> is a mechanism to connect output of one stream to another stream and create a chain of multiple stream operations. It is normally used with piping operations.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q31-what-is-the-purpose-of-settimeout-function">Q31: What is the purpose of setTimeout function? ☆☆☆</h3>
<p><strong>Answer:</strong>
The <code>setTimeout(cb, ms)</code> global function is used to run callback <code>cb</code> after at least <code>ms</code> milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q32-how-can-you-avoid-callback-hells">Q32: How can you avoid callback hells? ☆☆☆</h3>
<p><strong>Answer:</strong>
To do so you have more options:</p>
<ul>
<li><strong>modularization</strong>: break callbacks into independent functions</li>
<li>use <em>Promises</em></li>
<li>use <code>yield</code> with <em>Generators</em> and/or <em>Promises</em></li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q33-whats-the-event-loop">Q33: What's the event loop? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>The event loop</strong> is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.</p>
<div class="text-center">
<img src="https://i.stack.imgur.com/Lbs9z.png" class="img-fluid" />
</div>

<p>Every I/O requires a callback - once they are done they are pushed onto the event loop for execution. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background. When one of these operations completes, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q34-how-to-avoid-callback-hell-in-nodejs">Q34: How to avoid callback hell in Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
Node.js internally uses a single-threaded event loop to process queued events. But this approach may lead to blocking the entire process if there is a task running longer than expected.</p>
<p>Node.js addresses this problem by incorporating callbacks also known as higher-order functions. So whenever a long-running process finishes its execution, it triggers the callback associated. </p>
<p>sometimes, it could lead to complex and unreadable code. More the no. of callbacks, longer the chain of returning callbacks would be.</p>
<p>There are four solutions which can address the callback hell problem.</p>
<p><strong>Make your program modular</strong></p>
<p>It proposes to split the logic into smaller modules. And then join them together from the main module to achieve the desired result.</p>
<p><strong>Use async mechanism</strong></p>
<p>It is a widely used Node.js module which provides a sequential flow of execution.</p>
<p>The async module has  API which passes data from one operation to other using the next callback.</p>
<p>Another async API  allows iterating over a list of items in parallel and calls back with another list of results.</p>
<p>With the async approach, the caller’s callback gets called only once. The caller here is the main method using the async module.</p>
<p><strong>Use promises mechanism</strong></p>
<p>Promises give an alternate way to write async code. They either return the result of execution or the error/exception. Implementing promises requires the use of &lt;.then()&gt; function which waits for the promise object to return. It takes two optional arguments, both functions. Depending on the state of the promise only one of them will get called. The first function call proceeds if the promise gets fulfilled. However, if the promise gets rejected, then the second function will get called.</p>
<p><strong>Use generators</strong></p>
<p>Generators are lightweight routines, they make a function wait and resume via the yield keyword. Generator functions uses a special syntax . They can also suspend and resume asynchronous operations using constructs such as promises or  and turn a synchronous code into asynchronous.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q35-explain-how-does-nodejs-work">Q35: Explain how does Node.js work? ☆☆☆</h3>
<p><strong>Answer:</strong>
A Node.js application creates a single thread on its invocation. Whenever Node.js receives a request, it first completes its processing before moving on to the next request.</p>
<p>Node.js works asynchronously by using the event loop and callback functions, to handle multiple requests coming in parallel. An Event Loop is a functionality which handles and processes all your external events and just converts them to a callback function. It invokes all the event handlers at a proper time. Thus, lots of work is done on the back-end, while processing a single request, so that the new incoming request doesn’t have to wait if the processing is not complete.</p>
<div class="text-center">
<img src="https://csharpcorner-mindcrackerinc.netdna-ssl.com/article/node-js-event-loop/Images/1.png" class="img-fluid" />
</div>

<p>While processing a request, Node.js attaches a callback function to it and moves it to the back-end. Now, whenever its response is ready, an event is called which triggers the associated callback function to send this response.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q16-when-should-we-use-nodejs">Q16: When should we use Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Node.js</strong> is well suited for applications that have a lot of concurrent connections and each <em>request only needs very few CPU cycles</em>, because the event loop (with all the other clients) is blocked during execution of a function. I believe Node.js is best suited for real-time applications: online games, collaboration tools, chat rooms, or anything where what one user (or robot? or sensor?) does with the application needs to be seen by other users immediately, without a page refresh.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q17-how-does-nodejs-handle-child-threads">Q17: How does Node.js handle child threads? ☆☆☆</h3>
<p><strong>Answer:</strong>
Node.js, in its essence, is a single thread process. It does not expose child threads and thread management methods to the developer. Technically, Node.js does spawn child threads for certain tasks such as asynchronous I/O, but these run behind the scenes and do not execute any application JavaScript code, nor block the main event loop.</p>
<p>If threading support is desired in a Node.js application, there are tools available to enable it, such as the ChildProcess module.</p>
<p><strong>Source:</strong> <em>lazyquestion.com</em></p>
<h3 id="heading-q18-what-is-the-preferred-method-of-resolving-unhandled-exceptions-in-nodejs">Q18: What is the preferred method of resolving unhandled exceptions in Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
Unhandled exceptions in Node.js can be caught at the <code>Process</code> level by attaching a handler for <code>uncaughtException</code> event.</p>
<pre><code class="lang-js">process.on(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Caught exception: '</span> + err);
});
</code></pre>
<p>However, <code>uncaughtException</code> is a very crude mechanism for exception handling and may be removed from Node.js in the future. An exception that has bubbled all the way up to the <code>Process</code> level means that your application, and Node.js may be in an undefined state, and the only sensible approach would be to restart everything.</p>
<p>The preferred way is to add another layer between your application and the Node.js process which is called the <a target="_blank" href="http://nodejs.org/api/domain.html">domain</a>.</p>
<p>Domains provide a way to handle multiple different I/O operations as a single group. So, by having your application, or part of it, running in a separate domain, you can safely handle exceptions at the domain level, before they reach the <code>Process</code> level.</p>
<p><strong>Source:</strong> <em>lazyquestion.com</em></p>
<h3 id="heading-q19-what-is-stream-and-what-are-types-of-streams-available-in-nodejs">Q19: What is stream and what are types of streams available in Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Streams</strong> are a collection of data that might not be available all at once and don’t have to fit in memory. Streams provide chunks of data in a continuous manner. It is useful to read a large set of data and process it.</p>
<p>There is four fundamental type of streams:</p>
<ul>
<li>Readable.</li>
<li>Writeable.</li>
<li>Duplex.</li>
<li>Transform.</li>
</ul>
<p>Readable streams as the name suggest used in reading a large chunk of data from a source. Writable streams are used in writing a large chunk of data to the destination.</p>
<p>Duplex streams are both readable and writable ( Eg socket). Transform stream is the duplex stream which is used in modifying the data (eg zip creation).</p>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q20-what-are-the-global-objects-of-nodejs">Q20: What are the global objects of Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
These objects are available in all modules:</p>
<ul>
<li><strong>process</strong> - The process object is a global that provides information about, and control over, the current Node.js process. </li>
<li><strong>console</strong> - Used to print to stdout and stderr. </li>
<li><strong>buffer</strong> - Used to handle binary data. </li>
</ul>
<p><strong>Source:</strong> <em>github.com/jimuyouyou</em></p>
<h3 id="heading-q1-what-is-piping-in-node">Q1: What is Piping in Node? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Piping</strong> is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q2-name-some-of-the-events-fired-by-streams">Q2: Name some of the events fired by streams. ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Each type of Stream is an <strong>EventEmitter</strong> instance and throws several events at different instance of times. For example, some of the commonly used events are:</p>
<ul>
<li><strong>data</strong> - This event is fired when there is data is available to read.</li>
<li><strong>end</strong> - This event is fired when there is no more data to read.</li>
<li><strong>error</strong> - This event is fired when there is any error receiving or writing data.</li>
<li><strong>finish</strong> - This event is fired when all data has been flushed to underlying system</li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q3-what-is-the-purpose-of-filename-variable">Q3: What is the purpose of __filename variable? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
The <code>__filename</code> represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q4-how-can-you-listen-on-port-80-with-node">Q4: How can you listen on port 80 with Node? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Run the application on any port above 1024, then put a reverse proxy like <a target="_blank" href="http://nginx.org/">nginx</a> in front of it.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q5-what-tools-can-be-used-to-assure-consistent-code-style">Q5: What tools can be used to assure consistent code style? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
You have plenty of options to do so:</p>
<ul>
<li><a target="_blank" href="http://jslint.com/">JSLint</a> by Douglas Crockford</li>
<li><a target="_blank" href="http://jshint.com/">JSHint</a></li>
<li><a target="_blank" href="http://eslint.org/">ESLint</a></li>
<li><a target="_blank" href="http://jscs.info/">JSCS</a></li>
</ul>
<p>These tools are really helpful when developing code in teams, to enforce a given style guide and to catch common errors using static analysis.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q6-whats-a-stub-name-a-use-case">Q6: What's a stub? Name a use case. ☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Stubs</strong> are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.</p>
<p>A use-case can be a file read, when you do not want to read an actual file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">var</span> readFileStub = sinon.stub(fs, <span class="hljs-string">'readFile'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">path, cb</span>) </span>{
  <span class="hljs-keyword">return</span> cb(<span class="hljs-literal">null</span>, <span class="hljs-string">'filecontent'</span>);
});

expect(readFileStub).to.be.called;
readFileStub.restore();
</code></pre>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q7-does-nodejs-support-multi-core-platforms-and-is-it-capable-of-utilizing-all-the-cores">Q7: Does Node.js support multi-core platforms? And is it capable of utilizing all the cores? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, Node.js would run on a multi-core system without any issue. But it is by default a single-threaded application, so it can’t completely utilize the multi-core system.</p>
<p>However, Node.js can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q8-is-nodejs-entirely-based-on-a-single-thread">Q8: Is Node.js entirely based on a single-thread? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.</p>
<p>Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.</p>
<p>To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q9-is-nodejs-entirely-based-on-a-single-thread">Q9: Is Node.js entirely based on a single-thread? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.</p>
<p>Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.</p>
<p>To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q10-when-to-not-use-nodejs">Q10: When to not use Node.js? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
We can use Node.js for a variety of applications. But it is a single threaded framework, so we should not use it for cases where the application requires long processing time. If the server is doing some calculation, it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q11-why-to-use-buffers-instead-of-binary-strings-to-handle-binary-data">Q11: Why to use Buffers instead of binary strings to handle binary data ? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Pure JavaScript does not able to handle straight binary data very well. Since Node.js servers have to deal with TCP streams for reading and writing of data, binary strings will become problematic to work with as it is very slow and has a tendency to break. That's why it is always advisable to use Buffers instead of binary strings to handle binary data.</p>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q12-how-to-use-buffer-in-nodejs">Q12: How to use Buffer in Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
Buffer is used to process binary data, such as pictures, mp3, database files, etc. Buffer supports a variety of encoding and decoding, binary string conversion.</p>
<p><strong>Source:</strong> <em>github.com/jimuyouyou</em></p>
<h3 id="heading-q13-when-should-i-use-eventemitter">Q13: When should I use EventEmitter? ☆☆☆</h3>
<p><strong>Answer:</strong>
Whenever it makes sense for code to <em>subscribe</em> to something rather than get a callback from something. The typical use case would be that there's multiple blocks of code in your application that may need to do something when an event happens.</p>
<p><strong>Source:</strong> <em>stackoverflow.com/</em></p>
<h3 id="heading-q14-how-do-you-debug-nodejs-applications">Q14: How do you debug Node.js applications? ☆☆☆</h3>
<p><strong>Answer:</strong>
Node has its own built in GUI debugger as of version 6.3 (using Chrome's DevTools).</p>
<pre><code class="lang-js">node --inspect server.js
</code></pre>
<p>Some other options for debugging are:</p>
<ul>
<li><a target="_blank" href="http://www.joyent.com/developers/node/debug">Joyent's Guide</a></li>
<li><a target="_blank" href="https://nodejs.org/api/debugger.html">Debugger</a></li>
<li><a target="_blank" href="https://github.com/node-inspector/node-inspector">Node Inspector</a></li>
<li><a target="_blank" href="https://code.visualstudio.com/docs/runtimes/nodejs#_debugging-your-node-application">Visual Studio Code</a></li>
<li><a target="_blank" href="https://docs.c9.io/running_and_debugging_code.html">Cloud9</a></li>
<li><a target="_blank" href="https://github.com/adobe-research/theseus">Brackets</a></li>
</ul>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q15-rewrite-promise-based-nodejs-applications-to-asyncawait">Q15: Rewrite promise-based Node.js applications to Async/Await ☆☆☆</h3>
<p><strong>Details:</strong>
Rewrite this code to Async/Await:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncTask</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> functionA()
        .then(<span class="hljs-function">(<span class="hljs-params">valueA</span>) =&gt;</span> functionB(valueA))
        .then(<span class="hljs-function">(<span class="hljs-params">valueB</span>) =&gt;</span> functionC(valueB))
        .then(<span class="hljs-function">(<span class="hljs-params">valueC</span>) =&gt;</span> functionD(valueC))
        .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> logger.error(err))
}
</code></pre>
<p><strong>Answer:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">asyncTask</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> valueA = <span class="hljs-keyword">await</span> functionA()
        <span class="hljs-keyword">const</span> valueB = <span class="hljs-keyword">await</span> functionB(valueA)
        <span class="hljs-keyword">const</span> valueC = <span class="hljs-keyword">await</span> functionC(valueB)
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> functionD(valueC)
    } <span class="hljs-keyword">catch</span> (err) {
        logger.error(err)
    }
}
</code></pre>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q16-what-is-the-relationship-between-nodejs-and-v8">Q16: What is the relationship between Node.js and V8? ☆☆☆</h3>
<p><strong>Answer:</strong>
V8 is the Javascript engine inside of node.js that parses and runs your Javascript. The same V8 engine is used inside of Chrome to run javascript in the Chrome browser. Google open-sourced the V8 engine and the builders of node.js used it to run Javascript in node.js.</p>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q17-what-is-n-api-in-nodejs">Q17: What is N-API in Node.js? ☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>N-API</strong> (pronounced N as in the letter, followed by API) is an API for building native Addons. It is independent from the underlying JavaScript runtime (ex V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate Addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation.</p>
<p><strong>Source:</strong> <em>medium.com</em></p>
<h3 id="heading-q18-explain-the-concept-of-domain-in-nodejs">Q18: Explain the concept of Domain in Node.js ☆☆☆</h3>
<p><strong>Answer:</strong>
Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an <code>error</code> event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the <code>process.on('uncaughtException')</code> handler, or causing the program to exit immediately with an error code.</p>
<p>Domain error handlers are not a substitute for closing down a process when an error occurs. The safest way to respond to a thrown error is to shut down the process. In a normal web server, the better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'domain'</span>);
<span class="hljs-keyword">var</span> d = domain.create();
<span class="hljs-comment">// Domain emits 'error' when it's given an unhandled error</span>
d.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>) </span>{
    <span class="hljs-built_in">console</span>.log(err.stack);
    <span class="hljs-comment">// Our handler should deal with the error in an appropriate way</span>
});

<span class="hljs-comment">// Enter this domain</span>
d.run(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// If an un-handled error originates from here, process.domain will handle it</span>
    <span class="hljs-built_in">console</span>.log(process.domain === d); <span class="hljs-comment">// true</span>
});

<span class="hljs-comment">// domain has now exited. Any errors in code past this point will not be caught.</span>
</code></pre>
<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q19-are-you-familiar-with-differences-between-nodejs-nodules-and-es6-nodules">Q19: Are you familiar with differences between Node.js nodules and ES6 nodules? ☆☆☆</h3>
<p><strong>Answer:</strong>
The modules used in Node.js follow a module specification known as the <strong>CommonJS</strong> specification. The recent updates to the JavaScript programming language, in the form of ES6, specify changes to the language, adding things like new class syntax and a module system. This module system is different from Node.js modules. To import ES6 module, we'd use the ES6 <code>import</code> functionality.</p>
<p>Now ES6 modules are incompatible with Node.js modules. This has to do with the way modules are loaded differently between the two formats. If you use a compiler like Babel, you can mix and match module formats.</p>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q20-what-are-the-use-cases-for-the-nodejs-vm-core-module">Q20: What are the use cases for the Node.js "vm" core module? ☆☆☆</h3>
<p><strong>Answer:</strong>
It can be used to safely execute a piece of code contained in a string or file. The execution is performed in a separate environment that by default has no access to the environment of the program that created it. Moreover, you can specify execution timeout and context-specific error handling.</p>
<p><strong>Source:</strong> <em>quora.com</em></p>
<h3 id="heading-q1-what-is-piping-in-node-1">Q1: What is Piping in Node? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Piping</strong> is a mechanism to connect output of one stream to another stream. It is normally used to get data from one stream and to pass output of that stream to another stream. There is no limit on piping operations.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q2-name-some-of-the-events-fired-by-streams-1">Q2: Name some of the events fired by streams. ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Each type of Stream is an <strong>EventEmitter</strong> instance and throws several events at different instance of times. For example, some of the commonly used events are:</p>
<ul>
<li><strong>data</strong> - This event is fired when there is data is available to read.</li>
<li><strong>end</strong> - This event is fired when there is no more data to read.</li>
<li><strong>error</strong> - This event is fired when there is any error receiving or writing data.</li>
<li><strong>finish</strong> - This event is fired when all data has been flushed to underlying system</li>
</ul>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q3-what-is-the-purpose-of-filename-variable-1">Q3: What is the purpose of __filename variable? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
The <code>__filename</code> represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.</p>
<p><strong>Source:</strong> <em>tutorialspoint.com</em></p>
<h3 id="heading-q4-how-can-you-listen-on-port-80-with-node-1">Q4: How can you listen on port 80 with Node? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Run the application on any port above 1024, then put a reverse proxy like <a target="_blank" href="http://nginx.org/">nginx</a> in front of it.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q5-what-tools-can-be-used-to-assure-consistent-code-style-1">Q5: What tools can be used to assure consistent code style? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
You have plenty of options to do so:</p>
<ul>
<li><a target="_blank" href="http://jslint.com/">JSLint</a> by Douglas Crockford</li>
<li><a target="_blank" href="http://jshint.com/">JSHint</a></li>
<li><a target="_blank" href="http://eslint.org/">ESLint</a></li>
<li><a target="_blank" href="http://jscs.info/">JSCS</a></li>
</ul>
<p>These tools are really helpful when developing code in teams, to enforce a given style guide and to catch common errors using static analysis.</p>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q6-whats-a-stub-name-a-use-case-1">Q6: What's a stub? Name a use case. ☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Stubs</strong> are functions/programs that simulate the behaviours of components/modules. Stubs provide canned answers to function calls made during test cases. Also, you can assert on with what these stubs were called.</p>
<p>A use-case can be a file read, when you do not want to read an actual file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);

<span class="hljs-keyword">var</span> readFileStub = sinon.stub(fs, <span class="hljs-string">'readFile'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">path, cb</span>) </span>{
  <span class="hljs-keyword">return</span> cb(<span class="hljs-literal">null</span>, <span class="hljs-string">'filecontent'</span>);
});

expect(readFileStub).to.be.called;
readFileStub.restore();
</code></pre>
<p><strong>Source:</strong> <em>blog.risingstack.com</em></p>
<h3 id="heading-q7-does-nodejs-support-multi-core-platforms-and-is-it-capable-of-utilizing-all-the-cores-1">Q7: Does Node.js support multi-core platforms? And is it capable of utilizing all the cores? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, Node.js would run on a multi-core system without any issue. But it is by default a single-threaded application, so it can’t completely utilize the multi-core system.</p>
<p>However, Node.js can facilitate deployment on multi-core systems where it does use the additional hardware. It packages with a Cluster module which is capable of starting multiple Node.js worker processes that will share the same port.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q8-is-nodejs-entirely-based-on-a-single-thread-1">Q8: Is Node.js entirely based on a single-thread? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.</p>
<p>Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.</p>
<p>To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q9-is-nodejs-entirely-based-on-a-single-thread-1">Q9: Is Node.js entirely based on a single-thread? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes, it’s true that Node.js processes all requests on a single thread. But it’s just a part of the theory behind Node.js design. In fact, more than the single thread mechanism, it makes use of events and callbacks to handle a large no. of requests asynchronously.</p>
<p>Moreover, Node.js has an optimized design which utilizes both JavaScript and C++ to guarantee maximum performance. JavaScript executes at the server-side by Google Chrome v8 engine. And the C++ lib UV library takes care of the non-sequential I/O via background workers.</p>
<p>To explain it practically, let’s assume there are 100s of requests lined up in Node.js queue. As per design, the main thread of Node.js event loop will receive all of them and forwards to background workers for execution. Once the workers finish processing requests, the registered callbacks get notified on event loop thread to pass the result back to the user.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q10-when-to-not-use-nodejs-1">Q10: When to not use Node.js? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
We can use Node.js for a variety of applications. But it is a single threaded framework, so we should not use it for cases where the application requires long processing time. If the server is doing some calculation, it won’t be able to process any other requests. Hence, Node.js is best when processing needs less dedicated CPU time.</p>
<p><strong>Source:</strong> <em>techbeamers.com</em></p>
<h3 id="heading-q11-why-to-use-buffers-instead-of-binary-strings-to-handle-binary-data-1">Q11: Why to use Buffers instead of binary strings to handle binary data ? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Pure JavaScript does not able to handle straight binary data very well. Since Node.js servers have to deal with TCP streams for reading and writing of data, binary strings will become problematic to work with as it is very slow and has a tendency to break. That's why it is always advisable to use Buffers instead of binary strings to handle binary data.</p>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q12-how-to-gracefully-shutdown-nodejs-server">Q12: How to gracefully Shutdown Node.js Server? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
We can gracefully shutdown Node.js server by using the generic signal called SIGTERM or SIGINT which is used for program termination. We need to call SIGTERM or SIGINT which will terminate the program and clean up the resources utilized by the program.</p>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q13-what-are-the-timing-features-of-nodejs">Q13: What are the timing features of Node.js? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
The Timers module in Node.js contains functions that execute code after a set period of time. </p>
<ul>
<li><strong>setTimeout/clearTimeout</strong> - can be used to schedule code execution after a designated amount of milliseconds</li>
<li><strong>setInterval/clearInterval</strong> - can be used to execute a block of code multiple times </li>
<li><strong>setImmediate/clearImmediate</strong> - will execute code at the end of the current event loop cycle</li>
<li><strong>process.nextTick</strong> - used to schedule a callback function to be invoked in the next iteration of the Event Loop</li>
</ul>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cb</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processed in next iteration'</span>);
}
process.nextTick(cb);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Processed in the first iteration'</span>);
</code></pre>
<p>Output:</p>
<pre><code class="lang-js">Processed <span class="hljs-keyword">in</span> the first iteration
Processed <span class="hljs-keyword">in</span> next iteration
</code></pre>
<p><strong>Source:</strong> <em>github.com/jimuyouyou</em></p>
<h3 id="heading-q14-explain-usage-of-nodeenv">Q14: Explain usage of NODE_ENV ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Node encourages the convention of using a variable called NODE_ENV to flag whether we’re in production right now. This determination allows components to provide better diagnostics during development, for example by disabling caching or emitting verbose log statements. Setting NODE_ENV to production makes your application 3 times faster.</p>
<pre><code class="lang-sh">// Setting environment variables <span class="hljs-keyword">in</span> bash before starting the node process
$ NODE_ENV=development
$ node

// Reading the environment variable using code
<span class="hljs-keyword">if</span> (process.env.NODE_ENV === “production”)
    useCaching = <span class="hljs-literal">true</span>;
</code></pre>
<p><strong>Source:</strong> <em>github.com/i0natan/nodebestpractices</em></p>
<h3 id="heading-q15-what-is-lts-releases-of-nodejs-why-should-you-care">Q15: What is LTS releases of Node.js why should you care? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
An <strong>LTS(Long Term Support)</strong> version of Node.js receives all the critical bug fixes, security updates and performance improvements. </p>
<p>LTS versions of Node.js are supported for at least 18 months and are indicated by even version numbers (e.g. 4, 6, 8). They're best for production since the LTS release line is focussed on stability and security, whereas the <em>Current</em> release line has a shorter lifespan and more frequent updates to the code. Changes to LTS versions are limited to bug fixes for stability, security updates, possible npm updates, documentation updates and certain performance improvements that can be demonstrated to not break existing applications.</p>
<p><strong>Source:</strong> <em>github.com/i0natan/nodebestpractices</em></p>
<h3 id="heading-q16-provide-some-example-of-config-file-separation-for-dev-and-prod-environments">Q16: Provide some example of config file separation for dev and prod environments ☆☆☆☆</h3>
<p><strong>Answer:</strong>
A perfect and flawless configuration setup should ensure:</p>
<ul>
<li>keys can be read from file AND from environment variable</li>
<li>secrets are kept outside committed code</li>
<li>config is hierarchical for easier findability</li>
</ul>
<p>Consider the following config file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> config = {
  <span class="hljs-attr">production</span>: {
    <span class="hljs-attr">mongo</span> : {
      <span class="hljs-attr">billing</span>: <span class="hljs-string">'****'</span>
    }
  },
  <span class="hljs-attr">default</span>: {
    <span class="hljs-attr">mongo</span> : {
      <span class="hljs-attr">billing</span>: <span class="hljs-string">'****'</span>
    }
  }
}

<span class="hljs-built_in">exports</span>.get = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params">env</span>) </span>{
  <span class="hljs-keyword">return</span> config[env] || config.default;
}
</code></pre>
<p>And it's usage:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> config = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./config/config.js'</span>).get(process.env.NODE_ENV);
<span class="hljs-keyword">const</span> dbconn = mongoose.createConnection(config.mongo.billing);
</code></pre>
<p><strong>Source:</strong> <em>github.com/i0natan/nodebestpractices</em></p>
<h3 id="heading-q17-how-would-you-handle-errors-for-async-code-in-nodejs">Q17: How would you handle errors for async code in Node.js? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
Handling async errors in callback style (error-first approach) is probably the fastest way to hell (a.k.a the pyramid of doom). It's better to use a reputable promise library or async-await instead which enables a much more compact and familiar code syntax like try-catch.</p>
<p>Consider promises to catch errors:</p>
<pre><code class="lang-js">doWork()
 .then(doWork)
 .then(doOtherWork)
 .then(<span class="hljs-function">(<span class="hljs-params">result</span>) =&gt;</span> doWork)
 .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {<span class="hljs-keyword">throw</span> error;})
 .then(verify);
</code></pre>
<p>or using async/await:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params">req, res</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> someOtherFunction();
        <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> somethingElseFunction();
        res.send(<span class="hljs-string">"result"</span>)
    } <span class="hljs-keyword">catch</span> (error) {
        res.send(error.stack);
    }
}
</code></pre>
<p><strong>Source:</strong> <em>github.com/i0natan/nodebestpractices</em></p>
<h3 id="heading-q18-whats-the-difference-between-dependencies-devdependencies-and-peerdependencies-in-npm-packagejson-file">Q18: What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file? ☆☆☆☆</h3>
<p><strong>Answer:</strong></p>
<ul>
<li><p><strong>dependencies</strong> - Dependencies that your project needs to run, like a library that provides functions that you call from your code. They are installed transitively (if A depends on B depends on C, npm install on A will install B and C).</p>
</li>
<li><p><strong>devDependencies</strong> - Dependencies you only need during development or releasing, like compilers that take your code and compile it into javascript, test frameworks or documentation generators. They are not installed transitively (if A depends on B dev-depends on C, npm install on A will install B only).</p>
</li>
<li><strong>peerDependencies</strong> - Dependencies that your project hooks into, or modifies, in the parent project, usually a plugin for some other library or tool. It is just intended to be a check, making sure that the parent project (project that will depend on your project) has a dependency on the project you hook into. So if you make a plugin C that adds functionality to library B, then someone making a project A will need to have a dependency on B if they have a dependency on C. They are not installed (unless npm &lt; 3), they are only checked for.</li>
</ul>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q19-how-do-you-convert-an-existing-callback-api-to-promises">Q19: How do you convert an existing callback API to promises? ☆☆☆☆</h3>
<p><strong>Details:</strong>
How to convert this callback code to Promise? Provide some examples.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divisionAPI</span> (<span class="hljs-params">number, divider, successCallback, errorCallback</span>) </span>{
    <span class="hljs-keyword">if</span> (divider == <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">return</span> errorCallback( <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Division by zero"</span>) )
    }
    successCallback( number / divider )
}
</code></pre>
<p><strong>Answer:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divisionAPI</span>(<span class="hljs-params">number, divider</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">fulfilled, rejected</span>) </span>{
        <span class="hljs-keyword">if</span> (divider == <span class="hljs-number">0</span>) {
            <span class="hljs-keyword">return</span> rejected(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Division by zero"</span>))
        }
        fulfilled(number / divider)
    })
}

<span class="hljs-comment">// Promise can be used with together async\await in ES7 to make the program flow wait for a fullfiled result</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">var</span> result = <span class="hljs-keyword">await</span> divisionAPI(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// awaits for a fulfilled result!</span>
    <span class="hljs-built_in">console</span>.log(result);
}

<span class="hljs-comment">// Another usage with the same code by using .then() method</span>
divisionAPI(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(result)
})
</code></pre>
<p>Node.js 8.0.0 includes a new <code>util.promisify()</code> API that allows standard Node.js callback style APIs to be wrapped in a function that returns a Promise. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>);

<span class="hljs-keyword">const</span> readfile = util.promisify(fs.readFile);

readfile(<span class="hljs-string">'/some/file'</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-comment">/** ... **/</span> 
     })
    .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
        <span class="hljs-comment">/** ... **/</span> 
    });
</code></pre>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q20-what-are-async-functions-in-node-provide-some-examples">Q20: What are async functions in Node? Provide some examples. ☆☆☆☆</h3>
<p><strong>Answer:</strong>
With the release of Node.js 8, the long awaited async functions have landed in Node.js as well. ES 2017 introduced Asynchronous functions. Async functions are essentially a cleaner way to work with asynchronous code in JavaScript.</p>
<p>Async/Await is:</p>
<ul>
<li>The newest way to write asynchronous code in JavaScript.</li>
<li>It is non blocking (just like promises and callbacks).</li>
<li>Async/Await was created to simplify the process of working with and writing chained promises.</li>
<li>Async functions return a Promise. If the function throws an error, the Promise will be rejected. If the function returns a value, the Promise will be resolved.</li>
</ul>
<p><strong>Async functions</strong> can make use of the <code>await</code> expression. This will pause the async function and wait for the <em>Promise</em> to resolve prior to moving on.</p>
<h3 id="heading-q1-consider-following-code-snippet">Q1: Consider following code snippet ☆☆☆☆☆</h3>
<p><strong>Details:</strong>
Consider following code snippet:</p>
<pre><code class="lang-js">{
  <span class="hljs-built_in">console</span>.time(<span class="hljs-string">"loop"</span>);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000</span>; i += <span class="hljs-number">1</span>) {
    <span class="hljs-comment">// Do nothing</span>
  }
  <span class="hljs-built_in">console</span>.timeEnd(<span class="hljs-string">"loop"</span>);
}
</code></pre>
<p>The time required to run this code in Google Chrome is considerably more than the time required to run it in Node.js Explain why this is so, even though both use the v8 JavaScript Engine.</p>
<p><strong>Answer:</strong>
Within a web browser such as Chrome, declaring the variable <code>i</code> outside of any function’s scope makes it global and therefore binds it as a property of the <code>window</code> object. As a result, running this code in a web browser requires repeatedly resolving the property <code>i</code> within the heavily populated <code>window</code> namespace in each iteration of the <code>for</code> loop.</p>
<p>In Node.js, however, declaring any variable outside of any function’s scope binds it only to the module’s own scope (not the <code>window</code> object) which therefore makes it much easier and faster to resolve.</p>
<p><strong>Source:</strong> <em>toptal.com</em></p>
<h3 id="heading-q2-can-nodejs-use-other-engines-than-v8">Q2: Can Node.js use other engines than V8? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
Yes. Microsoft Chakra is another JavaScript engine which can be used with Node.js. It’s not officially declared yet.</p>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q3-how-would-you-scale-node-application">Q3: How would you scale Node application? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
We can scale Node application in following ways:</p>
<ul>
<li>cloning using <em>Cluster</em> module.</li>
<li>decomposing the application into smaller services – i.e micro services.</li>
</ul>
<p><strong>Source:</strong> <em>codeforgeek.com</em></p>
<h3 id="heading-q4-what-is-the-difference-between-processnexttick-and-setimmediate">Q4: What is the difference between process.nextTick() and setImmediate() ? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
The difference between <code>process.nextTick()</code> and <code>setImmediate()</code> is that <code>process.nextTick()</code> defers the execution of an action till the next pass around the event loop or it simply calls the callback function once the ongoing execution of the event loop is finished whereas <code>setImmediate()</code> executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.</p>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q5-how-to-solve-process-out-of-memory-exception-in-nodejs">Q5: How to solve "Process out of Memory Exception" in Node.js ? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
To solve the process out of memory exception in Node.js we need to increase the <code>max-old-space-size</code>. By default the max size of max-old-space-size is 512 mb which you can increase by the command:</p>
<pre><code class="lang-sh">node --max-old-space-size=1024 file.js
</code></pre>
<p><strong>Source:</strong> <em>codingdefined.com</em></p>
<h3 id="heading-q6-explain-what-is-reactor-pattern-in-nodejs">Q6: Explain what is Reactor Pattern in Node.js? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Reactor Pattern</strong> is an idea of non-blocking I/O operations in Node.js. This pattern provides a handler(in case of Node.js, a <em>callback function</em>) that is associated with each I/O operation. When an I/O request is generated, it is submitted to a <em>demultiplexer</em>.</p>
<p>This <em>demultiplexer</em> is a notification interface that is used to handle concurrency in non-blocking I/O mode and collects every request in form of an event and queues each event in a queue. Thus, the demultiplexer provides the <em>Event Queue</em>. </p>
<p>At the same time, there is an Event Loop which iterates over the items in the Event Queue. Every event has a callback function associated with it, and that callback function is invoked when the Event Loop iterates.</p>
<p><strong>Source:</strong> <em>hackernoon.com</em></p>
<h3 id="heading-q7-explain-some-error-handling-approaches-in-nodejs-you-know-about-which-one-will-you-use">Q7: Explain some Error Handling approaches in Node.js you know about. Which one will you use? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
Error handling in an asynchronous language works in a unique way and presents many challenges, some unexpected. There are four main error handling patterns in node:</p>
<ul>
<li><strong>Error return value</strong> - doesn't work asynchronously</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> validateObject = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">'object'</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid object'</span>);
    }
};
</code></pre>
<ul>
<li><strong>Error throwing</strong> - well-establish pattern, in which a function does its thing and if an error situation arises, it simply bails out throwing an error. Can leave you in an unstable state. It requires extra work to catch them. Also wrapping the async calls in try/catch won't help because the errors happen asynchronously. To fix this, we need <em>domains</em>. Domains provide an asynchronous try...catch.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> validateObject = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">'object'</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid object'</span>);
    }
};

<span class="hljs-keyword">try</span> {
    validateObject(<span class="hljs-string">'123'</span>);
}
<span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Thrown: '</span> + err.message);
}
</code></pre>
<ul>
<li><strong>Error callback</strong> - returning an error via a callback is the most common error handling pattern in Node.js. Handling error callbacks can become a mess (callback hell or the pyramid of doom).</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> validateObject = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">obj, callback</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">'object'</span>) {
        <span class="hljs-keyword">return</span> callback(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid object'</span>));
    }
    <span class="hljs-keyword">return</span> callback();
};

validateObject(<span class="hljs-string">'123'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Callback: '</span> + err.message);
});
</code></pre>
<ul>
<li><strong>Error emitting</strong> - when emitting errors, the errors are broadcast to any interested subscribers and handled within the same process tick, in the order subscribed.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> Events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">var</span> emitter = <span class="hljs-keyword">new</span> Events.EventEmitter();

<span class="hljs-keyword">var</span> validateObject = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> a !== <span class="hljs-string">'object'</span>) {
        emitter.emit(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Invalid object'</span>));
    }
};

emitter.on(<span class="hljs-string">'error'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Emitted: '</span> + err.message);
});

validateObject(<span class="hljs-string">'123'</span>);
</code></pre>
<ul>
<li><strong>Promises</strong> for async error handling</li>
</ul>
<pre><code class="lang-js">doWork()
.then(doWork)
.then(doError)
.then(doWork)
.catch(errorHandler)
.then(verify);
</code></pre>
<ul>
<li><strong>Try...catch with async/await</strong> - ES7 Async/await allows us as developers to write asynchronous JS code that look synchronous.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'http://no-such-url'</span>);
  } <span class="hljs-keyword">catch</span>(err) {
    alert(err); <span class="hljs-comment">// TypeError: failed to fetch</span>
  }
}

f();
</code></pre>
<ul>
<li><strong>Await-to-js lib</strong> - async/await without try-catch blocks in Javascript</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> to <span class="hljs-keyword">from</span> <span class="hljs-string">'await-to-js'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">main</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-keyword">const</span> [err,quote] = <span class="hljs-keyword">await</span> to(getQuote());

    <span class="hljs-keyword">if</span>(err || !quote) <span class="hljs-keyword">return</span> callback(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'No Quote found'</span>);

    callback(<span class="hljs-literal">null</span>,quote);

}
</code></pre>
<p><strong>Source:</strong> <em>gist.github.com</em></p>
<h3 id="heading-q8-why-should-you-separate-express-app-and-server">Q8: Why should you separate Express 'app' and 'server'? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
Keeping the API declaration separated from the network related configuration (port, protocol, etc) allows testing the API in-process, without performing network calls, with all the benefits that it brings to the table: fast testing execution and getting coverage metrics of the code. It also allows deploying the same API under flexible and different network conditions. Bonus: better separation of concerns and cleaner code.</p>
<p>API declaration, should reside in app.js:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> app = express();
app.use(bodyParser.json());
app.use(<span class="hljs-string">"/api/events"</span>, events.API);
app.use(<span class="hljs-string">"/api/forms"</span>, forms);
</code></pre>
<p>Server network declaration, should reside in /bin/www:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> app = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../app'</span>);
<span class="hljs-keyword">var</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);

<span class="hljs-comment">/**
 * Get port from environment and store in Express.
 */</span>

<span class="hljs-keyword">var</span> port = normalizePort(process.env.PORT || <span class="hljs-string">'3000'</span>);
app.set(<span class="hljs-string">'port'</span>, port);

<span class="hljs-comment">/**
 * Create HTTP server.
 */</span>

<span class="hljs-keyword">var</span> server = http.createServer(app);
</code></pre>
<p><strong>Source:</strong> <em>github.com/i0natan/nodebestpractices</em></p>
<h3 id="heading-q9-rewrite-the-code-sample-without-trycatch-block">Q9: Rewrite the code sample without try/catch block ☆☆☆☆☆</h3>
<p><strong>Details:</strong>
Consider the code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">check</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> someOtherFunction();
    <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> somethingElseFunction();
    res.send(<span class="hljs-string">"result"</span>)
  } <span class="hljs-keyword">catch</span> (error) {
    res.send(error.stack);
  }
}
</code></pre>
<p>Rewrite the code sample without try/catch block.</p>
<p><strong>Answer:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getData</span>(<span class="hljs-params"></span>)</span>{
  <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> someFunction().catch(<span class="hljs-function">(<span class="hljs-params">error</span>)=&gt;</span><span class="hljs-built_in">console</span>.log(error));
  <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> someOtherFunction().catch(<span class="hljs-function">(<span class="hljs-params">error</span>)=&gt;</span><span class="hljs-built_in">console</span>.log(error));
  <span class="hljs-keyword">if</span> (a &amp;&amp; b) <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"some result"</span>)
}
</code></pre>
<p>or if you wish to know which specific function caused error:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loginController</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> loginService().
    catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> CustomErrorHandler({
        <span class="hljs-attr">code</span>: <span class="hljs-number">101</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">"a failed"</span>,
        <span class="hljs-attr">error</span>: error
      })
    });
    <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> someUtil().
    catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> CustomErrorHandler({
        <span class="hljs-attr">code</span>: <span class="hljs-number">102</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">"b failed"</span>,
        <span class="hljs-attr">error</span>: error
      })
    });
    <span class="hljs-comment">//someoeeoe</span>
    <span class="hljs-keyword">if</span> (a &amp;&amp; b) <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"no one failed"</span>)
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">if</span> (!(error <span class="hljs-keyword">instanceof</span> CustomErrorHandler)) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"gen error"</span>, error)
    }
  }
}
</code></pre>
<p><strong>Source:</strong> <em>medium.com</em></p>
<h3 id="heading-q10-how-many-threads-does-node-actually-create">Q10: How many threads does Node actually create? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>4 extra threads</strong> are for use by V8. V8 uses these threads to perform various tasks, such as GC-related background tasks and optimizing compiler tasks.</p>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q11-can-nodejs-work-without-v8">Q11: Can Node.js work without V8? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
No. The current node.js binary cannot work without V8. It would have no Javascript engine and thus no ability to run code which would obviously render it non-functional. Node.js was not designed to run with any other Javascript engine and, in fact, all the native code bindings that come with node.js (such as the fs module or the net module) all rely on the specific V8 interface between C++ and Javascript.</p>
<p>There is an effort by Microsoft to allow the Chakra Javascript engine (that's the engine in Edge) to be used with node.js. Node.js can actually function to some extent without V8, through use of the node-chakracore project. There is ongoing work to reduce the tight coupling between V8 and Node, so that different JavaScript engines can be used in-place.</p>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q12-how-the-v8-engine-works">Q12: How the V8 engine works? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>V8</strong> is a JavaScript engine built at the google development center, in Germany. It is open source and written in C++. It is used for both client side (Google Chrome) and server side (node.js) JavaScript applications.</p>
<p>V8 was first designed to increase the performance of the JavaScript execution inside web browsers. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter. It compiles JavaScript code into machine code at execution by implementing a <strong>JIT (Just-In-Time)</strong> compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn’t produce bytecode or any intermediate code.</p>
<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q13-what-is-the-purpose-of-using-hidden-classes-in-v8">Q13: What is the purpose of using hidden classes in V8? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
JavaScript is a prototype-based language: there are no classes and objects are created by using a cloning process. JavaScript is also dynamically typed: types and type informations are not explicit and properties can be added to and deleted from objects on the fly. </p>
<p>Accessing types and properties effectively makes a first big challenge for V8. Instead of using a dictionary-like data structure for storing object properties and doing a dynamic lookup to resolve the property location (like most JavaScript engines do), V8 creates<strong> hidden classes</strong>, at runtime, in order to have an internal representation of the type system and to improve the property access time.</p>
<p><strong>Source:</strong> <em>thibaultlaurens.github.io</em></p>
<h3 id="heading-q14-how-v8-compiles-javascript-code">Q14: How V8 compiles JavaScript code? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
V8 has two compilers:</p>
<ul>
<li><p>A <strong>“Full” Compiler</strong> that can generate good code for any JavaScript: good but not great JIT code. The goal of this compiler is to generate code quickly. To achieve its goal, it doesn’t do any type analysis and doesn’t know anything about types. Instead, it uses an Inline Caches or “IC” strategy to refine knowledge about types while the program runs. IC is very efficient and brings about 20 times speed improvment.</p>
</li>
<li><p>An <strong>Optimizing Compiler</strong> that produces great code for most of the JavaScript language. It comes later and re-compiles hot functions. The optimizing compiler takes types from the Inline Cache and make decisions about how to optimize the code better. However, some language features are not supported yet like try/catch blocks for instance. (The workaround for try/catch blocks is to write the “non stable” code in a function and call the function in the try block)</p>
</li>
</ul>
<p>V8 also supports <strong>de-optimization</strong>: the optimizing compiler makes optimistic assumptions from the Inline Cache about the different types, de-optimization comes if these assumptions are invalid. For example, if a hidden class generated was not the one expected, V8 throws away the optimized code and comes back to the Full Compiler to get types again from the Inline Cache. This process is slow and should be avoided by trying to not change functions after they are optimized.</p>
<p><strong>Source:</strong> <em>thibaultlaurens.github.io</em></p>
<h3 id="heading-q15-how-does-libuv-work-under-the-hood">Q15: How does libuv work under the hood? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
There is only one thread that executes JavaScript code and this is the thread where the event loop is running provided by <strong>libuv</strong>. The execution of callbacks (know that every userland code in a running Node.js application is a callback) is done by the event loop.</p>
<p>Libuv by default creates a thread pool with four threads to offload asynchronous work to. Today’s operating systems already provide asynchronous interfaces for many I/O tasks (e.g. AIO on Linux).
Whenever possible, libuv will use those asynchronous interfaces, avoiding usage of the thread pool.</p>
<p>The event loop as a process is a set of phases with specific tasks that are processed in a round-robin manner. Each phase has a FIFO queue of callbacks to execute. While each phase is special in its own way, generally, when the event loop enters a given phase, it will perform any operations specific to that phase, then execute callbacks in that phase's queue until the queue has been exhausted or the maximum number of callbacks has executed. When the queue has been exhausted or the callback limit is reached, the event loop will move to the next phase, and so on.</p>
<ul>
<li><strong>timers</strong>: this phase executes callbacks scheduled by <code>setTimeout()</code> and <code>setInterval()</code>.</li>
<li><strong>pending callbacks</strong>: executes I/O callbacks deferred to the next loop iteration.</li>
<li><strong>idle, prepare</strong>: only used internally.</li>
<li><strong>poll</strong>: retrieve new I/O events; execute I/O related callbacks (almost all with the exception of close callbacks, the ones scheduled by timers, and <code>setImmediate()</code>); node will block here when appropriate.</li>
<li><strong>check</strong>: <code>setImmediate()</code> callbacks are invoked here.</li>
<li><strong>close callbacks</strong>: some close callbacks, e.g. <code>socket.on('close', ...)</code>.</li>
</ul>
<div class="text-center">
<img src="https://cdn-images-1.medium.com/max/800/1*ROxiavz7LeRpIfcgRDE7CA.png" class="img-fluid" />
</div>


<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q16-how-does-the-cluster-module-work-whats-the-difference-between-it-and-a-load-balancer">Q16: How does the cluster module work? What’s the difference between it and a load balancer? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
The cluster module performs fork from your server (at that moment it is already an OS process), thus creating several slave processes. The cluster module supports two methods of distributing incoming connections.</p>
<ul>
<li><p>The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process.</p>
</li>
<li><p>The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.</p>
</li>
</ul>
<p>The difference between a cluster module and a load balancer is that instead of distributing load between processes, the balancer distributes requests.</p>
<p><strong>Source:</strong> <em>imasters.com</em></p>
<h3 id="heading-q17-what-is-v8-templates">Q17: What is V8 Templates? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
A template is a blueprint for JavaScript functions and objects. You can use a template to wrap C++ functions and data structures within JavaScript objects. V8 has two types of templates: Function Templates and Object Templates.</p>
<ul>
<li><p><strong>Function Template</strong> is the blueprint for a single function. You create a JavaScript instance of template by calling the template’s GetFunction method from within the context in which you wish to instantiate the JavaScript function. You can also associate a C++ callback with a function template which is called when the JavaScript function instance is invoked.</p>
</li>
<li><p><strong>Object Template</strong> is used to configure objects created with function template as their constructor. You can associate two types of C++ callbacks with object templates: accessor callback and interceptor callback. Accessor callback is invoked when a specific object property is accessed by a script. Interceptor callback is invoked when any object property is accessed by a script. In a nutshell, you can wrap C++ objects\structures within JavaScript objects.</p>
</li>
</ul>
<p><strong>Source:</strong> <em>blog.ghaiklor.com</em></p>
<h3 id="heading-q18-why-do-we-need-c-addons-in-nodejs">Q18: Why do we need C++ Addons in Node.js? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
<strong>Node.js Addons</strong> are dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.</p>
<p>There can be many reasons to write nodejs addons:</p>
<ol>
<li>You may want to access some native apis that is difficult using JS alone.</li>
<li>You may want to integrate a third party library written in C/C++ and use it directly in Node.js.</li>
<li>You may want to rewrite some of the modules in C++ for performance reasons.</li>
</ol>
<p>N-API (pronounced N as in the letter, followed by API) is an API for building native Addons.</p>
<p><strong>Source:</strong> <em>nodejs.org</em></p>
<h3 id="heading-q19-is-it-possible-to-use-class-in-nodejs">Q19: Is it possible to use "Class" in Node.js? ☆☆☆☆</h3>
<p><strong>Answer:</strong>
With ES6, you are able to make "actual" classes just like this:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{

    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.name = name;
    }

    print() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Name is :'</span> + <span class="hljs-built_in">this</span>.name);
    }
}
</code></pre>
<p>You can export a class just like anything else:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{

};
</code></pre>
<p>Once imported into another module, then you can treat it as if it were defined in that file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> Animal = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./Animal'</span>);

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    ...
}
</code></pre>
<p><strong>Source:</strong> <em>stackoverflow.com</em></p>
<h3 id="heading-q20-why-nodejs-devs-tend-to-lean-towards-the-module-requiring-vs-dependency-injection">Q20: Why Node.js devs tend to lean towards the Module Requiring vs Dependency Injection? ☆☆☆☆☆</h3>
<p><strong>Answer:</strong>
Dependency injection is somewhat the opposite of normal <em>module design</em>. In normal module design, a module uses <code>require()</code> to load in all the other modules that it needs with the goal of making it simple for the caller to use your module. The caller can just require() in your module and your module will load all the other things it needs.</p>
<p>With dependency injection, rather than the module loading the things it needs, the caller is required to pass in things (usually objects) that the module needs. This can make certain types of testing easier and it can make mocking certain things for testing purposes easier.</p>
<p>Modules and dependency injection are orthogonal: if you need dependency injection for testability or extensibility then use it. If not, importing modules is fine. The great thing about JS is that you can modify just about anything to achieve what you want. This comes in handy when it comes to testing.</p>
<p><strong>Source:</strong> <em>reddit.com</em></p>
<h3 id="heading-q1-explain-the-result-of-this-code-execution">Q1: Explain the result of this code execution ☆☆☆☆☆</h3>
<p><strong>Details:</strong>
Explain the result of that code execution:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">"events"</span>);

<span class="hljs-keyword">var</span> crazy = <span class="hljs-keyword">new</span> EventEmitter();

crazy.on(<span class="hljs-string">'event1'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event1 fired!'</span>);
    crazy.emit(<span class="hljs-string">'event2'</span>);
});

crazy.on(<span class="hljs-string">'event2'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event2 fired!'</span>);
    crazy.emit(<span class="hljs-string">'event3'</span>);

});

crazy.on(<span class="hljs-string">'event3'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event3 fired!'</span>);
    crazy.emit(<span class="hljs-string">'event1'</span>);
});

crazy.emit(<span class="hljs-string">'event1'</span>);
</code></pre>
<p><strong>Answer:</strong>
You’ll get an exception that basically says the call stack has exploded. Why? Every emit will invoke synchronous code. Because all callbacks are executed in a synchronous manner it’ll just recursive call itself to infinity and beyond.</p>
<p>Output:</p>
<pre><code class="lang-sh">console.js:165
    <span class="hljs-keyword">if</span> (isStackOverflowError(e))
        ^

RangeError: Maximum call stack size exceeded
    at write (console.js:165:9)
    at Console.log (console.js:197:3)
    at EventEmitter.&lt;anonymous&gt; (C:\Work\Node\main.js:6:13)
    at EventEmitter.emit (events.js:182:13)
    at EventEmitter.&lt;anonymous&gt; (C:\Work\Node\main.js:18:11)
    at EventEmitter.emit (events.js:182:13)
    at EventEmitter.&lt;anonymous&gt; (C:\Work\Node\main.js:12:11)
    at EventEmitter.emit (events.js:182:13)
    at EventEmitter.&lt;anonymous&gt; (C:\Work\Node\main.js:7:11)
    at EventEmitter.emit (events.js:182:13)
</code></pre>
<p><strong>Source:</strong> <em>codementor.io</em></p>
<h3 id="heading-q2-explain-the-result-of-this-code-execution">Q2: Explain the result of this code execution ☆☆☆☆☆</h3>
<p><strong>Details:</strong>
Explain the result of this code execution</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);

<span class="hljs-keyword">var</span> crazy = <span class="hljs-keyword">new</span> EventEmitter();

crazy.on(<span class="hljs-string">'event1'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event1 fired!'</span>);
    setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event2'</span>);
    });
});

crazy.on(<span class="hljs-string">'event2'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event2 fired!'</span>);
    setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event3'</span>);
    });

});

crazy.on(<span class="hljs-string">'event3'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event3 fired!'</span>);
    setImmediate(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event1'</span>);
    });
});

crazy.emit(<span class="hljs-string">'event1'</span>);
</code></pre>
<p><strong>Answer:</strong>
Shortly - the app will be run infinitely. Any function passed as the setImmediate() argument is a callback that's executed in the <em>next iteration</em> of the event loop. Without <code>setImmidiate</code> all callbacks are executed in a synchronous manner. With <code>setImmidiate</code> each call back executed as a part of next event loop iteration so no recursion/stuck occurs.</p>
<p><strong>Source:</strong> <em>codementor.io</em></p>
<h3 id="heading-q3-what-will-happen-when-that-code-will-be-executed">Q3: What will happen when that code will be executed? ☆☆☆☆☆</h3>
<p><strong>Details:</strong></p>
<p>What will happen when that code will be executed?</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);

<span class="hljs-keyword">var</span> crazy = <span class="hljs-keyword">new</span> EventEmitter();

crazy.on(<span class="hljs-string">'event1'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event1 fired!'</span>);
    process.nextTick(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event2'</span>);
    });
});

crazy.on(<span class="hljs-string">'event2'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event2 fired!'</span>);
    process.nextTick(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event3'</span>);
    });

});

crazy.on(<span class="hljs-string">'event3'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'event3 fired!'</span>);
    process.nextTick(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        crazy.emit(<span class="hljs-string">'event1'</span>);
    });
});

crazy.emit(<span class="hljs-string">'event1'</span>);
</code></pre>
<p><strong>Answer:</strong>
It’ll get stuck! And if you wait long enough, about 30 seconds, it’ll eventually give you a “process out of memory” exception. Now, the problem is not stack overflow, it’s GC not being able to reclaim memory. Every handler has its own closure to access the crazy on the outer layer. This cost comes out of the heap. Though you might not be 100% why GC can't successfully get the memory back, you can probably guess that the program got stuck in some even loop phase because there’s always another <code>process.nextTick</code> callback to be processed. So essentially, the event loop is blocked completely. </p>
<p><strong>Source:</strong> _codementor.io_Consider the code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doubleAfter2Seconds</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            resolve(x * <span class="hljs-number">2</span>);
        }, <span class="hljs-number">2000</span>);
    });
}
</code></pre>
<p>What if we want to run a few different values through our function and add the result?</p>
<p>Promise-based solution will be:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addPromise</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> {
        doubleAfter2Seconds(<span class="hljs-number">10</span>).then(<span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> {
            doubleAfter2Seconds(<span class="hljs-number">20</span>).then(<span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> {
                doubleAfter2Seconds(<span class="hljs-number">30</span>).then(<span class="hljs-function">(<span class="hljs-params">c</span>) =&gt;</span> {
                    resolve(x + a + b + c);
                })
            })
        })
    });
}

addPromise(<span class="hljs-number">10</span>).then(<span class="hljs-function">(<span class="hljs-params">sum</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(sum);
});
</code></pre>
<p>Async/Await solution will look like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addAsync</span>(<span class="hljs-params">x</span>) </span>{
    <span class="hljs-keyword">const</span> a = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">10</span>);
    <span class="hljs-keyword">const</span> b = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">20</span>);
    <span class="hljs-keyword">const</span> c = <span class="hljs-keyword">await</span> doubleAfter2Seconds(<span class="hljs-number">30</span>);
    <span class="hljs-keyword">return</span> x + a + b + c;
}

addAsync(<span class="hljs-number">10</span>).then(<span class="hljs-function">(<span class="hljs-params">sum</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(sum);
});
</code></pre>
<p><strong>Source:</strong> <em>medium.com</em></p>
]]></content:encoded></item><item><title><![CDATA[TOP NODEJS Interview Questions]]></title><description><![CDATA[What is NPM & how its being used with Node JS npm is the package manager for JavaScript based application and the world’s largest software registry having…]]></description><link>https://articles.tkssharma.com/top-nodejs-interview-questions</link><guid isPermaLink="true">https://articles.tkssharma.com/top-nodejs-interview-questions</guid><category><![CDATA[CRACK NODEJS]]></category><category><![CDATA[Node.js]]></category><category><![CDATA[interview]]></category><category><![CDATA[jobs]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Fri, 04 Oct 2024 16:40:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728068955022/f37c60ca-09c2-41fd-baaf-4ddf1ac5ab82.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-question-1">Question 1</h1>
<p>What is NPM &amp; how its being used with Node JS</p>
<p>npm is the package manager for JavaScript based application and the world’s largest software registry having thousands of javascript modules.You can Discover packages of reusable code — and assemble them in powerful new ways.</p>
<p>NPM is powerful package manager to install new package for your application. It will give you common js modules.</p>
<p>NPM gives you capability to initialize application using package.json.</p>
<p>NPM and yarn are most popular package manager to manage javascript modules.If you are creating some reusable code and wanted to share with others you can create NPM module and push in to NPM and that module can be used by others.</p>
<pre><code>npm initnpm install -save reactnpm instal -g webpacknpm instal — save-dev gulp
</code></pre><p>We can install package globally, Locally and install package in dev dependencies.</p>
<p>Global packages will be available system wide and can be accessed on system cli like webpack and webpack-dev-server modules.</p>
<p>npm as package manager install new package for application which can be added globally locally in your application as local module or local dependencies.</p>
<p>Node js is using NPM and its coming with node version as default package manager to manage dependencies locally and globally.</p>
<h1 id="heading-question-2">Question 2</h1>
<p>What is Node.JS? When should we use Node JS</p>
<p>Node.js is a server side language based on Google’s V8 JavaScript engine.</p>
<p>It is used to build scalable programs and need to run very fast. Its built on top of V8 runtime engine whose baseline in libio &amp; libuv Libraries for c ++.</p>
<p>Node js can be used to build api and application required real time interface like reading live data, streaming data and doing socket communication.</p>
<p>Node js should never be used with CPU intensive tasks like reading huge files and reading lot of data from database and sending it somewhere else.</p>
<p>Node.js is a highly efficient which can scale enough &amp; provide non-blocking I/O running on single thread event loop that was built on top of Google Chrome V8 engine and its ECMAScript.</p>
<ul>
<li>Node JS provide scalable applications</li>
<li>Node JS is server side javascript and single threaded.</li>
<li>Node JS adds non I/O blocking platform.</li>
<li>Node JS is built on top of v8 chrome engine.</li>
<li>Node JS provides faster way to create REST APIs and have good stack of library to support applications.</li>
<li>Node JS providing faster application development and can be used in microservices like environments.</li>
</ul>
<h1 id="heading-question-3">Question 3</h1>
<p>What is of Node js platform stack, what are different libraries it is using.</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/512/0*8D6zO4umZz-oBEPT" /></p>
<p>Node JS using V8 runtime Engine same as chrome is using, it built on top of same chrome engine.</p>
<p>It’s an open source JIT(Just In Time) compiler written in c++ which has outperformed PHP, Ruby and python performance wise. V8 compiler compiles Javascript directly into assembly level code. V8 Runtime environment comprises into 3 major component</p>
<p>Compiler : dissects the JS code</p>
<p>Optimizer : Optimizer called crankshaft create abstract syntax tree(AST) which further converts to SSA : static single assignment and gets optimized</p>
<p>Garbage Collector : it removes dead objects from new space and puts into old space. Garbage collector play vital role in keeping Node Js lightweight.</p>
<p>Base library are c++ library and libeio managing thread pool so javascript engine here is single thread but internally its managing thread pool.</p>
<ol start="2">
<li>Libuv/libio : A C++ library</li>
</ol>
<p>This library handles Node’s asynchronous I/O operation and main event loop. There are thread pool reserve in Libuv which handles the thread allocation to individual I/O operations.</p>
<p>On top of c++ library node js has binding with http, socket io binding which are being invoked by core modules of node js like fs, net, dns, socket.io, http.</p>
<p>Node js standard library are written in javascript to access c++ library interface and access interface as Node js will be running on server not on simple browser accessing html and javascript.</p>
<h1 id="heading-question-4">Question 4</h1>
<p>What is Node JS Architecture.</p>
<p>Node is single threaded and based on non I/O blocking way of dealing with operation.</p>
<p>It is fast and scalable while running on single thread and doing I/O operation like database read, file read in asynchronous way using event loop.</p>
<p>Node JS is single threaded or its javascript interface is single threaded, but this is a half truth, actually it is event-driven and single-threaded with background workers. The Event loop is single-threaded but most of the I/O works run on separate threads, because the I/O APIs in Node.js are asynchronous/non-blocking by design, in order to accommodate the event loop.</p>
<p>Node js event loop is feature of Node js base library, Node js is running on single threaded environment and can provide more performance using this single threaded event driven model, Node js manages event loop keeps running in search of asynchronous request.</p>
<p>Node js event loop keeps running and whenever any asynchronous request comes its places in event loop if event loop is not busy and gets processed and further notified once execution over, Once you are getting multiple async requests then it pushed all request to event queue and start processing request one by one without blocking the code execution.</p>
<p>Event loop is a part of Libeio library and running as single thread keeps waiting for async request ina cycle once it sees anything coming it will process it.</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/2190/0*VOFPFmZjhWpUXXhH" /></p>
<h1 id="heading-question-5">Question 5</h1>
<p>Explain in depth about event loop mechanism in Node JS.</p>
<p>The Event Loop is a queue of callback functions. When an async function executes like setTimeout, the callback function is pushed to the queue. The JavaScript engine doesn’t continue processing the event loop until the code after an async function has executed.</p>
<p>Event-loop is the main part of the node js system. it keeps running and executing as long as node js process are active in memory. It’s responsible for handling asynchronous operations in application like http call, I/O operation and database read. These all request will be queued to the event loop waiting to be executed on the next free I/O, on execution completion the event loop will got notified to trigger a callback to the main function.</p>
<pre><code>request(‘http:<span class="hljs-comment">//www.google.com', function(error, response, body) {console.log(body);});  </span>
<span class="hljs-built_in">console</span>.log(‘Done!’);
</code></pre><p>In above code example, using request module we are making an http call on google.com url. It is asynchronous operation as you will reading data from network. This task will be pushed to event queue if event loop is busy in processing tasks &amp; further once event loop if free, event queue will send that I/O request to event loop for execution. we will get response from the callback added in this code, it will get executed once we have response from I/O task.</p>
<p>Node js runtime execution is not blocked by asynchronous tasks, it will move to the next statement like in above example after running http call using request module it will move to console.log statement. we will see output on console and after sometime we will be notified with this callback with data coming from network request.</p>
<h1 id="heading-question-6">Question 6</h1>
<ol>
<li>What is the role of package.json and what are NPM scripts</li>
</ol>
<p>This file package.json has the information about the project. this gives information to npm that allows it to identify the project as well as handle the project’s dependencies either local or devdependencies.</p>
<p>Some of the fields are basic information like name, name, description, author and dependencies, script and some meta tags.</p>
<p>if you install application using npm then all the dependencies listed will be installed as well. Additionally, after installation it create./node_modules directory.</p>
<p>Package.json is just json file having meta information about application. Here main part is npm scripts which are important part and will be executing our application with different commands. Like running node js process either we write node index.js on terminal directly or we just run npm run start.</p>
<p>Which one is better</p>
<p>We use npm scripts to automate our tasks and list all them together in npm scripts where we can execute them using npm run , npm scripts are powerful you can add pre and post hooks for these tasks. These will work like task runners we used to have like gulp and grunt.</p>
<pre><code>{  
 “name”: “node-js-sample”,  
 “version”: “<span class="hljs-number">0.2</span><span class="hljs-number">.0</span>”,  
 “description”: “A sample Node.js app using Express <span class="hljs-number">4</span>”,  
 “main”: “index.js”,  
 “scripts”: {  
 “start”: “node index.js”  
 },  
 “dependencies”: {  
 “express”: “⁴<span class="hljs-number">.13</span><span class="hljs-number">.3</span>”  
 },  
 “engines”: {  
 “node”: “<span class="hljs-number">4.0</span><span class="hljs-number">.0</span>”  
 },  
 “repository”: {  
 “type”: “git”,  
 “url”: “https:<span class="hljs-comment">//github.com/heroku/node-js-sample"  </span>
 },  
 “keywords”: [  
 “node”,  
 “heroku”,  
 “express”  
 ],  
 “author”: “Mark Pundsack”,  
 “contributors”: [  
 “Zeke Sikelianos &lt;zeke@sikelianos.com&gt; (http:<span class="hljs-comment">//zeke.sikelianos.com)"  </span>
 ],  
 “license”: “MIT”  
}
</code></pre><p>In this above mentioned package.json we have script tag and having start task, so npm scripts enable execution of this tasks using</p>
<p>npm run start will run node index.js</p>
<h1 id="heading-question-7">Question 7</h1>
<p>What is Event-driven programming? And how Node JS is event driven language</p>
<p>From the name itself its clean that what is event driven something driven by some event so in node js we can write events can trigger something once those event occurs</p>
<p>Event driven programming : Node js is having event loop on single thread and there is always one event will be running and always there will be one handle to handle that event without interruption.</p>
<p>Before getting into code of eventEmitter we should understand why event loop is best example of event driven programming.</p>
<p>Event loop perform two operation in a loop</p>
<pre><code><span class="hljs-keyword">var</span> events = <span class="hljs-built_in">require</span>(‘events’);  
<span class="hljs-keyword">var</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();  
<span class="hljs-comment">//Create an event handler:  </span>
<span class="hljs-keyword">var</span> EventHandler = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(‘I hear a voice!’);  
}  
<span class="hljs-comment">//Assign the event handler to an event:  </span>
eventEmitter.on(‘’horror’’, EventHandler);  
<span class="hljs-comment">//Fire the ‘scream’ event:  </span>
eventEmitter.emit(‘horror’)
</code></pre><ol>
<li>Event detection</li>
<li>Event handler triggering</li>
</ol>
<p>There can be different events like on database read do that or on doing this successfully after that run this code.</p>
<p>Those things can be done using events, event is a core modules where we can emit event from one place and can define handler which can take care of handling that event.</p>
<p>Example below showing events by extending EventEmitter class, its code sample using classes where we have created custom event emitter by extending EventEmitter class and emitting event and capturing it.</p>
<pre><code><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(‘events’);  
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EventEmitter</span> </span>{}  
<span class="hljs-keyword">const</span> CustomEmitter = <span class="hljs-keyword">new</span> MyEmitter();  
CustomEmitter.on(‘event’, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(‘processed <span class="hljs-keyword">in</span> first iteration’,a,b);  
});  
CustomEmitter.emit(‘event’, ‘Hi’, ‘Hello’);
</code></pre><h1 id="heading-question-8">Question 8</h1>
<p>How Node JS V8 runtime is different from what we have on chrome console</p>
<p>Chrome console and Node js both are using V8 javascript runtime engine but major difference is Node JS using other c++ core libraries to manage http and socket communication and Chrome V8 engine is mainly browser oriented environments where node js is browserless environment mainly CLI based to execute tasks.</p>
<p>On browser we have access to window, document and console objects and in Node js we don’t have document &amp; window objects available, it is server side runtime environment which can be executed from command line. Node js mainly used for creating HTTP server, socket communication or reading or writing real time data.</p>
<h1 id="heading-question-9">Question 9</h1>
<p>What is the difference between Asynchronous function, Synchronous function or pure functions</p>
<p>Synchronous function : Those function which do simple execution and don’t deal with I/O, These are simple function where we can predict output also and have only basic operation having data manipulation</p>
<p>Asynchronous Function : Special function which deals with network I/O operations like database read, file read or getting data from some api. These operation always takes time while executing and you do not receive instant response from these api.</p>
<p>simple example asynchronous code sample :</p>
<pre><code><span class="hljs-keyword">var</span> userDetails;  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">initialize</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-comment">// Setting URL and headers for request  </span>
 <span class="hljs-keyword">var</span> options = {  
 <span class="hljs-attr">url</span>: ‘https:<span class="hljs-comment">//api.github.com/users/narenaryan'  </span>
 };  
 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{  
 <span class="hljs-comment">// Do async job  </span>
 request.get(options, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, resp, body</span>) </span>{  
 <span class="hljs-keyword">if</span> (err) {  
 reject(err);  
 } <span class="hljs-keyword">else</span> {  
 resolve(<span class="hljs-built_in">JSON</span>.parse(body));  
 }  
 })  
 })  
}<span class="hljs-comment">// Synchronous code samplefunction foo(){}  </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bar</span>(<span class="hljs-params"></span>)</span>{  
 foo();  
}  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">baz</span>(<span class="hljs-params"></span>)</span>{  
 bar();  
}  
baz();
</code></pre><h1 id="heading-question-10">Question 10</h1>
<p>what are different options to write asynchronous code in Node.</p>
<blockquote>
<p>Using setTimeout we can run some code after defined time</p>
<p>Using callback : return function from another function after asynchronous task is over.</p>
<p>Using Async module : async module in node js</p>
<p>Using promises : using native promises and wait until promise is resolved</p>
<p>Using some library like bluebird,Q library.</p>
<p>Using async/await : write less line of code by using async await</p>
</blockquote>
<h2 id="heading-node-js-interview-question-set-01">Node JS Interview Question — Set #01</h2>
<h1 id="heading-question-11">Question 11</h1>
<p>how single threaded Node JS handles concurrency when multiple I/O operations happening</p>
<p>Node provides a single thread to the code we are writing so that code can be written easily and without bottleneck and without I/O blocking Node internally uses multiple POSIX/unix threads for various I/O operations such as network read, database read or file read operations.</p>
<p>When Node apis or code get I/O request it creates a thread from thread pool to perform that asynchronous operation and once the operation is done, it pushes the result to the event queue. On each such event, event loop runs and checks the queue and if the execution stack of Node is empty then it adds the queue result to execution stack.</p>
<p>This is how Node manages concurrency.</p>
<p>Reference : <a target="_blank" href="https://strongloop.com/strongblog/node-js-is-faster-than-java/">https://strongloop.com/strongblog/node-js-is-faster-than-java/</a></p>
<p>Request modeling is different, In node js its not creating separate thread for every request, just running event loop and delegating to async thread for running async tasks.</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3200/0*fr65aKR3wSjSnulo" /></p>
<h1 id="heading-question-12">Question 12</h1>
<p>What is Node JS callback and how it helps to run Async tasks</p>
<p>Callback is a Node.js function which can be created with plain javascript code. While writing callback you don’t need node js environment. It’s just higher order function which takes function as argument and return callback function . This function is used to avoid I/O or network blocking and allows next instruction to run</p>
<p>Node JS handle all asynchronous calls via callback natively. Callbacks are just functions that you pass to other functions. which we call as higher order function in javascript. Example on callback is while reading file using fs node js core module we pass first argument is the path of the file and second argument is a function, which is nothing but a callback function</p>
<p>Node.js use callback function extensively. Node APIs are written to support callbacks of Node JS.</p>
<pre><code><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(“fs”);  
 fs.readFile(‘app.txt’, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err, data</span>) </span>{  
 <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">return</span> <span class="hljs-built_in">console</span>.error(err);  
 <span class="hljs-built_in">console</span>.log(data.toString());  
 });  
 <span class="hljs-built_in">console</span>.log(“Program Ended”);
</code></pre><h1 id="heading-question-13">Question 13</h1>
<p>Explain basic async apis in javascript like setTimeout, setImmediate &amp; setInterval</p>
<p>The setTimeout &amp; setInterval are the 2 timers functions.these function are being used to create timer function.</p>
<p>setTimeout :- This function is used to delay the execution of code written under it. This will execute once after the defined delay in milliseconds.</p>
<p>After 1 second we will get console message saying “Hello”</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(‘Hello’);  
}  
<span class="hljs-built_in">setTimeout</span>(sayHi, <span class="hljs-number">1000</span>);<span class="hljs-built_in">setInterval</span> :-  <span class="hljs-keyword">if</span> you want to execute a <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">many</span> <span class="hljs-title">times</span> <span class="hljs-title">or</span> <span class="hljs-title">unlimited</span> <span class="hljs-title">times</span> <span class="hljs-title">then</span> <span class="hljs-title">we</span> <span class="hljs-title">can</span> <span class="hljs-title">use</span> .<span class="hljs-title">setInterval</span>(<span class="hljs-params"></span>) <span class="hljs-title">by</span> <span class="hljs-title">passing</span> <span class="hljs-title">the</span> <span class="hljs-title">interval</span> <span class="hljs-title">duration</span>.</span>
</code></pre><p>This function will keep executing after every second and print value of i on console</p>
<pre><code><span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span>(<span class="hljs-params"></span>) </span>{  
i++;  
_console_.log(i);  
}  
<span class="hljs-keyword">var</span> myVar = <span class="hljs-built_in">setInterval</span>(increment, <span class="hljs-number">1000</span>);  
<span class="hljs-comment">// clearInterval(myVar);</span>
</code></pre><p>clearInterval method will be used to clearout the execution of method from setInterval</p>
<p>setImmediate() and setTimeout() are based on the event loop.</p>
<p>Another important method in setImmediate, we use setImmediate if we want to queue the function behind whatever I/O event callbacks that are already in the event queue.</p>
<p>we can use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes. It queues them immediately after the last I/O handler somewhat like process.nextTick. So it is faster.</p>
<h1 id="heading-question-14">Question 14</h1>
<p>What is REPL in Node JSand how it helps to run code.</p>
<p>Node.js comes with environment called REPL (aka Node shell). REPL stands for Read-Eval-Print-Loop, its easiest way to run node js code on console.</p>
<p>The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using:</p>
<p>will give you a result which is similar to the one you will get in the console of Google Chrome browser, it look like chrome console without browser based apis</p>
<p>const repl = require(‘repl’);</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/2512/0*7l-UKBgt62cia0fG" /></p>
<h1 id="heading-question-15">Question 15</h1>
<p>What are core and important modules in node JS which used frequently and explain difference between core module and user defined module</p>
<p>Node.js being lightweight framework. All the core modules include minimum functionalities of Node.js. These core modules are compiled into its binary distribution and load automatically when Node.js process starts</p>
<blockquote>
<p>Cluster The cluster module helps us to create children process that runs simultaneously and share the same server port. So using this we can create process running on same port, As node js is single threaded and efficiently use memory by consuming single core only but when we are running on multi core system in such case to take advantage of multi-core systems Cluster module allows you to easily create child processes that each runs on their own single thread, to handle the load.</p>
</blockquote>
<p>Crypto — To handle OpenSSL cryptographic functions<br />Dgram — Provides implementation of UDP datagram sockets<br />Dns — To do DNS lookups and name resolution functions<br />Domain — Deprecated. To handle unhandled errors<br />Events — To handle events<br />Fs — To handle the file system<br />Http — To make Node.js act as an HTTP server<br />Https — To make Node.js act as an HTTPS server.<br />Net — To create servers and clients<br />Os — Provides information about the operation system<br />Path — To handle file paths</p>
<p>All above mentioned are code module in node js as they are coming bundled with node js installation. User defined module are those which we are creating in node js application and writing module.export in file and again making them require in another file.</p>
<p>Reference : <a target="_blank" href="https://nodejs.org/api/synopsis.html">https://nodejs.org/api/synopsis.html</a></p>
<h1 id="heading-question-16">Question 16</h1>
<p>Explain events in Node JS and how events are helping us to create event driven system.</p>
<p>every action has reaction similarly every event has it handler to catch the action and take action on it.</p>
<p>In node js we have event emitter which is used to emit event and further that event can be captured to perform some operation.</p>
<p>Events can be compared by simple socker.io example when server broadcast a message it can be captured by all client who are subscribing to that channel.</p>
<p>Node.js has a built-in core module known as “Events”, where you can create, fire, and listen for your own events.</p>
<p>Its plain and simple we create events and written handler at another place to capture that event</p>
<p>To include the built-in Events module use the require() method. All event properties and methods are an instance of EventEmitter object available on events so to be able to access these properties and methods we need to create an EventEmitter object:</p>
<pre><code><span class="hljs-keyword">var</span> events = <span class="hljs-built_in">require</span>(‘events’);  
<span class="hljs-keyword">var</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();
</code></pre><p>Here is the example where we are emitting event name “scream” and there is a handler my eventHandler which is capturing this event and processing task. These events are like fire and forget you fire and forget them.</p>
<pre><code><span class="hljs-keyword">var</span> events = <span class="hljs-built_in">require</span>(‘events’);  
<span class="hljs-keyword">var</span> eventEmitter = <span class="hljs-keyword">new</span> events.EventEmitter();<span class="hljs-comment">//Create an event handler:  </span>
<span class="hljs-keyword">var</span> myEventHandler = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(‘I hear a scream!’);  
}<span class="hljs-comment">//Assign the event handler to an event:  </span>
eventEmitter.on(‘scream’, myEventHandler);<span class="hljs-comment">//Fire the ‘scream’ event:  </span>
eventEmitter.emit(‘scream’);
</code></pre><h1 id="heading-question-17">Question 17</h1>
<p>How we can read file in synchronous way &amp; asynchronous way using fs module.</p>
<p>The normal behaviour in Node.js is to read in the content of a file in a non-blocking,asynchronous way. That is to tell Node to read the file and return callback once you are done with reading file, there are different events also like file read started or file read over.</p>
<p>We use core module fs and fs.readfile provides asynchronous way of reading file</p>
<p>For this we can use the readFile method of the fs core module</p>
<p>Node js core module fs takes 3 arguments, These arguments are name of the file (‘app.txt’ in this case), the encoding of the file (‘utf8’), and a callback function as argument. This function which is a callback function going to be called when the file-reading operation has finished and we will see file content printed on terminal.</p>
<p>As this operation is non I/O blocking and asynchronous in nature, this will be process using event loop but execution will not be blocked we will see message “file read is over” before getting file contents on terminal</p>
<pre><code><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(‘fs’);  
fs.readFile(app.txt, ‘utf8’, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err, contents</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(contents);  
});  
<span class="hljs-built_in">console</span>.log(‘file read is Over’);
</code></pre><p>There is another way to use blocking file read operation using fs.readFileSync which will read file in synchronous way and it block the execution until unless file read operation is over.</p>
<pre><code><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(‘fs’);  
<span class="hljs-keyword">var</span> contents = fs.readFileSync(‘app.txt’, ‘utf8’);  
<span class="hljs-built_in">console</span>.log(contents);<span class="hljs-built_in">console</span>.log(‘file read is Over’);
</code></pre><h1 id="heading-question-18">Question 18</h1>
<p>How to capture command line arguments while executing node js process.</p>
<p>The arguments are stored in process.argv when you pass args with node command</p>
<p>like node index.js “hello” “world”</p>
<p>[runtime] [script_name] [argument-1 argument-2 argument-3 … argument-n]</p>
<p>process.argv is an array containing the command line arguments. The first element will be ‘node’, the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.</p>
<p>we can get all arguments printed using this Loop</p>
<p>and we can pass information to an application before it starts. This is particularly useful if you want to perform some settings before starting application like passing env and port</p>
<pre><code>process.argv.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">val, index, array</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(index + ‘: ‘ + val);  
});
</code></pre><h1 id="heading-question-19">Question 19</h1>
<p>What is error check first in callback handler defined in Node JS code.</p>
<p>generally, the first argument to any callback handler is an an error object and there is a reason to pass first argument as error object in callback handler which can be either null or error object so while dealing with callback we can check if we have received null or some error object</p>
<p>if we get error object then we will perform our action based on error. Error handling by a typical callback handler could be as follows:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callback</span>(<span class="hljs-params">err, results</span>) </span>{  
 <span class="hljs-comment">// usually we’ll check for the error before handling results  </span>
 <span class="hljs-keyword">if</span>(err) {  
 <span class="hljs-comment">// handle error somehow and return  </span>
 }  
 <span class="hljs-comment">// no error, perform standard callback handling  </span>
}
</code></pre><p>This is applied to all callbacks we write in our code and its part of ESLint configuration which force developer to write code in this way.</p>
<h1 id="heading-question-20">Question 20</h1>
<p>What are different module pattern in javascript, can you explain common JS modules.</p>
<p>In JavaScript, the word “modules” refers to small units of independent, reusable code. They are the foundation of many JavaScript design patterns and are critically necessary when building any non-trivial JavaScript-based application.</p>
<p>We have different module pattern in javascript like commonjs, AMD, UMD and ES6 modules</p>
<p>A CommonJS module is essentially a reusable piece of code can be fetched from either nomjs.com repository or created locally. From module we can exports specific objects, making them available for other modules to require in their programs. While writing node js code you have seen this and may be very familiar with this format.</p>
<p>Using Common JS every JavaScript file stores modules in its own unique module context (just like wrapping it in a closure).We use module.export to export module and require to require that module in another file.</p>
<p>module.export and require syntax we use everywhere in Node js Code, all common js modules are imported in such a way only</p>
<pre><code><span class="hljs-keyword">var</span> app = <span class="hljs-built_in">require</span>(‘./app’)  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myModule</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">this</span>.hello = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-keyword">return</span> ‘hello!’;  
 }  
 <span class="hljs-built_in">this</span>.goodbye = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-keyword">return</span> ‘goodbye!’;  
 }  
}  
<span class="hljs-built_in">module</span>.exports = myModule;
</code></pre><p><img class="cp t u fv ak" src="https://miro.medium.com/max/1400/0*wsNJ7KtXPU4p9X-m" /></p>
<h1 id="heading-question-21">Question 21</h1>
<p>What is callback hell and how can it be avoided any library which can be used and how to promisify the library</p>
<p>Callback hell refers to a coding style which we use like when we add nested callbacks in application, Lot of nesting of callback functions create callback hell. The code it becomes difficult to debug and understand in such cases we can use other library to overcome with callback hell problem</p>
<blockquote>
<p>a. Using promises<br />b. Yield operator and Generator functions from ES6<br />c. Modularising code<br />d. Using async library using async waterfall<br />e. by not doing nested callback</p>
</blockquote>
<p>In javascript most of library supports callback way of writing code like redis-client, mysql-client all such library are callback based so better if we promisify these library and use them with promises</p>
<p>We can use util core module to promisify module in node js like we can promisify fs module which provide callback based operation fileread.</p>
<p>Now callback based file read write operation become promise based and we need to do “.then()” to capture response from resolved promise.</p>
<h1 id="heading-question-22">Question 22</h1>
<p>What are promises and how to use promises for simple AJAX call or for multiple AJAX calls</p>
<p>Promises give an alternate way to write asynchronous code and it gives advantages over callback.</p>
<p>We can use promises instead of using callbacks. Promises either return the result of execution or the error/exception. Promises have different state resolved, rejected or pending state. Once promise resolved or rejected .then method gets triggered Promises simply requires the use of &lt;.then()&gt; function which waits for the promise object to return and once you have final state it gets executed. Promise.then() function takes two arguments, both are callback functions first for success callback and another error callbacks.</p>
<pre><code>readFileAsync(filePath, {<span class="hljs-attr">encoding</span>: ‘utf8’})  
 .then(<span class="hljs-function">(<span class="hljs-params">text</span>) =&gt;</span> {  
 <span class="hljs-built_in">console</span>.log(‘CONTENT:’, text);  
 })  
 .catch(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {  
 <span class="hljs-built_in">console</span>.log(‘ERROR:’, err);  
 });  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">readFileAsync</span>(<span class="hljs-params"></span>)</span>{  
 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Promises(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve,reject</span>)</span>{  
 resolve(‘some data’)  
 })  
}
</code></pre><h1 id="heading-question-23">Question 23</h1>
<p>What is global object in Node JS &amp; how it can used to manage environments in application.</p>
<p>The Global keyword represents the global namespace object, we can get what is in global by opening node terminal or you can do console.log(global) in your application</p>
<p>when we declare variable using let/const those are module specific modules but when we declare without using let/var they gets added to global namespace of application.</p>
<p>We can also add few things on global object like runtime environment configuration</p>
<p>Process, buffer is also part of Global object</p>
<p>Process in very big object having all information about process here we also have global.process.env where we can manage environment specific configuration</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3200/0*KY0SPQbYlOW3TfM4" /></p>
<p>In our application we pass these env variable while running node application like</p>
<blockquote>
<p>Node index.js node_env=local port=5009</p>
</blockquote>
<p>In this example we will get local when we try to get value of process.env.node_env and will get 5009 when we do process.env.port in our code.</p>
<h1 id="heading-question-24">Question 24</h1>
<p>What are streams and how it’s different from normal api response</p>
<p>Streams are just flow of data, steam pipes that let you easily read data from a source and pipe it to a destination. so stream are easy to pipe from one source to another, A stream is nothing but an EventEmitter and implements some specials methods. Depending on the applied methods in node js code , a stream becomes Readable, Writable, or Duplex (both readable and writable).</p>
<p>There are different use cases of streams we can use stream to pipe response to api server.</p>
<p>For example we can create file reader stream which read file until data in completed from that file and during that we have some events also like read start or data event or error events</p>
<pre><code><span class="hljs-keyword">var</span> fs = <span class="hljs-built_in">require</span>(“fs”);  
<span class="hljs-keyword">var</span> data = ‘’;  
<span class="hljs-keyword">var</span> readerStream = fs.createReadStream(‘input.txt’);  
readerStream.setEncoding(‘UTF8’);  
readerStream.on(‘data’, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">chunk</span>) </span>{  
 data += chunk;  
});  
readerStream.on(‘end’,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{  
 <span class="hljs-built_in">console</span>.log(data);  
});  
readerStream.on(‘error’, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">err</span>)</span>{  
 <span class="hljs-built_in">console</span>.log(err.stack);  
});
</code></pre><h1 id="heading-question-25">Question 25</h1>
<p>How we can have separate config for development &amp; production</p>
<p>environments, configuration file like which manages database connection</p>
<p>There are different option either you can use .dotenv module to manage configuration for application runtime.</p>
<p>We can manage different config file based on different environments like dev.properties qa.properties file</p>
<p>At runtime we should pass process.env.NODE_DNV as either development or production so in code we can load appropriate env file and further we can load its configurations like mongodb url, Mysql connection url which will be different for development and production</p>
<p>we can require that file and can get configuration object and pass them wherever required.</p>
<pre><code><span class="hljs-keyword">var</span> config = {  
 <span class="hljs-attr">production</span>: {  
 <span class="hljs-attr">mongo</span> : {  
 <span class="hljs-attr">url</span>: ‘’  
 }  
 },  
 <span class="hljs-attr">dev</span>: {  
 <span class="hljs-attr">mongo</span> : {  
 <span class="hljs-attr">url</span>: ‘’  
 }  
 }  
}  
<span class="hljs-built_in">exports</span>.get = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">get</span>(<span class="hljs-params">env</span>) </span>{  
 <span class="hljs-keyword">return</span> config[env] || config.default;  
}  
<span class="hljs-keyword">const</span> config = <span class="hljs-built_in">require</span>(‘./config/config.js’).get(process.env.NODE_ENV);  
<span class="hljs-keyword">const</span> dbconn = mongoose.createConnection(config.mongo.url);
</code></pre><h1 id="heading-question-26">Question 26</h1>
<p>What are the modules type which node js currently supporting.</p>
<p>In Javascript we have modules like es6, commonjs, AMD,UMD.</p>
<p>The obvious one for Node JS is CommonJS, which is the current module system used by Node JS (the one that uses require and module.exports). CommonJS already is a module system for NodeJS, and ES Modules has to learn to live side by side and interoperate with it</p>
<p>whatever we do today using module.export &amp; require all are common js modules available on npm repository</p>
<p>All module downloaded from npmjs.com or npm repository supports common js style of require and exports</p>
<p>Till now if we want to use ES6 modules in ES6 like using import and export syntax we have to use babel polyfill like babel-register or babel-node as there is no native support for ES6 modules in node js</p>
<p>Node js native doesn’t support ES6 modules or code like import/export</p>
<p>But now native support is coming but with slight change, these will be called ESM module with extension of .esm</p>
<pre><code><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> spout = ‘the spout’  
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handle = ‘the handle’  
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> tea = ‘hot tea’<span class="hljs-keyword">import</span> {handle, spout, tea} <span class="hljs-keyword">from</span> ‘./<span class="hljs-number">01</span>-kettle.mjs’<span class="hljs-built_in">console</span>.log(handle) <span class="hljs-comment">// ==&gt; the handle  </span>
<span class="hljs-built_in">console</span>.log(spout) <span class="hljs-comment">// ==&gt; the spout  </span>
<span class="hljs-built_in">console</span>.log(tea) <span class="hljs-comment">// ==&gt; hot tea</span>
</code></pre><h1 id="heading-question-27">Question 27</h1>
<p>what is the differences between promises, callback &amp; async await</p>
<p>Async await has been introduced recently and powerful tool to write asynchronous code in synchronous fashion, async await code look like simple synchronous code and it blocks the event loop and implemented on top of promises only.</p>
<p>Async functions</p>
<p>For async we just need to add it before function name as “async” function</p>
<pre><code><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;  
}
</code></pre><p>Async before a function always returns a promise. If the code has return  in it, then JavaScript automatically wraps it into a resolved promise with that value.</p>
<p>let value = await promise;</p>
<p>The keyword await makes JavaScript wait until that promise settles and returns its result.</p>
<p>Here’s example with a promise that resolves in 1 second:</p>
<pre><code><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">f</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {  
 <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> resolve(“done!”), <span class="hljs-number">1000</span>)  
 });  
 <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> promise; <span class="hljs-comment">// wait till the promise resolves (*)  </span>
 alert(result); <span class="hljs-comment">// “done!”  </span>
}  
f();
</code></pre><p>Promises are another important tool in javascript to manage asynchronous code.</p>
<p>Promises either return the result of execution or the error/exception. Promises have different state resolved, rejected or pending state. Once promise resolved or rejected .then method gets triggered, Promises simply requires the use of &lt;.then()&gt; function which waits for the promise object to return and once you have final state it gets executed. Promise.then() function takes two arguments, both are callback functions first for success callback and another error callbacks.</p>
<p>Promises allow us to cleanly chain chain subsequent operations while avoiding callback hell and as long as you always return a promise for each of your then blocks, it will continue down the chain.</p>
<p>Promises are now supported in native code so no need to add external library. Promises are just representation of asynchronous code which can be in resolved/rejected state and accordingly .then function will execute with proper callback</p>
<p>Little bit about callback</p>
<p>Node handles all asynchronous operation using callback natively. Callbacks are just functions that you pass to other functions. Example like while reading file using fs core module we pass first argument is the path of the file and second argument is a function, which is nothing but a callback function</p>
<h1 id="heading-question-28">Question 28</h1>
<p>What is event loop, is it part of V8 runtime environment and also available on browser.</p>
<p>The event loop is provided by the libuv library. It is not part of V8 runtime env.</p>
<p>it is single thread entity keeps running in node js process and keep listening the event queue.</p>
<p>The Event Loop is the entity that handles external events and converts them into callback invocations. It is a loop that picks events from the event queues and pushes their callbacks into the Call Stack.</p>
<p>There is only one thread that executes JavaScript code and this is the thread where the event loop is running. The execution of callbacks is done by the event loop.</p>
<p>To understand more on event loop you can use this reference link</p>
<p><a target="_blank" href="https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c">https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c</a></p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/2748/0*jhSp7O52Z6XpZopT" /></p>
<h1 id="heading-question-29">Question 29</h1>
<p>what will be the state of Node JS process when event loop is empty and call stack both are empty.</p>
<p>In such case node js process will exit as it has nothing to process nothing to execute, it is different from any other process, when we start node js process it will start event loop and if there is nothing to execute in event loop it will exit from there</p>
<p>To prevent this situation we always create http server where server keeps telling event loop for listening http request events and event loop is not totally idle.</p>
<pre><code><span class="hljs-keyword">var</span> http=<span class="hljs-built_in">require</span>(‘http’)  
<span class="hljs-keyword">var</span> server=http.createServer(serverFn)  
server.listen(<span class="hljs-number">7000</span>);
</code></pre><h1 id="heading-question-30">Question 30</h1>
<p>What is call stack, is it part of V8 runtime environment ?</p>
<p>Yes call stack is a part of Javascript having either chrome V8 engine or chakra engine.</p>
<p>The JavaScript engine V8 is a single threaded interpreter having a heap and a single call stack. The browser additionally provides some APIs like the DOM, AJAX, and Timers. This is main core functionality which is responsible to execute functions using heap and call stack (Stack which use LIFO pattern)</p>
<p>Call stack operates by principle of Last In, First Out known as LIFO, it says that the last function that gets pushed into the stack is the first to be pop out, when the function returns.It pure stack like data structure based operation.</p>
<p>We can see that in below example where function calling each other.</p>
<ol>
<li><p>When secondFn() gets executed, an empty stack frame is created. It is the main entry point of the program.</p>
</li>
<li><p>secondFn() then calls firstFn() which is pushed into the stack using LIFO pattern.</p>
</li>
<li><p>firstFn() returns and prints “Hello from firstFn” to the console.</p>
</li>
<li><p>firstFn() is pop off the stack.</p>
</li>
<li><p>The execution order then move to secondFunction().</p>
</li>
<li><p>secondFn() returns and print “The end from secondFunction” to the console.</p>
</li>
<li><p>secondFn() is pop off the stack, clearing the memory occupied.</p>
</li>
</ol>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">firstFn</span>(<span class="hljs-params"></span>)</span>{  
 <span class="hljs-built_in">console</span>.log(‘hello <span class="hljs-keyword">from</span> first Fn’);  
}  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">secondFn</span>(<span class="hljs-params"></span>)</span>{  
 firstFn();  
}  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">thirdFn</span>(<span class="hljs-params"></span>)</span>{  
 secondFn();  
}  
thirdFn();
</code></pre><h1 id="heading-question-31">Question 31</h1>
<p>Have you used yarn as package manager and how its different from NPM</p>
<p>Yarn is just another package manager for installing and managing javascript libraries for application. Yarn is using the same registry that npm does. That means that every package that is a available on npm is the same on Yarn.</p>
<p>To add a package, run yarn add .</p>
<p>If you need a specific version of the package, you can use yarn add package@version</p>
<p>yarn also have init command</p>
<p>The yarn init command will walk you through the creation of a package.json file to configure some information about your package. This is same as we do npm init using npm package manager</p>
<p>these are following differences we can see</p>
<p>Yarn has a few differences from npm. Yarn is doing caching of all installed packages. Yarn is installing the packages simultaneously and when we install packages with Yarn it look like faster than NPM. Both yarn and NPM downloading packages from same NPM repository.</p>
<p>On the contrary to npm, Yarn provides stability, putting lock on versions of installed packages. The speed is higher while installing packages. It is very important for big projects, which have more dependencies</p>
<h1 id="heading-question-32">Question 32</h1>
<p>What are the tools to deploy node js application on server.</p>
<p>There are many popular tool to deploy node js app on server which will keep node js application up and running and if there is any issue it will restart process like PM2, forever, supervisord</p>
<p>PM2 provides :</p>
<ol>
<li>Built in load balancer</li>
<li>Multiple instance of application running on same port.</li>
<li>Can run application in cluster mode.</li>
<li>Can manage deployment of multiple application using single config.</li>
<li>Provides multiple deployment options.</li>
<li>Provides zero downtime on application deployment.</li>
</ol>
<p>If you use pm2, you can easily hook it with keymetrics.io monitoring tool to see api statics.</p>
<p>npm install -g pm2<br />pm2 start app.js</p>
<p>Zero-config Load-Balancer Link</p>
<p>PM2 enable use to create multiple instance to scale up your application by creating instances that share the same server port. Doing this also allow you to restart your app with zero-seconds downtimes.</p>
<p>PM commands to start/stop/delete application instance</p>
<p>pm2 start app.js — name “my-api”</p>
<p>pm2 start web.js — name “web-interface”</p>
<p>pm2 stop web-interface. …</p>
<p>pm2 restart web-interface. …</p>
<p>pm2 delete web-interface. …</p>
<p>pm2 restart /http-[1,2]/ …</p>
<p>pm2 list # Or pm2 [list|ls|l|status]</p>
<p>pm2 list command showing all available instances and pm2 monit command showing monitoring for all running instances</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3200/0*pzO-erzJeIVNZLnO" /></p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3200/0*R4av-BTK2E76Pb8Q" /></p>
<p>PM2 has lot of advantages over other tools it gives you everything and its is industry standard for node js deployments.</p>
<h1 id="heading-question-33">Question 33</h1>
<p>How to graceful shutdown your Node JS process when something bad happens in code like database connection lost.</p>
<p>graceful shutdown means whenever node js process shut down in that case we need to shut process down gracefully by closing all db connection by releasing TCP port and releasing all occupied resources so when node process comes up again there should be no any issues</p>
<p>graceful shot down can be done in different way</p>
<p>Shutdown can happen using some code issue like unhandled promise rejection, some javascript code null check missing or database shutdown or forcefully by user using Ctrl + C</p>
<pre><code>process.on(‘unhandledRejection’, ErrorHandler.unhandledRejection);  
process.on(‘SIGINT’, ErrorHandler.shutdown);  
process.on(‘uncaughtException’, ErrorHandler.onError);process  
 .on(‘unhandledRejection’, <span class="hljs-function">(<span class="hljs-params">reason, p</span>) =&gt;</span> {  
 <span class="hljs-built_in">console</span>.error(reason, ‘Unhandled Rejection at <span class="hljs-built_in">Promise</span>’, p);  
 <span class="hljs-comment">// release database connection   </span>
 <span class="hljs-comment">// release resources  </span>
 });
</code></pre><h1 id="heading-question-34">Question 34</h1>
<p>How can you make sure of zero downtime while Node JS deployment of your application</p>
<p>zero downtime means whenever we deploy node js application it stop the application and then start it again in this case there is a downtime of some seconds until application gets connected to database like redis, mysql. Zero downtime can’t be achieved with single instance when we have huge traffic coming for APIs.</p>
<p>PM2 is powerful tool to manage multiple instances running multiple core of one machine. On multi core system we should always have multiple instance of PM2 to optimally consume multiple cores of system.</p>
<ol>
<li>For having zero downtime we should run application in cluster mode which allows networked Node.js applications (http(s)/tcp/udp server) to be scaled across all CPUs available, without any code modifications. This greatly increases the performance and reliability of your applications, depending on the number of CPUs available</li>
</ol>
<p>To enable the cluster mode, just pass the -i option:</p>
<p>pm2 start app.js -i max ( max means that PM2 will auto detect the number of available CPUs and run as many processes as possible)</p>
<p>For zero downtime we should use pm2 reload not restart command, reload is different from restart as it will start reloading one by one and not doing reload on all instance together. pm2 restart app-name ,which kills and restarts the process. pm2 reload app-name which restart your workers one by one, and for each worker, wait till the new one has spawned before killing the old one. Using this reload we can serve request by live workers without having any issue in api-services.</p>
<p>This below mentioned configuration “ecosystem.config.js” will create max number of instances based on available core on system and run all instances in cluster mode.</p>
<p>pm2 startOrReload ecosystem.config.js — update-env</p>
<p>This command will start max number of instance if they have not been created yet or reload the existing created instances. — update-env parameter will reload instance with some newly added configuration.</p>
<pre><code>Ecosystem.config.js file:<span class="hljs-built_in">module</span>.exports = {  
 <span class="hljs-attr">apps</span>: [  
 {  
 <span class="hljs-attr">name</span>: ‘api_app’,  
 <span class="hljs-attr">script</span>: ‘app/server.js’,  
 <span class="hljs-attr">instances</span>: “max”  
 }  
 ]  
};
</code></pre><h1 id="heading-question-35">Question 35</h1>
<p>What is the use of cluster module and how to use it.</p>
<p>cluster module provide a way to create child process. In some cases we may need to have a child process for running some independent process and want to distribute some process. For that purpose we can use Cluster module which will create another child process and that process is created using like forking a process.</p>
<p>The cluster module is core node js module like fs,net module. Cluster module contains a set of functions and properties that help us forking processes to take advantage of multi-core systems. Node js runs on single core system but when we have multi core system and in that case to use that multi core system we should create child process which are equal to number of processor in system</p>
<pre><code><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(‘cluster’);  
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(‘http’);  
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(‘os’).cpus().length;  
<span class="hljs-keyword">if</span> (cluster.isMaster) {  
 masterProcess();  
} <span class="hljs-keyword">else</span> {  
 childProcess();   
}  
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">masterProcess</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Master <span class="hljs-subst">${process.pid}</span> is running`</span>);  
 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numCPUs; i++) {  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Forking process number <span class="hljs-subst">${i}</span>…`</span>);  
 cluster.fork();  
 }  
 process.exit();  
}
</code></pre><h1 id="heading-question-37">Question 37</h1>
<p>How can you debug you Node JSapplication.</p>
<p>If you are using vscode like tool for writing node js apps then debugging is easier you can just run debugger in few simple steps.</p>
<p>To start debugging, run your Node.js application with the — inspect flag.</p>
<p>$ node — inspect .js</p>
<p>And you need to add chrome dev tools for that so you can launch debugger on chrome on some port and can do debugging like you do for client side javascript code.</p>
<p>Another option is node-inspector</p>
<p>$ npm install -g node-inspector</p>
<p>$ node-debug app.js</p>
<p>where app.js is the name of your main Node application JavaScript file.</p>
<p>The node-debug command will load Node Inspector in your default browser.</p>
<h1 id="heading-question-38">Question 38</h1>
<p>what are streams and why we should use it with large data.</p>
<p>Streams are collections of items such as we have array as collection. The difference is that streams data might not be available all at same time and not necessary they all fit in existing memory. Stream data are not for synchronous execution. Stream are meant to be received over the time asynchronously.</p>
<p>Stream are powerful tools to send response from apis when you have big data to send.</p>
<p>This makes streams really powerful when working with large amounts of data, or data that’s coming from an external source one chunk at a time like file reading of big size. In that case we have to read file in chunks and need to stream that data to send in response.</p>
<p>They also give us the power of sending data in chunks. Just like we use pipe command in linux and send data of one command to another command, we can do exactly the same in Node with streams.</p>
<pre><code><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(‘fs’);  
<span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(‘http’).createServer();server.on(‘request’, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
 fs.readFile(‘./app.txt’, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {  
 <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;  

 res.end(data);  
 });  
});<span class="hljs-comment">// using streams //  </span>
server.on(‘request’, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {  
 <span class="hljs-keyword">const</span> src = fs.createReadStream(‘./xpp.txt’);  
 src.pipe(res);  
});Question <span class="hljs-number">39</span>
</code></pre><h1 id="heading-question-39">Question 39</h1>
<p>What are code module in Node JS explain few of them and their use.</p>
<p>‘Events’,</p>
<p>‘fs’,</p>
<p>‘http’,</p>
<p>‘https’,</p>
<p>‘module’,</p>
<p>‘net’,</p>
<p>‘os’,</p>
<p>‘path’,</p>
<p>‘stream’</p>
<p>child_process</p>
<p>The child_process module provides the ability to spawn child processes in a manner that is similar, but not</p>
<p>identical, to popen(3).</p>
<p><a target="_blank" href="https://nodejs.org/api/child_process.html">https://nodejs.org/api/child_process.html</a></p>
<p>cluster</p>
<p>A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will</p>
<p>sometimes want to launch a cluster of Node.js processes to handle the load. The cluster module allows you to</p>
<p>easily create child processes that all share server ports.</p>
<p><a target="_blank" href="https://nodejs.org/api/cluster.html">https://nodejs.org/api/cluster.html</a></p>
<p>Events</p>
<p>Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain</p>
<p>kinds of objects (called “emitters”) periodically emit named events that cause Function objects (“listeners”) to be Called.</p>
<p><a target="_blank" href="https://nodejs.org/api/events.html">https://nodejs.org/api/events.html</a></p>
<p>fs</p>
<p>File I/O is provided by simple wrappers around standard POSIX functions. To use this module do require(‘fs’). All the methods have asynchronous and synchronous forms.</p>
<p><a target="_blank" href="https://nodejs.org/api/fs.html">https://nodejs.org/api/fs.html</a></p>
<p>http</p>
<p>The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages.</p>
<p>readline</p>
<p>The readline module provides an interface for reading data from a Readable stream (such as process.stdin) one line at a time.</p>
<p>repl</p>
<p>The repl module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications.</p>
<h1 id="heading-question-40">Question 40</h1>
<p>Explain event loop lifecycle and explain few events inside event loop.</p>
<p>In latest release of V8 event loop is also available in JavaScript engine (v8, spiderMonkey etc). Event loop is part of Libuv library &amp; in reality event-loop is the master which uses the JavaScript engines to execute JavaScript code. event loop runs on separate thread.</p>
<p>When you run node index.js in your console, node start the event-loop and then runs your main module main module from index.js outside the event loop. Once the main module is executed, node will check if the loop is alive if event loop is not alive then node js process simply exit otherwise it will keep listening the event queue</p>
<p>At some point during the event loop, the runtime starts handling the messages on the queue, starting with the oldest one. Once that execution is over event is emitted about completion of task and handed over to handler.</p>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3200/0*RvIia4KcBmfyhwmI" /></p>
<h1 id="heading-question-41">Question 41</h1>
<p>How to prevent Unhandled Exception in Node JS and if they are occurring how to handle them</p>
<p>Node.js event loop runs on a single thread and uncaught exceptions are critical issue and need to be aware of when developing applications.</p>
<p>Silently Handling Exceptions</p>
<p>Most of the people let node.js server(s) silently swallow up the errors.</p>
<p>Silently handling the exception</p>
<pre><code>process.on(‘uncaughtException’, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">err</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(err);  
});
</code></pre><p>This is bad, it will work but:</p>
<p>In this case Root cause of problem will remains unknown, as such will not contribute to resolution of what caused the Exception (Error ).</p>
<p>In case of node application having database connection ( pool ) which gets closed for some reason will result in constant propagation of errors, meaning that server will be running but it will not reconnect to db. So you should write a code which can manage and do not generate Unhandled exception and for debugging purpose you can caught those process and identify the cause.</p>
<h1 id="heading-question-42">Question 42</h1>
<p>How to convert callback based library to promise based library so instead of writing callback we can write promises.</p>
<p>This is an important aspect and this is being used for many library like redis-client, mysql-client, we can use bluebird.promisifyAll to convert any callback based library to promise based.</p>
<pre><code>db.notification.email.find({<span class="hljs-attr">subject</span>: ‘promisify callback’}, <span class="hljs-function">(<span class="hljs-params">error, result</span>) =&gt;</span> {  
 <span class="hljs-keyword">if</span> (error) {  
 <span class="hljs-built_in">console</span>.log(error);  
 }  
 <span class="hljs-comment">// normal code here  </span>
});
</code></pre><p>It is using bluebird’s promisifyAll method to promisify what is conventionally callback-based library.</p>
<p>After applying these change promise-based methods names wil have Async appended to them:</p>
<pre><code><span class="hljs-keyword">let</span> email = bluebird.promisifyAll(db.notification.email);  
email.findAsync({<span class="hljs-attr">subject</span>: ‘promisify callback’}).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> {  
 <span class="hljs-comment">// normal code here  </span>
})  
.catch(<span class="hljs-built_in">console</span>.error);
</code></pre><p>Same thing can be done for redis library which is callback based library</p>
<pre><code><span class="hljs-keyword">const</span> redis = <span class="hljs-built_in">require</span>(‘redis’);  
bluebird.promisifyAll(redis);  
client.getAsync(‘data:key’).then(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">res</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(res); <span class="hljs-comment">// =&gt; ‘bar’  </span>
});
</code></pre><h1 id="heading-question-43">Question 43</h1>
<p>What is global object in Node JS how to add object to global variable &amp; how it’s different from browser global environment.</p>
<p>In browsers when we do console.log(this) it represent the window object and in node JS the global scope of a module is the module itself, so when you define a variable in the global scope of your node JS module, it will be local to this module.</p>
<p>In node js global represents global scope only you can add variable in global object it will be available on node js process and can be accessed in any other local module.</p>
<p>We can add some common configuration to global object like mysql connection object or logger object as we will using these objects on different places in application.</p>
<pre><code><span class="hljs-keyword">const</span> mysql = <span class="hljs-built_in">require</span>(‘mysql2’);  
<span class="hljs-built_in">global</span>.connection = <span class="hljs-literal">null</span>;  
<span class="hljs-keyword">try</span> {  
 <span class="hljs-built_in">global</span>.connection = mysql.createConnection(<span class="hljs-built_in">global</span>.configuration.db);  
} <span class="hljs-keyword">catch</span> (err) {  
 <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(err);  
}  
<span class="hljs-built_in">global</span>.connection.connect(<span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {  
 <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;  
});  
<span class="hljs-built_in">global</span>.connection.on(‘error’, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {  
 logger.info(<span class="hljs-string">`Cannot establish a connection with the database (<span class="hljs-subst">${err.code}</span>)`</span>);  
});  
<span class="hljs-built_in">module</span>.exports = <span class="hljs-built_in">global</span>.connection;
</code></pre><p>global The global namespace object.</p>
<p>In browsers, the top-level scope is the global scope. That means that in browsers if you’re in the global scope var something will define a global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.</p>
<h1 id="heading-question-44">Question 44</h1>
<p>What is circular dependency in modules while executing Node JS and how to fix this issue</p>
<p>In this example there two file which are doing require each other foo file one is requiring file and same thing is happening with bar.js</p>
<p>It’s like circular dependency &amp; these is no issue it will compile as expected but at run time behaviour is totally different then expected.</p>
<p>foo is being imported in bar module &amp; bar is being imported in foo module</p>
<p>The important part is it is being done synchronously,no module.export calls have yet been made!. So when bar.js was required intofoo.js, it immediately tried to require bar.js back into itself, but foo.js hasn’t been exported yet. The result is that foo.js only has a reference to an empty object!</p>
<p>This is called circular dependency and you should import export modules not in circular way.</p>
<p><a target="_blank" href="https://www.npmjs.com/package/madge">https://www.npmjs.com/package/madge</a> can be used to detect such kind of circular dependencies</p>
<pre><code><span class="hljs-comment">// hello.js  </span>
<span class="hljs-keyword">var</span> bar = <span class="hljs-built_in">require</span>(‘./foo.js’);   
<span class="hljs-built_in">console</span>.log(‘<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">b</span>:’, <span class="hljs-title">bar</span>)</span>;  
<span class="hljs-keyword">var</span> foo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{   
 <span class="hljs-built_in">this</span>.bInstance = bar();  
 <span class="hljs-built_in">this</span>.property = <span class="hljs-number">5</span>;  
}  
<span class="hljs-built_in">module</span>.exports = foo;<span class="hljs-comment">// hello1.js  </span>
<span class="hljs-keyword">var</span> foo = <span class="hljs-built_in">require</span>(‘./foo.js’);  
<span class="hljs-keyword">var</span> bar = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{}  
bar.prototype.doSomethingLater = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{   
 <span class="hljs-built_in">console</span>.log(foo.property);  
}  
<span class="hljs-built_in">module</span>.exports = bar;
</code></pre><h1 id="heading-question-45">Question 45</h1>
<p>What is the Node JS require cache and how to invalidate it</p>
<p>when we require module in one file it gets cached in node js and its gets passed to another module requiring same module again this is require cache which node js maintain in node js execution cycle. It can also be invalidated when needed</p>
<p>and Yes, you can access the cache via require.cache[moduleName] where moduleName is the name of the module you wish to access. Deleting an entry by calling delete require.cache[moduleName] will cause require to load the actual file.</p>
<p>So from the above description we can say yes, you can invalidate cache.</p>
<p>The cache is stored in object require.cache which you can access according to filenames (e.g. — ~/home/index.js as opposed to ./home which you would use in a require(‘./home’) statement).</p>
<h1 id="heading-question-46">Question 46</h1>
<p>What is the best way to add security to apis in Node JS application, what are some well known module should can be used.</p>
<p>For security we should take care of lot of things but here let’s see how we can make apis more secure</p>
<ul>
<li>Don’t use deprecated or vulnerable versions of Express</li>
<li>Use latest version of NPM &amp; run ( npm audit )</li>
<li>Use Helmet, csurf module for adding security</li>
<li>Add security to the cookies by signing cookies or making them secure.</li>
<li>Add rate limiter to prevent brute force attack</li>
<li>Send Security HTTP Headers</li>
<li>Prevent SQL injection in your code.</li>
<li>APIs should be running on HTTPS</li>
<li>run npm audit regularly</li>
</ul>
<p>Secure Express.js Sessions and Cookies</p>
<p>Session cookie name reveals your application’s internals</p>
<p>Revealing what technologies you are using for your application is one of the key things that you should not do. If an attacker knows what kind of technology you are using, he can drastically reduce his scope in finding vulnerable components in your application. There are a couple of ways which reveals internal implementation details of your application. One of them is the session cookie name of your application.</p>
<p>Make cookies more secure</p>
<p>When you use cookies in your application make sure to add HttpOnly flag to the cookies. Adding HttpOnly flag makes sure that no external script other than an HTTP connection can fetch cookies in your application. This is a good protection mechanism against cross site scripting attacks where attackers read your cookies through malicious scripts.</p>
<p>Signing cookies</p>
<p>Signing cookies provide prevention of cookie forging. A signed cookie is a value which has the cookie value as well as a digital signature attached to itself. Once the cookie is received from the server end, the server will validate the integrity of the cookie by validating its signature</p>
<p><a target="_blank" href="https://medium.com/@tkssharma/secure-node-js-apps-7613973b6971">https://medium.com/@tkssharma/secure-node-js-apps-7613973b6971</a></p>
<pre><code>app.disable(‘x-powered-by’);  
 app.use(helmet());  
 app.use(helmet.noCache({ <span class="hljs-attr">noEtag</span>: <span class="hljs-literal">true</span> })); <span class="hljs-comment">// set Cache-Control header  </span>
 app.use(helmet.noSniff()); <span class="hljs-comment">// set X-Content-Type-Options header  </span>
 app.use(helmet.frameguard()); <span class="hljs-comment">// set X-Frame-Options header  </span>
 app.use(helmet.xssFilter()); <span class="hljs-comment">// set X-XSS-Protection header  </span>
 app.enable(‘trust proxy’, [‘loopback’, ‘linklocal’, ‘uniquelocal’]);  
 app.use(expressSession({  
 <span class="hljs-attr">name</span>: ‘SESS_ID’,  
 <span class="hljs-attr">secret</span>: configServer.SESSION_SECRET,  
 <span class="hljs-attr">proxy</span>: <span class="hljs-literal">true</span>,  
 <span class="hljs-attr">resave</span>: <span class="hljs-literal">true</span>,  
 <span class="hljs-attr">saveUninitialized</span>: <span class="hljs-literal">true</span>,  
 }));
</code></pre><h1 id="heading-question-47">Question 47</h1>
<p>How error handling can be done in Node JS api app like handling api errors.</p>
<p>Error handling is a feature of express which can be done by using some middleware. Error can be some defined errors codes or some errors are runtime errors coming from database, redis or some other data store.</p>
<p>Server Errors : There are many error codes which are returned from API like 301,404,403 or 500.</p>
<p>API Error Codes : In APIs we can return error codes with our own message to notify client about situation at server side like “user data not found”, These are some known errors which we are throwing explicitly from code but what should we do with runtime errors like some database connection issue, some column is missing or query is not correctly written.</p>
<pre><code>router.get(‘/users/:id’, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req, res, next</span>) </span>{  
 <span class="hljs-keyword">var</span> user = users.getUserById(req.params.id);  
 <span class="hljs-keyword">if</span> (user == <span class="hljs-literal">null</span> || user == ‘<span class="hljs-literal">undefined</span>’) {   
 res.status(<span class="hljs-number">400</span>).json({‘message’ : ‘user not found’});  
 }  
});
</code></pre><p>For handling such unknown runtime errors we can just create middleware and this middleware will have error object additional which will give us detail about what error occured with stack trace &amp; status code.</p>
<p>Create error handler middleware as global Middleware and register this middleware with app instance.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">errorHandlers</span> </span>{  
 <span class="hljs-keyword">static</span> internalServerError(err, req, res, next) {  
 res.status(<span class="hljs-number">500</span>).json({  
 <span class="hljs-attr">success</span>: <span class="hljs-literal">false</span>,  
 <span class="hljs-attr">message</span>: err.message,  
 <span class="hljs-attr">error</span>: err.stack ,  
 });   
 }  
}  
<span class="hljs-built_in">module</span>.exports = errorHandlers;  
<span class="hljs-comment">// in your server.js  </span>
app.use(errorHandlers.internalServerError);
</code></pre><h1 id="heading-question-48">Question 48</h1>
<p>How to create basic middleware and how to register middleware in application.</p>
<p>Middleware functions are simple javascript functions that have access to the request response object and the next function during application request response cycle. In middleware we do pre and post processing with request and response object.</p>
<p>We can talk about basic example of pre processing requests like</p>
<ol>
<li>HTTP post method should not have empty body an example of pre processing of request</li>
<li>HTTP Methods should have application/json as content type.</li>
<li>Secured routes should have some token available in request for checking authorisation. This can be done using some middleware which will check request for protected routes and validate if available token in request is valid.</li>
</ol>
<p>Middleware function should call next function to execute or move to next middleware.</p>
<p>Middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function otherwise, the request will be left stuck or hanging in middle.</p>
<p>we use middleware to do pre processing and post processing for request processing.</p>
<p>We can have simple example of Express application. We create an express application which is sending response “hello world” on “/” route request and serving on HTTP Port 3000.</p>
<pre><code><span class="hljs-keyword">var</span> express = <span class="hljs-built_in">require</span>(‘express’)  
<span class="hljs-keyword">var</span> app = express()app.get(‘/’, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{  
 res.send(‘Hello World!’)  
})app.listen(<span class="hljs-number">3000</span>)
</code></pre><p>Middleware function logger example</p>
<p>Here is a simple example of a middleware function called “logger”. This function will be logging message ‘LOGGED’ on each and every request as we have registered this middleware on app instance by doing app.use(middleware).</p>
<pre><code><span class="hljs-keyword">var</span> myLogger = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res, next</span>) </span>{  
 <span class="hljs-built_in">console</span>.log(‘LOGGED’)  
 next()  
}  
<span class="hljs-comment">// this is how we register middleware  </span>
app.use(myLogger)
</code></pre><p>We can add middleware to a route itself instead of doing it on express instance and making that middleware global for each and every request, in this case this middleware will be available for this route only.</p>
<p>We do have global middleware which we register on app instance like body parser which is used to extract req body from coming request from client.</p>
<pre><code><span class="hljs-comment">// parse application/x-www-form-urlencoded  </span>
app.use(bodyParser.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> })<span class="hljs-comment">// parse application/json  </span>
app.use(bodyParser.json())Example <span class="hljs-keyword">of</span> middleware registered only to a route.var middleware = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req,res,next</span>)</span>{  
 next()  
}  
app.get(‘/’, middleware, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req, res</span>) </span>{  
 res.send(‘Hello World!’)  
})
</code></pre><h1 id="heading-question-49">Question 49</h1>
<p>Can you explain how logging can be done in Node JS application api logging or simple logging in some file</p>
<p>logging is important aspect of node js programming, There are different modules available in node js to add logging in node js application</p>
<p>Logging is needed in Node.js to capture bugs during application runtime.</p>
<p>logging is needed because we want to :</p>
<ol>
<li>To have a better understanding of how your applications works,</li>
<li>To discover what errors you may encounter runtime.</li>
<li>To find out if your services are running properly without unhandled errors.</li>
</ol>
<p>winston is important module which you can have for logging purpose. Winston is a multi-transport async logging library for Node.js. When i say multi transport means i can have different medium to manage my logs.</p>
<ol>
<li>Storing logs on files with custom log format.</li>
<li>Pushing logs on console.</li>
<li>Sending logs to any another TCP channel.</li>
<li>Winston has different log levels and different format can be specified for logging</li>
</ol>
<p>You can add winston to your project by installing it:</p>
<p>npm install winston — save</p>
<p>Once you have it, you can add winston to your project this way:</p>
<pre><code><span class="hljs-keyword">const</span> winston = <span class="hljs-built_in">require</span>(‘winston’);  
<span class="hljs-keyword">const</span> logger = <span class="hljs-keyword">new</span> winston.Logger({  
 <span class="hljs-attr">transports</span>: [  
 <span class="hljs-keyword">new</span> winston.transports.File(options.file),  
 <span class="hljs-keyword">new</span> winston  
 .transports  
 .Console({}),  
 ],  
 <span class="hljs-attr">exceptionHandlers</span>: [  
 <span class="hljs-comment">// new winston.transports.File(options.errorLog)  </span>
 ],  
 <span class="hljs-attr">exitOnError</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// do not exit on handled exceptions  </span>
});<span class="hljs-comment">// create a stream object with a ‘write’ function that will be used by `morgan`  </span>
logger.stream = {  
 write(message, encoding) {  
 logger.info(message);  
 }  
};  
<span class="hljs-built_in">module</span>.exports = logger;
</code></pre><h1 id="heading-question-50">Question 50</h1>
<p>How to monitor Node JS process and api transactions by using any tool or library ?</p>
<p>There are many tools available which can provide real time transaction monitoring and logging of apis like keymatrics and newrelic tools which gives you in detail knowledge about node js process status like memory consumption and time taken.</p>
<p>These tools are also being used for performance monitoring of APIs</p>
<p>Newrelic &amp; keymatrics are industry standards and being used in many enterprises to check and monitor Node js process</p>
<p><a target="_blank" href="https://rpm.newrelic.com">https://rpm.newrelic.com</a></p>
<p><a target="_blank" href="http://pm2.io/">http://pm2.io/</a></p>
<p>Tools for Node js process Monitoring</p>
<ol>
<li>appdynamics</li>
<li>nodemon, forever modules to run process in background without monitoring.</li>
<li>newRelic gives detailed monitoring statics.</li>
<li>keymetrics is PM2 based tool which shows statics of individual instance and make application highly available. PM2 gives advantages of having multiple instances of application on system so we can use multi-core system efficiently.</li>
</ol>
<p><img class="cp t u fv ak" src="https://miro.medium.com/max/3112/0*OhKB8whwauyV8y6J" /></p>
]]></content:encoded></item><item><title><![CDATA[ELK Stack with Nestjs]]></title><description><![CDATA[Elasticsearch is a highly scalable, distributed search engine that forms the core of the ELK Stack (Elasticsearch, Logstash, Kibana). It is responsible for…]]></description><link>https://articles.tkssharma.com/elk-stack-with-nestjs</link><guid isPermaLink="true">https://articles.tkssharma.com/elk-stack-with-nestjs</guid><category><![CDATA[elasticsearch]]></category><category><![CDATA[nestjs]]></category><category><![CDATA[logstash]]></category><category><![CDATA[kibana]]></category><category><![CDATA[filebeat]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Mon, 30 Sep 2024 06:47:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727678810452/9d294ab4-7d92-4d7f-a263-f2900ef4d0a7.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Elasticsearch</strong> is a highly scalable, distributed search engine that forms the core of the ELK Stack (Elasticsearch, Logstash, Kibana). It is responsible for <strong>storing, indexing, and searching log data</strong>.</p>
<p>Here's a breakdown of its role:</p>
<ol>
<li><p><strong>Data Storage:</strong> Elasticsearch stores log data in a highly scalable and distributed manner, allowing it to handle large volumes of data.</p>
</li>
<li><p><strong>Indexing:</strong> Elasticsearch indexes the log data, creating an inverted index that enables efficient search.</p>
</li>
<li><p><strong>Search:</strong> Elasticsearch provides powerful search capabilities, allowing you to query and analyze your log data using a variety of search criteria.</p>
</li>
<li><p><strong>Analytics:</strong> Elasticsearch can be used for advanced analytics tasks, such as time-based analysis, trend detection, and anomaly detection.</p>
</li>
<li><p><strong>Integration with Kibana:</strong> Elasticsearch is tightly integrated with Kibana, providing a seamless way to visualize and explore your log data.</p>
</li>
</ol>
<p><strong>Key Benefits of Elasticsearch:</strong></p>
<ul>
<li><p><strong>Scalability:</strong> Elasticsearch can handle large volumes of data and can be easily scaled horizontally.</p>
</li>
<li><p><strong>Speed:</strong> Elasticsearch is highly performant and can handle complex search queries efficiently.</p>
</li>
<li><p><strong>Flexibility:</strong> Elasticsearch supports a wide range of data types and can be used for a variety of use cases.</p>
</li>
<li><p><strong>Integration with ELK Stack:</strong> Elasticsearch is a core component of the ELK Stack, providing a powerful foundation for log management and analysis.</p>
</li>
</ul>
<p><strong>In summary, Elasticsearch is a powerful and scalable search engine that plays a crucial role in the ELK Stack. It provides the foundation for storing, indexing, and searching log data, enabling effective analysis and visualization.</strong></p>
<p><strong>Logstash</strong> is a central component of the ELK Stack (Elasticsearch, Logstash, Kibana) responsible for <strong>processing and enriching logs</strong> before they are sent to Elasticsearch for storage and analysis.</p>
<p>Here's a breakdown of its role:</p>
<ol>
<li><p><strong>Data Ingestion:</strong> Logstash can ingest logs from various sources, including files, syslog, and network sockets.</p>
</li>
<li><p><strong>Data Processing:</strong> Logstash can transform and filter log data using plugins and filters. This includes tasks like:</p>
<ul>
<li><p>Parsing log messages into structured fields.</p>
</li>
<li><p>Adding or removing fields.</p>
</li>
<li><p>Applying geo-location or other enrichments.</p>
</li>
<li><p>Filtering logs based on specific criteria.</p>
</li>
</ul>
</li>
<li><p><strong>Data Enrichment:</strong> Logstash can enrich log data with additional information, such as IP addresses, hostnames, or user identities.</p>
</li>
<li><p><strong>Data Shipping:</strong> Logstash sends the processed log data to Elasticsearch for storage and analysis.</p>
</li>
</ol>
<p><strong>Key Benefits of Logstash:</strong></p>
<ul>
<li><p><strong>Flexibility:</strong> Logstash can handle a wide variety of log formats and sources.</p>
</li>
<li><p><strong>Processing Power:</strong> It provides powerful data processing capabilities, allowing you to transform and filter logs as needed.</p>
</li>
<li><p><strong>Integration with ELK Stack:</strong> Logstash is tightly integrated with Elasticsearch and Kibana, providing a seamless workflow for log management and analysis.</p>
</li>
<li><p><strong>Scalability:</strong> Logstash can be scaled horizontally to handle large volumes of logs.</p>
</li>
</ul>
<p><strong>In summary, Logstash plays a crucial role in the ELK Stack by processing and enriching log data before it is stored in Elasticsearch. This allows for more efficient and effective analysis of log data using Kibana.</strong></p>
<p><strong>Kibana</strong> is a powerful visualization and analysis tool that is part of the ELK Stack (Elasticsearch, Logstash, Kibana). It provides a user-friendly interface for exploring, searching, and visualizing data stored in Elasticsearch.</p>
<p>Here's a breakdown of its role:</p>
<ol>
<li><p><strong>Data Visualization:</strong> Kibana allows you to create custom dashboards and visualizations to visualize your log data in a meaningful way.</p>
</li>
<li><p><strong>Search and Discovery:</strong> Kibana provides advanced search capabilities to query and analyze your log data.</p>
</li>
<li><p><strong>Time-Based Analysis:</strong> You can analyze your logs over time to identify trends, anomalies, and patterns.</p>
</li>
<li><p><strong>Alerting:</strong> Kibana can be configured to trigger alerts based on specific conditions, such as when certain error messages appear or performance metrics exceed thresholds.</p>
</li>
<li><p><strong>Integration with Other Tools:</strong> Kibana can be integrated with other tools in the ELK Stack, as well as external applications, to provide a comprehensive analytics solution.</p>
</li>
</ol>
<p><strong>Key Benefits of Kibana:</strong></p>
<ul>
<li><p><strong>User-Friendly Interface:</strong> Kibana provides an intuitive interface that is easy to learn and use.</p>
</li>
<li><p><strong>Powerful Visualization Capabilities:</strong> Create a variety of visualizations, including charts, graphs, and maps.</p>
</li>
<li><p><strong>Advanced Search:</strong> Kibana offers advanced search features to help you find the information you need.</p>
</li>
<li><p><strong>Integration with Elasticsearch:</strong> Kibana is tightly integrated with Elasticsearch, providing seamless access to your log data.</p>
</li>
</ul>
<p><strong>In summary, Kibana is a vital component of the ELK Stack, providing a powerful and flexible tool for visualizing and analyzing your log data.</strong></p>
<p><strong>Filebeat</strong> is a lightweight agent that is part of the <strong>ELK Stack</strong> (Elasticsearch, Logstash, Kibana). It's primarily responsible for <strong>shipping logs from various sources to Logstash for centralized processing.</strong></p>
<p>Here's a breakdown of its role:</p>
<ol>
<li><p><strong>File Monitoring:</strong> Filebeat watches specific files or directories for changes.</p>
</li>
<li><p><strong>Log Collection:</strong> When new log lines appear, Filebeat reads them and prepares them for shipment.</p>
</li>
<li><p><strong>Data Enrichment:</strong> Filebeat can add context or metadata to the logs before sending them to Logstash.</p>
</li>
<li><p><strong>Shipment to Logstash:</strong> Filebeat forwards the collected logs to Logstash for further processing.</p>
</li>
</ol>
<p><strong>Key Benefits of Filebeat:</strong></p>
<ul>
<li><p><strong>Lightweight and Efficient:</strong> Filebeat has a minimal footprint and is designed for efficient log collection.</p>
</li>
<li><p><strong>Flexible:</strong> It can handle various log formats and sources.</p>
</li>
<li><p><strong>Scalable:</strong> Filebeat can be easily scaled to handle large volumes of logs.</p>
</li>
<li><p><strong>Integration with ELK Stack:</strong> It seamlessly integrates with Logstash and Elasticsearch for centralized logging and analysis.</p>
</li>
</ul>
<p><strong>In summary, Filebeat plays a crucial role in the ELK Stack by efficiently collecting logs from various sources and forwarding them to Logstash for further processing.</strong></p>
]]></content:encoded></item><item><title><![CDATA[Nextjs Course with Live Demo Applications 2024]]></title><description><![CDATA[Nextjs Course with Live Demo Applications 2024 Introduction Next.js is a powerful React framework that simplifies the process of building full-stack web…]]></description><link>https://articles.tkssharma.com/nextjs-course-with-live-demo-applications-2024</link><guid isPermaLink="true">https://articles.tkssharma.com/nextjs-course-with-live-demo-applications-2024</guid><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sat, 28 Sep 2024 08:27:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727465436440/17a0762a-2862-42d9-bab3-38999e12327a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Nextjs Course with Live Demo Applications 2024</p>
<h2 id="heading-build-modern-web-apps-with-live-demos-2024">Build Modern Web Apps with Live Demos (2024)</h2>
<p><strong>Introduction</strong></p>
<p>Next.js is a powerful React framework that simplifies the process of building full-stack web applications. In this comprehensive course, you'll learn how to leverage Next.js to create high-performance, SEO-friendly, and feature-rich applications.</p>
<p><strong>Key Topics Covered:</strong></p>
<ul>
<li><p><strong>Understanding Next.js:</strong> Explore the core concepts and benefits of Next.js.</p>
</li>
<li><p><strong>Setting Up a Next.js Project:</strong> Create a new Next.js project and configure your development environment.</p>
</li>
<li><p><strong>Server-Side Rendering (SSR):</strong> Learn how to render your React components on the server for improved SEO and performance.</p>
</li>
<li><p><strong>Static Site Generation (SSG):</strong> Pre-render your pages at build time for lightning-fast load times.</p>
</li>
<li><p><strong>Data Fetching:</strong> Fetch data from APIs using <code>getStaticProps</code> and <code>getServerSideProps</code>.</p>
</li>
<li><p><strong>Routing:</strong> Define routes for your application using Next.js's built-in routing system.</p>
</li>
<li><p><strong>API Routes:</strong> Create backend API routes within your Next.js application.</p>
</li>
<li><p><strong>Deployment:</strong> Deploy your Next.js applications to various platforms like Vercel, Netlify, or your own server.</p>
</li>
<li><p><strong>Advanced Features:</strong> Explore advanced features like Incremental Static Regeneration (ISR), internationalization, and custom server.</p>
</li>
</ul>
<p><strong>Live Demos:</strong></p>
<p>Throughout the course, you'll be guided through hands-on live demos, where you'll build real-world applications step-by-step. These demos will reinforce your understanding of the concepts and provide practical experience.</p>
<p><strong>Benefits of Taking This Course:</strong></p>
<ul>
<li><p><strong>Master Next.js:</strong> Gain a deep understanding of Next.js and its capabilities.</p>
</li>
<li><p><strong>Build Modern Web Apps:</strong> Learn how to create high-performance, SEO-friendly web applications.</p>
</li>
<li><p><strong>Improve Your Skills:</strong> Enhance your React and JavaScript skills.</p>
</li>
<li><p><strong>Get Hands-On Experience:</strong> Learn through practical examples and live demos.</p>
</li>
</ul>
<p><strong>Join us on this exciting journey to become a Next.js expert and build amazing web applications!</strong></p>
<h2 id="heading-introduction">Introduction</h2>
<ul>
<li><p>Using the Code Snasphots</p>
</li>
<li><p>Module Introduction</p>
</li>
<li><p>What Is React &amp; Why Would You Use It?</p>
</li>
<li><p>React Projects - Requirements</p>
</li>
<li><p>Creating React Projects</p>
</li>
<li><p>Our Starting Project</p>
</li>
<li><p>Undertanding How React Works</p>
</li>
<li><p>Building A First Custom Component</p>
</li>
<li><p>Outputting Dynamic Values</p>
</li>
<li><p>Reusing Components</p>
</li>
<li><p>Passing Data to Components with Props</p>
</li>
<li><p>CSS Styling &amp; CSS Modules</p>
</li>
<li><p>Exercise &amp; Another Component</p>
</li>
<li><p>Preparing the App For State Management</p>
</li>
<li><p>Adding Event Listeners</p>
</li>
<li><p>Working with State Lifting State Up</p>
</li>
<li><p>The Special "children" Prop</p>
</li>
<li><p>State &amp; Conditional Content</p>
</li>
<li><p>Adding a Shared Header &amp; More State Management</p>
</li>
<li><p>Adding Form Buttons</p>
</li>
<li><p>Handling Form Submission</p>
</li>
<li><p>Updating State Based On Previous State</p>
</li>
<li><p>Outputting List Data</p>
</li>
<li><p>Adding a Backend to the React SPA</p>
</li>
<li><p>Sending a POST HTTP Request</p>
</li>
<li><p>Handling Side Effects with useEffect()</p>
</li>
<li><p>Handle Loading State</p>
</li>
<li><p>Understanding &amp; Adding Routing Adding Routes</p>
</li>
<li><p>Working with Layout Routes</p>
</li>
<li><p>Refactoring Route Components &amp; More Nesting</p>
</li>
<li><p>Linking &amp; Navigating</p>
</li>
<li><p>Data Fetching via loader()s</p>
</li>
<li><p>Submitting Data with action()s</p>
</li>
<li><p>Dynamic Routes Module Summary</p>
</li>
<li><p>IMPORTANT -- LEGACY CONTENT BELOW</p>
</li>
<li><p>Module Introduction What is ReactJS?</p>
</li>
<li><p>Why ReactJS &amp; A First Demo</p>
</li>
<li><p>Building Single-Page Applications (SPAs)</p>
</li>
<li><p>React Alternatives</p>
</li>
<li><p>Creating a New React Project</p>
</li>
<li><p>Setting Up A Code Editor</p>
</li>
</ul>
<h2 id="heading-react">React</h2>
<ul>
<li><p>Diving Into The Created Project</p>
</li>
<li><p>How React Works &amp; Understanding Components</p>
</li>
<li><p>More Component Work &amp; Styling With CSS Classes</p>
</li>
<li><p>Building &amp; Re-using Components</p>
</li>
<li><p>Passing Data With Props &amp; Dynamic Content Handling Events</p>
</li>
<li><p>Adding More Components-<br />  Introducing State</p>
</li>
<li><p>Workng with "Event Props"</p>
</li>
<li><p>Use The Right React Router Version Adding Routing</p>
</li>
<li><p>Adding Links &amp; Navigation</p>
</li>
<li><p>Scoping Component Styles With CSS Modules</p>
</li>
<li><p>Outputting Lists Of Data &amp; Components</p>
</li>
<li><p>Adding Even More Components</p>
</li>
<li><p>Creating "Wrapper" Components</p>
</li>
<li><p>Working With Forms</p>
</li>
<li><p>Getting User Input &amp; Handling Form Submission</p>
</li>
<li><p>Preparing The App For Http Requests &amp; Adding a Backend</p>
</li>
<li><p>Sending a POST Http Request</p>
</li>
<li><p>Navigating Programmatically</p>
</li>
<li><p>Getting Started with Fetching Data</p>
</li>
<li><p>Using the "useEffect" Hook</p>
</li>
<li><p>Introducing React Context</p>
</li>
<li><p>Updating State Based On Previous State</p>
</li>
<li><p>Using Context In Components</p>
</li>
<li><p>More Context Usage</p>
</li>
<li><p>Module Summary</p>
</li>
<li><p>Module Resources</p>
</li>
</ul>
<h2 id="heading-nextjs-ssr">Nextjs SSR</h2>
<ul>
<li><p>Module Introduction</p>
</li>
<li><p>Starting Setup</p>
</li>
<li><p>Understanding File-based Routing &amp; React Server Components</p>
</li>
<li><p>Adding Another Route via the File System</p>
</li>
<li><p>Navigating Between Pages - Wrong &amp; Right Solution</p>
</li>
<li><p>Working with Pages &amp; Layouts</p>
</li>
<li><p>Reserved File Names, Custom Components &amp; How To Organize A NextJS Project</p>
</li>
<li><p>Reserved Filenames</p>
</li>
<li><p>Configuring Dynamic Routes &amp; Using Route Parameters</p>
</li>
<li><p>Onwards to the Main Project The Foodies App</p>
</li>
<li><p>Exercise Your Task-<br />  Exercise Solution</p>
</li>
<li><p>Revisiting The Concept Of Layouts</p>
</li>
<li><p>Adding a Custom Component To A Layout</p>
</li>
<li><p>Styling NextJS Project Your Options &amp; Using CSS Modules</p>
</li>
<li><p>Optimizing Images with the NextJS Image Component</p>
</li>
<li><p>Using More Custom Components</p>
</li>
<li><p>Populating The Starting Page Content</p>
</li>
<li><p>Preparing an Image Slideshow</p>
</li>
<li><p>React Server Components vs Client Components - When To Use What</p>
</li>
<li><p>Using Client Components Efficiently</p>
</li>
<li><p>Outputting Meals Data &amp; Images With Unknown Dimensions</p>
</li>
<li><p>Setting Up A SQLite Database</p>
</li>
<li><p>Fetching Data By Leveraging NextJS &amp; Fullstack Capabilities</p>
</li>
<li><p>Adding A Loading Page</p>
</li>
<li><p>Using Suspense &amp; Streamed Responses For Granular Loading State Management-<br />  Handling Errors</p>
</li>
<li><p>Handling "Not Found" States</p>
</li>
<li><p>Loading &amp; Rendering Meal Details via Dynamic Routes &amp; Route Parameters</p>
</li>
<li><p>Throwng Not Found Errors For Individual Meals</p>
</li>
<li><p>Getting Started with the "Share Meal" Form</p>
</li>
<li><p>Introducing &amp; Using Server Actions for Handling Form Submissions</p>
</li>
<li><p>Storing Server Actions in Separate Files</p>
</li>
<li><p>Creating a Slug &amp; Sanitizing User Input for XSS Protection</p>
</li>
<li><p>Storing Uploaded Images &amp; Storing Data in the Database</p>
</li>
<li><p>Managing the Form Submission Status with useFormStatus</p>
</li>
<li><p>Adding Server-Side Input Validation</p>
</li>
<li><p>Using useFormState()</p>
</li>
<li><p>Working with Server Action Responses &amp; useFormState</p>
</li>
<li><p>Building For Production &amp; Understanding NextJS Caching</p>
</li>
<li><p>Triggering Cache Revalidations</p>
</li>
<li><p>Don't Store Files Locally On The Filesystem!</p>
</li>
<li><p>Bonus Storing Uploaded Images In The Cloud (AWS S)</p>
</li>
<li><p>Adding Static Metadata</p>
</li>
<li><p>Adding Dynamic Metadata</p>
</li>
</ul>
<h2 id="heading-nextjs-internals">Nextjs Internals</h2>
<ul>
<li><p>Module Introduction</p>
</li>
<li><p>Project Setup, Overview &amp; An Exercise!</p>
</li>
<li><p>Exercise Solution - Part</p>
</li>
<li><p>Exercise Solution - Part</p>
</li>
<li><p>App Styling &amp; Using Dummy Data</p>
</li>
<li><p>Handling "Not Found" Errors &amp; Showing "Not Found" Pages</p>
</li>
<li><p>Setting Up &amp; Using Parallel Routes</p>
</li>
<li><p>Working with Parallel Routes &amp; Nested Routes</p>
</li>
<li><p>Configuring Catch-All Routes</p>
</li>
<li><p>Catch-All Fallback Routes &amp; Dealing With Multiple Path Segments</p>
</li>
<li><p>Throwing (Route-related) Errors</p>
</li>
<li><p>Handling Errors With Error Pages</p>
</li>
<li><p>Server vs Client Components</p>
</li>
<li><p>Nested Routes Inside Dynamic Routes</p>
</li>
<li><p>Intercepting Navigation &amp; Using Interception Routes</p>
</li>
<li><p>Combining Parallel &amp; Intercepting Routes</p>
</li>
<li><p>Replace page.js with default.js</p>
</li>
<li><p>Navigating Programmatically</p>
</li>
<li><p>Defining the Base HTML Document</p>
</li>
<li><p>Using &amp; Understanding Route Groups</p>
</li>
<li><p>Building APIs with Route Handlers-</p>
</li>
<li><p>Using Middleware</p>
</li>
<li><p>Module Introduction-</p>
</li>
<li><p>Adding a Backend</p>
</li>
<li><p>Option Client-side Data Fetching</p>
</li>
<li><p>Option Server-side Data Fetching</p>
</li>
<li><p>Why Use A Separate Backend? Fetching Directly From The Source!</p>
</li>
<li><p>Showing a "Loading" Fallback</p>
</li>
<li><p>Migrating An Entire Application To A Local Data Source (Database)</p>
</li>
<li><p>Granular Data Fetching With Suspense</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Buddy Clone App using nextjs 14.x]]></title><description><![CDATA[I'd be glad to provide a comprehensive guide on building a full-stack clone app using Next.js and Prisma: Prerequisites: Node.js and npm (or yarn)…]]></description><link>https://articles.tkssharma.com/buddy-clone-app-using-nextjs-14x</link><guid isPermaLink="true">https://articles.tkssharma.com/buddy-clone-app-using-nextjs-14x</guid><category><![CDATA[NEXTAUT]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[nextauth.js]]></category><category><![CDATA[nextjs 13.4]]></category><category><![CDATA[nextjs 14]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Mon, 23 Sep 2024 06:12:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727071897711/b829f46f-5c8f-47ab-8a4d-0a7348f7abce.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I'd be glad to provide a comprehensive guide on building a full-stack clone app using Next.js and Prisma:</p>
<p><strong>Prerequisites:</strong></p>
<ul>
<li><p>Node.js and npm (or yarn) installed</p>
</li>
<li><p>Basic understanding of React and Next.js</p>
</li>
<li><p>Familiarity with Prisma ORM</p>
</li>
</ul>
<p><strong>Getting Started:</strong></p>
<ol>
<li><p><strong>Create a New Next.js Project:</strong></p>
<pre><code class="lang-bash"> npx create-next-app your-app-name
</code></pre>
</li>
<li><p><strong>Install Dependencies:</strong></p>
<pre><code class="lang-bash"> <span class="hljs-built_in">cd</span> your-app-name
 npm install @prisma/client next-auth
</code></pre>
</li>
<li><p><strong>Set Up Prisma:</strong></p>
<ul>
<li><p>Create a <code>schema.prisma</code> file in the root directory.</p>
</li>
<li><p>Define your Prisma schema with models, fields, and relationships.</p>
</li>
<li><p>Run <code>npx prisma generate</code> to generate the Prisma client.</p>
</li>
</ul>
</li>
<li><p><strong>Configure NextAuth.js:</strong> Create an <code>auth/[...nextauth].js</code> file in your <code>pages</code> directory and configure NextAuth.js with your desired authentication providers (e.g., Google, GitHub, Email).</p>
</li>
</ol>
<p><strong>Key Features and Technologies:</strong></p>
<ul>
<li><p><strong>Next.js:</strong> A powerful React framework for building server-rendered React applications.</p>
</li>
<li><p><strong>Prisma:</strong> A modern ORM for Node.js that simplifies database interactions.</p>
</li>
<li><p><strong>NextAuth.js:</strong> A simple, flexible authentication solution for Next.js applications.</p>
</li>
<li><p><strong>MongoDB:</strong> A popular NoSQL database for storing user data.</p>
</li>
<li><p><strong>TypeScript (optional):</strong> Use TypeScript for improved type safety and code maintainability.</p>
</li>
</ul>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=POMKrG4L3hQ&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=4">https://www.youtube.com/watch?v=POMKrG4L3hQ&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=4</a></div>
<p> 
Now playing</p>
<ul>
<li>Let's start our App Development || Github and Project Kanban Board setup #03</li>
<li>FullStack Clone || Baseline Repo Like a Pro with Husky, Commitlint , prettier #04</li>
<li>Nextjs setup with Prisma and NextAuth Part-1 #05</li>
<li>Next-Auth v5 is Almost Here! Learn it Fast on the NextJS App #06</li>
<li>Authentication in NextJS using NextAuth | NextJS in Hindi #07</li>
<li>NextJS Dashboard Layout with Middlewares &amp; nextauth #08</li>
<li>Next.js EXPERT Shares Top Database Design Secrets for Fullstack Applications #09</li>
<li>Nextjs Server Actions Made EASY with React Hook Form Hacks #10</li>
<li>Nextjs Server Actions  vs APIs</li>
<li>Nextjs Server Actions for Components</li>
<li>Nextjs Server Actions for listing all Ideas </li>
<li>Nextjs Server Actions to join and leave ideas </li>
<li>Nextjs Server Actions and componet to add comment and bookmark, like Ideas</li>
<li>Deploying Nextjs application to vercel </li>
</ul>
<p>https://github.com/tkssharma/buddy-clone</p>
<h3 id="heading-follow-these-branches">Follow these Branches</h3>
<ul>
<li>baseline (develop branch)</li>
<li>Auth screens feat-auth-screens</li>
<li>dashboard layouts feat-dashboard-layouts</li>
</ul>
<table id="customers">
  <tbody><tr>
    <th>Video</th>
    <th>Link</th>
  </tr>
  <tr>
    <td>Build Full Stack App || Open collaboration, come and Build Apps with Me #02</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
  <tr>
    <td>Video thumbnail: Let's start our App Development || Github and Project Kanban Board setup #03</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
  <tr>
    <td>Let's start our App Development || Github and Project Kanban Board setup #03</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
  <tr>
    <td>FullStack Clone || Baseline Repo Like a Pro with Husky, Commitlint , prettier #04</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
  <tr>
    <td>Video thumbnail: Nextjs setup with Prisma and NextAuth Part-1 #05</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
  <tr>
    <td>Video thumbnail: Next-Auth v5 is Almost Here! Learn it Fast on the NextJS App #06</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
    <tr>
    <td>Video thumbnail: Authentication in NextJS using NextAuth | NextJS in Hindi #07</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
    <tr>
    <td>Premiere thumbnail: NextJS Dashboard Layout with Middlewares &amp;  nextauth  #08
</td>
    <td>https://www.youtube.com/watch?v=Ay-_KqkkOag&amp;list=PLU-FndeNRY4Cw7Kq7SHtqpI5bK06s8wt0&amp;index=2</td>
  </tr>
</tbody></table>

<p><strong>Conclusion:</strong></p>
<p>By following these steps and leveraging the power of Next.js, Prisma, and NextAuth.js, you can create a robust and scalable full-stack clone app. This project will provide you with valuable experience in building modern web applications with a strong foundation.</p>
]]></content:encoded></item><item><title><![CDATA[Nestjs crash Course (Basics Only)]]></title><description><![CDATA[Introduction to NestJS Setting Up a NestJS Project Modules and Dependency Injection Controllers and Routes Services Providers Pipes and Filters Middleware…]]></description><link>https://articles.tkssharma.com/nestjs-crash-course-basics-only</link><guid isPermaLink="true">https://articles.tkssharma.com/nestjs-crash-course-basics-only</guid><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 11:24:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727004262506/1574c761-6e83-44fd-9204-1446336dc3d6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-nestjs-crash-course-key-topics">NestJS Crash Course: Key Topics</h2>
<p><strong>Introduction to NestJS</strong></p>
<ul>
<li>What is NestJS?</li>
<li>Core concepts and features of NestJS</li>
<li>Benefits of using NestJS for building Node.js applications</li>
</ul>
<p><strong>Setting Up a NestJS Project</strong></p>
<ul>
<li>Creating a new NestJS project using the CLI</li>
<li>Understanding the project structure</li>
<li>Configuring your development environment</li>
</ul>
<p><strong>Modules and Dependency Injection</strong></p>
<ul>
<li>Creating modules in NestJS</li>
<li>Understanding dependency injection in NestJS</li>
<li>Using providers and controllers</li>
</ul>
<p><strong>Controllers and Routes</strong></p>
<ul>
<li>Defining routes in NestJS</li>
<li>Creating controllers to handle HTTP requests</li>
<li>Using HTTP methods (GET, POST, PUT, DELETE)</li>
</ul>
<p><strong>Services</strong></p>
<ul>
<li>Creating services for business logic</li>
<li>Injecting services into controllers</li>
<li>Using dependency injection to manage dependencies</li>
</ul>
<p><strong>Providers</strong></p>
<ul>
<li>Understanding providers in NestJS</li>
<li>Creating custom providers</li>
<li>Using built-in providers</li>
</ul>
<p><strong>Pipes and Filters</strong></p>
<ul>
<li>Using pipes for data validation and transformation</li>
<li>Creating custom pipes</li>
<li>Using filters for handling exceptions and logging</li>
</ul>
<p><strong>Middleware</strong></p>
<ul>
<li>Understanding middleware in NestJS</li>
<li>Creating custom middleware</li>
<li>Using built-in middleware</li>
</ul>
<p><strong>Testing</strong></p>
<ul>
<li>Writing unit tests for NestJS components</li>
<li>Using testing frameworks like Jest</li>
<li>Integrating testing into your development workflow</li>
</ul>
<p><strong>Deployment</strong></p>
<ul>
<li>Deploying NestJS applications to different environments (development, staging, production)</li>
<li>Using tools like Docker and Kubernetes for deployment</li>
</ul>
<p><strong>Additional Topics:</strong></p>
<ul>
<li>NestJS CLI</li>
<li>NestJS modules</li>
<li>NestJS configuration</li>
<li>NestJS security</li>
<li>NestJS best practices</li>
</ul>
<p><strong>Note:</strong> This is just a suggested outline. You can customize the topics and depth of coverage based on your specific learning goals and the target audience for your course.</p>
]]></content:encoded></item><item><title><![CDATA[Microservices Design Aspects]]></title><description><![CDATA[Microservices architecture has gained significant popularity in recent years due to its ability to build scalable, maintainable, and resilient…]]></description><link>https://articles.tkssharma.com/microservices-design-aspects</link><guid isPermaLink="true">https://articles.tkssharma.com/microservices-design-aspects</guid><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 08:57:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727464240391/ab89f18e-4f51-4c4c-ae58-f853f0508701.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=YOcnhHC5GEA">https://www.youtube.com/watch?v=YOcnhHC5GEA</a></div>
<h2 id="heading-microservices-design-aspects-a-comprehensive-guide">Microservices Design Aspects: A Comprehensive Guide</h2>
<p>Microservices architecture has gained significant popularity in recent years due to its ability to build scalable, maintainable, and resilient applications. By breaking down large monolithic applications into smaller, independent services, microservices architecture offers several advantages.</p>
<p><strong>Key Design Aspects of Microservices</strong></p>
<ol>
<li><strong>Bounded Contexts:</strong> Define clear boundaries between microservices based on business domains or functionalities. This helps isolate changes and improve maintainability.</li>
<li><strong>API-First Approach:</strong> Design microservices with well-defined APIs that clearly communicate their capabilities and contracts.</li>
<li><strong>Decentralized Governance:</strong> Allow each microservice team to make independent decisions about technology stacks and development practices.</li>
<li><strong>Asynchronous Communication:</strong> Utilize asynchronous communication patterns like messaging queues to decouple microservices and improve scalability.</li>
<li><strong>Data Management:</strong> Consider how to manage data across multiple microservices, such as using event sourcing or CQRS.</li>
<li><strong>Deployment and Scaling:</strong> Implement strategies for deploying and scaling microservices independently.</li>
<li><strong>Monitoring and Observability:</strong> Use monitoring tools to track performance, identify issues, and ensure the overall health of your microservices.</li>
</ol>
<p><strong>Benefits of Microservices Architecture</strong></p>
<ul>
<li><strong>Scalability:</strong> Each microservice can be scaled independently based on demand.</li>
<li><strong>Resilience:</strong> Failures in one microservice don't necessarily affect the entire application.</li>
<li><strong>Technology Agnostic:</strong> Microservices can be built using different technologies.</li>
<li><strong>Continuous Delivery:</strong> Deploy and update microservices independently, enabling faster development cycles.</li>
<li><strong>Team Autonomy:</strong> Empower teams to own and develop their own microservices.</li>
</ul>
<p><strong>Challenges of Microservices Architecture</strong></p>
<ul>
<li><strong>Increased Complexity:</strong> Managing multiple microservices can be more complex than a monolithic architecture.</li>
<li><strong>Distributed Transactions:</strong> Coordinating transactions across multiple microservices can be challenging.</li>
<li><strong>Network Latency:</strong> Communication between microservices can introduce latency.</li>
<li><strong>Testing and Debugging:</strong> Testing and debugging microservices can be more complex due to their distributed nature.</li>
</ul>
<p><strong>Best Practices for Microservices Design</strong></p>
<ul>
<li><strong>Start Small:</strong> Begin with a small number of microservices and gradually add more as your application grows.</li>
<li><strong>Use Domain-Driven Design:</strong> Apply domain-driven design principles to model your business domains and create well-defined microservices.</li>
<li><strong>Choose the Right Technology Stack:</strong> Select the appropriate technology stack for each microservice based on its requirements.</li>
<li><strong>Implement Strong Testing:</strong> Ensure code quality and reliability through thorough testing.</li>
<li><strong>Monitor and Optimize:</strong> Use monitoring tools to track performance and identify bottlenecks.</li>
</ul>
<p>By carefully considering these design aspects and best practices, you can successfully implement a microservices architecture that meets the needs of your application and provides numerous benefits.</p>
]]></content:encoded></item><item><title><![CDATA[Building Scalable Microservices with NestJS and Kafka]]></title><description><![CDATA[Introduction NestJS, a progressive Node.js framework, and Kafka, a distributed streaming platform, form a powerful combination for building scalable and…]]></description><link>https://articles.tkssharma.com/building-scalable-microservices-with-nestjs-and-kafka</link><guid isPermaLink="true">https://articles.tkssharma.com/building-scalable-microservices-with-nestjs-and-kafka</guid><category><![CDATA[nestjs]]></category><category><![CDATA[kafka]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 08:57:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727464284160/8a7ce4a6-1ee1-42c0-9626-87cb9d2d380b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=fGT6aKJpXdY">https://www.youtube.com/watch?v=fGT6aKJpXdY</a></div>
<h2 id="heading-building-scalable-microservices-with-nestjs-and-kafka">Building Scalable Microservices with NestJS and Kafka</h2>
<p><strong>Introduction</strong></p>
<p>NestJS, a progressive Node.js framework, and Kafka, a distributed streaming platform, form a powerful combination for building scalable and real-time microservices. This guide will explore how to leverage these technologies to create efficient and resilient applications.</p>
<p><strong>Understanding Microservices</strong></p>
<p>Microservices architecture involves breaking down large applications into smaller, independent services that communicate via APIs. This approach offers several benefits, including:</p>
<ul>
<li><strong>Scalability:</strong> Each microservice can be scaled independently based on demand.</li>
<li><strong>Resilience:</strong> Failures in one microservice don't necessarily affect the entire application.</li>
<li><strong>Technology Agnostic:</strong> Microservices can be built using different technologies.</li>
</ul>
<p><strong>Introducing Kafka</strong></p>
<p>Kafka is a distributed streaming platform that is ideal for handling high-volume, real-time data streams. It offers features like:</p>
<ul>
<li><strong>Pub/Sub Model:</strong> Producers publish messages to topics, and consumers subscribe to those topics.</li>
<li><strong>Durability:</strong> Messages are persisted to disk, ensuring they are not lost.</li>
<li><strong>Scalability:</strong> Kafka clusters can be easily scaled horizontally to handle increasing workloads.</li>
</ul>
<p><strong>Integrating NestJS with Kafka</strong></p>
<p>NestJS provides a convenient way to integrate with Kafka using the <code>@nestjs/microservices</code> package. This package allows you to create microservices that communicate using various protocols, including Kafka.</p>
<p><strong>Creating a Kafka Producer</strong></p>
<p>To create a Kafka producer in NestJS, you can use the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { KafkaOptions, Transport } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/microservices'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KafkaProducerService {
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> kafkaClient: ClientKafka;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.kafkaClient = <span class="hljs-keyword">new</span> ClientKafka({
      transport: Transport.KAFKA,
      options: {
        client: {
          brokers: [<span class="hljs-string">'localhost:9092'</span>],
        },
      },
    });
  }

  <span class="hljs-keyword">async</span> send(message: <span class="hljs-built_in">any</span>) {
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.kafkaClient.emit(<span class="hljs-string">'topic-name'</span>, message);
  }
}
</code></pre>
<p><strong>Creating a Kafka Consumer</strong></p>
<p>To create a Kafka consumer in NestJS, you can use the following code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { KafkaOptions, Transport } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/microservices'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KafkaConsumerService {
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> kafkaClient: ClientKafka;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.kafkaClient = <span class="hljs-keyword">new</span> ClientKafka({
      transport: Transport.KAFKA,
      options: {
        client: {
          brokers: [<span class="hljs-string">'localhost:9092'</span>],
        },
      },
    });
  }

  <span class="hljs-meta">@EventPattern</span>(<span class="hljs-string">'topic-name'</span>)
  <span class="hljs-keyword">async</span> handleEvent(message: <span class="hljs-built_in">any</span>) {
    <span class="hljs-comment">// Process the message</span>
  }
}
</code></pre>
<p><strong>Best Practices for Microservices with Kafka</strong></p>
<ul>
<li><strong>Design for Scalability:</strong> Ensure your microservices are designed to be scalable and can handle increasing workloads.</li>
<li><strong>Use Asynchronous Communication:</strong> Utilize Kafka's asynchronous messaging capabilities to decouple microservices.</li>
<li><strong>Handle Failures Gracefully:</strong> Implement retry mechanisms and error handling strategies to ensure reliability.</li>
<li><strong>Monitor and Optimize:</strong> Use monitoring tools to track performance and identify bottlenecks.</li>
</ul>
<p><strong>Conclusion</strong></p>
<p>By combining NestJS and Kafka, you can build highly scalable and resilient microservices that can handle real-time data processing and event-driven architectures. Following the best practices outlined in this guide will help you create successful microservices applications.</p>
]]></content:encoded></item><item><title><![CDATA[nestjs with kafkajs Producer and Consumer]]></title><description><![CDATA[Introduction Kafka is a distributed streaming platform that is widely used for real-time data processing and messaging. NestJS, on the other hand, is a…]]></description><link>https://articles.tkssharma.com/nestjs-with-kafkajs-producer-and-consumer</link><guid isPermaLink="true">https://articles.tkssharma.com/nestjs-with-kafkajs-producer-and-consumer</guid><category><![CDATA[nestjs]]></category><category><![CDATA[kafkajs]]></category><category><![CDATA[Microservices]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 08:53:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727464376057/6758f632-e22b-4737-bfb0-a34ab413a786.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=CDgwIkE8nmg&amp;t=107s">https://www.youtube.com/watch?v=CDgwIkE8nmg&amp;t=107s</a></div>
<h2 id="heading-nestjs-with-kafkajs-a-powerful-combination-for-building-scalable-applications">NestJS with Kafkajs: A Powerful Combination for Building Scalable Applications</h2>
<p>https://github.com/tkssharma/nestjs-kafka-monorepo</p>
<p><strong>Introduction</strong></p>
<p>Kafka is a distributed streaming platform that is widely used for real-time data processing and messaging. NestJS, on the other hand, is a progressive Node.js framework for building scalable and efficient applications. Combining Kafka with NestJS can create a powerful and scalable solution for various use cases.</p>
<p><strong>Integrating Kafka with NestJS</strong></p>
<p>To integrate Kafka with NestJS, we can use the <code>@nestjs/microservices</code> package. This package provides a convenient way to create microservices that communicate using different protocols, including Kafka.</p>
<p><strong>Creating a Kafka Producer</strong></p>
<p>To create a Kafka producer in NestJS, we can use the <code>@nestjs/microservices</code> module and the <code>KafkaOptions</code> interface. Here's an example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { KafkaOptions, Transport } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/microservices'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KafkaProducerService {
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> kafkaClient: ClientKafka;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.kafkaClient = <span class="hljs-keyword">new</span> ClientKafka({
      transport: Transport.KAFKA,
      options: {
        client: {
          brokers: [<span class="hljs-string">'localhost:9092'</span>],
        },
      },
    });
  }

  <span class="hljs-keyword">async</span> send(message: <span class="hljs-built_in">any</span>) {
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.kafkaClient.emit(<span class="hljs-string">'topic-name'</span>, message);
  }
}
</code></pre>
<p><strong>Creating a Kafka Consumer</strong></p>
<p>To create a Kafka consumer in NestJS, we can use the <code>@nestjs/microservices</code> module and the <code>KafkaOptions</code> interface. Here's an example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { KafkaOptions, Transport } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/microservices'</span>;

<span class="hljs-meta">@Injectable</span>()
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KafkaConsumerService {
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> kafkaClient: ClientKafka;

  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-built_in">this</span>.kafkaClient = <span class="hljs-keyword">new</span> ClientKafka({
      transport: Transport.KAFKA,
      options: {
        client: {
          brokers: [<span class="hljs-string">'localhost:9092'</span>],
        },
      },
    });
  }

  <span class="hljs-meta">@EventPattern</span>(<span class="hljs-string">'topic-name'</span>)
  <span class="hljs-keyword">async</span> handleEvent(message: <span class="hljs-built_in">any</span>) {
    <span class="hljs-comment">// Process the message</span>
  }
}
</code></pre>
<p><strong>Using Kafka Producer and Consumer</strong></p>
<p>Once you have created the producer and consumer, you can use them to send and receive messages. Here's an example:</p>
<pre><code class="lang-typescript"><span class="hljs-meta">@Controller</span>(<span class="hljs-string">'kafka'</span>)
<span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> KafkaController {
  <span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> kafkaProducerService: KafkaProducerService</span>) {}

  <span class="hljs-meta">@Post</span>()
  <span class="hljs-keyword">async</span> sendMessage(<span class="hljs-meta">@Body</span>() message: <span class="hljs-built_in">any</span>) {
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.kafkaProducerService.send(message);
    <span class="hljs-keyword">return</span> { message: <span class="hljs-string">'Message sent successfully'</span> };
  }
}
</code></pre>
<p>Integrate nestjs with simple kafkajs library </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Module } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { KafkaService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./kafka.service'</span>;
<span class="hljs-keyword">import</span> { AppConfigModule } <span class="hljs-keyword">from</span> <span class="hljs-string">'@app/config'</span>;
<span class="hljs-keyword">import</span> { KafkaConsumerService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./kafka.consumer.service'</span>;
<span class="hljs-keyword">import</span> { KafkaProducerService } <span class="hljs-keyword">from</span> <span class="hljs-string">'./kafka.producer.service'</span>;

@Module({
  <span class="hljs-attr">imports</span>: [AppConfigModule],
  <span class="hljs-attr">providers</span>: [KafkaConsumerService, KafkaProducerService],
  <span class="hljs-attr">exports</span>: [KafkaConsumerService, KafkaProducerService],
})
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaModule</span> </span>{ }
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { AppConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@app/config'</span>;
<span class="hljs-keyword">import</span> { Injectable, OnApplicationShutdown } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;
<span class="hljs-keyword">import</span> { ConfigService } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/config'</span>;
<span class="hljs-keyword">import</span> { ConsumerConfig, ConsumerSubscribeTopic, KafkaMessage } <span class="hljs-keyword">from</span> <span class="hljs-string">'kafkajs'</span>;
<span class="hljs-keyword">import</span> { KafkaConsumer } <span class="hljs-keyword">from</span> <span class="hljs-string">'./consumer.service'</span>;

interface KafkajsConsumerOptions {
  <span class="hljs-attr">topic</span>: ConsumerSubscribeTopic;
  config: ConsumerConfig;
  onMessage: <span class="hljs-function">(<span class="hljs-params">message: KafkaMessage</span>) =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;;
}

<span class="hljs-keyword">export</span> interface IConsumer {
  <span class="hljs-attr">connect</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;;
  disconnect: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;;
  consume: <span class="hljs-function">(<span class="hljs-params">message: any</span>) =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;;
}


@Injectable()
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaConsumerService</span> <span class="hljs-title">implements</span> <span class="hljs-title">OnApplicationShutdown</span> </span>{
  private readonly consumers: IConsumer[] = [];

  <span class="hljs-keyword">constructor</span>(
    private readonly configService: AppConfigService,
  ) { }

  <span class="hljs-keyword">async</span> consume({ topic, config, onMessage }: KafkajsConsumerOptions) {
    <span class="hljs-keyword">const</span> consumer = <span class="hljs-keyword">new</span> KafkaConsumer(
      topic,
      config,
      <span class="hljs-built_in">this</span>.configService.kafka.broker
    );
    <span class="hljs-keyword">await</span> consumer.connect();
    <span class="hljs-keyword">await</span> consumer.consume(onMessage);
    <span class="hljs-built_in">this</span>.consumers.push(consumer);
  }

  <span class="hljs-keyword">async</span> onApplicationShutdown() {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> consumer <span class="hljs-keyword">of</span> <span class="hljs-built_in">this</span>.consumers) {
      <span class="hljs-keyword">await</span> consumer.disconnect();
    }
  }
}
</code></pre>
<p>Consumer service </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Consumer, ConsumerConfig, ConsumerSubscribeTopic, Kafka, KafkaMessage, Producer } <span class="hljs-keyword">from</span> <span class="hljs-string">"kafkajs"</span>;
<span class="hljs-keyword">import</span> { IProducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"./kafka.producer.service"</span>;
<span class="hljs-keyword">import</span> { Logger } <span class="hljs-keyword">from</span> <span class="hljs-string">"@nestjs/common"</span>;
<span class="hljs-keyword">import</span> { IConsumer } <span class="hljs-keyword">from</span> <span class="hljs-string">"./kafka.consumer.service"</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> retry <span class="hljs-keyword">from</span> <span class="hljs-string">'async-retry'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> sleep = <span class="hljs-function">(<span class="hljs-params">timeout: number</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, timeout));
};

<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">KafkaConsumer</span> <span class="hljs-title">implements</span> <span class="hljs-title">IConsumer</span> </span>{
  private readonly kafka: Kafka;
  private readonly consumer: Consumer;
  private readonly logger: Logger;

  <span class="hljs-keyword">constructor</span>(
    private readonly topic: ConsumerSubscribeTopic,
    config: ConsumerConfig,
    broker: string) {
    <span class="hljs-built_in">this</span>.kafka = <span class="hljs-keyword">new</span> Kafka({
      <span class="hljs-attr">brokers</span>: [broker]
    })
    <span class="hljs-built_in">this</span>.consumer = <span class="hljs-built_in">this</span>.kafka.consumer(config);
    <span class="hljs-built_in">this</span>.logger = <span class="hljs-keyword">new</span> Logger(<span class="hljs-string">`<span class="hljs-subst">${topic}</span>-<span class="hljs-subst">${config.groupId}</span>`</span>)
  }
  <span class="hljs-keyword">async</span> consume(onMessage: <span class="hljs-function">(<span class="hljs-params">message: KafkaMessage</span>) =&gt;</span> <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-keyword">void</span>&gt;) {
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.consumer.subscribe(<span class="hljs-built_in">this</span>.topic)
    <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.consumer.run({
      <span class="hljs-attr">eachMessage</span>: <span class="hljs-keyword">async</span> ({ message, partition }) =&gt; {
        <span class="hljs-built_in">this</span>.logger.debug(<span class="hljs-string">`Processing message partition: <span class="hljs-subst">${partition}</span>`</span>);
        <span class="hljs-keyword">try</span> {
          <span class="hljs-keyword">await</span> retry(<span class="hljs-keyword">async</span> () =&gt; onMessage(message), {
            <span class="hljs-attr">retries</span>: <span class="hljs-number">3</span>,
            <span class="hljs-attr">onRetry</span>: <span class="hljs-function">(<span class="hljs-params">error, attempt</span>) =&gt;</span>
              <span class="hljs-built_in">this</span>.logger.error(
                <span class="hljs-string">`Error consuming message, executing retry <span class="hljs-subst">${attempt}</span>/3...`</span>,
                error,
              ),
          });
        } <span class="hljs-keyword">catch</span> (err) {
          <span class="hljs-comment">// handle failure of message </span>
          <span class="hljs-comment">// write then to DB table or log them </span>
          <span class="hljs-comment">// better write to DATABASE </span>
        }
      },
    })
  }

  <span class="hljs-keyword">async</span> connect() {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.consumer.connect();
    } <span class="hljs-keyword">catch</span> (err) {
      <span class="hljs-built_in">this</span>.logger.error(<span class="hljs-string">'Failed to connect to Kafka. trying again ...'</span>, err);
      <span class="hljs-keyword">await</span> sleep(<span class="hljs-number">5000</span>);
      <span class="hljs-keyword">await</span> <span class="hljs-built_in">this</span>.connect();
    }

  }
  <span class="hljs-keyword">async</span> disconnect() {
    <span class="hljs-built_in">this</span>.consumer.disconnect()
  }
}
</code></pre>
<p><strong>Conclusion</strong></p>
<p>By integrating Kafka with NestJS, you can build scalable and distributed applications that can handle high volumes of data and real-time processing. The <code>@nestjs/microservices</code> module provides a convenient way to interact with Kafka, making it easy to incorporate into your NestJS projects.</p>
]]></content:encoded></item><item><title><![CDATA[Nestjs Workspaces to build Monorepo]]></title><description><![CDATA[Introduction In modern software development, managing multiple projects within a single repository, known as a monorepo, has become increasingly popular…]]></description><link>https://articles.tkssharma.com/nestjs-workspaces-to-build-monorepo</link><guid isPermaLink="true">https://articles.tkssharma.com/nestjs-workspaces-to-build-monorepo</guid><category><![CDATA[nestjs workspaces]]></category><category><![CDATA[npm workspaces]]></category><category><![CDATA[nestjs]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 08:52:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727464472316/7e96f538-dc6b-49c2-8f38-a18f1ed5e1d6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=ChpamP3zvIU&amp;t=1s">https://www.youtube.com/watch?v=ChpamP3zvIU&amp;t=1s</a></div>
<h2 id="heading-nestjs-workspaces-a-powerful-tool-for-monorepo-development">NestJS Workspaces: A Powerful Tool for Monorepo Development</h2>
<p><strong>Introduction</strong></p>
<p>In modern software development, managing multiple projects within a single repository, known as a monorepo, has become increasingly popular. It offers several advantages, including improved code sharing, simplified dependency management, and faster build times. NestJS Workspaces is a powerful tool that simplifies the process of building monorepo-based NestJS applications.</p>
<p><strong>What is NestJS Workspaces?</strong></p>
<p>NestJS Workspaces is a feature within the NestJS framework that allows you to manage multiple NestJS applications within a single repository. It provides a convenient way to share code, dependencies, and configuration between different projects, making it easier to maintain and develop complex applications.</p>
<p><strong>Key Benefits of Using NestJS Workspaces:</strong></p>
<ul>
<li><strong>Improved Code Sharing:</strong> Easily share code and libraries between different applications within the workspace.</li>
<li><strong>Simplified Dependency Management:</strong> Manage dependencies at the workspace level, ensuring consistency across all projects.</li>
<li><strong>Consistent Development Environment:</strong> Maintain a consistent development environment for all applications in the workspace.</li>
<li><strong>Faster Builds and Testing:</strong> Leverage caching and parallel execution to improve build and test times.</li>
<li><strong>Enhanced Collaboration:</strong> Facilitate collaboration among team members by working on multiple projects within a single repository.</li>
</ul>
<p><strong>Setting Up a NestJS Workspace</strong></p>
<p>To set up a NestJS workspace, follow these steps:</p>
<ol>
<li><strong>Create a New Workspace:</strong> Use the <code>nest new workspace-name</code> command to create a new workspace.</li>
<li><strong>Generate Applications:</strong> Use the <code>nest generate app app-name</code> command to generate individual applications within the workspace.</li>
<li><strong>Share Code:</strong> Create shared libraries or modules within the workspace and import them into your applications.</li>
</ol>
<p><strong>Managing Dependencies</strong></p>
<p>NestJS Workspaces uses a shared package.json file to manage dependencies for all applications within the workspace. This simplifies dependency management and ensures consistency across projects.</p>
<p><strong>Building and Testing</strong></p>
<p>You can use the <code>nest run build</code> and <code>nest test</code> commands to build and test all applications within the workspace. NestJS Workspaces automatically detects changes and rebuilds only the affected applications, improving build times.</p>
<p><strong>Deployment</strong></p>
<p>You can deploy your NestJS applications from the workspace using your preferred deployment strategy. Consider using tools like Docker, Kubernetes, or serverless platforms for efficient deployment.</p>
<p><strong>Conclusion</strong></p>
<p>NestJS Workspaces is a valuable tool for building and managing complex NestJS applications. By leveraging the benefits of monorepo, you can improve code sharing, simplify dependency management, and streamline your development workflow. Consider using NestJS Workspaces in your next NestJS project to experience its advantages firsthand.</p>
]]></content:encoded></item><item><title><![CDATA[DiagramGPT Review of Eraser AI]]></title><description><![CDATA[Eraser AI is a revolutionary AI-powered tool that simplifies the process of creating professional-looking diagrams. With its advanced capabilities, Eraser…]]></description><link>https://articles.tkssharma.com/diagramgpt-review-of-eraser-ai</link><guid isPermaLink="true">https://articles.tkssharma.com/diagramgpt-review-of-eraser-ai</guid><category><![CDATA[eraser ai]]></category><category><![CDATA[chatgpt]]></category><dc:creator><![CDATA[tkssharma]]></dc:creator><pubDate>Sun, 22 Sep 2024 08:52:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727464564077/c0209e50-32b4-4233-b4ea-3c3cf78d4262.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=70asK1jfUmc">https://www.youtube.com/watch?v=70asK1jfUmc</a></div>
<h2 id="heading-eraser-ai-a-powerful-tool-for-creating-stunning-diagrams">Eraser AI: A Powerful Tool for Creating Stunning Diagrams</h2>
<p>Eraser AI is a revolutionary AI-powered tool that simplifies the process of creating professional-looking diagrams. With its advanced capabilities, Eraser AI can quickly generate various types of diagrams, from flowcharts and UML diagrams to mind maps and network diagrams.</p>
<p><strong>Key Features of Eraser AI:</strong></p>
<ul>
<li><strong>Natural Language Processing:</strong> Eraser AI understands natural language prompts, allowing you to describe your diagram concept in plain English.</li>
<li><strong>AI-Powered Generation:</strong> The tool leverages AI algorithms to generate accurate and visually appealing diagrams based on your input.</li>
<li><strong>Customization Options:</strong> Easily customize your diagrams with different shapes, colors, and styles to match your preferences.</li>
<li><strong>Export and Sharing:</strong> Export your diagrams in various formats (e.g., PNG, SVG, PDF) and share them with others.</li>
<li><strong>Integration with Other Tools:</strong> Eraser AI can seamlessly integrate with your existing design workflow.</li>
</ul>
<p><strong>How to Use Eraser AI:</strong></p>
<ol>
<li><strong>Access the Tool:</strong> Visit the Eraser AI website or download the desktop app.</li>
<li><strong>Describe Your Diagram:</strong> Use natural language to describe the type of diagram you want to create.</li>
<li><strong>Customize the Diagram:</strong> Modify the generated diagram to suit your specific needs.</li>
<li><strong>Export and Share:</strong> Export your diagram in your desired format and share it with others.</li>
</ol>
<p><strong>Benefits of Using Eraser AI:</strong></p>
<ul>
<li><strong>Save Time and Effort:</strong> Create professional-looking diagrams in a fraction of the time it would take to draw them manually.</li>
<li><strong>Improve Accuracy:</strong> Ensure that your diagrams are technically correct and visually appealing.</li>
<li><strong>Enhance Collaboration:</strong> Share and collaborate on diagrams with your team members.</li>
<li><strong>Streamline Your Workflow:</strong> Integrate Eraser AI into your existing design process.</li>
</ul>
<p><strong>Use Cases for Eraser AI:</strong></p>
<ul>
<li><strong>Software Architecture:</strong> Create UML diagrams to visualize your software architecture.</li>
<li><strong>Data Flow Diagrams:</strong> Illustrate data flow within your system.</li>
<li><strong>Business Process Diagrams:</strong> Model your business processes and workflows.</li>
<li><strong>Mind Mapping:</strong> Create visual representations of ideas and concepts.</li>
<li><strong>Technical Documentation:</strong> Generate diagrams to accompany technical documentation.</li>
</ul>
<p>Eraser AI is a powerful tool that can significantly improve your efficiency and productivity when creating diagrams. By leveraging AI, Eraser AI automates the process, allowing you to focus on your ideas and concepts. Give Eraser AI a try and experience the benefits of AI-powered diagram creation for yourself!</p>
]]></content:encoded></item></channel></rss>