{"id":20076277,"url":"https://github.com/aakashdeveloper/javascript-interview-question","last_synced_at":"2025-10-20T07:40:01.399Z","repository":{"id":98117041,"uuid":"307894304","full_name":"Aakashdeveloper/JavaScript-Interview-Question","owner":"Aakashdeveloper","description":"JavaScript-Interview-Question","archived":false,"fork":false,"pushed_at":"2024-05-11T07:00:09.000Z","size":568,"stargazers_count":50,"open_issues_count":1,"forks_count":23,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-01-13T00:49:27.414Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Aakashdeveloper.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-10-28T03:16:29.000Z","updated_at":"2024-10-09T18:15:26.000Z","dependencies_parsed_at":"2024-05-11T08:22:05.547Z","dependency_job_id":"ab1915b7-233a-47ce-9fb2-99fd6c33e2fd","html_url":"https://github.com/Aakashdeveloper/JavaScript-Interview-Question","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2FJavaScript-Interview-Question","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2FJavaScript-Interview-Question/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2FJavaScript-Interview-Question/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Aakashdeveloper%2FJavaScript-Interview-Question/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Aakashdeveloper","download_url":"https://codeload.github.com/Aakashdeveloper/JavaScript-Interview-Question/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241509624,"owners_count":19974070,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-13T15:02:08.466Z","updated_at":"2025-10-20T07:40:01.323Z","avatar_url":"https://github.com/Aakashdeveloper.png","language":"HTML","readme":"# JavaScript Interview Questions\n\n*Click \u003cimg src=\"assets/star.png\" width=\"18\" height=\"18\" align=\"absmiddle\" title=\"Star\" /\u003e if you like the project. Pull Request are highly appreciated.*\n\n## Table of Contents\n\n* *[ES6 Interview Questions and Answers](es6-questions.md)*\n* *[Programming in JavaScript](javascript-programs.md)*\n\n\u003cbr/\u003e\n\n|Sl.No| Questions                                                                         |\n|-----|-----------------------------------------------------------------------------------|\n| 01.|[What is difference between document.getElementById() and document.uerySelector()?](#q-what-is-difference-between-document-getelementbyid-and-document-ueryselector)|\n| 02.|[When to use reduce(), map(), foreach() and filter() in JavaScript?](#q-when-to-use-reduce-map-foreach-and-filter-in-javascript)|\n| 03.|[What is Hoisting in JavaScript?](#q-what-is-hoisting-in-javascript)|\n| 04.|[What are closures?](#q-what-are-closures)|\n| 05.|[How do you clone an object in JavaScript?](#q-how-do-you-clone-an-object-in-javascript)|\n| 06.|[What are the possible ways to create objects in JavaScript?](#q-what-are-the-possible-ways-to-create-objects-in-javascript)|\n| 07.|[What are the javascript data types?](#q-what-are-the-javascript-data-types)|\n| 08.|[What are global variables?](#q-what-are-global-variables)|\n| 09.|[What is variable shadowing in javascript?](#q-what-is-variable-shadowing-in-javascript)|\n| 10.|[What is an event flow?](#q-what-is-an-event-flow)|\n| 11.|[What is event bubbling?](#q-what-is-event-bubbling)|\n| 12.|[What is event capturing?](#q-what-is-event-capturing)|\n| 13.|[What is prototype chain?](#q-what-is-prototype-chain)|\n| 14.|[What is the difference between Call, Apply and Bind?](#q-what-is-the-difference-between-call-apply-and-bind)|\n| 15.|[What is the difference between == and === operators?](#q-what-is-the-difference-between-and-operators)|\n| 16.|[What is a first class function?](#q-what-is-a-first-class-function)|\n| 17.|[What is a higher order function?](#q-what-is-a-higher-order-function)|\n| 18.|[What is a unary function?](#q-what-is-a-unary-function)|\n| 19.|[What is currying function?](#q-what-is-currying-function)|\n| 20.|[What is a pure function?](#q-what-is-a-pure-function)|\n| 21.|[What is memoization in JavaScript?](#q-what-is-memoization-in-javascript)|\n| 22.|[What is a service worker?](#q-what-is-a-service-worker)|\n| 23.|[How do you manipulate DOM using service worker?](#q-how-do-you-manipulate-dom-using-service-worker)|\n| 24.|[How do you reuse information across service worker restarts?](#q-how-do-you-reuse-information-across-service-worker-restarts)|\n| 25.|[What is a post message?](#q-what-is-a-post-message)|\n| 26.|[What is a web-storage event and its event handler?](#q-what-is-a-web-storage-event-and-its-event-handler)|\n| 27.|[How to use Web Workers in javascript?](#q-how-to-use-web-workers-in-javascript)|\n| 28.|[What are the restrictions of web workers on DOM?](#q-what-are-the-restrictions-of-web-workers-on-dom)|\n| 29.|[What is a promise?](#q-what-is-a-promise)|\n| 30.|[What is a callback function?](#q-what-is-a-callback-function)|\n| 31.|[Why do we need callbacks?](#q-why-do-we-need-callbacks)|\n| 32.|[What is a callback hell?](#q-what-is-a-callback-hell)|\n| 33.|[What is server-sent events?](#q-what-is-server-sent-events)|\n| 34.|[What is callback in callback?](#q-what-is-callback-in-callback)|\n| 35.|[What is promise chaining?](#q-what-is-promise-chaining)|\n| 36.|[What is promise.all()?](#q-what-is-promiseall)|\n| 37.|[What is the purpose of race method in promise?](#q-what-is-the-purpose-of-race-method-in-promise)|\n| 38.|[What is a strict mode in javascript?](#q-what-is-a-strict-mode-in-javascript)|\n| 39.|[What is the purpose of double exclamation?](#q-what-is-the-purpose-of-double-exclamation)|\n| 40.|[What is the purpose of delete operator?](#q-what-is-the-purpose-of-delete-operator)|\n| 41.|[What is typeof operator?](#q-what-is-typeof-operator)|\n| 42.|[What is undefined property?](#q-what-is-undefined-property)|\n| 43.|[What is the difference between null and undefined?](#q-what-is-the-difference-between-null-and-undefined)|\n| 44.|[What is eval?](#q-what-is-eval)|\n| 45.|[What is the difference between window and document?](#q-what-is-the-difference-between-window-and-document)|\n| 46.|[How do you access history in javascript?](#q-how-do-you-access-history-in-javascript)|\n| 47.|[What is isNaN?](#q-what-is-isnan)|\n| 48.|[What are the differences between undeclared and undefined variables?](#q-what-are-the-differences-between-undeclared-and-undefined-variables)|\n| 49.|[What is NaN property?](#q-what-is-nan-property)|\n| 50.|[What is the purpose of isFinite function?](#q-what-is-the-purpose-of-isfinite-function)|\n| 51.|[How do you submit a form using JavaScript?](#q-how-do-you-submit-a-form-using-javascript)|\n| 52.|[How do you find operating system details?](#q-how-do-you-find-operating-system-details)|\n| 53.|[What is the difference between document load and DOMContentLoaded events?](#q-what-is-the-difference-between-document-load-and-domcontentloaded-events)|\n| 54.|[What is the difference between native, host and user objects?](#q-what-is-the-difference-between-native-host-and-user-objects)|\n| 55.|[What are the pros and cons of promises over callbacks?](#q-what-are-the-pros-and-cons-of-promises-over-callbacks)|\n| 56.|[What is the difference between an attribute and a property?](#q-what-is-the-difference-between-an-attribute-and-a-property)|\n| 57.|[What is same-origin policy?](#q-what-is-same-origin-policy)|\n| 58.|[What is the purpose of void(0)?](#q-what-is-the-purpose-of-void-0)|\n| 59.|[Is JavaScript a compiled or interpreted language?](#q-is-javascript-a-compiled-or-interpreted-language)|\n| 60.|[Is JavaScript a case-sensitive language?](#q-is-javascript-a-case-sensitive-language)|\n| 61.|[What are events?](#q-what-are-events)|\n| 62.|[What is the use of preventDefault method?](#q-what-is-the-use-of-preventdefault-method)|\n| 63.|[What is the use of stopPropagation method?](#q-what-is-the-use-of-stoppropagation-method)|\n| 64.|[What are the steps involved in return false usage?](#q-what-are-the-steps-involved-in-return-false-usage)|\n| 65.|[What is BOM?](#q-what-is-bom)|\n| 66.|[What is the use of setTimeout?](#q-what-is-the-use-of-settimeout)|\n| 67.|[What is the use of setInterval?](#q-what-is-the-use-of-setinterval)|\n| 68.|[Why is JavaScript treated as Single threaded?](#q-why-is-javascript-treated-as-single-threaded)|\n| 69.|[What is an event delegation?](#q-what-is-an-event-delegation)|\n| 70.|[What is the purpose JSON stringify?](#q-what-is-the-purpose-json-stringify)|\n| 71.|[How do you parse JSON string?](#q-how-do-you-parse-json-string)|\n| 72.|[What is the purpose of clearTimeout method?](#q-what-is-the-purpose-of-cleartimeout-method)|\n| 73.|[What is the purpose of clearInterval method?](#q-what-is-the-purpose-of-clearinterval-method)|\n| 74.|[How do you redirect new page in javascript?](#q-how-do-you-redirect-new-page-in-javascript)|\n| 75.|[How do you check whether a string contains a substring?](#q-how-do-you-check-whether-a-string-contains-a-substring)|\n| 76.|[How do you validate an email in javascript?](#q-how-do-you-validate-an-email-in-javascript)|\n| 77.|[How do you get the current url with javascript?](#q-how-do-you-get-the-current-url-with-javascript)|\n| 78.|[What are the various url properties of location object?](#q-what-are-the-various-url-properties-of-location-object)|\n| 79.|[How do get uery string values in javascript?](#q-how-do-get-uery-string-values-in-javascript)|\n| 80.|[How do you check if a key exists in an object?](#q-how-do-you-check-if-a-key-exists-in-an-object)|\n| 81.|[How do you loop through or enumerate javascript object?](#q-how-do-you-loop-through-or-enumerate-javascript-object)|\n| 82.|[How do you test for an empty object?](#q-how-do-you-test-for-an-empty-object)|\n| 83.|[What is an arguments object?](#q-what-is-an-arguments-object)|\n| 84.|[How do you make first letter of the string in an uppercase?](#q-how-do-you-make-first-letter-of-the-string-in-an-uppercase)|\n| 85.|[What are the pros and cons of for loop?](#q-what-are-the-pros-and-cons-of-for-loop)|\n| 86.|[How do you display the current date in javascript?](#q-how-do-you-display-the-current-date-in-javascript)|\n| 87.|[How do you compare two date objects?](#q-how-do-you-compare-two-date-objects)|\n| 88.|[How do you check if a string starts with another string?](#q-how-do-you-check-if-a-string-starts-with-another-string)|\n| 89.|[How do you trim a string in javascript?](#q-how-do-you-trim-a-string-in-javascript)|\n| 90.|[How do you add a key value pair in javascript?](#q-how-do-you-add-a-key-value-pair-in-javascript)|\n| 91.|[How do you assign default values to variables?](#q-how-do-you-assign-default-values-to-variables)|\n| 92.|[Can we define properties for functions?](#q-can-we-define-properties-for-functions)|\n| 93.|[What is the way to find the number of parameters expected by a function?](#q-what-is-the-way-to-find-the-number-of-parameters-expected-by-a-function)|\n| 94.|[What are break and continue statements?](#q-what-are-break-and-continue-statements)|\n| 95.|[What are js labels?](#q-what-are-js-labels)|\n| 96.|[What are the benefits of keeping declarations at the top?](#q-what-are-the-benefits-of-keeping-declarations-at-the-top)|\n| 97.|[What are the benefits of initializing variables?](#q-what-are-the-benefits-of-initializing-variables)|\n| 98.|[What are the recommendations to create new object?](#q-what-are-the-recommendations-to-create-new-object)|\n| 99.|[How do you define JSON arrays?](#q-how-do-you-define-json-arrays)|\n| 100.|[How do you generate random integers?](#q-how-do-you-generate-random-integers)|\n| 101.|[Can you write a random integers function to print integers with in a range?](#q-can-you-write-a-random-integers-function-to-print-integers-with-in-a-range)|\n| 102.|[What are the string methods available in Regular expression?](#q-what-are-the-string-methods-available-in-regular-expression)|\n| 103.|[What are modifiers in regular expression?](#q-what-are-modifiers-in-regular-expression)|\n| 104.|[What are regular expression patterns?](#q-what-are-regular-expression-patterns)|\n| 105.|[What is a RegExp object?](#q-what-is-a-regexp-object)|\n| 106.|[How do you search a string for a pattern?](#q-how-do-you-search-a-string-for-a-pattern)|\n| 107.|[What is the purpose of exec method?](#q-what-is-the-purpose-of-exec-method)|\n| 108.|[How do you change style of a HTML element?](#q-how-do-you-change-style-of-a-html-element)|\n| 109.|[What is a debugger statement?](#q-what-is-a-debugger-statement)|\n| 110.|[What is the purpose of breakpoints in debugging?](#q-what-is-the-purpose-of-breakpoints-in-debugging)|\n| 111.|[Can I use reserved words as identifiers?](#q-can-i-use-reserved-words-as-identifiers)|\n| 112.|[How do you detect a mobile browser without regexp?](#q-how-do-you-detect-a-mobile-browser-without-regexp)|\n| 113.|[How do you get the image width and height using JS?](#q-how-do-you-get-the-image-width-and-height-using-js)|\n| 114.|[How do you make synchronous HTTP reuest?](#q-how-do-you-make-synchronous-http-reuest)|\n| 115.|[How do you make asynchronous HTTP reuest?](#q-how-do-you-make-asynchronous-http-reuest)|\n| 116.|[How do you convert date to another timezone in javascript?](#q-how-do-you-convert-date-to-another-timezone-in-javascript)|\n| 117.|[What are the properties used to get size of window?](#q-what-are-the-properties-used-to-get-size-of-window)|\n| 118.|[What is a conditional operator in javascript?](#q-what-is-a-conditional-operator-in-javascript)|\n| 119.|[Can you apply chaining on conditional operator?](#q-can-you-apply-chaining-on-conditional-operator)|\n| 120.|[What are the ways to execute javascript after page load?](#q-what-are-the-ways-to-execute-javascript-after-page-load)|\n| 121.|[What is the difference between proto and prototype?](#q-what-is-the-difference-between-proto-and-prototype)|\n| 122.|[Give an example where do you really need semicolon?](#q-give-an-example-where-do-you-really-need-semicolon)|\n| 123.|[What is a freeze method?](#q-what-is-a-freeze-method)|\n| 124.|[What is the purpose of freeze method?](#q-what-is-the-purpose-of-freeze-method)|\n| 125.|[Why do I need to use freeze method?](#q-why-do-i-need-to-use-freeze-method)|\n| 126.|[How do you detect a browser language preference?](#q-how-do-you-detect-a-browser-language-preference)|\n| 127.|[How to convert string to title case with javascript?](#q-how-to-convert-string-to-title-case-with-javascript)|\n| 128.|[How do you detect javascript disabled in the page?](#q-how-do-you-detect-javascript-disabled-in-the-page)|\n| 129.|[What are various operators supported by javascript?](#q-what-are-various-operators-supported-by-javascript)|\n| 130.|[What is a rest parameter?](#q-what-is-a-rest-parameter)|\n| 131.|[What happens if you do not use rest parameter as a last argument?](#q-what-happens-if-you-do-not-use-rest-parameter-as-a-last-argument)|\n| 132.|[What are the bitwise operators available in javascript?](#q-what-are-the-bitwise-operators-available-in-javascript)|\n| 133.|[How do you determine whether object is frozen or not?](#q-how-do-you-determine-whether-object-is-frozen-or-not)|\n| 134.|[How do you determine two values same or not using object?](#q-how-do-you-determine-two-values-same-or-not-using-object)|\n| 135.|[What is the purpose of using object is method?](#q-what-is-the-purpose-of-using-object-is-method)|\n| 136.|[How do you copy properties from one object to other?](#q-how-do-you-copy-properties-from-one-object-to-other)|\n| 137.|[What are the applications of assign method?](#q-what-are-the-applications-of-assign-method)|\n| 138.|[What is a proxy object?](#q-what-is-a-proxy-object)|\n| 139.|[What is the purpose of seal method?](#q-what-is-the-purpose-of-seal-method)|\n| 140.|[What are the applications of seal method?](#q-what-are-the-applications-of-seal-method)|\n| 141.|[What are the differences between freeze and seal methods?](#q-what-are-the-differences-between-freeze-and-seal-methods)|\n| 142.|[How do you determine if an object is sealed or not?](#q-how-do-you-determine-if-an-object-is-sealed-or-not)|\n| 143.|[How do you get enumerable key and value pairs?](#q-how-do-you-get-enumerable-key-and-value-pairs)|\n| 144.|[What is the main difference between Object.values and Object.entries method?](#q-what-is-the-main-difference-between-objectvalues-and-objectentries-method)|\n| 145.|[How can you get the list of keys of any object?](#q-how-can-you-get-the-list-of-keys-of-any-object)|\n| 146.|[How do you create an object with prototype?](#q-how-do-you-create-an-object-with-prototype)|\n| 147.|[What is a WeakSet?](#q-what-is-a-weakset)|\n| 148.|[What are the differences between WeakSet and Set?](#q-what-are-the-differences-between-weakset-and-set)|\n| 149.|[List down the collection of methods available on WeakSet?](#q-list-down-the-collection-of-methods-available-on-weakset)|\n| 150.|[What is a WeakMap?](#q-what-is-a-weakmap)|\n| 151.|[What are the differences between WeakMap and Map?](#q-what-are-the-differences-between-weakmap-and-map)|\n| 152.|[List down the collection of methods available on WeakMap?](#q-list-down-the-collection-of-methods-available-on-weakmap)|\n| 153.|[What is the purpose of uneval?](#q-what-is-the-purpose-of-uneval)|\n| 154.|[How do you encode an URL?](#q-how-do-you-encode-an-url)|\n| 155.|[How do you decode an URL?](#q-how-do-you-decode-an-url)|\n| 156.|[How do you print the contents of web page?](#q-how-do-you-print-the-contents-of-web-page)|\n| 157.|[What is the difference between uneval and eval?](#q-what-is-the-difference-between-uneval-and-eval)|\n| 158.|[What is an anonymous function?](#q-what-is-an-anonymous-function)|\n| 159.|[What is the precedence order between local and global variables?](#q-what-is-the-precedence-order-between-local-and-global-variables)|\n| 160.|[What are javascript accessors?](#q-what-are-javascript-accessors)|\n| 161.|[How do you define property on Object constructor?](#q-how-do-you-define-property-on-object-constructor)|\n| 162.|[What is the difference between get and defineProperty?](#q-what-is-the-difference-between-get-and-defineproperty)|\n| 163.|[What are the advantages of Getters and Setters?](#q-what-are-the-advantages-of-getters-and-setters)|\n| 164.|[Can I add getters and setters using defineProperty method?](#q-can-i-add-getters-and-setters-using-defineproperty-method)|\n| 165.|[What is the purpose of switch-case?](#q-what-is-the-purpose-of-switch-case)|\n| 166.|[What are the conventions to be followed for the usage of swtich case?](#q-what-are-the-conventions-to-be-followed-for-the-usage-of-swtich-case)|\n| 167.|[What are the different ways to access object properties?](#q-what-are-the-different-ways-to-access-object-properties)|\n| 168.|[What are the function parameter rules?](#q-what-are-the-function-parameter-rules)|\n| 169.|[What is an error object?](#q-what-is-an-error-object)|\n| 170.|[When you get a syntax error?](#q-when-you-get-a-syntax-error)|\n| 171.|[What are the different error names from error object?](#q-what-are-the-different-error-names-from-error-object)|\n| 172.|[What are the various statements in error handling?](#q-what-are-the-various-statements-in-error-handling)|\n| 173.|[What are the two types of loops in javascript?](#q-what-are-the-two-types-of-loops-in-javascript)|\n| 174.|[What is an Intl object?](#q-what-is-an-intl-object)|\n| 175.|[How do you perform language specific date and time formatting?](#q-how-do-you-perform-language-specific-date-and-time-formatting)|\n| 176.|[What is an Iterator?](#q-what-is-an-iterator)|\n| 177.|[What is a decorator?](#q-what-is-a-decorator)|\n| 178.|[What are the properties of Intl object?](#q-what-are-the-properties-of-intl-object)|\n| 179.|[What is an Unary operator?](#q-what-is-an-unary-operator)|\n| 180.|[How do you sort elements in an array?](#q-how-do-you-sort-elements-in-an-array)|\n| 181.|[What is the purpose of compareFunction while sorting arrays?](#q-what-is-the-purpose-of-comparefunction-while-sorting-arrays)|\n| 182.|[How do you reversing an array?](#q-how-do-you-reversing-an-array)|\n| 183.|[How do you find min and max value in an array?](#q-how-do-you-find-min-and-max-value-in-an-array)|\n| 184.|[How do you find min and max values without Math functions?](#q-how-do-you-find-min-and-max-values-without-math-functions)|\n| 185.|[What is an empty statement and purpose of it?](#q-what-is-an-empty-statement-and-purpose-of-it)|\n| 186.|[How do you get meta data of a module?](#q-how-do-you-get-meta-data-of-a-module)|\n| 187.|[What is a comma operator?](#q-what-is-a-comma-operator)|\n| 188.|[What is the advantage of a comma operator?](#q-what-is-the-advantage-of-a-comma-operator)|\n| 189.|[Explain event delegation?](#q-explain-event-delegation)|\n| 190.|[Explain how prototypal inheritance works?](#q-explain-how-prototypal-inheritance-works)|\n| 191.|[Example of Prototypal Inheritance?](#q-example-of-prototypal-inheritance)|\n| 192.|[What do you think of AMD vs CommonJS?](#q-what-do-you-think-of-amd-vs-commonjs)|\n| 193.|[Explain why the following does not work as an IIFE: `function foo(){ }();`. What needs to be changed to properly make it an IIFE?](#q-explain-why-the-following-does-not-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife)|\n| 194.|[What is the difference between a variable that is: `null`, `undefined` or undeclared? How would you go about checking for any of these states?](#q-what-is-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states)|\n| 195.|[Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other?](#q-can-you-describe-the-main-difference-between-a-foreach-loop-and-a-map-loop-and-why-you-would-pick-one-versus-the-other)|\n| 196.|[What is a typical use case for anonymous functions?](#q-what-is-a-typical-use-case-for-anonymous-functions)|\n| 197.|[How do you organize your code? (module pattern, classical inheritance?)](#q-how-do-you-organize-your-code-module-pattern-classical-inheritance)|\n| 198.|[What is the difference between host objects and native objects?](#q-what-is-the-difference-between-host-objects-and-native-objects)|\n| 199.|[Difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`?](#q-difference-between-function-person-var-person-person-and-var-person-new-person)|\n| 200.|[What is the difference between `.call` and `.apply`?](#q-what-is-the-difference-between-call-and-apply)|\n| 201.|[Explain `Function.prototype.bind`?](#q-explain-functionprototypebind)|\n| 202.|[When would you use `document.write()`?](#q-when-would-you-use-documentwrite)|\n| 203.|[What is the difference between feature detection, feature inference, and using the UA string?](#q-what-is-the-difference-between-feature-detection-feature-inference-and-using-the-ua-string)|\n| 204.|[Explain Ajax in detail?](#q-explain-ajax-in-detail)|\n| 205.|[Explain how JSONP works (and how It is not really Ajax)](#q-explain-how-jsonp-works-and-how-it-s-not-really-ajax)|\n| 206.|[What is the difference between an \"attribute\" and a \"property\"?](#q-what-is-the-difference-between-an-attribute-and-a-property)|\n| 207.|[Why is extending built-in JavaScript objects not a good idea?](#q-why-is-extending-built-in-javascript-objects-not-a-good-idea)|\n| 208.|[Difference between document `load` event and document `DOMContentLoaded` event?](#q-difference-between-document-load-event-and-document-domcontentloaded-event)|\n| 209.|[What is the difference between `==` and `===`?](#q-what-is-the-difference-between-and)|\n| 210.|[Explain the same-origin policy with regards to JavaScript?](#q-explain-the-same-origin-policy-with-regards-to-javascript)|\n| 211.|[Why is it called a Ternary expression, what does the word \"Ternary\" indicate?](#q-why-is-it-called-a-ternary-expression-what-does-the-word-ternary-indicate)|\n| 212.|[What is `\"use strict\";`? What are the advantages and disadvantages to using it?](#q-what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it)|\n| 213.|[Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?](#q-why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it)|\n| 214.|[Why would you use something like the `load` event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?](#q-why-would-you-use-something-like-the-load-event-does-this-event-have-disadvantages-do-you-know-any-alternatives-and-why-would-you-use-those)|\n| 215.|[What is the extent of your experience with Promises and/or their polyfills?](#q-what-is-the-extent-of-your-experience-with-promises-and-or-their-polyfills)|\n| 216.|[What are the pros and cons of using Promises instead of callbacks?](#q-what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks)|\n| 217.|[What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#q-what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript)|\n| 218.|[What tools and techniues do you use for debugging JavaScript code?](#q-what-tools-and-techniues-do-you-use-for-debugging-javascript-code)|\n| 219.|[What language constructions do you use for iterating over object properties and array items?](#q-what-language-constructions-do-you-use-for-iterating-over-object-properties-and-array-items)|\n| 220.|[Explain the difference between mutable and immutable objects?](#q-explain-the-difference-between-mutable-and-immutable-objects)|\n| 221.|[What is an example of an immutable object in JavaScript?](#q-what-is-an-example-of-an-immutable-object-in-javascript)|\n| 222.|[How can you achieve immutability in your own code?](#q-how-can-you-achieve-immutability-in-your-own-code)|\n| 223.|[Explain the difference between synchronous and asynchronous functions?](#q-explain-the-difference-between-synchronous-and-asynchronous-functions)|\n| 224.|[What is event loop? What is the difference between call stack and task ueue?](#q-what-is-event-loop-what-is-the-difference-between-call-stack-and-task-ueue)|\n| 225.|[Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}`?](#q-explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function)|\n| 226.|[What are the differences between variables created using `let`, `var` or `const`?](#q-what-are-the-differences-between-variables-created-using-let-var-or-const)|\n| 227.|[What is the definition of a higher-order function?](#q-what-is-the-definition-of-a-higher-order-function)|\n| 228.|[Can you give an example of a curry function and why this syntax offers an advantage?](#q-can-you-give-an-example-of-a-curry-function-and-why-this-syntax-offers-an-advantage)|\n| 229.|[How can you share code between files?](#q-how-can-you-share-code-between-files)|\n| 230.|[Why you might want to create static class members?](#q-why-you-might-want-to-create-static-class-members)|\n| 231.|[What is the difference between `undefined` and `not defined` in JavaScript?](#q-what-is-the-difference-between-undefined-and-not-defined-in-javascript)|\n| 232.|[For which value of `x` the results of the following statements are not the same?](#q-for-which-value-of-x-the-results-of-the-following-statements-are-not-the-same)|\n| 233.|[What is the drawback of declaring methods directly in JavaScript objects?](#q-what-is-the-drawback-of-declaring-methods-directly-in-javascript-objects)|\n| 234.|[What is “closure” in javascript? Can you provide an example?](#q-what-is-closure-in-javascript-can-you-provide-an-example)|\n| 235.|[Write a mul function which will work properly when invoked with following syntax?](#q-write-a-mul-function-which-will-work-properly-when-invoked-with-following-syntax)|\n| 236.|[How to empty an array in JavaScript?](#q-how-to-empty-an-array-in-javascript)|\n| 237.|[How to check if an object is an array or not?](#q-how-to-check-if-an-object-is-an-array-or-not)|\n| 238.|[What is `undefined x 1` in JavaScript?](#q-what-is-undefined-x-1-in-javascript)|\n| 239.|[What is the difference between declaring a function in the formats listed below?](#q-what-is-the-difference-between-declaring-a-function-in-the-formats-listed-below)|\n| 240.|[In which case the function definition is not hoisted in JavaScript?](#q-in-which-case-the-function-definition-is-not-hoisted-in-javascript)|\n| 241.|[What’s the difference between `typeof` and `instanceof`?](#q-what-s-the-difference-between-typeof-and-instanceof)|\n| 242.|[Calculate the length of the associative array?](#q-calculate-the-length-of-the-associative-array)|\n| 243.|[Difference between `Function`, `Method` and `Constructor` calls in JavaScript?](#q-difference-between-function-method-and-constructor-calls-in-javascript)|\n| 244.|[What are Service Workers and when can you use them?](#q-what-are-service-workers-and-when-can-you-use-them)|\n| 245.|[What is the difference between a method and a function in javascript?](#q-what-is-the-difference-between-a-method-and-a-function-in-javascript)|\n| 246.|[What is IIFE (Immediately Invoked Function Expression) and how it can be useful?](#q-what-is-iife-immediately-invoked-function-expression-and-how-it-can-be-useful)|\n| 247.|[Describe Singleton Pattern In JavaScript?](#q-describe-singleton-pattern-in-javascript)|\n| 248.|[Singleton Design Pattern Implementation?](#q-singleton-design-pattern-implementation)|\n| 249.|[Write a function called deepClone which takes an object and creates a object copy of it?](#q-write-a-function-called-deepclone-which-takes-an-object-and-creates-a-object-copy-of-it)|\n| 250.|[Best way to detect `undefined` object property in JavaScript?](#q-best-way-to-detect-undefined-object-property-in-javascript)|\n| 251.|[Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object?](#q-write-a-function-called-clone-which-takes-an-object-and-creates-a-object-copy-of-it-but-not-copy-deep-property-of-object)|\n| 252.|[What are promises and how they are useful?](#q-what-are-promises-and-how-they-are-useful)|\n| 253.|[How to check whether a key exist in a JavaScript object or not?](#q-how-to-check-whether-a-key-exist-in-a-javascript-object-or-not)|\n| 254.|[What is NaN, why do we need it, and when can it break the page?](#q-what-is-nan-why-do-we-need-it-and-when-can-it-break-the-page)|\n| 255.|[How to check if the value of a variable in an array?](#q-how-to-check-if-the-value-of-a-variable-in-an-array)|\n| 256.|[Best way to detect reference values of any type in JavaScript?](#q-best-way-to-detect-reference-values-of-any-type-in-javascript)|\n| 257.|[How does Object.create method works JavaScript?](#q-how-does-objectcreate-method-works-javascript)|\n| 258.|[How to use constructor functions for inheritance in JavaScript?](#q-how-to-use-constructor-functions-for-inheritance-in-javascript)|\n| 259.|[How we can prevent modification of object in JavaScript?](#q-how-we-can-prevent-modification-of-object-in-javascript)|\n| 260.|[Write a log function which will add prefix `(your message)` to every message you log using console.log ?](#q-write-a-log-function-which-will-add-prefix-your-message-to-every-message-you-log-using-consolelog)|\n| 261.|[Write a function which will test string as a literal and as an object ?](#q-write-a-function-which-will-test-string-as-a-literal-and-as-an-object)|\n| 262.|[What is typical use case for anonymous function in JavaScript?](#q-what-is-typical-use-case-for-anonymous-function-in-javascript)|\n| 263.|[How to set a default parameter value?](#q-how-to-set-a-default-parameter-value)|\n| 264.|[Write code for merge two JavaScript Object dynamically?](#q-write-code-for-merge-two-javascript-object-dynamically)|\n| 265.|[What is non-enumerable property in JavaScript and how you can create one?](#q-what-is-non-enumerable-property-in-javascript-and-how-you-can-create-one)|\n| 266.|[What is Function binding ?](#q-what-is-function-binding)|\n| 267.|[Explain event delegation?](#q-explain-event-delegation)|\n| 268.|[Explain how `this` works in JavaScript?](#q-explain-how-this-works-in-javascript)|\n| 269.|[Explain how prototypal inheritance works?](#q-explain-how-prototypal-inheritance-works)|\n| 270.|[What do you think of AMD vs CommonJS?](#q-what-do-you-think-of-amd-vs-commonjs)|\n| 274.|[Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other?](#q-can-you-describe-the-main-difference-between-a-foreach-loop-and-a-map-loop-and-why-you-would-pick-one-versus-the-other)|\n| 283.|[Have you ever used JavaScript templating? If so, what libraries have you used?](#q-have-you-ever-used-javascript-templating-if-so-what-libraries-have-you-used)|\n| 285.|[What is the difference between an \"attribute\" and a \"property\"?](#q-what-is-the-difference-between-an-attribute-and-a-property)|\n| 287.|[Difference between document `load` event and document `DOMContentLoaded` event?](#q-difference-between-document-load-event-and-document-domcontentloaded-event)\n| 289.|[What is JSON and its common operations?](#q-what-is-json-and-its-common-operations)|\n| 290.|[What is the purpose of array slice method?](#q-what-is-the-purpose-of-array-slice-method)|\n| 291.|[What is the purpose of array splice method?](#q-what-is-the-purpose-of-array-splice-method)|\n| 292.|[What is the difference between slice and splice?](#q-what-is-the-difference-between-slice-and-splice)|\n| 293.|[How do you compare Object and Map?](#q-how-do-you-compare-object-and-map)|\n| 294.|[How do you redeclare variables in switch block without an error?](#q-how-do-you-redeclare-variables-in-switch-block-without-an-error)|\n| 295.|[How to create and trigger events in javascript?](#q-how-to-create-and-trigger-events-in-javascript)|\n| 296.|[What is difference between window.frames window.parent and window.top in JavaScript?](#q-what-is-difference-between-windowframes-windowparent-and-windowtop-in-javascript)|\n| 297.|[In JavaScript, what is the difference between var x = 1 and x = 1?](#q-in-javascript-what-is-the-difference-between-var-x-1-and-x-1)|\n| 298.|[What is Associative Array? How do we use it?](#q-what-is-associative-array-how-do-we-use-it)|\n| 299.|[What is difference between Classic Inheritance and Prototypical Inheritance?](#q-what-is-difference-between-classic-inheritance-and-prototypical-inheritance)|\n| 300.|[What is difference between private variable, public variable and static variable? How we achieve this in JS?](#q-what-is-difference-between-private-variable-public-variable-and-static-variable-how-we-achieve-this-in-js)|\n| 301.|[How to add and remove properties to object in runtime?](#q-how-to-add-and-remove-properties-to-object-in-runtime)|\n| 302.|[How to extend built-in objects?](#q-how-to-extend-built-in-objects)|\n| 303.|[Why extending array is bad idea?](#q-why-extending-array-is-bad-idea)|\n| 304.|[What is difference between browser detection and feature detection?](#q-what-is-difference-between-browser-detection-and-feature-detection)|\n| 305.|[What is difference between Graceful Degradation and Progressive Enhancement?](#q-what-is-difference-between-graceful-degradation-and-progressive-enhancement)|\n| 306.|[In JavaScript, why is the “this” operator inconsistent?](#q-in-javascript-why-is-the-this-operator-inconsistent)|\n| 307.|[What unit testing framework do you use? and why?](#q-what-unit-testing-framework-do-you-use-and-why)|\n| 308.|[Explain the difference between Object.freeze() vs const?](#q-explain-the-difference-between-objectfreeze-vs-const)|\n| 309.|[What is generator in JS?](#q-what-is-generator-in-js)|\n| 310.|[Describe the Revealing Module Pattern in javascript?](#q-describe-the-revealing-module-pattern-in-javascript)|\n| 311.|[Compare Async-Await and Generators usage to achive same functionality?](#q-compare-async-await-and-generators-usage-to-achive-same-functionality)|\n| 312.|[Explain escape() and unescape() functions?](#q-explain-escape-and-unescape-functions)|\n| 313.|[What do you understand by Screen objects?](#q-what-do-you-understand-by-screen-objects)|\n| 314.|[How will you remove duplicates from an array in JavaScript?](#q-how-will-you-remove-duplicates-from-an-array-in-javascript)|\n| 315.|[Explain NEGATIVE_INFINITY in JavaScript?](#q-explain-negative-infinity-in-javascript)|\n| 316.|[What do you understand by ViewState and SessionState?](#q-what-do-you-understand-by-viewstate-and-sessionstate)|\n| 317.|[Explain var self = this in JavaScript?](#q-explain-var-self-this-in-javascript)|\n| 318.|[What is difference between append() vs appendChild()?](#q-what-is-difference-between-append-vs-appendchild)|\n| 319.|[What is difference between null vs undefined?](#q-what-is-difference-between-null-vs-undefined)|\n| 320.|[What is difference between array[] vs object()?](#q-what-is-difference-between-array-vs-object)|\n| 321.|[What is difference between async() or defer() keyword in JavaScript?](#q-what-is-difference-between-async-or-defer-keyword-in-javascript)|\n| 322.|[What is difference between async() and await() in ajax?](#q-what-is-difference-between-async-and-await-in-ajax)|\n| 323.|[What is reuest header in javascript?](#q-what-is-reuest-header-in-javascript)|\n| 324.|[What is rendering in JavaScript?](#q-what-is-rendering-in-javascript)|\n| 325.|[Define the various types of errors which occur in JavaScript programming language?](#q-define-the-various-types-of-errors-which-occur-in-javascript-programming-language)|\n| 326.|[What is unshift() method in JavaScript?](#q-what-is-unshift-method-in-javascript)|\n| 327.|[What is the difference between HTMLCollection and NodeList?](#q-what-is-the-difference-between-htmlcollection-and-nodelist)|\n| 328.|[What is the difference between firstChild and firstElementChild?](#q-what-is-the-difference-between-firstchild-and-firstelementchild)|\n| 329.|[Name the two functions that are used to create an HTML element dynamically?](#q-name-the-two-functions-that-are-used-to-create-an-html-element-dynamically)|\n| 330.|[What is callback() function in javascript?](#q-what-is-callback-function-in-javascript)|\n| 331.|[What is shallow copy and deep copy in javascript?](#q-what-is-shallow-copy-and-deep-copy-in-javascript)|\n| 332.|[What is difference between stoppropagation vs stopimmediatepropagation vs preventdefault in javascript?](#q-what-is-difference-between-stoppropagation-vs-stopimmediatepropagation-vs-preventdefault-in-javascript)|\n| 333.|[Explain array methods [ join(), pop(), push(), shift(), unshift(), concat(), map(), filter(), reduce(), reduceRight(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex(), includes() ]](#q-explain-array-methods-join-pop-push-shift-unshift-concat-map-filter-reduce-reduceright-every-some-indexof-lastindexof-find-findindex-includes)|\n| 334.|[When to use function declarations and expressions in JavaScript?](#q-when-to-use-function-declarations-and-expressions-in-javascript)|\n| 335.|[How to avoid callback hell in javascript?](#q-how-to-avoid-callback-hell-in-javascript)|\n| 336.|[Why is eval() considered evil and dangerous?](#q-why-is-eval-considered-evil-and-dangerous)|\n| 337.|[What is the difference between encryption and hashing?](#q-what-is-the-difference-between-encryption-and-hashing)|\n| 338.|[What is Proxies and Reflection in JavaScript?](#q-what-is-proxies-and-reflection-in-javascript)|\n| 339.|[How do you check whether an object can be extendable or not?](#q-how-do-you-check-whether-an-object-can-be-extendable-or-not)|\n| 340.|[What are the different ways to make an object non-extensible?](#q-what-are-the-different-ways-to-make-an-object-non-extensible)|\n| 341.|[Is enums feature available in javascript?](#q-is-enums-feature-available-in-javascript)|\n| 342.|[How do I modify the url without reloading the page?](#q-how-do-i-modify-the-url-without-reloading-the-page)|\n| 343.|[What is throttling and debouncing in javascript?](#q-what-is-throttling-and-debouncing-in-javascript)|\n| 344.|[How to validate JSON Object in javascript?](#q-how-to-validate-json-object-in-javascript)|\n| 345.|[How to check if page is fully loaded using javascript?](#q-how-to-check-if-page-is-fully-loaded-using-javascript)|\n| 346.|[Explain browser console logs features?](#q-explain-browser-console-logs-features)|\n| 347.|[What are the difference between console.log() and console.dir()?](#q-what-are-the-difference-between-consolelog-and-consoledir)|\n| 348.|[How to Copy Text to Clipboard?](#q-how-to-copy-text-to-clipboard)|\n| 349.|[Explain types of Memory Leaks in JavaScript?](#q-explain-types-of-memory-leaks-in-javascript)|\n| 350.|[How accidental closures might cause memory leaks in IE?](#q-how-accidental-closures-might-cause-memory-leaks-in-ie)|\n| 351.|[How to convert Decimal to Binary in JavaScript?](#q-how-to-convert-decimal-to-binary-in-javascript)|\n\n\u003cbr/\u003e\n\n## Q. ***What is difference between document.getElementById() and document.querySelector()?***\n\n* **document.getElementById()**\n\nReturns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.\n\n```javascript\nelement = document.getElementById(id);\n```\n\n* **document.querySelector()**\n\nReturns the first matching Element node within the node\\'s subtree. If no matching node is found, null is returned.\n\n```javascript\nelement = document.querySelector(selectors);\n```\n\n* **document.querySelectorAll()**\n\nReturns a NodeList containing all matching Element nodes within the node\\'s subtree, or an empty NodeList if no matches are found.\n\n```javascript\nelement = document.querySelectorAll(selectors);\n```\n\n*Note: `querySelector()` is more useful when we want to use more complex selectors*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***When to use reduce(), map(), foreach() and filter() in JavaScript?***\n\n* **forEach()**  \n\nIt takes a callback function and run that callback function on each element of array one by one.\n\nBasically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them.\n\n```javascript\nvar arr = [10, 20, 30];\n\narr.forEach(function (elem, index){\n   console.log(elem + ' comes at ' + index);\n})\n```\nOutput\n```\n10 comes at 0\n20 comes at 1\n30 comes at 2\n```\n\n* **filter()** \n\nThe main difference between forEach() and filter() is that forEach just loop over the array and executes the callback but filter executes the callback and check its return value. If the value is true element remains in the resulting array but if the return value is false the element will be removed for the resulting array.\n\n*Note: filter does not update the existing array it will return a new filtered array every time*.\n\n```javascript\nvar arr = [10, 20, 30]; \n\nvar result = arr.filter(function(elem){\n    return elem !== 20;\n})\nconsole.log(result)\n```\nOutput\n```\n[10, 30]\n```\n\n* **map()**\n\nmap() like filter() \u0026 forEach() takes a callback and run it against every element on the array but whats makes it unique is it generate a new array based on your existing array.\n\nLike filter(), map() also returns an array. The provided callback to map modifies the array elements and save them into the new array upon completion that array get returned as the mapped array.\n\n```javascript\nvar arr = [10, 20, 30];\n\nvar mapped = arr.map(function(elem) {\n    return elem * 10;\n});\nconsole.log(mapped)\n```\nOutput\n```\n[100, 200, 300]\n```\n\n* **reduce()** \n\nreduce() method of the array object is used to reduce the array to one single value.\n\n```javascript\nvar arr = [10, 20, 30];\n\nvar sum = arr.reduce(function(sum, elem) {\n    return sum + elem;\n});\nconsole.log(sum); // Output: 60\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is Hoisting in JavaScript?***\n\nHoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.\n\n**Example 01:** Variable Hoisting  \n\n```javascript\nconsole.log(message); // output : undefined\nvar message = \"The variable Has been hoisted\";\n```\nThe above code looks like as below to the interpreter,\n\n```javascript\nvar message;\nconsole.log(message);\nmessage = \"The variable Has been hoisted\";\n```\n**Example 02:** Function Hoisting\n\n```javascript\nfunction hoist() {\n  a = 20;\n  var b = 100;\n}\n\nhoist();\n\nconsole.log(a);\n/* \nAccessible as a global variable outside hoist() function\nOutput: 20\n*/\n\nconsole.log(b);\n/*\nSince it was declared, it is confined to the hoist() function scope.\nWe can't print it out outside the confines of the hoist() function.\nOutput: ReferenceError: b is not defined\n*/\n```\n\nAll declarations (function, var, let, const and class) are hoisted in JavaScript, while the `var` declarations are initialized with `undefined`, but `let` and `const` declarations remain uninitialized.\n\n```javascript\nconsole.log(a);\nlet a = 3;\n\n// Output: ReferenceError: a is not defined\n```\nThey will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means we can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call **Temporal Dead Zone**, A time span between variable creation and its initialization where they can’t be accessed.\n\n*Note: JavaScript only hoists declarations, not initialisation*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are closures?***\n\nA closure is the combination of a function and the 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. The closure has three scope chains\n\n* Own scope where variables defined between its curly brackets\n* Outer function’s variables\n* Global variables\n\n```javascript\nfunction Welcome(name) {\n  var greetingInfo = function(message) {\n    console.log(message+' '+name);\n  }\n  return greetingInfo;\n}\nvar myFunction = Welcome('John');\nmyFunction('Welcome '); // Output: Welcome John\nmyFunction('Hello Mr.'); // output: Hello Mr.John\n```\n\nAs per the above code, the inner `function greetingInfo()` has access to the variables in the outer `function Welcome()` even after outer function has returned.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you clone an object in JavaScript?***\n\nUsing the object spread operator `...`, the object own enumerable properties can be copied into the new object. This creates a shallow clone of the object.\n\n```javascript\nconst obj = { a: 1, b: 2 }\nconst shallowClone = { ...obj }\n```\n\nWith this technique, prototypes are ignored. In addition, nested objects are not cloned, but rather their references get copied, so nested objects still refer to the same objects as the original. Deep-cloning is much more complex in order to effectively clone any type of object (Date, RegExp, Function, Set, etc) that may be nested within the object.\n\nOther alternatives include:\n\n* **JSON.parse(JSON.stringify(obj))** can be used to deep-clone a simple object, but it is CPU-intensive and only accepts valid JSON (therefore it strips functions and does not allow circular references).\n* **Object.assign({}, obj)** is another alternative.\n* **Object.keys(obj).reduce((acc, key) =\u003e (acc[key] = obj[key], acc), {})** is another more verbose alternative that shows the concept in greater depth.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the possible ways to create objects in JavaScript?***\n\n**a.) Object constructor**: The simpliest way to create an empty object is using Object constructor. Currently this approach is not recommended.\n\n```javascript\n var object = new Object();\n```\n\n**b.) Object create method**: The create method of Object creates a new object by passing the prototype object as a parameter\n\n```javascript\n var object = Object.create(null);\n```\n\n**c.) Object literal syntax**: The object literal syntax is equivalent to create method when it passes null as parameter\n\n```javascript\n var object = {};\n```\n\n**d.) Function constructor**: Create any function and apply the new operator to create object instances,\n\n```javascript\n function Person(name) {\n  var object = {};\n  object.name = name;\n  object.age = 26;\n  return object;\n }\n var object = new Person(\"Alex\");\n```\n\n**e.) Function constructor with prototype**: This is similar to function constructor but it uses prototype for their properties and methods,\n\n```javascript\nfunction Person(){}\nPerson.prototype.name = \"Alex\";\nvar object = new Person();\n```\n\nThis is equivalent to an instance created with an object create method with a function prototype and then call that function with an instance and parameters as arguments.\n\n```javascript\nfunction func {};\n\nnew func(x, y, z);\n\n// **(OR)**\n\n// Create a new instance using function prototype.\nvar newInstance = Object.create(func.prototype)\n\n// Call the function\nvar result = func.call(newInstance, x, y, z),\n\n// If the result is a non-null object then use it otherwise just use the new instance.\nconsole.log(result \u0026\u0026 typeof result === 'object' ? result : newInstance);\n```\n\n**f.) ES6 Class syntax**: ES6 introduces class feature to create the objects\n\n```javascript\nclass Person {\n constructor(name) {\n    this.name = name;\n }\n}\n\nvar object = new Person(\"Alex\");\n```\n\n**g.) Singleton pattern**: A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance and this way one can ensure that they don't accidentally create multiple instances.\n\n```javascript\nvar object = new function() {\n  this.name = \"Alex\";\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the javascript data types?***\n\nBelow are the list of javascript data types available\n1. Number\n2. String\n3. Boolean\n4. Object\n5. Undefined\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are global variables?***\n\nGlobal 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\n\n```javascript\nmsg = \"Hello\" // var is missing, it becomes global variable\n```\n\nThe 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is variable shadowing in javascript?***\n\nVariable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.\n\nIf there is a variable in the global scope, and you'd like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope.\n\n```javascript\nvar val = 10;\n\nfunction Hoist(val) {\n    alert(val);\n}\n\nHoist(20);\n```\n\nOutput\n```\n20\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an event flow?***\n\nEvent 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 each of its parent elements first, starting at the top with the global window object.\n\nThere are two ways of event flow\n* Top to Bottom(Event Capturing)\n* Bottom to Top (Event Bubbling)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is event bubbling?***\n\nEvent 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.\n\nExample: If you click on EM, the handler on DIV runs.  \n\n```html\n\u003cdiv onclick=\"alert('The handler!')\"\u003e\n  \u003cem\u003eIf you click on \u003ccode\u003eEM\u003c/code\u003e, the handler on \u003ccode\u003eDIV\u003c/code\u003e runs.\u003c/em\u003e\n\u003c/div\u003e\n```\n\n* **Stopping bubbling**  \n\n```html\n\n\u003cbody onclick=\"alert(`the bubbling doesn\\'t reach here`)\"\u003e\n  \u003cbutton onclick=\"event.stopPropagation()\"\u003eClick me\u003c/button\u003e\n\u003c/body\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is event capturing?***\n\nEvent 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 inner DOM element.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is prototype chain?***\n\nNearly all objects in JavaScript are instances of **Object**. That means all the objects in JavaScript inherit the properties and methods from **Object.prototype**. This is called **Prototype chaining**.\n\n**Prototype chaining** is used to build new types of objects based on existing ones. It is similar to inheritance in a class based language. The prototype on object instance is available through `Object.getPrototypeOf(object)` or `__proto__` property whereas prototype on constructors function is available through **Object.prototype**.\n\n```javascript\nfunction Person(firstName, lastName, age) {\n  this.firstName = firstName;\n  this.lastName = lastName;\n  this.age = age;\n}\n//Person class created\nPerson.prototype.getFullName = function() {\n  return this.firstName + \" \" + this.lastName;\n}\n\n// we have added getFullName method in Person’s prototype.\nvar person = new Person(\"John\", \"K\", 25);\n// It will create an instance of the Person class\n\u003e person.hasOwnProperty(\"firstName\");  // true\n\u003e person.hasOwnProperty(\"getFullName\");  // false\n\u003e person.getFullName(); // John K\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between Call, Apply and Bind?***\n\n**a.) call()**\n\nThe call() method invokes a function with a given `this` value and arguments provided one by one\n\n```javascript\nvar employee1 = {firstName: 'John', lastName: 'Rodson'};\nvar employee2 = {firstName: 'Jimmy', lastName: 'Baily'};\n\nfunction invite(greeting1, greeting2) {\n    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);\n}\n\ninvite.call(employee1, 'Hello', 'How are you?'); // Hello John Rodson, How are you?\ninvite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you?\n```\n**b.) apply()** \n\nInvokes the function and allows you to pass in arguments as an array\n\n```javascript\nvar employee1 = {firstName: 'John', lastName: 'Rodson'};\nvar employee2 = {firstName: 'Jimmy', lastName: 'Baily'};\n\nfunction invite(greeting1, greeting2) {\n    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);\n}\n\ninvite.apply(employee1, ['Hello', 'How are you?']); // Hello John Rodson, How are you?\ninvite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you?\n```\n\n**c.) bind()**\n\nreturns a new function, allowing you to pass in an array and any number of arguments\n\n```javascript\nvar employee1 = {firstName: 'John', lastName: 'Rodson'};\nvar employee2 = {firstName: 'Jimmy', lastName: 'Baily'};\n\nfunction invite(greeting1, greeting2) {\n    console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2);\n}\n\nvar inviteEmployee1 = invite.bind(employee1);\nvar inviteEmployee2 = invite.bind(employee2);\ninviteEmployee1('Hello', 'How are you?'); // Hello John Rodson, How are you?\ninviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you?\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between == and === operators?***\n\nJavaScript provides both strict(===, !==) and type-converting(==, !=) equality comparison. The strict operators takes 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,\n1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.\n2. Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value.\n   There are two special cases in this,\n   1. NaN is not equal to anything, including NaN.\n   2. Positive and negative zeros are equal to one another.\n3. Two Boolean operands are strictly equal if both are true or both are false.\n4. Two objects are strictly equal if they refer to the same Object.\n5. Null and Undefined types are not equal with ===, but equal with ==. i.e,\n    null===undefined --\u003e false but null==undefined --\u003e true\n\n**Examples**\n\n```javascript\n0 == false   // true\n0 === false  // false\n1 == \"1\"     // true\n1 === \"1\"    // false\nnull == undefined // true\nnull === undefined // false\n'0' == false // true\n'0' === false // false\n[]==[] or []===[] //false, refer different objects in memory\n{}=={} or {}==={} //false, refer different objects in memory\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a first class function?***\n\nJavaScript functions are first-class functions meaning functions and objects are treated as the same thing. Functions can be stored as a variable inside an object or an array as well as it can be passed as an argument or be returned by another function. That makes function \"first-class citizens in JavaScript\"\n\n**Example:** Assign a function to a variable\n\n```javascript\nconst message = function() {\n   console.log(\"Hello World!\");\n}\n\nmessage(); // Invoke it using the variable\n```\n\n**Example:** Pass a function as an Argument\n\n```javascript\nfunction sayHello() {\n   return \"Hello, \";\n}\nfunction greeting(helloMessage, name) {\n  console.log(helloMessage() + name);\n}\n// Pass `sayHello` as an argument to `greeting` function\ngreeting(sayHello, \"JavaScript!\");\n```\n\n**Example:** Return a function\n\n```javascript\nfunction sayHello() {\n   return function() {\n      console.log(\"Hello!\");\n   }\n}\n```\n\n**Example:** Using a variable\n\n```javascript\nconst sayHello = function() {\n   return function() {\n      console.log(\"Hello!\");\n   }\n}\nconst myFunc = sayHello();\nmyFunc();\n```\n\n**Example:** Using double parentheses\n\n```javascript\nfunction sayHello() {\n   return function() {\n      console.log(\"Hello!\");\n   }\n}\nsayHello()();\n```\nWe are using double parentheses `()()` to invoke the returned function as well.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a higher order function?***\n\nA Higher-Order function is a function that receives a function as an argument or returns the function as output.\n\nFor example, `Array.prototype.map()`, `Array.prototype.filter()` and `Array.prototype.reduce()` are some of the Higher-Order functions in javascript.\n\n```javascript\nconst arr1 = [1, 2, 3];\nconst arr2 = arr1.map(function(item) {\n  return item * 2;\n});\nconsole.log(arr2);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a unary function?***\n\nUnary function (i.e. monadic) is a function that accepts exactly one argument. Let us take an example of unary function. It stands for single argument accepted by a function.\n\n```javascript\nconst unaryFunction = a =\u003e console.log (a + 10); //Add 10 to the given argument and display the value\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is currying function?***\n\nCurrying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.\n\n```javascript\nfunction volume(length) {\n  return function(width) {\n    return function(height) {\n      return height * width * length;\n    }\n  }\n}\n\nvolume(2)(3)(4); // 24\n```\nCurried functions are great to improve code re-usability and functional composition.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a pure function?***\n\nPure functions are functions that accept an input and returns a value without modifying any data outside its scope(Side Effects). Its output or return value must depend on the input/arguments and pure functions must return a value.\n\n**Example**\n\n```javascript\nfunction impure(arg) {\n    finalR.s = 90\n    return arg * finalR.s\n}\n```\nThe above function is not a pure function because it modified a state `finalR.s` outside its scope.\n\n```javascript\nfunction pure(arg) {\n    return arg * 4\n}\n```\nHere is a pure function. It didn’t side effect any external state and it returns an output based on the input.\n\nA function must pass two tests to be considered “pure”:\n\n1. Same inputs always return same outputs\n1. No side-effects\n\n**1. Same Input =\u003e Same Output**  \nCompare this:\n\n```javascript\nconst add = (x, y) =\u003e x + y;\n\nadd(2, 4); // 6\n```\nTo this\n\n```javascript\nlet x = 2;\n\nconst add = (y) =\u003e {\n  x += y;\n};\n\nadd(4); // x === 6 (the first time)\n```\n**2. Pure Functions = Consistent Results**  \nThe first example returns a value based on the given parameters, regardless of where/when you call it.\n\nIf you pass 2 and 4, you’ll always get 6.\n\nNothing else affects the output.\n\n**Benefits**  \n* One of the major benefits of using pure functions is they are immediately testable. They will always produce the same result if you pass in the same arguments.\n* The pure functions are easier to parallelize\n* They also makes maintaining and refactoring code much easier.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is memoization in JavaScript?***\n\nMemoization is a 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.\n\n```javascript\n// A simple memoized function to Add Number\nconst memoizedAdd = () =\u003e {\n  let cache = {};\n  return (number) =\u003e {\n    if (number in cache) {\n      console.log('Fetching from cache: ');\n      return cache[number];\n    }\n    else {\n      console.log('Calculating result: ');\n      let result = number + 10;\n      cache[number] = result;\n      return result;\n    }\n  }\n}\n// returned function from memoizedAdd\nconst sum = memoizedAdd();\nconsole.log(sum(10)); // Calculating result: 20\nconsole.log(sum(10)); // Fetching from cache: 20\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a service worker?***\n\nA Service worker is basically a JavaScript file that runs in background, separate from a web page and provide features that don't need a web page or user interaction. \n\nSome of the major features of service workers are \n* Offline first web application development\n* Periodic background syncs, push notifications\n* Intercept and handle network requests\n* Programmatically managing a cache of responses\n\n**Lifecycle of a Service Worker**\n\nIt consists of the following phases:\n* Download\n* Installation\n* Activation\n\n**Registering a Service Worker**\n\nTo register a service worker we first check if the browser supports it and then register it.\n\n```javascript\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker.register('/ServiceWorker.js')\n  .then(function(response) {\n\n    // Service worker registration done\n    console.log('Registration Successful', response);\n  }, function(error) {\n    // Service worker registration failed\n    console.log('Registration Failed', error);\n  }\n```\n\n**Installation of service worker**\n\nAfter the controlled page that takes care of the registration process, we come to the service worker script that handles the installation part.\n\nBasically, you will need to define a callback for the install event and then decide on the files that you wish to cache. Inside a callback, one needs to take of the following three points –\n\n* Open a cache\n* Cache the files\n* Seek confirmation for the required caches and whether they have been successful.\n\n```javascript\nvar CACHENAME = 'My site cache'; \nvar urlstocache = [ \n\t'/', \n  '/styles/main1.css', \n\t'/script/main1.js' \n]; \nself.addEventListener('install', function(event) { \n\t// Performing installation steps \n\tevent.waitUntil( \n\t\tcaches.open(CACHENAME) \n\t\t.then(function(cache) { \n\t\t\tconsole.log('Opening of cache'); \n\t\t\treturn cache.addAll(urlstocache);\n\t\t}) \n);\n```\n\n**Cache and return requests**\n\nAfter a service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events, an example of which is below.\n\n```javascript\nself.addEventListener('fetch', function(event) {\n  event.respondWith(\n    caches.match(event.request)\n      .then(function(response) {\n        // Cache hit - return response\n        if (response) {\n          return response;\n        }\n        return fetch(event.request);\n      }\n    )\n  );\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you manipulate DOM using service worker?***\n\nService worker can\\'t access the DOM directly. But it can communicate with the pages it controls by responding to messages sent via the `postMessage` interface, and those pages can manipulate the DOM.\n\n**Example:** service-worker.html\n```html\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n\u003cmeta charset=\"UTF-8\"\u003e\n\u003ctitle\u003eService Worker\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n(Look in the console.)\n\u003cscript\u003e\n(function() {\n    \"use strict\";\n\n    if (!navigator.serviceWorker || !navigator.serviceWorker.register) {\n        console.log(\"This browser doesn't support service workers\");\n        return;\n    }\n\n    // Listen to messages from service workers.\n    navigator.serviceWorker.addEventListener('message', function(event) {\n        console.log(\"Got reply from service worker: \" + event.data);\n    });\n\n    // Are we being controlled?\n    if (navigator.serviceWorker.controller) {\n        // Yes, send our controller a message.\n        console.log(\"Sending 'hi' to controller\");\n        navigator.serviceWorker.controller.postMessage(\"hi\");\n    } else {\n        // No, register a service worker to control pages like us.\n        // Note that it won't control this instance of this page, it only takes effect\n        // for pages in its scope loaded *after* It is installed.\n        navigator.serviceWorker.register(\"service-worker.js\")\n            .then(function(registration) {\n                console.log(\"Service worker registered, scope: \" + registration.scope);\n                console.log(\"Refresh the page to talk to it.\");\n                // If we want to, we might do `location.reload();` so that we'd be controlled by it\n            })\n            .catch(function(error) {\n                console.log(\"Service worker registration failed: \" + error.message);\n            });\n    }\n})();\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n**service-worker.js** \n\n```javascript\nself.addEventListener(\"message\", function(event) {\n    //event.source.postMessage(\"Responding to \" + event.data);\n    self.clients.matchAll().then(all =\u003e all.forEach(client =\u003e {\n        client.postMessage(\"Responding to \" + event.data);\n    }));\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you reuse information across service worker restarts?***\n\nThe problem with service worker is that it get terminated when not in use, and restarted when it is next needed, so you cannot rely on global state within a service worker `onfetch` and `onmessage` handlers. In this case, service workers will have access to IndexedDB API in order to persist and reuse across restarts.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a post message?***\n\nPost 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).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a web-storage event and its event handler?***\n\nThe 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.\nThe syntax would be as below\n\n```javascript\n  window.onstorage = functionRef;\n```\n\nLet us take the example usage of onstorage event handler which logs the storage key and its values\n\n```javascript\nif (typeof(Storage) !== \"undefined\") {\n  window.onstorage = function(e) {\n    console.log('The ' + e.key +\n      ' key has been changed from ' + e.oldValue +\n      ' to ' + e.newValue + '.');\n  };\n} else {\n  // Browser doesnot support web-storage \n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to use Web Workers in javascript?***\n\n**Step 01: Create a Web Workers file**: Write a script to increment the count value.\n\n```javascript\n// counter.js\nlet i = 0;\n\nfunction timedCount() {\n  i = i + 1;\n  postMessage(i);\n  setTimeout(\"timedCount()\",500);\n}\n\ntimedCount();\n```\n\nHere `postMessage()` method is used to post a message back to the HTML page.  \n\n**Step 02: Create a Web Worker Object**: Create a web worker object by checking for browser support.\n\n```javascript\nif (typeof(w) == \"undefined\") {\n  w = new Worker(\"counter.js\");\n}\n```\nand we can receive messages from web workers\n\n```javascript\nw.onmessage = function(event){\n  document.getElementById(\"message\").innerHTML = event.data;\n};\n```\n**Step 03: Terminate a Web Workers**: Web workers will continue to listen for messages (even after the external script is finished) until it is terminated. You can use terminate() method to terminate listening the messages.\n\n```javascript\nw.terminate();\n```\n\n**Step 04: Reuse the Web Workers**: If you set the worker variable to undefined you can reuse the code\n\n```javascript\nw = undefined;\n```\n\nExample:\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003cbody\u003e\n  \u003cp\u003eCount numbers: \u003coutput id=\"result\"\u003e\u003c/output\u003e\u003c/p\u003e\n  \u003cbutton onclick=\"startWorker()\"\u003eStart\u003c/button\u003e\n  \u003cbutton onclick=\"stopWorker()\"\u003eStop\u003c/button\u003e\n  \n  \u003cscript\u003e\n    var w;\n\n    function startWorker() {\n      if (typeof(Worker) !== \"undefined\") {\n        if (typeof(w) == \"undefined\") {\n          w = new Worker(\"counter.js\");\n        }\n        w.onmessage = function(event) {\n          document.getElementById(\"result\").innerHTML = event.data;\n        };\n      } else {\n        document.getElementById(\"result\").innerHTML = \"Sorry! No Web Worker support.\";\n      }\n    }\n\n    function stopWorker() {\n      w.terminate();\n      w = undefined;\n    }\n  \u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the restrictions of web workers on DOM?***\n\nWebWorkers do not have access to below javascript objects since they are defined in an external files\n1. Window object\n2. Document object\n3. Parent object\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a promise?***\n\nA 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.\nSyntax\n\n```javascript\nconst promise = new Promise(function(resolve, reject) {\n  // promise description\n})\n```\n\nPromises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code.\n\nPromises have three states:\n1. **Pending:** This is an initial state of the Promise before an operation begins\n2. **Fulfilled:** This state indicates that specified operation was completed.\n3. **Rejected:** This state indicates that the operation did not complete. In this case an error value will be thrown.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a callback function?***\n\nA callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action.\n\n```javascript\nfunction callbackFunction(name) {\n  console.log('Hello ' + name);\n}\n\nfunction outerFunction(callback) {\n  let name = prompt('Please enter your name.');\n  callback(name);\n}\n\nouterFunction(callbackFunction);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why do we need callbacks?***\n\nThe callbacks are needed because javascript is a event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events.\n\nLet us take an example with first function invoking an API call(simulated by setTimeout) and next function which logs the message.\n\n```javascript\nfunction firstFunction() {\n  // Simulate a code delay\n  setTimeout( function() {\n    console.log('First function called');\n  }, 1000 );\n}\nfunction secondFunction() {\n  console.log('Second function called');\n}\nfirstFunction();\nsecondFunction();\n\nOutput\n// Second function called\n// First function called\n```\nAs observed from the output, javascript didnot wait for the response of first function and remaining code block get executed. So callbacks used in a way to make sure that certain code does not execute until other code finished execution.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a callback hell?***\n\nCallback 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,\n\n```javascript\nasync1(function() {\n    async2(function() {\n        async3(function() {\n            async4(function() {\n                ....\n            });\n        });\n    });\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is server-sent events?***\n\nServer-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 is been used in Facebook/Twitter updates, stock price updates, news feeds etc.\n\nThe `EventSource` object is used to receive server-sent event notifications. For example, we can receive messages from server as below,\n\n```javascript\nif(typeof(EventSource) !== \"undefined\") {\n  var source = new EventSource(\"sse_generator.js\");\n  source.onmessage = function(event) {\n    document.getElementById(\"output\").innerHTML += event.data + \"\u003cbr\u003e\";\n  };\n}\n```\nBelow are the list of events available for server sent events\n\n| Event | Description |\n|------ |--------------|\n| onopen  | It is used when a connection to the server is opened |\n| onmessage | This event is used when a message is received  |\n| onerror | It happens when an error occurs|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is callback in callback?***\n\nYou can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks.\n\n```javascript\nloadScript('/script1.js', function(script) {\n    console.log('first script is loaded');\n\n  loadScript('/script2.js', function(script) {\n\n    console.log('second script is loaded');\n\n    loadScript('/script3.js', function(script) {\n\n        console.log('third script is loaded');\n      // after all scripts are loaded\n    });\n  })\n});\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is promise chaining?***\n\nThe process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining.\n\n```javascript\nnew Promise(function(resolve, reject) {\n\n  setTimeout(() =\u003e resolve(1), 1000);\n\n}).then(function(result) {\n\n  console.log(result); // 1\n  return result * 2;\n\n}).then(function(result) {\n\n  console.log(result); // 2\n  return result * 3;\n\n}).then(function(result) {\n\n  console.log(result); // 6\n  return result * 4;\n\n});\n```\nIn the above handlers, the result is passed to the chain of .then() handlers with the below work flow,\n1. The initial promise resolves in 1 second,\n2. After that `.then` handler is called by logging the result(1) and then return a promise with the value of result * 2.\n3. After that the value passed to the next `.then` handler by logging the result(2) and return a promise with result * 3.\n4. Finally the value passed to the last `.then` handler by logging the result(6) and return a promise with result * 4.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is promise.all()?***\n\n`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.\n\n```javascript\nPromise.all([Promise1, Promise2, Promise3]) \n        .then(result) =\u003e {   \n            console.log(result) \n          }) \n        .catch(error =\u003e console.log(`Error in promises ${error}`));\n```\n*Note: Remember that the order of the promises(output the result) is maintained as per input order*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of race method in promise?***\n\n`Promise.race()` method will return the promise instance which is firstly resolved or rejected. Let us take an example of race() method where promise2 is resolved first\n\n```javascript\nvar promise1 = new Promise(function(resolve, reject) {\n    setTimeout(resolve, 500, 'one');\n});\nvar promise2 = new Promise(function(resolve, reject) {\n    setTimeout(resolve, 100, 'two');\n});\n\nPromise.race([promise1, promise2]).then(function(value) {\n  console.log(value); // \"two\" // Both promises will resolve, but promise2 is faster\n});\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a strict mode in javascript?***\n\nStrict Mode is a new feature in ECMAScript 5 that allows 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 `'use strict';` instructs the browser to use the javascript code in the Strict mode.\n\nStrict 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.\n\nThe strict mode is declared by adding \"use strict\"; to the beginning of a script or a function.\nIf declare at the beginning of a script, it has global scope.\n\n```javascript\n'use strict';\nx = 3.14; // This will cause an error because x is not declared\n```\nand if you declare inside a function, it has local scope\n\n```javascript\nx = 3.14;       // This will not cause an error.\nmyFunction();\n\nfunction myFunction() {\n  'use strict';\n  y = 3.14;   // This will cause an error\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of double exclamation?***\n\nThe 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, true.\nFor example, you can test IE version using this expression as below,\n\n```javascript\nlet isIE11 = false;\nisIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\\./);\nconsole.log(isIE11); // returns true or false\n```\nIf you do not use this expression then it returns the original value.\n\n```javascript\nconsole.log(navigator.userAgent.match(/Trident.*rv[ :]*11\\./));  // returns either an Array or null\n```\n*Note: The expression !! is not an operator, but it is just twice of ! operator*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of delete operator?***\n\nThe delete keyword is used to delete the property as well as its value.\n\n```javascript\nvar user= {name: \"John\", age:20};\ndelete user.age;\n\nconsole.log(user); // {name: \"John\"}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is typeof operator?***\n\nYou can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression.\n\n```javascript\ntypeof \"John Abraham\"     // Returns \"string\"\ntypeof (1 + 2)        // Returns \"number\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is undefined property?***\n\nThe undefined property indicates that a variable has not been assigned a value, or not declared at all. The type of undefined value is undefined too.\n\n```javascript\nvar user;    // Value is undefined, type is undefined\nconsole.log(typeof(user)) //undefined\n```\nAny variable can be emptied by setting the value to undefined.\n\n```javascript\nuser = undefined\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between null and undefined?***\n\nBelow are the main differences between null and undefined,\n\n| Null | Undefined |\n|---- | -----------|\n| 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. |\n| Type of null is object | Type of undefined is undefined  |\n| 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.|\n| Indicates the absence of a value for a variable | Indicates absence of variable itself |\n| Converted to zero (0) while performing primitive operations | Converted to NaN while performing primitive operations |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is eval?***\n\nThe eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements.\n\n```javascript\nconsole.log(eval('1 + 2')); //  3\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between window and document?***\n\nThe window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.\n\nThe document object is html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc.\n\n| Window | Document |\n|------- | ---------|\n| 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) |\n| By default window object is available implicitly in the page | You can access it via window.document or document.  |\n| It has methods like alert(), confirm() and properties like document, location | It provides methods like getElementById(), getElementByTagName(), createElement() etc  |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you access history in javascript?***\n\nThe window.history object contains the browsers history. You can load previous and next URLs in the history using back() and next() methods.\n\n```javascript\nfunction goBack() {\n  window.history.back()\n}\nfunction goForward() {\n  window.history.forward()\n}\n```\n*Note: You can also access history without window prefix*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is isNaN?***\n\nThe 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.\n\n```javascript\nisNaN('Hello') //true\nisNaN('100') //false\ntypeof(NaN) //Number\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the differences between undeclared and undefined variables?***\n\nBelow are the major differences between undeclared and undefined variables,\n\n| undeclared | undefined |\n|---- | ---------\n| These variables do not exist in a program and are not declared  | These variables declared in the program but have not assigned any value |\n| 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.  |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is NaN property?***\n\nThe 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\n\n```javascript\nMath.sqrt(-1)\nparseInt(\"Hello\")\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of isFinite function?***\n\nThe 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.\n\n```javascript\nisFinite(Infinity);  // false\nisFinite(NaN);       // false\nisFinite(-Infinity); // false\n\nisFinite(100);         // true\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you submit a form using JavaScript?***\n\nYou can submit a form using JavaScript use document.form[0].submit(). All the form input information is submitted using onsubmit event handler\n\n```javascript\nfunction submit() {\n    document.form[0].submit();\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you find operating system details?***\n\nThe window.navigator object contains information about the visitor\\'s browser os details. Some of the OS properties are avaialble under platform property,\n\n```javascript\nconsole.log(navigator.platform);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between document load and DOMContentLoaded events?***\n\nThe `DOMContentLoaded` 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).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between native, host and user objects?***\n\n* `Native objects` 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.\n* `Host objects` are objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc considered as host objects.\n* `User objects` are objects defined in the javascript code. For example, User object created for profile information.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the pros and cons of promises over callbacks?***\n\nBelow are the list of pros and cons of promises over callbacks,  \n**Pros:**\n1. It avoids callback hell which is unreadable\n2. Easy to write sequential asynchronous code with .then()\n3. Easy to write parallel asynchronous code with Promise.all()\n4. Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions)\n\n**Cons:**\n1. It makes little complex code\n2. You need to load a polyfill if ES6 is not supported\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between an attribute and a property?***\n\nAttributes 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,\n```html\n\u003cinput type=\"text\" value=\"Name:\"\u003e\n```\nYou can retrieve the attribute value as below,\n\n```javascript\nconst input = document.querySelector('input');\nconsole.log(input.getAttribute('value')); // Good morning\nconsole.log(input.value); // Good morning\n```\nAnd after you change the value of the text field to \"Good evening\", it becomes like\n\n```javascript\nconsole.log(input.getAttribute('value')); // Good morning\nconsole.log(input.value); // Good evening\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is same-origin policy?***\n\nThe 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).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of void(0)?***\n\nThe `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 document that uses `href=\"JavaScript:void(0);\"` within an `\u003ca\u003e` 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.  \nFor example, the below link notify the message without reloading the page\n```html\n\u003ca href=\"JavaScript:void(0);\" onclick=\"alert('Well done!')\"\u003eClick Me!\u003c/a\u003e\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Is JavaScript a compiled or interpreted language?***\n\nJavaScript 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Is JavaScript a case-sensitive language?***\n\nYes, JavaScript is a case sensitive language. The language keywords, variables, function \u0026 object names, and any other identifiers must always be typed with a consistent capitalization of letters.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are events?***\n\nEvents are \"things\" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can `react` on these events. Some of the examples of HTML events are,\n\n1. Web page has finished loading\n2. Input field was changed\n3. Button was clicked\n\nExample: click event for button element\n\n```html\n\u003c!doctype html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n  \u003cscript\u003e\n    function greeting() {\n      alert('Hello! Good morning');\n    }\n  \u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n  \u003cbutton type=\"button\" onclick=\"greeting()\"\u003eClick me\u003c/button\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the use of preventDefault method?***\n\nThe 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 hyper link are some common usecases.\n\n```javascript\ndocument.getElementById(\"link\").addEventListener(\"click\", function(event) {\n   event.preventDefault();\n});\n```\n\n*Note: Remember that not all events are cancelable*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the use of stopPropagation method?***\n\nThe 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)\n```html\n\u003cp\u003eClick DIV1 Element\u003c/p\u003e\n\u003cdiv onclick=\"secondFunc()\"\u003eDIV 2\n  \u003cdiv onclick=\"firstFunc(event)\"\u003eDIV 1\u003c/div\u003e\n\u003c/div\u003e\n\n\u003cscript\u003e\nfunction firstFunc(event) {\n  alert(\"DIV 1\");\n  event.stopPropagation();\n}\n\nfunction secondFunc() {\n  alert(\"DIV 2\");\n}\n\u003c/script\u003e\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the steps involved in return false usage?***\n\nThe return false statement in event handlers performs the below steps,\n1. First it stops the browser default action or behaviour.\n2. It prevents the event from propagating the DOM\n3. Stops callback execution and returns immediately when called.\n\n## Q. ***What is BOM?***\n\nThe 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 window. The Browser Object Model is not standardized and can change based on different browsers.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the use of setTimeout?***\n\nThe setTimeout() method is used to call a function or evaluates an expression after a specified number of milliseconds. For example, let us log a message after 2 seconds using setTimeout method,\n\n```javascript\nsetTimeout(function() { console.log(\"Good morning\"); }, 2000);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the use of setInterval?***\n\nThe setInterval() method is used to call a function or evaluates an expression at specified intervals (in milliseconds). For example, let us log a message after 2 seconds using setInterval method,\n\n```javascript\nsetInterval(function() { console.log(\"Good morning\"); }, 2000);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why is JavaScript treated as Single threaded?***\n\nJavaScript 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an event delegation?***\n\nEvent 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.\nFor example, if you wanted to detect field changes in inside a specific form, you can use event delegation technique,\n\n```javascript\nvar form = document.querySelector('#registration-form');\n\n// Listen for changes to fields inside the form\nform.addEventListener('input', function (event) {\n\n// Log the field that was changed\nconsole.log(event.target);\n\n}, false);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose JSON stringify?***\n\nWhen 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.\n\n```javascript\nvar userJSON = {'name': 'John', age: 31}\nvar userString = JSON.stringify(user);\nconsole.log(userString); //\"{\"name\":\"John\",\"age\":31}\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you parse JSON string?***\n\nWhen receiving the data from a web server, the data is always in a string format. But you can convert this string value to javascript object using parse() method.\n\n```javascript\nvar userString = '{\"name\":\"John\",\"age\":31}';\nvar userJSON = JSON.parse(userString);\nconsole.log(userJSON);// {name: \"John\", age: 31}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of clearTimeout method?***\n\nThe `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.\nFor example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method.\n\n```javascript\nvar msg;\nfunction greeting() {\n  alert('Good morning');\n}\nfunction start() {\n  msg =setTimeout(greeting, 3000);\n}\nfunction stop() {\n    clearTimeout(msg);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of clearInterval method?***\n\nThe `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.\nFor example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by clearInterval() method.\n\n```javascript\nvar msg;\nfunction greeting() {\n  alert('Good morning');\n}\nfunction start() {\n  msg = setInterval(greeting, 3000);\n}\nfunction stop() {\n    clearInterval(msg);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you redirect new page in javascript?***\n\nIn vanilla javascript, you can redirect to a new page using `location` property of window object. The syntax would be as follows,\n\n```javascript\nfunction redirect() {\n  window.location.href = 'newPage.html';\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you check whether a string contains a substring?***\n\nThere are 3 possible ways to check whether a string contains a substring or not,  \n**a.) Using includes:** ES6 provided `String.prototype.includes` method to test a string contains a substring\n\n```javascript\nvar mainString = \"hello\", subString = \"hell\";\nmainString.includes(subString)\n```\n**b.) Using indexOf:** In an ES5 or older environments, you can use `String.prototype.indexOf` which returns the index of a substring. If the index value is not equal to -1 then it means the substring exist in the main string.\n\n```javascript\nvar mainString = \"hello\", subString = \"hell\";\nmainString.indexOf(subString) !== -1\n```\n**c.) Using RegEx:** The advanced solution is using Regular expression test method(`RegExp.test`), which allows for testing for against regular expressions\n\n```javascript\nvar mainString = \"hello\", regex = \"/hell/\";\nregex.test(mainString)\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you validate an email in javascript?***\n\nYou can validate an email in javascript using regular expressions. It is recommended to do validations on the server side instead client side. Because the javascript can be disabled on the client side.\n\n```javascript\nfunction validateEmail(email) {\n    var re = /^(([^\u003c\u003e()\\[\\]\\\\.,;:\\s@\"]+(\\.[^\u003c\u003e()\\[\\]\\\\.,;:\\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,}))$/;\n    return re.test(String(email).toLowerCase());\n}\n```\nThe above regular expression regular accepts unicode characters.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you get the current url with javascript?***\n\nYou can use `window.location.href` expression to get the current url path and you can use the same expression for updating the URL too. You can also use `document.URL` for read-only purpose but this solution has issues in FF.\n\n```javascript\nconsole.log('location.href', window.location.href); // Returns full URL\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the various url properties of location object?***\n\nThe below `Location` object properties can be used to access URL components of the page\n\n|Properties|Description|\n|----------|------------|\n|href      |The entire URL|\n|protocol  |The protocol of the URL|\n|host      |The hostname and port of the URL|\n|hostname  |The hostname of the URL|\n|port      |The port number in the URL|\n|pathname  |The path name of the URL|\n|search    |The query portion of the URL|\n|hash      |The anchor portion of the URL|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do get query string values in javascript?***\n\nYou can use URLSearchParams to get query string values in javascript. Let us see an example to get the client code value from URL query string,\n\n```javascript\nconst urlParams = new URLSearchParams(window.location.search);\nconst clientCode = urlParams.get('clientCode');\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you check if a key exists in an object?***\n\n**a.) Using in operator:** You can use the in operator whether a key exists in an object or not\n\n```javascript\n\"key\" in obj\n```\nand If you want to check if a key doesn't exist, remember to use parenthesis,\n\n```javascript\n!(\"key\" in obj)\n```\n**b.) Using hasOwnProperty method:** You can use `hasOwnProperty` to particularly test for properties of the object instance (and not inherited properties)\n\n```javascript\nobj.hasOwnProperty(\"key\") // true\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you loop through or enumerate javascript object?***\n\nYou can use the `for-in` 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 `hasOwnProperty` method.\n\n```javascript\nvar object = {\n    \"k1\": \"value1\",\n    \"k2\": \"value2\",\n    \"k3\": \"value3\"\n};\n\nfor (var key in object) {\n    if (object.hasOwnProperty(key)) {\n        console.log(key + \" -\u003e \" + object[key]); // k1 -\u003e value1 ...\n    }\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you test for an empty object?***\n\n**a.) Using Object keys(ECMA 5+):** You can use object keys length along with constructor type.\n\n```javascript\nObject.keys(obj).length === 0 \u0026\u0026 obj.constructor === Object \n```\n**b.) Using Object entries(ECMA 7+):** You can use object entries length along with constructor type.\n\n```javascript\nObject.entries(obj).length === 0 \u0026\u0026 obj.constructor === Object \n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an arguments object?***\n\nThe arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let us see how to use arguments object inside sum function,\n\n```javascript\nfunction sum() {\n    var total = 0;\n    for (var i = 0, len = arguments.length; i \u003c len; ++i) {\n        total += arguments[i];\n    }\n    return total;\n}\n\nsum(1, 2, 3) // returns 6\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you make first letter of the string in an uppercase?***\n\nYou can create a function which uses chain of string methods such as charAt, toUpperCase and slice methods to generate a string with first letter in uppercase.\n\n```javascript\nfunction capitalizeFirstLetter(string) {\n    return string.charAt(0).toUpperCase() + string.slice(1);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the pros and cons of for loop?***\n\nThe for-loop is a commonly used iteration syntax in javascript. It has both pros and cons\n\n**Pros**  \n1. Works on every environment\n2. You can use break and continue flow control statements\n\n**Cons**  \n1. Too verbose\n2. Imperative\n3. You might face one-by-off errors\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you display the current date in javascript?***\n\nYou can use `new Date()` to generate a new Date object containing the current date and time. \n\nExample:\n```javascript\nvar today = new Date();\nvar dd = String(today.getDate()).padStart(2, '0');\nvar mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!\nvar yyyy = today.getFullYear();\n\ntoday = mm + '/' + dd + '/' + yyyy;\ndocument.write(today);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you compare two date objects?***\n\nYou need to use use date.getTime() method to compare date values instead comparision operators (==, !=, ===, and !== operators)\n\n```javascript\nvar d1 = new Date();\nvar d2 = new Date(d1);\nconsole.log(d1.getTime() === d2.getTime()); //True\nconsole.log(d1 === d2); // False\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you check if a string starts with another string?***\n\nYou can use ECMAScript 6 `String.prototype.startsWith()` method to check a string starts with another string or not. But it is not yet supported in all browsers. Let us see an example to see this usage,\n\n```javascript\n\"Good morning\".startsWith(\"Good\"); // true\n\"Good morning\".startsWith(\"morning\"); // false\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you trim a string in javascript?***\n\nJavaScript provided a trim method on string types to trim any whitespaces present at the begining or ending of the string.\n\n```javascript\n\"  Hello World   \".trim(); //Hello World\n```\n\nIf your browser(`\u003c IE9`) doesnot support this method then you can use below polyfill.\n\n```javascript\nif (!String.prototype.trim) {\n    (function() {\n        // Make sure we trim BOM and NBSP\n        var rtrim = /^[\\s\\uFEFF\\xA0]+|[\\s\\uFEFF\\xA0]+$/g;\n        String.prototype.trim = function() {\n            return this.replace(rtrim, '');\n        };\n    })();\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you add a key value pair in javascript?***\n\nThere are two possible solutions to add new properties to an object. Let us take a simple object to explain these solutions.\n\n```javascript\nvar object = {\n    key1: value1,\n    key2: value2\n};\n```\n\n**a.) Using dot notation:** This solution is useful when you know the name of the property\n\n```javascript\nobject.key3 = \"value3\";\n```\n**b.) Using square bracket notation:** This solution is useful when the name of the property is dynamically determined.\n\n```javascript\nobj[\"key3\"] = \"value3\";\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you assign default values to variables?***\n\nYou can use the logical or operator `||` in an assignment expression to provide a default value. The syntax looks like as below,\n\n```javascript\nvar a = b || c;\n```\n\nAs 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'.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can we define properties for functions?***\n\nYes, We can define properties for functions because functions are also objects.\n\n```javascript\nfn = function(x) {\n  //Function code goes here\n}\n\nfn.name = \"John\";\n\nfn.profile = function(y) {\n  //Profile code goes here\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the way to find the number of parameters expected by a function?***\n\nYou can use `function.length` syntax to find the number of parameters expected by a function. Let us take an example of `sum` function to calculate the sum of numbers,\n\n```javascript\nfunction sum(num1, num2, num3, num4){\n    return num1 + num2 + num3 + num4;\n}\nsum.length // 4 is the number of parameters expected.\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are break and continue statements?***\n\nThe break statement is used to \"jumps out\" of a loop. i.e, It breaks the loop and continues executing the code after the loop.\n\n```javascript\nfor (i = 0; i \u003c 10; i++) {\n  if (i === 5) { break; }\n  text += \"Number: \" + i + \"\u003cbr\u003e\";\n}\n```\n\nThe continue statement is used to \"jumps 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.\n\n```javascript\nfor (i = 0; i \u003c 10; i++) {\n    if (i === 5) { continue; }\n    text += \"Number: \" + i + \"\u003cbr\u003e\";\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are js labels?***\n\nThe 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,\n\n```javascript\nvar i, j;\n\nloop1:\nfor (i = 0; i \u003c 3; i++) {\n  loop2:\n  for (j = 0; j \u003c 3; j++) {\n      if (i === j) {\n        continue loop1;\n      }\n      console.log('i = ' + i + ', j = ' + j);\n  }\n}\n\n// Output is:\n//   \"i = 1, j = 0\"\n//   \"i = 2, j = 0\"\n//   \"i = 2, j = 1\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the benefits of keeping declarations at the top?***\n\nIt is recommended to keep all declarations at the top of each script or function. The benefits of doing this are,\n1. Gives cleaner code\n2. It provides a single place to look for local variables\n3. Easy to avoid unwanted global variables\n4. It reduces the possibility of unwanted re-declarations\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the benefits of initializing variables?***\n\nIt is recommended to initialize variables because of the below benefits,\n1. It gives cleaner code\n2. It provides a single place to initialize variables\n3. Avoid undefined values in the code\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the recommendations to create new object?***\n\nIt is recommended to avoid creating new objects using `new Object()`. Instead you can initialize values based on it is type to create the objects.\n1. Assign {} instead of new Object()\n2. Assign \"\" instead of new String()\n3. Assign 0 instead of new Number()\n4. Assign false instead of new Boolean()\n5. Assign [] instead of new Array()\n6. Assign /()/ instead of new RegExp()\n7. Assign function (){} instead of new Function()\n\nYou can define them as an example,\n\n```javascript\nvar v1 = {};\nvar v2 = \"\";\nvar v3 = 0;\nvar v4 = false;\nvar v5 = [];\nvar v6 = /()/;\nvar v7 = function(){};\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you define JSON arrays?***\n\nJSON arrays are written inside square brackets and array contain javascript objects. For example, the JSON array of users would be as below,\n\n```javascript\n\"users\":[\n  {\"firstName\":\"John\", \"lastName\":\"Abrahm\"},\n  {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n  {\"firstName\":\"Shane\", \"lastName\":\"Warn\"}\n]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you generate random integers?***\n\nYou 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,\n\n```javascript\nMath.floor(Math.random() * 10) + 1;     // returns a random integer from 1 to 10\nMath.floor(Math.random() * 100) + 1;     // returns a random integer from 1 to 100\n```\n*Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can you write a random integers function to print integers with in a range?***\n\nYes, you can create a proper random function to return a random number between min and max (both included)\n\n```javascript\nfunction randomInteger(min, max) {\n  return Math.floor(Math.random() * (max - min + 1) ) + min;\n}\nrandomInteger(1, 100); // returns a random integer from 1 to 100\nrandomInteger(1, 1000); // returns a random integer from 1 to 1000\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the string methods available in Regular expression?***\n\nRegular Expressions has two string methods: search() and replace().\nThe search() method uses an expression to search for a match, and returns the position of the match.\n\n```javascript\nvar msg = \"Hello John\";\nvar n = msg.search(/John/i); // 6\n```\nThe replace() method is used return a modified string where the pattern is replaced.\n\n```javascript\nvar msg = \"Hello John\";\nvar n = msg.search(/John/i, \"Buttler\"); // Hello Buttler\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are modifiers in regular expression?***\n\nModifiers can be used to perform case-insensitive and global searches. \n\n| Modifier | Description |\n|---- | -----------------|\n| i  | Perform case-insensitive matching |\n| g | Perform a global match rather than stops at first match  |\n| m | Perform multiline matching|\n\nExample: Global Modifier\n\n```javascript\n  var text = \"Learn JS one by one\";\n  var pattern = /one/g;\n  var result = text.match(pattern); // one,one\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are regular expression patterns?***\n\nRegular Expressions provided group of patterns in order to match characters. Basically they are categorized into 3 types,  \n\n**1. Brackets:** These are used to find a range of characters.\n  For example, below are some use cases,\n  * [abc]: Used to find any of the characters between the brackets(a,b,c)\n  * [0-9]: Used to find any of the digits between the brackets\n  * (a|b): Used to find any of the alternatives separated with |\n\n**2. Metacharacters:** These are characters with a special meaning\n  For example, below are some use cases,\n  * \\d: Used to find a digit\n  * \\s: Used to find a whitespace character\n  * \\b: Used to find a match at the beginning or ending of a word\n\n**3. Quantifiers:** These are useful to define quantities\n  For example, below are some use cases,\n  * n+: Used to find matches for any string that contains at least one n\n  * n*: Used to find matches for any string that contains zero or more occurrences of n\n  * n?: Used to find\tmatches for any string that contains zero or one occurrences of n\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a RegExp object?***\n\nRegExp object is a regular expression object with predefined properties and methods. \n\n```javascript\nvar regexp = new RegExp('\\\\w+');\nconsole.log(regexp);\n// expected output: /\\w+/\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you search a string for a pattern?***\n\nYou can use test() method of regular expression in order to search a string for a pattern, and returns true or false depending on the result.\n\n```javascript\nvar pattern = /you/;\nconsole.log(pattern.test(\"How are you?\")); //true\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of exec method?***\n\nThe purpose of exec method is similar to test method but it returns a founded text as an object instead of returning true/false.\n\n```javascript\nvar pattern = /you/;\nconsole.log(pattern.test(\"How are you?\")); //you\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you change style of a HTML element?***\n\nYou can change inline style or classname of a HTML element using javascript\n1. **Using style property:** You can modify inline style using style property\n\n```javascript\ndocument.getElementById(\"title\").style.fontSize = \"30px\";\n```\n2. **Using ClassName property:** It is easy to modify element class using className property\n\n```javascript\ndocument.getElementById(\"title\").style.className = \"custom-title\";\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a debugger statement?***\n\nThe debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect.\nFor 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.\n\n```javascript\nfunction getProfile() {\n// code goes here\ndebugger;\n// code goes here\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of breakpoints in debugging?***\n\nYou can set breakpoints in the javascript code once the debugger statement is executed and 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 play button.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can I use reserved words as identifiers?***\n\nNo, you cannot use the reserved words as variables, labels, object or function names.\n\n```javascript\nvar else = \"hello\"; // Uncaught SyntaxError: Unexpected token else\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you detect a mobile browser without regexp?***\n\nYou can detect mobile browser by simply running through a list of devices and checking if the useragent matches anything. This is an alternative solution for RegExp usage,\n\n```javascript\nfunction detectmob() {\nif( navigator.userAgent.match(/Android/i)\n|| navigator.userAgent.match(/webOS/i)\n|| navigator.userAgent.match(/iPhone/i)\n|| navigator.userAgent.match(/iPad/i)\n|| navigator.userAgent.match(/iPod/i)\n|| navigator.userAgent.match(/BlackBerry/i)\n|| navigator.userAgent.match(/Windows Phone/i)\n){\n    return true;\n  }\nelse {\n    return false;\n  }\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you get the image width and height using JS?***\n\nYou can programmatically get the image and check the dimensions(width and height) using Javascript.\n\n```javascript\nvar img = new Image();\nimg.onload = function() {\n  console.log(this.width + 'x' + this.height);\n}\nimg.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you make synchronous HTTP request?***\n\nBrowsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript\n\n```javascript\nfunction httpGet(theUrl)\n{\n    var xmlHttpReq = new XMLHttpRequest();\n    xmlHttpReq.open( \"GET\", theUrl, false ); // false for synchronous request\n    xmlHttpReq.send( null );\n    return xmlHttpReq.responseText;\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you make asynchronous HTTP request?***\n\nBrowsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing 3rd parameter as true.\n\n```javascript\nfunction httpGetAsync(theUrl, callback)\n{\n    var xmlHttpReq = new XMLHttpRequest();\n    xmlHttpReq.onreadystatechange = function() {\n        if (xmlHttpReq.readyState == 4 \u0026\u0026 xmlHttpReq.status == 200)\n            callback(xmlHttpReq.responseText);\n    }\n    xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous\n    xmlHttp.send(null);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you convert date to another timezone in javascript?***\n\nYou can use toLocaleString() method to convert date in one timezone to another. For example, let us convert current date to British English timezone as below,\n\n```javascript\nconsole.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); //29/06/2019, 09:56:00\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the properties used to get size of window?***\n\nYou can use innerWidth, innerHeight, clientWidth, clientHeight properties of windows, document element and document body objects to find the size of a window. Let us use them combination of these properties to calculate the size of a window or document,\n\n```javascript\nvar width = window.innerWidth\n|| document.documentElement.clientWidth\n|| document.body.clientWidth;\n\nvar height = window.innerHeight\n|| document.documentElement.clientHeight\n|| document.body.clientHeight;\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a conditional operator in javascript?***\n\nThe conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement.\n\n```javascript\nvar isAuthenticated = false;\nconsole.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated');\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can you apply chaining on conditional operator?***\n\nYes, you can apply chaining on conditional operator similar to if … else if … else if … else chain. The syntax is going to be as below,\n\n```javascript\nfunction traceValue(someParam) {\n    return condition1 ? value1\n        : condition2 ? value2\n        : condition3 ? value3\n        : value4;\n}\n\n// The above conditional operator is equivalent to:\n\nfunction traceValue(someParam) {\n    if (condition1) { return value1; }\n    else if (condition2) { return value2; }\n    else if (condition3) { return value3; }\n    else { return value4; }\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the ways to execute javascript after page load?***\n\nYou can execute javascript after page load in many different ways,  \n**a.) window.onload:**\n```javascript\nwindow.onload = function ...\n```\n**b.) document.onload:**\n```javascript\ndocument.onload = function ...\n```\n**c.) body onload:**\n```html\n\u003cbody onload=\"script();\"\u003e\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between proto and prototype?***\n\nThe `__proto__` object is the actual object that is used in the lookup chain to resolve methods, etc. Whereas `prototype` is the object that is used to build `__proto__` when you create an object with new\n```javascript\n( new Employee ).__proto__ === Employee.prototype;\n( new Employee ).prototype === undefined;\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Give an example where do you really need semicolon?***\n\nIt 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.\n```javascript\n// define a function\nvar fn = function () {\n    //...\n} // semicolon missing at this line\n\n// then execute some code inside a closure\n(function () {\n    //...\n})();\n```\nand it will be interpreted as\n```javascript\nvar fn = function () {\n    //...\n}(function () {\n    //...\n})();\n```\nIn this case, we are passing 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a freeze method?***\n\nThe freeze() method is used to freeze an object. Freezing an object does'nt allow adding new properties to an object,prevents from 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.\n```javascript\nconst obj = {\n  prop: 100\n};\n\nObject.freeze(obj);\nobj.prop = 200; // Throws an error in strict mode\n\nconsole.log(obj.prop); //100\n```\n*Note: It causes a TypeError if the argument passed is not an object*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of freeze method?***\n\nBelow are the main benefits of using freeze method,\n1. It is used for freezing objects and arrays.\n2. It is used to make an object immutable.\n\n## Q. ***Why do I need to use freeze method?***\n\nIn 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 `final` keyword which is used in various languages.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you detect a browser language preference?***\n\nYou can use navigator object to detect a browser language preference as below,\n```javascript\nvar language = navigator.languages \u0026\u0026 navigator.languages[0] || // Chrome / Firefox\n              navigator.language ||   // All browsers\n              navigator.userLanguage; // IE \u003c= 10\n\nconsole.log(language);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to convert string to title case with javascript?***\n\nTitle case means that the first letter of each word is capitalized. You can convert a string to title case using the below function,\n```javascript\n    function toTitleCase(str) {\n        return str.replace(\n            /\\w\\S*/g,\n            function(txt) {\n                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n            }\n        );\n    }\n    toTitleCase(\"good morning john\"); // Good Morning John\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you detect javascript disabled in the page?***\n\nYou can use `\u003cnoscript\u003e` tag to detect javascript disabled or not. The code block inside `\u003cnoscript\u003e` get executed when JavaScript is disabled, and are typically used to display alternative content when the page generated in JavaScript.\n```html\n\u003cscript type=\"javascript\"\u003e\n    // JS related code goes here\n\u003c/script\u003e\n\u003cnoscript\u003e\n    \u003ca href=\"next_page.html?noJS=true\"\u003eJavaScript is disabled in the apge. Please click Next Page\u003c/a\u003e\n\u003c/noscript\u003e\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are various operators supported by javascript?***\n\nAn operator is capable of manipulating(mathematical and logical computations) a certain value or operand. There are various operators supported by JavaScript as below,\n1. **Arithmetic Operators:** Includes + (Addition),– (Subtraction), * (Multiplication), / (Division), % (Modulus), + + (Increment)  and – – (Decrement)\n2. **Comparison Operators:** Includes = =(Equal),!= (Not Equal), ===(Equal with type), \u003e (Greater than),\u003e = (Greater than or Equal to),\u003c (Less than),\u003c= (Less than or Equal to)\n3. **Logical Operators:** Includes \u0026\u0026(Logical AND),||(Logical OR),!(Logical NOT)\n4. **Assignment Operators:** Includes = (Assignment Operator), += (Add and Assignment Operator), – = (Subtract and Assignment Operator), *= (Multiply and Assignment), /= (Divide and Assignment), %= (Modules and Assignment)\n5. **Ternary Operators:** It includes conditional(: ?) Operator\n6. **typeof Operator:** It uses to find type of variable. The syntax looks like `typeof variable`\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a rest parameter?***\n\nRest parameter is an improved way to handle function parameter which allows us to represent an indefinite number of arguments as an array. The syntax would be as below,\n```javascript\nfunction f(a, b, ...theArgs) {\n  // ...\n}\n```\nFor example, let us take a sum example to calculate on dynamic number of parameters,\n```javascript\nfunction total(…args) {\n  let sum = 0;\n  for(let i of args) {\n    sum+=i;\n  }\n return sum;\n}\nconsole.log(fun(1,2)); //3\nconsole.log(fun(1,2,3)); //6\nconsole.log(fun(1,2,3,4)); //13\nconsole.log(fun(1,2,3,4,5)); //15\n```\n\n*Note: Rest parameter is added in ES2015 or ES6*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What happens if you do not use rest parameter as a last argument?***\n\nThe 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 does not make any sense and will throw an error.\n\n```javascript\nfunction someFunc(a,…b,c) {\n  //You code goes here\n  return;\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the bitwise operators available in javascript?***\n\nBelow are the list of bit-wise logical operators used in JavaScript\n1. Bit-wise AND ( \u0026 )\n2. Bit-Wise OR ( | )\n3. Bit-Wise XOR ( ^ )\n4. Bit-Wise NOT ( ~ )\n5. Left Shift ( \u003c\u003c )\n6. Sign Propagating Right Shift ( \u003e\u003e )\n7. Zero fill Right Shift ( \u003e\u003e\u003e )\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you determine whether object is frozen or not?***\n\n`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,\n1. If it is not extensible.\n2. If all of its properties are non-configurable.\n3. If all its data properties are non-writable.\nThe usage is going to be as follows,\n```javascript\nconst object = {\n  property: 'Welcome JS world'\n};\nObject.freeze(object);\nconsole.log(Object.isFrozen(object));\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you determine two values same or not using object?***\n\nThe `Object.is()` method determines whether two values are the same value. For example, the usage with different types of values would be,\n```javascript\nObject.is('hello', 'hello'); // true\nObject.is(window, window); // true\nObject.is([], []) // false\n```\nTwo values are the same if one of the following holds:\n1. both undefined\n2. both null\n3. both true or both false\n4. both strings of the same length with the same characters in the same order\n5. both the same object (means both object have same reference)\n6. both numbers and\n  both +0\n  both -0\n  both NaN\n  both non-zero and both not NaN and both have the same value\n\n**Purpose**\n\n1. It is used for comparison of two strings.\n2. It is used for comparison of two numbers.\n3. It is used for comparing the polarity of two numbers.\n4. It is used for comparison of two objects.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you copy properties from one object to other?***\n\nYou can use `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 target object. The syntax would be as below,\n```javascript\nObject.assign(target, ...sources)\n```\nLet us take example with one source and one target object,\n```javascript\nconst target = { a: 1, b: 2 };\nconst source = { b: 3, c: 4 };\n\nconst returnedTarget = Object.assign(target, source);\n\nconsole.log(target); // { a: 1, b: 3, c: 5 }\nconsole.log(returnedTarget); // { a: 1, b: 3, c: 5 }\n```\nAs observed in the above code, there is a common property(`b`) from source to target so it is value is been overwritten.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the applications of assign method?***\n\nBelow are the some of main applications of `Object.assign()` method,\n1. It is used for cloning an object.\n2. It is used to merge object with same properties.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a proxy object?***\n\nThe Proxy object is used to define custom behavior for fundamental operations such as property lookup, assignment, enumeration, function invocation, etc. The syntax would be as follows,\n```javascript\nvar p = new Proxy(target, handler);\n```\nLet us take an example of proxy object,\n```javascript\nvar handler = {\n    get: function(obj, prop) {\n        return prop in obj ?\n            obj[prop] :\n            100;\n    }\n};\n\nvar p = new Proxy({}, handler);\np.a = 10;\np.b = null;\n\nconsole.log(p.a, p.b); // 1, null\nconsole.log('c' in p, p.c); // false, 100\n```\nIn the above code, it uses `get` handler which define the behavior of the proxy when an operation is performed on it\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of seal method?***\n\nThe `Object.seal()` method is used 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. \n```javascript\nconst object = {\n    property: 'Welcome JS world'\n};\nObject.freeze(object);\nobject.property = 'Welcome to object world';\nconsole.log(Object.isFrozen(object)); // Welcome to object world\ndelete object.property; // You cannot delete when sealed\nconsole.log(object.property); //Welcome to object world\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the applications of seal method?***\n\nBelow are the main applications of `Object.seal()` method,\n1. It is used for sealing objects and arrays.\n2. It is used to make an object immutable.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the differences between freeze and seal methods?***\n\nIf 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you determine if an object is sealed or not?***\n\nThe `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\n1. If it is not extensible.\n2. If all of its properties are non-configurable.\n3. If it is not removable (but not necessarily non-writable).\n\n\n```javascript\nconst object = {\n  property: 'Hello, Good morning'\n};\n\nObject.seal(object); // Using seal() method to seal the object\nconsole.log(Object.isSealed(object));      // checking whether the object is sealed or not\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you get enumerable key and value pairs?***\n\nThe `Object.entries()` method is used to return an array of a given object own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a `for...in` loop. Let us see the functionality of object.entries() method in an example,\n```javascript\nconst object = {\n  a: 'Good morning',\n  b: 100\n};\n\nfor (let [key, value] of Object.entries(object)) {\n  console.log(`${key}: ${value}`); // a: 'Good morning'\n                                  // b: 100\n}\n```\n*Note: The order is not guaranteed as object defined*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the main difference between Object.values and Object.entries method?***\n\nThe `Object.values()` method's behavior is similar to `Object.entries()` method but it returns an array of values instead [key,value] pairs.\n```javascript\nconst object = {\n  a: 'Good morning',\n  b: 100\n};\n\nfor (let value of Object.values(object)) {\n  console.log(`${value}`); // 'Good morning'\n                                100\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How can you get the list of keys of any object?***\n\nYou can use `Object.keys()` method which is used 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,\n```javascript\nconst user = {\n  name: 'John',\n  gender: 'male',\n  age: 40\n};\n\nconsole.log(Object.keys(user)); //['name', 'gender', 'age']\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you create an object with prototype?***\n\nThe `Object.create()` method is used to create a new object with the specified prototype object and properties. i.e, It uses existing object as the prototype of the newly created object. It returns a new object with the specified prototype object and properties.\n```javascript\nconst user = {\n  name: 'John',\n  printInfo: function () {\n    console.log(`My name is ${this.name}.`);\n  }\n};\n\nconst admin = Object.create(person);\nadmin.name = \"Nick\"; // Remember that \"name\" is a property set on \"admin\" but not on \"user\" object\nadmin.printInfo(); // My name is Nick\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a WeakSet?***\n\nWeakSet is used to store a collection of weakly(weak references) held objects. The syntax would be as follows,\n```javascript\nnew WeakSet([iterable]);\n```\nLet us see the below example to explain It is behavior,\n```javascript\nvar ws = new WeakSet();\nvar user = {};\nws.add(user);\nws.has(user);    // true\nws.delete(user); // removes user from the set\nws.has(user);    // false, user has been removed\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the differences between WeakSet and Set?***\n\nThe 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.\nOther differences are,\n1. Sets can store any value Whereas WeakSets can store only collections of objects\n2. WeakSet does not have size property unlike Set\n3. WeakSet does not have methods such as clear, keys, values, entries, forEach.\n4. WeakSet is not iterable.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***List down the collection of methods available on WeakSet?***\n\nBelow are the list of methods available on WeakSet,\n1. add(value): A new object is appended with the given value to the weakset\n2. delete(value): Deletes the value from the WeakSet collection.\n3. has(value): It returns true if the value is present in the WeakSet Collection, otherwise it returns false.\n4. length(): It returns the length of weakSetObject\nLet us see the functionality of all the above methods in an example,\n```javascript\nvar weakSetObject = new WeakSet();\nvar firstObject = {};\nvar secondObject = {};\n// add(value)\nweakSetObject.add(firstObject);\nweakSetObject.add(secondObject);\nconsole.log(weakSetObject.has(firstObject)); //true\nconsole.log(weakSetObject.length()); //2\nweakSetObject.delete(secondObject);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a WeakMap?***\n\nThe 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 is looking like as below,\n```javascript\nnew WeakMap([iterable])\n```\nLet us see the below example to explain It is behavior,\n```javascript\nvar ws = new WeakMap();\nvar user = {};\nws.set(user);\nws.has(user);    // true\nws.delete(user); // removes user from the map\nws.has(user);    // false, user has been removed\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the differences between WeakMap and Map?***\n\nThe 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.\nOther differences are,\n1. Maps can store any key type Whereas WeakMaps can store only collections of key objects\n2. WeakMap does not have size property unlike Map\n3. WeakMap does not have methods such as clear, keys, values, entries, forEach.\n4. WeakMap is not iterable.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***List down the collection of methods available on WeakMap?***\n\nBelow are the list of methods available on WeakMap,\n1. set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.\n2. delete(key): Removes any value associated to the key.\n3. has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.\n4. get(key): Returns the value associated to the key, or undefined if there is none.\nLet us see the functionality of all the above methods in an example,\n```javascript\nvar weakMapObject = new WeakMap();\nvar firstObject = {};\nvar secondObject = {};\n// set(key, value)\nweakMapObject.set(firstObject, 'John');\nweakMapObject.set(secondObject, 100);\nconsole.log(weakMapObject.has(firstObject)); //true\nconsole.log(weakMapObject.get(firstObject)); // John\nweakMapObject.delete(secondObject);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of uneval?***\n\nThe `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. \n```javascript\nvar a = 1;\nuneval(a); // returns a String containing 1\nuneval(function user() {}); // returns \"(function user(){})\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you encode an URL?***\n\nThe encodeURI() function is used to encode complete URI which has special characters except (, / ? : @ \u0026 = + $ #) characters.\n```javascript\nvar uri = 'https://mozilla.org/?x=шеллы';\nvar encoded = encodeURI(uri);\nconsole.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you decode an URL?***\n\nThe decodeURI() function is used to decode a Uniform Resource Identifier (URI) previously created by encodeURI().\n```javascript\nvar uri = 'https://mozilla.org/?x=шеллы';\nvar encoded = encodeURI(uri);\nconsole.log(encoded); // https://mozilla.org/?x=%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\ntry {\n  console.log(decodeURI(encoded)); // \"https://mozilla.org/?x=шеллы\"\n} catch(e) { // catches a malformed URI\n  console.error(e);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you print the contents of web page?***\n\nThe window object provided print() method which is used to prints the contents of the current window. It opens Print dialog box which lets you choose between various printing options. \n```html\n  \u003cinput type=\"button\" value=\"Print\" onclick=\"window.print()\" /\u003e\n```\n*Note: In most browsers, it will block while the print dialog is open*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between uneval and eval?***\n\nThe `uneval()` function returns the source of a given object; whereas the `eval` function does the opposite, by evaluating that source code in a different memory area. \n```javascript\nvar msg = uneval(function greeting() { return 'Hello, Good morning'; });\nvar greeting = eval(msg);\ngreeting(); // returns \"Hello, Good morning\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an anonymous function?***\n\nAn 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,\n```javascript\nfunction (optionalParameters) {\n  //do something\n}\n\nconst myFunction = function(){ //Anonymous function assigned to a variable\n  //do something\n};\n\n[1, 2, 3].map(function(element){ //Anonymous function used as a callback function\n  //do something\n});\n```\nExample:\n```javascript\nvar x = function (a, b) {return a * b};\nvar z = x(5, 10);\nconsole.log(z); // 50\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the precedence order between local and global variables?***\n\nA local variable takes precedence over a global variable with the same name. \n```javascript\nvar msg = \"Good morning\";\nfunction greeting() {\n  msg = \"Good Evening\";\n  console.log(msg);\n}\ngreeting();\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are javascript accessors?***\n\nECMAScript 5 introduced javascript object accessors or computed properties through getters and setters. Getters uses `get` keyword whereas Setters uses `set` keyword.\n```javascript\nvar user = {\n  firstName: \"John\",\n  lastName : \"Abraham\",\n  language : \"en\",\n  get lang() {\n    return this.language;\n  }\n  set lang(lang) {\n  this.language = lang;\n  }\n};\nconsole.log(user.lang); // getter access lang as en\nuser.lang = 'fr';\nconsole.log(user.lang); // setter used to set lang as fr\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you define property on Object constructor?***\n\nThe Object.defineProperty() static method is used to define a new property directly on an object, or modifies an existing property on an object, and returns the object. \n```javascript\nconst newObject = {};\n\nObject.defineProperty(newObject, 'newProperty', {\n  value: 100,\n  writable: false\n});\n\nconsole.log(newObject.newProperty); // 100\n\nnewObject.newProperty = 200; // It throws an error in strict mode due to writable setting\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between get and defineProperty?***\n\nBoth has similar results until unless you use classes. If you use `get` the property will be defined on the prototype of the object whereas using `Object.defineProperty()` the property will be defined on the instance it is applied to.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the advantages of Getters and Setters?***\n\nBelow are the list of benefits of Getters and Setters,\n1. They provide simpler syntax\n2. They are used for defining computed properties, or accessors in JS.\n3. Useful to provide equivalence relation between properties and methods\n4. They can provide better data quality\n5. Useful for doing things behind the scenes with the encapsulated logic.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can I add getters and setters using defineProperty method?***\n\nYes, You can use `Object.defineProperty()` method to add Getters and Setters. For example, the below counter object uses increment, decrement, add and substract properties,\n```javascript\nvar counterObj = {counter : 0};\n\n// Define getters\nObject.defineProperty(obj, \"increment\", {\n  get : function () {this.counter++;}\n});\nObject.defineProperty(obj, \"decrement\", {\n  get : function () {this.counter--;}\n});\n\n// Define setters\nObject.defineProperty(obj, \"add\", {\n  set : function (value) {this.counter += value;}\n});\nObject.defineProperty(obj, \"subtract\", {\n  set : function (value) {this.counter -= value;}\n});\n\nobj.add = 10;\nobj.subtract = 5;\nconsole.log(obj.increment); //6\nconsole.log(obj.decrement); //5\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of switch-case?***\n\nThe switch case statement in JavaScript is used for decision making purposes. In few cases, using the switch case statement is going to be more convenient than if-else statements. The syntax would be as below,\n```javascript\nswitch (expression)\n{\n    case value1:\n        statement1;\n        break;\n    case value2:\n        statement2;\n        break;\n    .\n    .\n    case valueN:\n        statementN;\n        break;\n    default:\n        statementDefault;\n}\n```\nThe above multi-way branch statement provides an easy way to dispatch execution to different parts of code based on the value of the expression.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the conventions to be followed for the usage of swtich case?***\n\nBelow are the list of conventions should be taken care,\n1. The expression can be of type either number or string.\n2. Duplicate values are not allowed for the expression.\n3. The default statement is optional. If the expression passed to switch does not matches with any case value then the statement within default case will be executed.\n4. The break statement is used inside the switch to terminate a statement sequence.\n5. The break statement is optional. But if it omitted, the execution will continue on into the next case.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the different ways to access object properties?***\n\nThere are 3 possible ways for accessing the property of an object.\n1. **Dot notation:** It uses dot for accessing the properties\n```javascript\nobjectName.property\n```\n2. **Square brackets notation:** It uses square brackets for property access\n```javascript\nobjectName[\"property\"]\n```\n3. **Expression notation:** It uses expression in the square brackets\n```javascript\nobjectName[expression]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the function parameter rules?***\n\nJavaScript functions follow below rules for parameters,\n1. The function definitions do not specify data types for parameters.\n2. Do not perform type checking on the passed arguments.\n3. Do not check the number of arguments received.\ni.e, The below function follows the above rules,\n```javascript\nfunction functionName(parameter1, parameter2, parameter3) {\n  console.log(parameter1); // 1\n}\nfunctionName(1);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an error object?***\n\nAn 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,\n```javascript\ntry {\n  greeting(\"Welcome\");\n}\ncatch(err) {\n  console.log(err.name + \"\u003cbr\u003e\" + err.message);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***When you get a syntax error?***\n\nA 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\n```javascript\ntry {\n  eval(\"greeting('welcome)\");   // Missing ' will produce an error\n}\ncatch(err) {\n  console.log(err.name);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the different error names from error object?***\n\nThere are 6 different types of error names returned from error object\n\n| Error Name | Description |\n|----------- |-------------|\n| EvalError  | An error has occurred in the eval() function |\n| RangeError | An error has occurred with a number \"out of range\"  |\n| ReferenceError | An error due to an illegal reference|\n| SyntaxError | An error due to a syntax error|\n| TypeError | An error due to a type error |\n| URIError | An error due to encodeURI() |\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the various statements in error handling?***\n\nBelow are the list of statements used in an error handling,\n1. **try:** This statement is used to test a block of code for errors\n2. **catch:** This statement is used to handle the error\n3. **throw:** This statement is used to create custom errors.\n4. **finally:** This statement is used to execute code after try and catch regardless of the result.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the two types of loops in javascript?***\n\n1. **Entry Controlled loops:** 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.\n2. **Exit Controlled Loops:** In this kind of loop typpe, the test condition is tested or evaluated at the end of loop body. i.e, the loop body will execute atleast once irrespective of test condition true or false. For example, do-while loop comes under this category.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an Intl object?***\n\nThe 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 an access to several constructors and language sensitive functions.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you perform language specific date and time formatting?***\n\nYou can use `Intl.DateTimeFormat` object which is constructor for objects that enable language-sensitive date and time formatting. Let us see this behavior with an example,\n```javascript\nvar date = new Date(Date.UTC(2019, 07, 07, 3, 0, 0));\nconsole.log(new Intl.DateTimeFormat('en-GB').format(date)); // 07/08/2019\nconsole.log(new Intl.DateTimeFormat('en-AU').format(date)); // 07/08/2019\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an Iterator?***\n\nAn iterator is an object which defines a sequence and a return value upon its termination. It implements the Iterator protocol with a `next()` method which returns an object with two properties: value (the next value in the sequence) and done (which is true if the last value in the sequence has been consumed).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a decorator?***\n\nA 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 us define admin decorator for user class at design time,\n```javascript\nfunction admin(isAdmin) {\n  return function(target) {\n      target.isAdmin = isAdmin;\n  }\n}\n\n@admin(true)\nclass User() {\n}\nconsole.log(User.isAdmin); //true\n\n@admin(false)\nclass User() {\n}\nconsole.log(User.isAdmin); //false\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the properties of Intl object?***\n\nBelow are the list of properties available on Intl object,\n1. **Collator:** These are the objects that enable language-sensitive string comparison.\n2. **DateTimeFormat:** These are the objects that enable language-sensitive date and time formatting.\n3. **ListFormat:** These are the objects that enable language-sensitive list formatting.\n4. **NumberFormat:** Objects that enable language-sensitive number formatting.\n5. **PluralRules:** Objects that enable plural-sensitive formatting and language-specific rules for plurals.\n6. **RelativeTimeFormat:** Objects that enable language-sensitive relative time formatting.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an Unary operator?***\n\nThe 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 us see this behavior in an action.\n```javascript\nvar x = \"100\";\nvar y = + x;\nconsole.log(typeof x, typeof y); // string, number\n\nvar a = \"Hello\";\nvar b = + a;\nconsole.log(typeof a, typeof b, b); // string, number, NaN\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you sort elements in an array?***\n\nThe sort() method is used to sort the elements of an array in place and returns the sorted array. The example usage would be as below,\n```javascript\nvar months = [\"Aug\", \"Sep\", \"Jan\", \"June\"];\nmonths.sort();\nconsole.log(months); //  [\"Aug\", \"Jan\", \"June\", \"Sep\"]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of compareFunction while sorting arrays?***\n\nThe 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. Let us take an example to see the usage of compareFunction,\n```javascript\nlet numbers = [1, 2, 5, 3, 4];\nnumbers.sort((a, b) =\u003e b - a);\nconsole.log(numbers); // [5, 4, 3, 2, 1]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you reversing an array?***\n\nYou can use reverse() method is used reverse the elements in an array. This method is useful to sort an array in descending order. Let us see the usage of reverse() method in an example,\n```javascript\nlet numbers = [1, 2, 5, 3, 4];\nnumbers.sort((a, b) =\u003e b - a);\nnumbers.reverse();\nconsole.log(numbers); // [1, 2, 3, 4 ,5]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you find min and max value in an array?***\n\nYou can use `Math.min` and `Math.max` methods on array variable to find the minimum and maximum elements with in an array. Let us create two functions to find the min and max value with in an array,\n```javascript\nvar marks = [50, 20, 70, 60, 45, 30];\nfunction findMin(arr) {\n  return Math.min.apply(null, arr);\n}\nfunction findMax(arr) {\n  return Math.max.apply(null, arr);\n}\n\nconsole.log(findMin(marks));\nconsole.log(findMax(marks));\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you find min and max values without Math functions?***\n\nYou can write functions which loops through an array comparing each value with the lowest value or highest value to find the min and max values. Let us create those functions to find min an max values,\n```javascript\nvar marks = [50, 20, 70, 60, 45, 30];\nfunction findMin(arr) {\n  var length = arr.length\n  var min = Infinity;\n  while (length--) {\n    if (arr[length] \u003c min) {\n      min = arr[len];\n    }\n  }\n  return min;\n}\n\nfunction findMax(arr) {\n  var length = arr.length\n  var max = -Infinity;\n  while (len--) {\n    if (arr[length] \u003e max) {\n      max = arr[length];\n    }\n  }\n  return max;\n}\n\nconsole.log(findMin(marks));\nconsole.log(findMax(marks));\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an empty statement and purpose of it?***\n\nThe 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 is 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,\n```javascript\n// Initialize an array a\nfor(int i=0; i \u003c a.length; a[i++] = 0) ;\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you get meta data of a module?***\n\nYou can use `import.meta` object which is a meta-property exposing context-specific meta data to a JavaScript module. It contains information about the current module, such as module's URL. In browser, you might get different meta data than NodeJS.\n```javascript\n\u003cscript type=\"module\" src=\"welcome-module.js\"\u003e\u003c/script\u003e\nconsole.log(import.meta); // { url: \"file:///home/user/welcome-module.js\" }\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a comma operator?***\n\nThe 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,\n```javascript\nvar x = 1;\nx = (x++, x);\n\nconsole.log(x); // 2\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the advantage of a comma operator?***\n\nIt is normally used to include multiple expressions in a location that requires a single expression. One of the common usage of this comma operator is to supply multiple parameters in a `for` loop. For example, the below for loop uses multiple expressions in a single location using comma operator,\n```javascript\nfor (var a = 0, b =10; a \u003c= 10; a++, b--)\n```\nYou can also use the comma operator in a return statement where it process before returning.\n```javascript\nfunction myFunction() {\n  var a = 1;\n  return (a += 10, a); // 11\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain event delegation?***\n\nEvent delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM. The benefits of this technique are:\n\n* Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant.\n* There is no need to unbind the handler from elements that are removed and to bind the event for new elements.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Example of Prototypal Inheritance?***\n\nWe already have a build-in `Object.create`, but if you were to provide a polyfill for it, that might look like:\n\n```javascript\nif (typeof Object.create !== 'function') {\n  Object.create = function (parent) {\n    function Tmp() {}\n    Tmp.prototype = parent;\n    return new Tmp();\n  };\n}\n\nconst Parent = function() {\n  this.name = \"Parent\";\n}\n\nParent.prototype.greet = function() { console.log(\"hello from Parent\"); }\n\nconst child = Object.create(Parent.prototype);\n\nchild.cry = function() {\n  console.log(\"waaaaaahhhh!\");\n}\n\nchild.cry();\n// Outputs: waaaaaahhhh!\n\nchild.greet();\n// Outputs: hello from Parent\n```\n\nThings to note are:\n\n* `.greet` is not defined on the _child_, so the engine goes up the prototype chain and finds `.greet` off the inherited from _Parent_.\n* We need to call `Object.create` in one of following ways for the prototype methods to be inherited:\n  * Object.create(Parent.prototype);\n  * Object.create(new Parent(null));\n  * Object.create(objLiteral);\n  * Currently, `child.constructor` is pointing to the `Parent`:\n\n```javascript\nchild.constructor\nƒ () {\n  this.name = \"Parent\";\n}\nchild.constructor.name\n\"Parent\"\n```\n  * If we'd like to correct this, one option would be to do:\n\n```javascript\nfunction Child() {\n  Parent.call(this);\n  this.name = 'child';\n}\n\nChild.prototype = Parent.prototype;\nChild.prototype.constructor = Child;\n\nconst c = new Child();\n\nc.cry();\n// Outputs: waaaaaahhhh!\n\nc.greet();\n// Outputs: hello from Parent\n\nc.constructor.name;\n// Outputs: \"Child\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What do you think of AMD vs CommonJS?***\n\nBoth are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is obviously asynchronous. CommonJS is designed with server-side development in mind while AMD, with its support for asynchronous loading of modules, is more intended for browsers.\n\nI find AMD syntax to be quite verbose and CommonJS is closer to the style you would write import statements in other languages. Most of the time, I find AMD unnecessary, because if you served all your JavaScript into one concatenated bundle file, you wouldn't benefit from the async loading properties. Also, CommonJS syntax is closer to Node style of writing modules and there is less context-switching overhead when switching between client side and server side JavaScript development.\n\nI'm glad that with ES2015 modules, that has support for both synchronous and asynchronous loading, we can finally just stick to one approach. Although it hasn't been fully rolled out in browsers and in Node, we can always use transpilers to convert our code.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain why the following does not work as an IIFE: `function foo(){ }();`. What needs to be changed to properly make it an IIFE?***\n\nIIFE stands for Immediately Invoked Function Expressions. The JavaScript parser reads `function foo(){ }();` as `function foo(){ }` and `();`, where the former is a *function declaration* and the latter (a pair of parentheses) is an attempt at calling a function but there is no name specified, hence it throws `Uncaught SyntaxError: Unexpected token )`.\n\nHere are two ways to fix it that involves adding more parentheses: `(function foo(){ })()` and `(function foo(){ }())`. Statements that begin with `function` are considered to be *function declarations*; by wrapping this function within `()`, it becomes a *function expression* which can then be executed with the subsequent `()`. These functions are not exposed in the global scope and you can even omit its name if you do not need to reference itself within the body.\n\nYou might also use `void` operator: `void function foo(){ }();`. Unfortunately, there is one issue with such approach. The evaluation of given expression is always `undefined`, so if your IIFE function returns anything, you can not use it. An example:\n\n```js\n// Do not add JS syntax to this code block to prevent Prettier from formatting it.\nconst foo = void function bar() { return 'foo'; }();\n\nconsole.log(foo); // undefined\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between a variable that is: `null`, `undefined` or undeclared? How would you go about checking for any of these states?***\n\n**Undeclared** variables are created when you assign a value to an identifier that is not previously created using `var`, `let` or `const`. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a `ReferenceError` will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad just like how global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a `try`/`catch` block.\n\n```javascript\nfunction foo() {\n  x = 1; // Throws a ReferenceError in strict mode\n}\n\nfoo();\nconsole.log(x); // 1\n```\n\nA variable that is `undefined` is a variable that has been declared, but not assigned a value. It is of type `undefined`. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of `undefined`. To check for it, compare using the strict equality (`===`) operator or `typeof` which will give the `'undefined'` string. Note that you should not be using the abstract equality operator to check, as it will also return `true` if the value is `null`.\n\n```javascript\nvar foo;\nconsole.log(foo); // undefined\nconsole.log(foo === undefined); // true\nconsole.log(typeof foo === 'undefined'); // true\n\nconsole.log(foo == null); // true. Wrong, don't use this to check!\n\nfunction bar() {}\nvar baz = bar();\nconsole.log(baz); // undefined\n```\n\nA variable that is `null` will have been explicitly assigned to the `null` value. It represents no value and is different from `undefined` in the sense that it has been explicitly assigned. To check for `null,` simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator (`==`) to check, as it will also return `true` if the value is `undefined`.\n\n```javascript\nvar foo = null;\nconsole.log(foo === null); // true\nconsole.log(typeof foo === 'object'); // true\n\nconsole.log(foo == undefined); // true. Wrong, don't use this to check!\n```\n\nAs a personal habit, I never leave my variables undeclared or unassigned. I will explicitly assign `null` to them after declaring if I do not intend to use it yet. If you use a linter in your workflow, it will usually also be able to check that you are not referencing undeclared variables.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is a typical use case for anonymous functions?***\n\nThey can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.\n\n```javascript\n(function() {\n  // Some code here.\n})();\n```\n\nAs a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.\n\n```javascript\nsetTimeout(function() {\n  console.log('Hello world!');\n}, 1000);\n```\n\nArguments to functional programming constructs or Lodash (similar to callbacks).\n\n```javascript\nconst arr = [1, 2, 3];\nconst double = arr.map(function(el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you organize your code? (module pattern, classical inheritance?)***\n\nIn the past, I've used Backbone for my models which encourages a more OOP approach, creating Backbone models and attaching methods to them.\n\nThe module pattern is still great, but these days, I use React/Redux which utilize a single-directional data flow based on Flux architecture. I would represent my app's models using plain objects and write utility pure functions to manipulate these objects. State is manipulated using actions and reducers like in any other Redux application.\n\nI avoid using classical inheritance where possible. When and if I do, I stick to [these rules](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between host objects and native objects?***\n\nNative objects are objects that are part of the JavaScript language defined by the ECMAScript specification, such as `String`, `Math`, `RegExp`, `Object`, `Function`, etc.\n\nHost objects are provided by the runtime environment (browser or Node), such as `window`, `XMLHTTPRequest`, etc.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`?***\n\nThis question is pretty vague. My best guess at its intention is that it is asking about constructors in JavaScript. Technically speaking, `function Person(){}` is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.\n\n`var person = Person()` invokes the `Person` as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return `undefined` and that gets assigned to the variable intended as the instance.\n\n`var person = new Person()` creates an instance of the `Person` object using the `new` operator, which inherits from `Person.prototype`. An alternative would be to use `Object.create`, such as: `Object.create(Person.prototype)`.\n\n```javascript\nfunction Person(name) {\n  this.name = name;\n}\n\nvar person = Person('John');\nconsole.log(person); // undefined\nconsole.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined\n\nvar person = new Person('John');\nconsole.log(person); // Person { name: \"John\" }\nconsole.log(person.name); // \"john\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between `.call` and `.apply`?***\n\nBoth `.call` and `.apply` are used to invoke functions and the first parameter will be used as the value of `this` within the function. However, `.call` takes in comma-separated arguments as the next arguments while `.apply` takes in an array of arguments as the next argument. An easy way to remember this is C for `call` and comma-separated and A for `apply` and an array of arguments.\n\n```javascript\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain `Function.prototype.bind`?***\n\n[MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind):\n\n\u003e The `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.\n\nIn my experience, it is most useful for binding the value of `this` in methods of classes that you want to pass into other functions. This is frequently done in React components.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***When would you use `document.write()`?***\n\n`document.write()` writes a string of text to a document stream opened by `document.open()`. When `document.write()` is executed after the page has loaded, it will call `document.open` which clears the whole document (`\u003chead\u003e` and `\u003cbody\u003e` removed!) and replaces the contents with the given parameter value. Hence it is usually considered dangerous and prone to misuse.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between feature detection, feature inference, and using the UA string?***\n\n**Feature Detection**\n\nFeature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. For example:\n\n```javascript\nif ('geolocation' in navigator) {\n  // Can use navigator.geolocation\n} else {\n  // Handle lack of feature\n}\n```\n\n[Modernizr](https://modernizr.com/) is a great library to handle feature detection.\n\n**Feature Inference**\n\nFeature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:\n\n```javascript\nif (document.getElementsByTagName) {\n  element = document.getElementById(id);\n}\n```\n\nThis is not really recommended. Feature detection is more foolproof.\n\n**UA String**\n\nThis is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via `navigator.userAgent`. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain Ajax in detail?***\n\nAjax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly substitute use JSON instead of XML, due to the advantages of JSON being native to JavaScript.\n\nThe `XMLHttpRequest` API is frequently used for the asynchronous communication or these days, the `fetch` API.\n\n**Advantages**\n\n* Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.\n* Reduce connections to the server since scripts and stylesheets only have to be requested once.\n* State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded.\n* Basically most of the advantages of an SPA.\n\n**Disadvantages**\n\n* Dynamic webpages are harder to bookmark.\n* Does not work if JavaScript has been disabled in the browser.\n* Some webcrawlers do not execute JavaScript and would not see content that has been loaded by JavaScript.\n* Basically most of the disadvantages of an SPA.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain how JSONP works (and how It is not really Ajax)***\n\nJSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.\n\nJSONP works by making a request to a cross-origin domain via a `\u003cscript\u003e` tag and usually with a `callback` query parameter, for example: `https://example.com?callback=printData`. The server will then wrap the data within a function called `printData` and return it to the client.\n\n```html\n\u003c!-- https://mydomain.com --\u003e\n\u003cscript\u003e\nfunction printData(data) {\n  console.log(`My name is ${data.name}!`);\n}\n\u003c/script\u003e\n\n\u003cscript src=\"https://example.com?callback=printData\"\u003e\u003c/script\u003e\n```\n\n```javascript\n// File loaded from https://example.com?callback=printData\nprintData({ name: 'Yang Shun' });\n```\n\nThe client has to have the `printData` function in its global scope and the function will be executed by the client when the response from the cross-origin domain is received.\n\nJSONP can be unsafe and has some security implications. As JSONP is really JavaScript, it can do everything else JavaScript can do, so you need to trust the provider of the JSONP data.\n\nThese days, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) is the recommended approach and JSONP is seen as a hack.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between an \"attribute\" and a \"property\"?***\n\nAttributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: `\u003cinput type=\"text\" value=\"Hello\"\u003e`.\n\n```javascript\nconst input = document.querySelector('input');\nconsole.log(input.getAttribute('value')); // Hello\nconsole.log(input.value); // Hello\n```\n\nBut after you change the value of the text field by adding \"World!\" to it, this becomes:\n\n```javascript\nconsole.log(input.getAttribute('value')); // Hello\nconsole.log(input.value); // Hello World!\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why is extending built-in JavaScript objects not a good idea?***\n\nExtending a built-in/native JavaScript object means adding properties/functions to its `prototype`. 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 `Array.prototype` by adding the same `contains` method, the implementations will overwrite each other and your code will break if the behavior of these two methods is not the same.\n\nThe 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.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Difference between document `load` event and document `DOMContentLoaded` event?***\n\nThe `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.\n\n`window`'s `load` event is only fired after the DOM and all dependent resources and assets have loaded.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between `==` and `===`?***\n\n`==` is the abstract equality operator while `===` is the strict equality operator. The `==` operator will compare for equality after doing any necessary type conversions. The `===` operator will not do type conversion, so if two values are not the same type `===` will simply return `false`. When using `==`, funky things can happen, such as:\n\n```javascript\n1 == '1'; // true\n1 == [1]; // true\n1 == true; // true\n0 == ''; // true\n0 == '0'; // true\n0 == false; // true\n```\n\nMy advice is never to use the `==` operator, except for convenience when comparing against `null` or `undefined`, where `a == null` will return `true` if `a` is `null` or `undefined`.\n\n```javascript\nvar a = null;\nconsole.log(a == null); // true\nconsole.log(a == undefined); // true\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain the same-origin policy with regards to JavaScript?***\n\nThe same-origin policy prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why is it called a Ternary expression, what does the word \"Ternary\" indicate?***\n\n\"Ternary\" indicates three, and a ternary expression accepts three operands, the test condition, the \"then\" expression and the \"else\" expression. Ternary expressions are not specific to JavaScript and I'm not sure why it is even in this list.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is `\"use strict\";`? What are the advantages and disadvantages to using it?***\n\n'use strict' 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.\n\nAdvantages:\n\n* Makes it impossible to accidentally create global variables.\n* Makes assignments which would otherwise silently fail to throw an exception.\n* Makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect).\n* Requires that function parameter names be unique.\n* `this` is undefined in the global context.\n* It catches some common coding bloopers, throwing exceptions.\n* It disables features that are confusing or poorly thought out.\n\nDisadvantages:\n\n* Many missing features that some developers might be used to.\n* No more access to `function.caller` and `function.arguments`.\n* Concatenation of scripts written in different strict modes might cause issues.\n\nOverall, I think the benefits outweigh the disadvantages, and I never had to rely on the features that strict mode blocks. I would recommend using strict mode.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?***\n\nEvery script has access to the global scope, and if everyone uses the global namespace to define their variables, collisions will likely occur. Use the module pattern (IIFEs) to encapsulate your variables within a local namespace.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why would you use something like the `load` event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?***\n\nThe `load` event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.\n\nThe DOM event `DOMContentLoaded` will fire after the DOM for the page has been constructed, but do not wait for other resources to finish loading. This is preferred in certain cases when you do not need the full page to be loaded before initializing.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the extent of your experience with Promises and/or their polyfills?***\n\nPossess working knowledge of it. A promise is an object that may produce a single value sometime in the future: either a resolved value or a reason that It is not resolved (e.g., a network error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.\n\nSome common polyfills are `$.deferred`, Q and Bluebird but not all of them comply with the specification. ES2015 supports Promises out of the box and polyfills are typically not needed these days.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the pros and cons of using Promises instead of callbacks?***\n\n**Pros**\n\n* Avoid callback hell which can be unreadable.\n* Makes it easy to write sequential asynchronous code that is readable with `.then()`.\n* Makes it easy to write parallel asynchronous code with `Promise.all()`.\n* With promises, these scenarios which are present in callbacks-only coding, will not happen:\n  * Call the callback too early\n  * Call the callback too late (or never)\n  * Call the callback too few or too many times\n  * Fail to pass along any necessary environment/parameters\n  * Swallow any errors/exceptions that may happen\n\n**Cons**\n\n* Slightly more complex code (debatable).\n* In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?***\n\nSome examples of languages that compile to JavaScript include CoffeeScript, Elm, ClojureScript, PureScript, and TypeScript.\n\nAdvantages:\n\n* Fixes some of the longstanding problems in JavaScript and discourages JavaScript anti-patterns.\n* Enables you to write shorter code, by providing some syntactic sugar on top of JavaScript, which I think ES5 lacks, but ES2015 is awesome.\n* Static types are awesome (in the case of TypeScript) for large projects that need to be maintained over time.\n\nDisadvantages:\n\n* Require a build/compile process as browsers only run JavaScript and your code will need to be compiled into JavaScript before being served to browsers.\n* Debugging can be a pain if your source maps do not map nicely to your pre-compiled source.\n* Most developers are not familiar with these languages and will need to learn it. There's a ramp up cost involved for your team if you use it for your projects.\n* Smaller community (depends on the language), which means resources, tutorials, libraries, and tooling would be harder to find.\n* IDE/editor support might be lacking.\n* These languages will always be behind the latest JavaScript standard.\n* Developers should be cognizant of what their code is being compiled to — because that is what would actually be running, and that is what matters in the end.\n\nPractically, ES2015 has vastly improved JavaScript and made it much nicer to write. I don't really see the need for CoffeeScript these days.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What tools and techniques do you use for debugging JavaScript code?***\n\n* React and Redux\n  * [React Devtools](https://github.com/facebook/react-devtools)\n  * [Redux Devtools](https://github.com/gaearon/redux-devtools)\n* Vue\n  * [Vue Devtools](https://github.com/vuejs/vue-devtools)\n* JavaScript\n  * [Chrome Devtools](https://hackernoon.com/twelve-fancy-chrome-devtools-tips-dc1e39d10d9d)\n  * `debugger` statement\n  * Good old `console.log` debugging\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What language constructions do you use for iterating over object properties and array items?***\n\nFor objects:\n\n* `for-in` loops - `for (var property in obj) { console.log(property); }`. However, this will also iterate through its inherited properties, and you will add an `obj.hasOwnProperty(property)` check before using it.\n* `Object.keys()` - `Object.keys(obj).forEach(function (property) { ... })`. `Object.keys()` is a static method that will lists all enumerable properties of the object that you pass it.\n* `Object.getOwnPropertyNames()` - `Object.getOwnPropertyNames(obj).forEach(function (property) { ... })`. `Object.getOwnPropertyNames()` is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it.\n\nFor arrays:\n\n* `for` loops - `for (var i = 0; i \u003c arr.length; i++)`. The common pitfall here is that `var` is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces `let` which has block scope and it is recommended to use that instead. So this becomes: `for (let i = 0; i \u003c arr.length; i++)`.\n* `forEach` - `arr.forEach(function (el, index) { ... })`. This construct can be more convenient at times because you do not have to use the `index` if all you need is the array elements. There are also the `every` and `some` methods which will allow you to terminate the iteration early.\n* `for-of` loops - `for (let elem of arr) { ... }`. ES6 introduces a new loop, the `for-of` loop, that allows you to loop over objects that conform to the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) such as `String`, `Array`, `Map`, `Set`, etc. It combines the advantages of the `for` loop and the `forEach()` method. The advantage of the `for` loop is that you can break from it, and the advantage of `forEach()` is that it is more concise than the `for` loop because you don't need a counter variable. With the `for-of` loop, you get both the ability to break from a loop and a more concise syntax.\n\nMost of the time, I would prefer the `.forEach` method, but it really depends on what you are trying to do. Before ES6, we used `for` loops when we needed to prematurely terminate the loop using `break`. But now with ES6, we can do that with `for-of` loops. I would use `for` loops when I need even more flexibility, such as incrementing the iterator more than once per loop.\n\nAlso, when using the `for-of` loop, if you need to access both the index and value of each array element, you can do so with the ES6 Array `entries()` method and destructuring:\n\n```javascript\nconst arr = ['a', 'b', 'c'];\n\nfor (let [index, elem] of arr.entries()) {\n  console.log(index, ': ', elem);\n}\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain the difference between mutable and immutable objects?***\n\nImmutability is a core principle in functional programming, and has lots to offer to object-oriented programs as well. A mutable object is an object whose state can be modified after it is created. An immutable object is an object whose state cannot be modified after it is created.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is an example of an immutable object in JavaScript?***\n\nIn JavaScript, some built-in types (numbers, strings) are immutable, but custom objects are generally mutable.\n\nSome built-in immutable JavaScript objects are `Math`, `Date`.\n\nHere are a few ways to add/simulate immutability on plain JavaScript objects.\n\n**Object Constant Properties**\n\nBy combining `writable: false` and `configurable: false`, you can essentially create a constant (cannot be changed, redefined or deleted) as an object property, like:\n\n```javascript\nlet myObject = {};\nObject.defineProperty(myObject, 'number', {\n  value: 42,\n  writable: false,\n  configurable: false,\n});\nconsole.log(myObject.number); // 42\nmyObject.number = 43;\nconsole.log(myObject.number); // 42\n```\n\n**Prevent Extensions**\n\nIf you want to prevent an object from having new properties added to it, but otherwise leave the rest of the object's properties alone, call `Object.preventExtensions(...)`:\n\n```javascript\nvar myObject = {\n  a: 2\n};\n\nObject.preventExtensions(myObject);\n\nmyObject.b = 3;\nmyObject.b; // undefined\n```\n\nIn non-strict mode, the creation of `b` fails silently. In strict mode, it throws a `TypeError`.\n\n**Seal**\n\n`Object.seal()` creates a \"sealed\" object, which means it takes an existing object and essentially calls `Object.preventExtensions()` on it, but also marks all its existing properties as `configurable: false`.\n\nSo, not only can you not add any more properties, but you also cannot reconfigure or delete any existing properties (though you can still modify their values).\n\n**Freeze**\n\n`Object.freeze()` creates a frozen object, which means it takes an existing object and essentially calls `Object.seal()` on it, but it also marks all \"data accessor\" properties as writable:false, so that their values cannot be changed.\n\nThis approach is the highest level of immutability that you can attain for an object itself, as it prevents any changes to the object or to any of its direct properties (though, as mentioned above, the contents of any referenced other objects are unaffected).\n\n```javascript\nvar immutable = Object.freeze({});\n```\n\nFreezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. `Object.freeze()` preserves the enumerability, configurability, writability and the prototype of the object. It returns the passed object and does not create a frozen copy.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How can you achieve immutability in your own code?***\n\nOne way to achieve immutability is to use libraries like [immutable.js](http://facebook.github.io/immutable-js/), [mori](https://github.com/swannodette/mori) or [immer](https://github.com/immerjs/immer).\n\nThe alternative is to use `const` declarations combined with the techniques mentioned above for creation. For \"mutating\" objects, use the spread operator, `Object.assign`, `Array.concat()`, etc., to create new objects instead of mutate the original object.\n\nExamples:\n\n```javascript\n// Array Example\nconst arr = [1, 2, 3];\nconst newArr = [...arr, 4]; // [1, 2, 3, 4]\n\n// Object Example\nconst human = Object.freeze({race: 'human'});\nconst john = { ...human, name: 'John' }; // {race: \"human\", name: \"John\"}\nconst alienJohn = { ...john, race: 'alien' }; // {race: \"alien\", name: \"John\"}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain the difference between synchronous and asynchronous functions?***\n\nSynchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. In this case, the program is evaluated exactly in order of the statements and execution of the program is paused if one of the statements take a very long time.\n\nAsynchronous functions usually accept a callback as a parameter and execution continue on 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).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is event loop? What is the difference between call stack and task queue?***\n\nThe event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the task queue. If the call stack is empty and there are callback functions in the task queue, a function is dequeued and pushed onto the call stack to be executed.\n\nIf you haven't already checked out Philip Robert's [talk on the Event Loop](https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html), you should. It is one of the most viewed videos on JavaScript.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}`?***\n\nThe former is a function declaration while the latter 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 variables). For more explanation on hoisting, refer to the question above [on hoisting](#explain-hoisting). If you try to invoke a function expression before it is defined, you will get an `Uncaught TypeError: XXX is not a function` error.\n\n**Function Declaration**\n\n```javascript\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\n**Function Expression**\n\n```javascript\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function() {\n  console.log('FOOOOO');\n};\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the differences between variables created using `let`, `var` or `const`?***\n\nVariables declared using the `var` keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. `let` and `const` are _block scoped_, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).\n\n```javascript\nfunction foo() {\n  // All variables are accessible within functions.\n  var bar = 'bar';\n  let baz = 'baz';\n  const qux = 'qux';\n\n  console.log(bar); // bar\n  console.log(baz); // baz\n  console.log(qux); // qux\n}\n\nconsole.log(bar); // ReferenceError: bar is not defined\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\n```javascript\nif (true) {\n  var bar = 'bar';\n  let baz = 'baz';\n  const qux = 'qux';\n}\n\n// var declared variables are accessible anywhere in the function scope.\nconsole.log(bar); // bar\n// let and const defined variables are not accessible outside of the block they were defined in.\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\n`var` allows variables to be hoisted, meaning they can be referenced in code before they are declared. `let` and `const` will not allow this, instead throwing an error.\n\n```javascript\nconsole.log(foo); // undefined\nvar foo = 'foo';\n\nconsole.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization\nlet baz = 'baz';\n\nconsole.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization\nconst bar = 'bar';\n```\n\nRedeclaring a variable with `var` will not throw an error, but 'let' and 'const' will.\n\n```javascript\nvar foo = 'foo';\nvar foo = 'bar';\nconsole.log(foo); // \"bar\"\n\nlet baz = 'baz';\nlet baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared\n```\n\n`let` and `const` differ in that `let` allows reassigning the variable's value while `const` does not.\n\n```javascript\n// This is fine.\nlet foo = 'foo';\nfoo = 'bar';\n\n// This causes an exception.\nconst baz = 'baz';\nbaz = 'qux';\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the definition of a higher-order function?***\n\nA 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. Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is `map`, which takes an array and a function as arguments. `map` 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 `forEach`, `filter`, and `reduce`. 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. `Function.prototype.bind` is one such example in JavaScript.\n\n**Map**\n\nLet say we have an array of names which we need to transform each string to uppercase.\n\n```javascript\nconst names = ['irish', 'daisy', 'anna'];\n```\n\nThe imperative way will be as such:\n\n```javascript\nconst transformNamesToUppercase = function(names) {\n  const results = [];\n  for (let i = 0; i \u003c names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n};\ntransformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']\n```\n\nUse `.map(transformerFn)` makes the code shorter and more declarative.\n\n```javascript\nconst transformNamesToUppercase = function(names) {\n  return names.map(name =\u003e name.toUpperCase());\n};\ntransformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can you give an example of a curry function and why this syntax offers an advantage?***\n\nCurrying is a pattern where a function with more than one parameter is broken into multiple functions that, when called in series, will accumulate all of the required parameters one at a time. This technique can be useful for making code written in a functional style easier to read and compose. It is important to note that for a function to be curried, it needs to start out as one function, then broken out into a sequence of functions that each accepts one parameter.\n\n```javascript\nfunction curry(fn) {\n  if (fn.length === 0) {\n    return fn;\n  }\n\n  function _curried(depth, args) {\n    return function(newArgument) {\n      if (depth - 1 === 0) {\n        return fn(...args, newArgument);\n      }\n      return _curried(depth - 1, [...args, newArgument]);\n    };\n  }\n\n  return _curried(fn.length, []);\n}\n\nfunction add(a, b) {\n  return a + b;\n}\n\nvar curriedAdd = curry(add);\nvar addFive = curriedAdd(5);\n\nvar result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How can you share code between files?***\n\nThis depends on the JavaScript environment.\n\nOn the client (browser environment), as long as the variables/functions are declared in the global scope (`window`), all scripts can refer to them. Alternatively, adopt the Asynchronous Module Definition (AMD) via RequireJS for a more modular approach.\n\nOn the server (Node.js), the common way has been to use CommonJS. Each file is treated as a module and it can export variables and functions by attaching them to the `module.exports` object.\n\nES2015 defines a module syntax which aims to replace both AMD and CommonJS. This will eventually be supported in both browser and Node environments.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why you might want to create static class members?***\n\nStatic class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it. Static properties are typically configuration variables and static methods are usually pure utility functions which do not depend on the state of the instance.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between `undefined` and `not defined` in JavaScript?***\n\nIn JavaScript if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error `var name is not defined` and the script will stop executing thereafter. But If you use `typeof undeclared_variable` then it will return `undefined`.\n\nBefore starting further discussion Let us understand the difference between declaration and definition.\n\n`var x` is a declaration because you are not defining what value it holds yet, but you are declaring its existence and the need for memory allocation.\n\n```javascript\nvar x; // declaring x\nconsole.log(x); // output: undefined\n```\n\n`var x = 1` is both declaration and definition (also we can say we are doing initialisation), Here declaration and assignment of value happen inline for variable x, In JavaScript every variable declaration and function declaration brings to the top of its current scope in which It is declared then assignment happen in order this term is called `hoisting`.\n\nA variable can be declared but not defined. When we try to access it, It will result `undefined`.\n\n```javascript\nvar x; // Declaration\ntypeof x === 'undefined'; // Will return true\n```\n\nA variable can be neither declared nor defined. When we try to reference such variable then the result will be `not defined`.\n\n```javascript\nconsole.log(y);  // Output: ReferenceError: y is not defined\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***For which value of `x` the results of the following statements are not the same?***\n\n```javascript\n//  if( x \u003c= 100 ) {...}\nif( !(x \u003e 100) ) {...}\n```\n`NaN \u003c= 100` is `false` and `NaN \u003e 100` is also `false`, so if the\nvalue of `x` is `NaN`, the statements are not the same.\n\nThe same holds true for any value of x that being converted to Number, returns NaN, e.g.: `undefined`, `[1,2,5]`, `{a:22}` , etc.\n\nThis is why you need to pay attention when you deal with numeric variables. `NaN` can’t be equal, less than or more than any other numeric value, so the only reliable way to check if the value is `NaN`, is to use `isNaN()` function.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the drawback of declaring methods directly in JavaScript objects?***\n\nOne of the drawback of declaring methods directly in JavaScript objects is that they are very memory inefficient.  When you do that, a new copy of the method is created for each instance of an object. Let us see it on example:\n\n```javascript\nvar Employee = function (name, company, salary) {\n  this.name = name || \"\";       \n  this.company = company || \"\";\n  this.salary = salary || 5000;\n\n  // We can create a method like this:\n  this.formatSalary = function () {\n      return \"$ \" + this.salary;\n  };\n};\n\n// we can also create method in Employee's prototype:\nEmployee.prototype.formatSalary2 = function() {\n    return \"$ \" + this.salary;\n}\n\n//creating objects\nvar emp1 = new Employee('Yuri Garagin', 'Company 1', 1000000);\nvar emp2 = new Employee('Dinesh Gupta', 'Company 2', 1039999);\nvar emp3 = new Employee('Erich Fromm', 'Company 3', 1299483);\n```\n\nHere each instance variable `emp1`, `emp2`, `emp3` has own copy of `formatSalary` method. However the `formatSalary2` will only be added once to an object `Employee.prototype`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is “closure” in javascript? Can you provide an example?***\n\nA closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope.\n\nThe closure has access to the variable in three scopes:\n- Variable declared in his own scope\n- Variable declared in parent function scope\n- Variable declared in the global namespace\n\n```javascript\nvar globalVar = \"abc\";\n\n// Parent self invoking function\n(function outerFunction (outerArg) { // begin of scope outerFunction\n  // Variable declared in outerFunction function scope\n  var outerFuncVar = 'x';    \n  // Closure self-invoking function\n  (function innerFunction (innerArg) { // begin of scope innerFunction\n    // variable declared in innerFunction function scope\n    var innerFuncVar = \"y\";\n    console.log(         \n      \"outerArg = \" + outerArg + \"\\n\" +\n      \"outerFuncVar = \" + outerFuncVar + \"\\n\" +\n      \"innerArg = \" + innerArg + \"\\n\" +\n      \"innerFuncVar = \" + innerFuncVar + \"\\n\" +\n      \"globalVar = \" + globalVar);\n  // end of scope innerFunction\n  })(5); // Pass 5 as parameter\n// end of scope outerFunction\n})(7); // Pass 7 as parameter\n```\n\n`innerFunction` is closure which is defined inside `outerFunction` and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside the function as closure has access to the variable which is declared in `global namespace`.\n\nOutput of above code would be:\n\n```javascript\nouterArg = 7\nouterFuncVar = x\ninnerArg = 5\ninnerFuncVar = y\nglobalVar = abc\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write a mul function which will work properly when invoked with following syntax?***\n\n```javascript\nconsole.log(mul(2)(3)(4)); // output : 24\nconsole.log(mul(4)(3)(4)); // output : 48\n```\n\n\nBelow is the code followed by the explanation of how it works:\n\n```javascript\nfunction mul (x) {\n  return function (y) { // anonymous function\n    return function (z) { // anonymous function\n      return x * y * z;\n    };\n  };\n}\n```\n\nHere the `mul` function accepts the first argument and returns the anonymous function which takes the second parameter and returns the anonymous function which takes the third parameter and returns the multiplication of arguments which is being passed in successive\n\nIn Javascript function defined inside has access to outer function variable and function is the first class object so it can be returned by the function as well and passed as an argument in another function.\n- A function is an instance of the Object type\n- A function can have properties and has a link back to its constructor method\n- A function can be stored as variable\n- A function can be pass as a parameter to another function\n- A function can be returned from another function\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to empty an array in JavaScript?***\n\nFor instance:\n\n```javascript\nvar arrayList =  ['a', 'b', 'c', 'd', 'e', 'f'];\n```\n\nHow can we empty the array above?\n\nThere are a couple of ways by which we can empty an array, So Let us discuss all the possible way by which we can empty an array.\n\n**Method 1**\n\n```javascript\narrayList = [];\n```\n\nThe code above will set the variable `arrayList` to a new empty array. This is recommended if you don't have **references to the original array** `arrayList` anywhere else because It will actually create a new empty array. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged, Only use this way if you have only referenced the array by its original variable `arrayList`.\n\nFor instance:\n\n```javascript\nvar arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array\nvar anotherArrayList = arrayList;  // Referenced arrayList by another variable\narrayList = []; // Empty the array\nconsole.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f']\n```\n\n**Method 2**\n\n```javascript\narrayList.length = 0;\n```\n\nThe code above will clear the existing array by setting its length to 0. This way of emptying an array will also update all the reference variables that point to the original array. \n\nFor instance:\n\n```javascript\nvar arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array\nvar anotherArrayList = arrayList;  // Referenced arrayList by another variable\narrayList.length = 0; // Empty the array by setting length to 0\nconsole.log(anotherArrayList); // Output []\n```\n\n**Method 3**\n\n```javascript\narrayList.splice(0, arrayList.length);\n```\n\nAbove implementation will also work perfectly. This way of empty the array will also update all the references of the original array.\n\n```javascript\nvar arrayList = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array\nvar anotherArrayList = arrayList;  // Referenced arrayList by another variable\narrayList.splice(0, arrayList.length); // Empty the array by setting length to 0\nconsole.log(anotherArrayList); // Output []\n```\n\n**Method 4**\n\n```javascript\nwhile(arrayList.length) {\n  arrayList.pop();\n}\n```\nAbove implementation can also empty the array. But not recommended to use often.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to check if an object is an array or not?***\n\nThe best way to find whether an object is instance of a particular class or not using `toString` method from `Object.prototype`\n\n```javascript\nvar arrayList = [1 , 2, 3];\n```\n\nOne of the best use cases of type checking of an object is when we do method overloading in JavaScript. To understand this, Let us say we have a method called `greet` which can take a single string and also a list of strings. To make our `greet` method workable in both situation we need to know what kind of parameter is being passed: is it single value or list of values?\n\n```javascript\nfunction greet(param) {\n  if() {\n    // here have to check whether param is array or not\n  }\n  else {\n  }\n}\n```\n\nHowever, in the above implementation it might not necessary to check the type of the array, we can check for single value string and put array logic code in else block, let see below code for the same.\n\n```javascript\n function greet(param) {\n   if(typeof param === 'string') {\n   }\n   else {\n     // If param is of type array then this block of code would execute\n   }\n }\n```\n\nNow it is fine we can go with the previous two implementations, but when we have a situation like a parameter can be `single value`, `array`, and `object` type then we will be in trouble.\n\nComing back to checking the type of an object, As we mentioned that we can use `Object.prototype.toString`\n\n```javascript\nif(Object.prototype.toString.call(arrayList) === '[object Array]') {\n  console.log('Array!');\n}\n```\n\nIf you are using `jQuery` then you can also used jQuery `isArray` method:\n\n```javascript\nif($.isArray(arrayList)) {\n  console.log('Array');\n} else {\n  console.log('Not an array');\n}\n```\n\nFYI jQuery uses `Object.prototype.toString.call` internally to check whether an object is an array or not.\n\nIn modern browser, you can also use:\n\n```javascript\nArray.isArray(arrayList);\n```\n\n`Array.isArray` is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is `undefined x 1` in JavaScript?***\n\n```javascript\nvar trees = [\"redwood\", \"bay\", \"cedar\", \"oak\", \"maple\"];\ndelete trees[3];\n```\n\n - When you run the code above and do `console.log(trees);` in chrome developer console then you will get `[\"redwood\", \"bay\", \"cedar\", undefined × 1, \"maple\"]`.\n - In the recent versions of Chrome you will see the word `empty` of `undefined x 1`.\n - When you run the same code in Firefox browser console then you will get `[\"redwood\", \"bay\", \"cedar\", undefined, \"maple\"]`\n  \nClearly we can see that Chrome has its own way of displaying uninitialized index in arrays. However when you check `trees[3] === undefined` in any browser you will get similar output as `true`.\n\n*Note: Please remember that you need not check for the uninitialized index of the array in  `trees[3] === 'undefined × 1'` it will give an error because `'undefined × 1'` this is just way of displaying an uninitialized index of an array in chrome*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between declaring a function in the formats listed below?***\n\n```javascript\nvar foo = function() {\n  // Some code\n}\n```\n\n```javascript\nfunction bar () {\n  // Some code\n}\n```\n\n\nThe main difference is that function `foo` is defined at `run-time` and is called a function expression, whereas function `bar` is defined at `parse time` and is called a function statement. To understand it better, Let us take a look at the code below :\n\n```javascript\n// Run-Time function declaration\n  foo(); // Call foo function here, It will give an error\n  var foo = function() {\n    console.log(\"Hi I am inside Foo\");\n  };\n```\n\n```javascript\n// Parse-Time function declaration\nbar(); // Call bar function here, It will not give an Error\nfunction bar() {\n  console.log(\"Hi I am inside Foo\");\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***In which case the function definition is not hoisted in JavaScript?***\n\nLet us take the following **function expression**\n\n```javascript\n var foo = function foo() {\n     return 12;\n }\n```\n\nIn JavaScript `var`-declared variables and functions are `hoisted`. Let us take function `hoisting` first. Basically, the JavaScript interpreter looks ahead to find all the variable declaration and hoists them to the top of the function where It is declared. For example:\n\n```javascript\nfoo(); // Here foo is still undefined\nvar foo = function foo() {\n  return 12;\n};\n```\n\nThe code above behind the scene look something like this:\n\n```javascript\nvar foo = undefined;\nfoo(); // Here foo is undefined\nfoo = function foo() {\n  // Some code stuff\n}\n```\n\n```javascript\nvar foo = undefined;\nfoo = function foo() {\n  // Some code stuff\n}\nfoo(); // Now foo is defined here\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between `typeof` and `instanceof`?***\n\n`typeof` is an operator that returns a string with the type of whatever you pass.\n\nThe `typeof` operator checks if a value belongs to one of the seven basic types: `number`, `string`, `boolean`, `object`, `function`, `undefined` or `Symbol`.\n\n`typeof(null)` will return `object`.\n\n`instanceof` is much more intelligent: it works on the level of prototypes. In particular, it tests to see if the right operand appears anywhere in the prototype chain of the left. `instanceof` doesn’t work with primitive types. It `instanceof` operator checks the current object and returns true if the object is of the specified type, for example:\n\n```javascript\nvar dog = new Animal();\ndog instanceof Animal; // Output : true\n```\n\nHere `dog instanceof Animal` is true since `dog` inherits from `Animal.prototype`\n\n```javascript\nvar name = new String(\"xyz\");\nname instanceof String; // Output : true\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Calculate the length of the associative array?***\n\n```javascript\nvar counterArray = {\n  A : 3,\n  B : 4\n};\ncounterArray[\"C\"] = 1;\n```\n\nFirst of all, in case of JavaScript an associative array is the same as an object. Secondly, even though is no built-in function or property available to calculate the length/size an object, we can write such function ourselves.\n\n**Method 1**\n\n`Object` has `keys` method which can we used to calculate the length of object.\n\n```javascript\nObject.keys(counterArray).length; // Output 3\n```\n\n**Method 2**\n\nWe can also calculate the length of object by iterating through the object and by doing a count of own property of object. This way we will ignoge the properties that came from the object's prototype chain:  \n\n```javascript\nfunction getLength(object) {\n  var count = 0;\n  for(key in object) {\n    // hasOwnProperty method check own property of object\n    if(object.hasOwnProperty(key)) count++;\n  }\n  return count;\n}\n```\n\n**Method 3**\n\nAll modern browsers (including IE9+) support the [`getOwnPropertyNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) method, so we can calculate the length using the following code: \n\n```javascript\nObject.getOwnPropertyNames(counterArray).length; // Output 3\n```\n\n**Method 4**\n\n[Underscore](https://underscorejs.org/#size) and [lodash](https://lodash.com/docs/4.17.10#size) libraries have the method `size` dedicated to calculate the object length. We don't recommend to include one of these libraries just to use the `size` method, but if It is already used in your project - why not? \n\n```javascript\n_.size({one: 1, two: 2, three: 3});\n=\u003e 3\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Difference between `Function`, `Method` and `Constructor` calls in JavaScript?***\n\nIf your are familiar with Object-oriented programming, More likely familiar to thinking of functions, methods, and class constructors as three separate things. But In JavaScript, these are just three different usage patterns of one single construct.\n\nfunctions : The simplest usages of function call:\n\n```javascript\nfunction helloWorld(name) {\n  return \"hello world, \" + name;\n}\n\nhelloWorld(\"JS Geeks\"); // \"hello world JS Geeks\"\n```\n\nMethods in JavaScript are nothing more than object properties that are functions.\n\n```javascript\nvar obj = {\n  helloWorld : function() {\n    return \"hello world, \" + this.name;\n  },\n  name: 'John Carter'\n}\nobj.helloWorld(); // // \"hello world John Carter\"\n```\n\nNotice how `helloWorld` refer to `this` properties of obj. Here It is clear or you might have already understood that `this` gets bound to `obj`. But the interesting point that we can copy a reference to the same function `helloWorld` in another object and get a difference answer. Let see:\n\n```javascript\nvar obj2 = {\n  helloWorld : obj.helloWorld,\n  name: 'John Doe'\n}\nobj2.helloWorld(); // \"hello world John Doe\"\n```\n\nYou might be wonder what exactly happens in a method call here. Here we call the expression itself determine the binding of this `this`, The expression `obj2.helloWorld()` looks up the `helloWorld` property of obj and calls it with receiver object `obj2`.\n\nThe third use of functions is as constructors. Like function and method, `constructors` are defined with function.\n\n```javascript\nfunction Employee(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nvar emp1 = new Employee('John Doe', 28);\nemp1.name; // \"John Doe\"\nemp1.age; // 28\n```\n\nUnlike function calls and method calls, a constructor call `new Employee('John Doe', 28)` creates a brand new object and passes it as the value of `this`, and implicitly returns the new object as its result.\n\nThe primary role of the constructor function is to initialize the object.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are Service Workers and when can you use them?***\n\nIt is a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First.\n\nService Workers actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.\n\nAs of 2017, Service Workers are not supported in IE and Safari.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between a method and a function in javascript?***\n\nIn JS, that difference is quite subtle. A function is a piece of code that is called by name and function itself not associated with any object and not defined inside any object. It can be passed data to operate on (i.e. parameter) and can optionally return data (the return value).\n\n```javascript\n// Function statement\nfunction myFunc() {\n  // Do some stuff;\n}\n\n// Calling the function\nmyFunc();\n```\n\nHere myFunc() function call is not associated with object hence not invoked through any object.\n\nA function can take a form of immediately invoked function expression (IIFE):\n\n```javascript\n\n// Anonymous Self-invoking Function\n(function() {\n  // Do some stuff;\n})();\n```\n\nFinally there are also arrow functions: \n\n```javascript\nconst myFunc = arg =\u003e {\n    console.log(\"hello\", arg)\n} \n```\n\nA method is a piece of code that is called by its name and that is associated with the object. Methods are functions. When you call a method like this `obj1.myMethod()`, the reference to `obj1` gets assigned (bound) to `this` variable. In other words, the value of `this` will be `obj1` inside `myMethod`. \n\nHere are some examples of methods: \n\n**Example 1**\n\n```javascript\nvar obj1 = {\n  attribute: \"xyz\",\n  myMethod: function () {  // Method\n    console.log(this.attribute);\n  }\n};\n\n// Call the method\nobj1.myMethod();\n```\n\nHere `obj1` is an object and `myMethod` is a method which is associated with `obj1`.\n\n**Example 2**\n\nIn ES6 we have classes. There the methods will look like this:\n\n```javascript\nclass MyAwesomeClass {\n  myMethod() {\n    console.log(\"hi there\");\n  }\n}\n\nconst obj1 = new MyAwesomeClass();\nobj1.myMethod();\n```\n\nUnderstand: the method is not some kind of special type of a function, and It is not about how you declare a function. It is the way we **call** a function. Look at that: \n\n```javascript\nvar obj1 = {\n  prop1: \"buddy\"\n}; \nvar myFunc = function () {\n  console.log(\"Hi there\", this);\n};\n// Let us call myFunc as a function: \nmyFunc(); // will output \"Hi there undefined\" or \"Hi there Window\"\n \nobj1.myMethod = myFunc;\n//now we're calling myFunc as a method of obj1, so this will point to obj1\nobj1.myMethod(); // will print \"Hi there\" following with obj1. \n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is IIFE (Immediately Invoked Function Expression) and how it can be useful?***\n\nIIFE a function that runs as soon as It is defined. Usually It is anonymous (doesn't have a function name), but it also can be named. Here's an example of IIFE:\n\n```javascript\n(function() {\n  console.log(\"Hi, I'm IIFE!\");\n})();\n// outputs \"Hi, I'm IIFE!\"\n```\n\nSo, here's how it works. Remember the difference between function statements (`function a () {}`) and function expressions (`var a = function() {}`)? So, IIFE is a function expression. To make it an expression we surround our function declaration into the parens. We do it to explicitly tell the parser that It is an expression, not a statement (JS doesn't allow statements in parens).\n\nAfter the function you can see the two `()` braces, this is how we run the function we just declared. \n\nThat's it. The rest is details.  \n- The function inside IIFE doesn't have to be anonymous. This one will work perfectly fine and will help to detect your function in a stacktrace during debugging: \n  ```javascript\n  (function myIIFEFunc() {\n    console.log(\"Hi, I'm IIFE!\");\n  })();\n  // outputs \"Hi, I'm IIFE!\"\n  ```\n- It can take some parameters:\n  ```javascript\n  (function myIIFEFunc(param1) {\n    console.log(\"Hi, I'm IIFE, \" + param1);\n  })(\"Yuri\");\n  // outputs \"Hi, I'm IIFE, Yuri!\"\n  ```\n  Here there value `\"Yuri\"` is passed to the `param1` of the function.\n- It can return a value: \n  ```javascript\n  var result = (function myIIFEFunc(param1) {\n    console.log(\"Hi, I'm IIFE, \" + param1);\n    return 1;\n  })(\"Yuri\");\n  // outputs \"Hi, I'm IIFE, Yuri!\"\n  // result variable will contain 1\n  ```\n- You do not have to surround the function declaration into parens, although It is the most common way to define IIFE. Instead you can use any of the following forms: \n  - `~function(){console.log(\"hi I'm IIFE\")}()`\n  - `!function(){console.log(\"hi I'm IIFE\")}()`\n  - `+function(){console.log(\"hi I'm IIFE\")}()`\n  - `-function(){console.log(\"hi I'm IIFE\")}()`\n  - `(function(){console.log(\"hi I'm IIFE\")}());`\n  - `var i = function(){console.log(\"hi I'm IIFE\")}();`\n  - `true \u0026\u0026 function(){ console.log(\"hi I'm IIFE\") }();`\n  - `0, function(){ console.log(\"hi I'm IIFE\") }();`\n  - `new function(){ console.log(\"hi I'm IIFE\") }`\n  - `new function(){ console.log(\"hi I'm IIFE\") }()`\n\n\n**Applications and usefulness**  \n\nVariables and functions that you declare inside an IIFE are not visible to the outside world, so you can:\n - Use the IIFE for isolating parts of the code to hide details of implementation.\n - Specify the input interface of your code by passing commonly used global objects (window, document, jQuery, etc.) IIFE’s parameters, and then reference these global objects within the IIFE via a local scope.\n - Use it in closures, when you use closures in loops.\n - IIFE is the basis of in the module pattern in ES5\ncode, it helps to prevent polluting the global scope and provide the module interface to the outside.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Describe Singleton Pattern In JavaScript?***\n\nThe singleton pattern is an often used JavaScript design pattern. It provides a way to wrap the code into a logical unit that can be accessed through a single variable. The Singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. In JavaScript, Singleton pattern have many uses, they can be used for NameSpacing, which reduce the number of global variables in your page (prevent from polluting global space), organizing the code in a consistent manner, which increase the readability and maintainability of your pages.\n\nThere are two important points in the traditional definition of Singleton pattern:\n- There should be only one instance allowed for a class and\n- We should allow global point of access to that single instance\n\nLet me define singleton pattern in JavaScript context:\n\n\u003e It is an object that is used to create namespace and group together a related set of methods and attributes (encapsulation) and if we allow to initiate then it can be initiated only once.\n\nIn JavaScript, we can create singleton though object literal. However, there is some another way but that I will cover in next post.\n\nA singleton object consists of two parts: The object itself, containing the members (Both methods and attributes) within it, and global variable used to access it. The variable is global so that object can be accessed anywhere in the page, this is a key feature of the singleton pattern.\n\n**JavaScript: A Singleton as a Namespace**\n\nAs I have already stated above that singleton can be used to declare Namespace in JavaScript. NameSpacing is a large part of responsible programming in JavaScript. Because everything can be overwritten, and it is very easy to wipe out variable by mistake or a function, or even a class without even knowing it. A common example which happens frequently when you are working with another team member parallel,  \n\n```javascript\nfunction findUserName(id) {\n\n}\n\n/* Later in the page another programmer\nadded code */\nvar findUserName = $('#user_list');\n\n/* You are trying to call :( */\nconsole.log(findUserName())\n```\n\nOne of the best ways to prevent accidentally overwriting variable is to namespace your code within a singleton object.\n\n```javascript\n/*  Using Namespace */\n\nvar MyNameSpace = {\n  findUserName : function(id) {},\n  // Other methods and attribute go here as well\n}\n\n/* Later in the page another programmer\nadded code */\nvar findUserName = $('#user_list');\n\n/* You are trying to call and you make this time workable */\nconsole.log(MyNameSpace.findUserName());\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Singleton Design Pattern Implementation?***\n\n```javascript\n/* Lazy Instantiation skeleton for a singleton pattern */\n\nvar MyNameSpace = {};\nMyNameSpace.Singleton = (function() {\n\n  // Private attribute that holds the single instance\n  var singletonInstance;  \n\n  // All of the normal code goes here\n  function constructor() {\n    // Private members\n    var privateVar1 = \"Alex\";\n    var privateVar2 = [1,2,3,4,5];\n\n    function privateMethod1() {\n      // code stuff\n    }\n\n    function privateMethod1() {\n      // code stuff\n    }\n\n    return {\n      attribute1 : \"Alex\",\n      publicMethod: function() {\n        alert(\"Alex\");// some code logic\n      }\n    }\n  }\n\n  return {\n    // public method (Global access point to Singleton object)\n    getInstance: function() {\n      //instance already exist then return  \n      if(!singletonInstance) {\n        singletonInstance = constructor();\n      }\n      return singletonInstance;\n    }\n  }\n\n})();\n\n// getting access of publicMethod\nconsole.log(MyNamespace.Singleton.getInstance().publicMethod());\n```\n\nThe singleton implemented above is easy to understand. The singleton class maintains a static reference to the lone singleton instance and return that reference from the static getInstance() method.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write a function called deepClone which takes an object and creates a object copy of it?***\n\n``` javascript\nvar newObject = deepClone(obj);\n```\nSolution:\n\n```javascript\nfunction deepClone(object){\n\tvar newObject = {};\n\tfor(var key in object){\n\t\tif(typeof object[key] === 'object'  \u0026\u0026 object[key] !== null ){\n\t\t newObject[key] = deepClone(object[key]);\n\t\t}else{\n\t\t newObject[key] = object[key];\n\t\t}\n\t}\n\treturn newObject;\n}\n```\n\n**Explanation:** We have been asked to do deep copy of object so What is basically It is mean ??. Let us understand in this way you have been given an object `personalDetail` this object contains some property which again a type of object here as you can see `address` is an object and `phoneNumber` in side an `address` is also an object. In simple term `personalDetail` is nested object(object inside object). So Here deep copy means we have to copy all the property of `personalDetail` object including nested object.\n\n```javascript\nvar personalDetail = {\n\tname : 'Alex',\n\taddress : {\n\t  location: 'xyz',\n\t  zip : '123456',\n\t  phoneNumber : {\n\t    homePhone: 8797912345,\n\t    workPhone : 1234509876\n\t  }\n\t}\n}\n```\nSo when we do deep clone then we should copy every property (including the nested object).\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Best way to detect `undefined` object property in JavaScript?***\n\n\u003e Suppose we have given an object `person`\n\n```javascript\nvar person = {\n\tname: 'Alex',\n\tage : 24\n}\n```\nHere the `person` object has a `name` and `age` property. Now we are trying to access the **salary** property which we haven't declared on the person object so while accessing it will return undefined. So how we will ensure whether property is undefined or not before performing some operation over it?\n\n**Explanation:**\n\nWe can use `typeof` operator to check undefined\n\n```javascript\nif(typeof someProperty === 'undefined'){\n\tconsole.log('something is undefined here');\n}\n```\nNow we are trying to access salary property of person object.\n\n```javascript\nif(typeof person.salary === 'undefined'){\n\tconsole.log(\"salary is undefined here because we haven't declared\");\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object?***\n\n```javascript\n  var objectLit = {foo : 'Bar'};\n\tvar cloneObj = Clone(obj); // Clone is the function which you have to write \n\tconsole.log(cloneObj === Clone(objectLit)); // this should return false\n\tconsole.log(cloneObj == Clone(objectLit)); // this should return true\n```\n**solution:**\n\n```javascript\nfunction Clone(object){\n  var newObject = {};\n  for(var key in object){\n  \tnewObject[key] = object[key];\n  }\n  return newObject;\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are promises and how they are useful?***\n\nWe use promises for handling asynchronous interactions in a sequential manner. They are especially useful when we need to do an async operation and THEN do another async operation based on the results of the first one. For example, if you want to request the list of all flights and then for each flight you want to request some details about it. The promise represents the future value. It has an internal state (`pending`, `fulfilled` and `rejected`) and works like a state machine.\n\nA promise object has `then` method, where you can specify what to do when the promise is fulfilled or rejected.\n\nYou can chain `then()` blocks, thus avoiding the callback hell. You can handle errors in the `catch()` block.  After a promise is set to fulfilled or rejected state, it becomes immutable.\n\nAlso mention that you know about more sophisticated concepts: \n - `async/await` which makes the code appear even more linear\n - RxJS observables can be viewed as the recyclable promises\n\nBe sure that you can implement the promise, read [one of the articles on a topic](https://opensourceconnections.com/blog/2014/02/16/a-simple-promise-implementation-in-about-20-lines-of-javascript/), and learn the source code of the [simplest promise implementation](https://gist.github.com/softwaredoug/9044640). \n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to check whether a key exist in a JavaScript object or not?***\n\nLet say we have `person` object with property **name** and **age**\n\n```javascript\nvar person = {\n\tname: 'Alex',\n\tage: 24\n}\n```\nNow we want to check whether `name` property exist in `person` object or not ?\n\nIn JavaScript object can have own property, in above example name and age is own property of person object. Object also have some of inherited property of base object like toString is inherited property of person object.\n\nSo how we will check whether property is own property or inherited property. \n\nMethod 1: We can use `in` operator on objet to check own property or inherited property. \n\n```javascript\nconsole.log('name' in person); // checking own property print true \nconsole.log('salary' in person); // checking undefined property print false\n```\n`in` operator also look into inherited property if it doesn't find property defined as own property. For instance If I check existence of toString property as we know that we haven't declared this property on person object so `in` operator look into there base property.\n\nHere \n\n```javascript\nconsole.log('toString' in person); // Will print true\n```\nIf we want to test property of object instance not inherited properties then we will use `hasOwnProperty` method of object instance.\n\n```javascript\nconsole.log(person.hasOwnProperty('toString')); // print false\nconsole.log(person.hasOwnProperty('name')); // print true\nconsole.log(person.hasOwnProperty('salary')); // print false\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is NaN, why do we need it, and when can it break the page?***\n\n`NaN` stands for “not a number.” and it can break your table of numbers when it has an arithmetic operation that is not allowed. Here are some examples of how you can get `NaN`:\n\n```javascript\nMath.sqrt(-5);\nMath.log(-1);\nparseFloat(\"foo\"); /* this is common: you get JSON from the server, convert some strings from JSON to a number and end up with NaN in your UI. */\n```\n\n`NaN` is not equal to any number, it’s not less or more than any number, also It is not equal to itself: \n\n```javascript\nNaN !== NaN\nNaN \u003c 2 // false\nNaN \u003e 2 // false\nNaN === 2 // false\n```\n\nTo check if the current value of the variable is NaN, you have to use the `isNaN` function. This is why we can often see NaN in the webpages: it requires special check which a lot of developers forget to do. \n\nFurther reading: [great blogpost on ariya.io](https://ariya.io/2014/05/the-curious-case-of-javascript-nan)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to check if the value of a variable in an array?***\n\nWe always encounter in such situation where we need to know whether value is type of array or not.\n\nFor instance : the code below perform some operation based value type\n\n```javascript\nfunction(value){\n\tif(\"value is an array\"){\n\t\t// Then perform some operation\n\t}else{\n\t\t// otherwise\n\t}\n}\n```\n\nLet us discuss some way to detect an array in JavaScript.\n\n**Method 1:**\n\nJuriy Zaytsev (Also known as kangax) proposed an elegant solution to this.\n\n```javascript\nfunction isArray(value){\n  return Object.prototype.toString.call(value) === '[object Array]';\n}\n```\nThis approach is most popular way to detecting a value of type array in JavaScript and recommended to use. This approach relies on the fact that, native toString() method on a given value produce a standard string in all browser. \n\n\n**Method 2:** \n\nDuck typing test for array type detection\n\n```javascript\n// Duck typing arrays\nfunction isArray(value){\n  return typeof value.sort === 'function';\n}\n```\nAs we can see above isArray method will return true if value object have `sort` method of type `function`. Now assume you have created a object with sort method\n\n```javascript\nvar bar = {\n  sort: function(){\n    // Some code \n  }\n}\n```\nNow when you check `isArray(bar)` then it will return true because bar object has sort method, But the fact is bar is not an array.\n\nSo this method is not a best way to detect an array as you can see It is not handle the case when some object has sort method.\n\n**Method 3:** \n\nECMAScript 5 has introduced **Array.isArray()** method to detect an array type value. The sole purpose of this method is accurately detecting whether a value is an array or not.\n\nIn many JavaScript libraries you may see the code below for detecting an value of type array.\n\n```javascript\nfunction(value){\n   // ECMAScript 5 feature\n\tif(typeof Array.isArray === 'function'){\n\t\treturn Array.isArray(value);\n\t}else{\n\t   return Object.prototype.toString.call(value) === '[object Array]';\n\t}\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Best way to detect reference values of any type in JavaScript?***\n\n In Javascript Object are called as reference type, Any value other then primitive is definitely a reference type. There are several built-in reference type such as **Object**, **Array**, **Function**, **Date**, **null** and **Error**.\n\nDetecting object using `typeof` operator\n\n```javascript\nconsole.log(typeof {});           // object\nconsole.log(typeof []);           // object\nconsole.log(typeof new Array());  // object\nconsole.log(typeof null);         // object \nconsole.log(typeof new RegExp()); // object\nconsole.log(typeof new Date());   // object\n```\nBut the downside of using typeof operator to detect an object is that typeof returns `object` for `null` (However this is fact that null is an object in JavaScript).\n\nThe best way to detect an object of specific reference type using `instanceof` operator.\n\n\u003eSyntax : **value** instanceof **constructor**   \n\n```javascript\n//Detecting an array\nif(value instanceof Array){\n\tconsole.log(\"value is type of array\");\n}\n```\n```javascript\n// Employee constructor function\nfunction Employee(name){\n\tthis.name = name; // Public property\n}\n\nvar emp1 = new Employee('John');\n\nconsole.log(emp1 instanceof Employee); // true\n```\n`instanceof` not only check the constructor which is used to create an object but also check It is prototype chain see below example.\n\n```javascript\nconsole.log(emp1 instanceof Object); // true\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How does Object.create method works JavaScript?***\n\nThe ECMAScript 5 **Object.create()** method is the easiest way for one object to inherit from another, without invoking a constructor function. \n\n**For instance:** \n\n```javascript\nvar employee = {\n  name: 'Alex',\n  displayName: function () {\n    console.log(this.name);\n  }\n};\n\nvar emp1 = Object.create(employee);\nconsole.log(emp1.displayName());  // output \"Alex\"\n```\n\nIn the example above, we create a new object `emp1` that inherits from `employee`. In other words `emp1`'s prototype is set to `employee`. After this emp1 is able to access the same properties and method on employee until new properties or method with the same name are defined.\n\n**For instance:** Defining `displayName()` method on `emp1` will not automatically override the employee `displayName`.\n\n```javascript\nemp1.displayName = function() {\n\tconsole.log('xyz-Anonymous');\n};\n\nemployee.displayName(); //Alex\nemp1.displayName();//xyz-Anonymous\n``` \n\nIn addition to this **`Object.create(`)** method also allows to specify a second argument which is an object containing additional properties and methods to add to the new object.\n\n**For example**\n\n```javascript\nvar emp1 = Object.create(employee, {\n\tname: {\n\t\tvalue: \"John\"\n\t}\n});\n\nemp1.displayName(); // \"John\"\nemployee.displayName(); // \"Alex\"\n```\nIn the example above, `emp1` is created with It is own value for name, so calling **displayName()** method will display `\"John\"` instead of `\"Alex\"`.\n\nObject created in this manner give you full control over newly created object. You are free to add, remove any properties and method you want.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to use constructor functions for inheritance in JavaScript?***\n\nLet say we have `Person` class which has name, age, salary properties and **incrementSalary()** method.\n\n```javascript\nfunction Person(name, age, salary) {\n  this.name = name;\n  this.age = age;\n  this.salary = salary;\n  this.incrementSalary = function (byValue) {\n    this.salary = this.salary + byValue;\n  };\n}\n```\n\nNow we wish to create Employee class which contains all the properties of Person class and wanted to add some additional properties into Employee class.\n\n```javascript\nfunction Employee(company){\n\tthis.company = company;\n}\n\n//Prototypal Inheritance \nEmployee.prototype = new Person(\"Alex\", 24,5000);\n```\nIn the example above, **Employee** type inherits from **Person**. It does so by assigning a new instance of `Person` to `Employee` prototype. After that, every instance of `Employee` inherits its properties and methods from `Person`.\n\n```javascript\n//Prototypal Inheritance \nEmployee.prototype = new Person(\"Alex\", 24,5000);\n\nvar emp1 = new Employee(\"Google\");\n\nconsole.log(emp1 instanceof Person); // true\nconsole.log(emp1 instanceof Employee); // true\n```\n\nLet us understand Constructor inheritance \n\n```javascript\n//Defined Person class\nfunction Person(name){\n\tthis.name = name || \"Alex\";\n}\n\nvar obj = {};\n\n// obj inherit Person class properties and method \nPerson.call(obj); // constructor inheritance\n\nconsole.log(obj); // Object {name: \"Alex\"}\n```\nHere we saw calling **Person.call(obj)** define the name properties from `Person` to `obj`.\n\n```javascript\nconsole.log(name in obj); // true\n```\nType-based inheritance is best used with developer defined constructor function rather than natively in JavaScript. In addition to this also allows flexibility in how we create similar type of object.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How we can prevent modification of object in JavaScript?***\n\nECMAScript 5 introduce several methods to prevent modification of object which lock down object to ensure that no one, accidentally or otherwise, change functionality of Object.\n\nThere are three levels of preventing modification: \n\n**1: Prevent extensions :** \n\nNo new properties or methods can be added to the object, but one can change the existing properties and method.\n\nFor example: \n\n```javascript\nvar employee = {\n\tname: \"Alex\"\n};\n\n// lock the object \nObject.preventExtensions(employee);\n\n// Now try to change the employee object property name\nemployee.name = \"John\"; // work fine \n\n//Now try to add some new property to the object\nemployee.age = 24; // fails silently unless It is inside the strict mode\n```\n**2: Seal :**\n\nIt is same as prevent extension, in addition to this also prevent existing properties and methods from being deleted.\n\nTo seal an object, we use **Object.seal()** method. you can check whether an object is sealed or not using **Object.isSealed();**\n\n```javascript\nvar employee = {\n\tname: \"Alex\"\n};\n\n// Seal the object \nObject.seal(employee);\n\nconsole.log(Object.isExtensible(employee)); // false\nconsole.log(Object.isSealed(employee)); // true\n\ndelete employee.name // fails silently unless It is in strict mode\n\n// Trying to add new property will give an error\nemployee.age = 30; // fails silently unless in strict mode\n``` \n\nwhen an object is sealed, its existing properties and methods can't be removed. Sealed object are also non-extensible.\n\n**3: Freeze :**\n\nSame as seal, In addition to this prevent existing properties methods from being modified (All properties and methods are read only).\n\nTo freeze an object, use Object.freeze() method. We can also determine whether an object is frozen using Object.isFrozen();\n\n```javascript\nvar employee = {\n\tname: \"Alex\"\n};\n\n//Freeze the object\nObject.freeze(employee); \n\n// Seal the object \nObject.seal(employee);\n\nconsole.log(Object.isExtensible(employee)); // false\nconsole.log(Object.isSealed(employee));     // true\nconsole.log(Object.isFrozen(employee));     // true\n\n\nemployee.name = \"xyz\"; // fails silently unless in strict mode\nemployee.age = 30;     // fails silently unless in strict mode\ndelete employee.name   // fails silently unless It is in strict mode\n``` \n\nFrozen objects are considered both non-extensible and sealed.\n\n**Recommended:**\n\nIf you are decided to prevent modification, sealed, freeze the object then use in strict mode so that you can catch the error.\n\n**Example:** \n\n```javascript\n\"use strict\";\n\nvar employee = {\n\tname: \"Alex\"\n};\n\n//Freeze the object\nObject.freeze(employee); \n\n// Seal the object \nObject.seal(employee);\n\nconsole.log(Object.isExtensible(employee)); // false\nconsole.log(Object.isSealed(employee));     // true\nconsole.log(Object.isFrozen(employee));     // true\n\n\nemployee.name = \"xyz\"; // fails silently unless in strict mode\nemployee.age = 30;     // fails silently unless in strict mode\ndelete employee.name;  // fails silently unless It is in strict mode\n``` \n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write a log function which will add prefix `(your message)` to every message you log using console.log ?***\n \n For example, If you log `console.log(\"Some message\")` then output should be **(your message) Some message**\n\nLogging error message or some informative message is always required when you dealing with client side JavaScript using console.log method. Some time you want to add some prefix to identify message generated log from your application hence you would like to prefix your app name in every console.log. \n\nA general way to do this keep adding your app name in every console.log message like \n\n```javascript\nconsole.log('your app name' + 'some error message');\n```\nBut doing in this way you have to write your app name everytime when you log message using console.\n\nThere are some best way we can achieve this \n\n```javascript\nfunction appLog() {\n  var args = Array.prototype.slice.call(arguments);\n  args.unshift('your app name');\n  console.log.apply(console, args);\n}\n\nappLog(\"Some error message\"); \n//output of above console: 'your app name Some error message'\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write a function which will test string as a literal and as an object ?***\n\nFor example: We can create string using string literal and using String constructor function. \n\n```javascript\n // using string literal\n var ltrlStr = \"Hi I am string literal\";\n // using String constructor function \n var objStr = new String(\"Hi I am string object\");\n```\n We can use typeof operator to test string literal and instanceof operator to test String object.\n\n```javascript\n function isString(str) {\n \treturn typeof(str) == 'string' || str instanceof String;\n }\n \n var ltrlStr = \"Hi I am string literal\";\n var objStr = new String(\"Hi I am string object\");\n console.log(isString(ltrlStr)); // true\n console.log(isString(objStr)); // true\n``` \n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is typical use case for anonymous function in JavaScript?***\n\nAnonymous functions basically used in following scenario.\n\na.) No name is needed if function is only used in one place, then there is no need to add a name to function.\n\nExample: setTimeout function\n\n```javascript\nsetTimeout(function(){\n\talert(\"Hello\");\n},1000);\n```\nHere there is no need of using named function when we are sure \tthat function which will alert `hello` would use only once in\tapplication.\n\nb.) Anonymous functions are declared inline and inline functions have advantages in the case that they can access variable in the parent scopes.\n\nLet us take a example of event handler. Notify event of particular \ttype (such as click) for a given object. \n\nLet say we have HTML element (button) on which we want to add click event and when user do click on button we would like toexecute some logic.\n\n```html\n\u003cbutton id=\"myBtn\"\u003e\u003c/button\u003e\n```\nAdd Event Listener \n\n```javascript\nvar btn = document.getElementById('myBtn');\nbtn.addEventListener('click', function () {\n  alert('button clicked');\n});\n```\n\t\nAbove example shows used of anonymous function as a callback function in event handler.\n\t\nc.) Passing anonymous function as a parameter to calling function.\n\t\n**Example:** \n\n```javascript\n// Function which will execute callback function\nfunction processCallback(callback){\n\tif(typeof callback === 'function'){\n\t\tcallback();\n\t}\n}\n\n// Call function and pass anonymous function as callback \nprocessCallback(function(){\n\talert(\"Hi I am anonymous callback function\");\n});\n```\nThe best way to make a decision for using anonymous function is to ask the following question:\n\nWill the function which I am going to define, be used anywhere else?\n\nIf your answer is yes then go and create named function rather anonymous function.\n\n**Advantage of using anonymous function:**\n\n* It can reduce a bit of code, particularly in recursive function and in callback function.\n* Avoid needless global namespace pollutions.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to set a default parameter value?***\n\n If you are coming from python/c# you might be using default value for function parameter incase value(formal parameter) has not been passed. For instance : \n\n```python\n// Define sentEmail function \n// configuration : Configuration object\n// provider : Email Service provider, Default would be gmail\ndef sentEmail(configuration, provider = 'Gmail'):\n\t# Your code logic\n```\n**In Pre ES6/ES2015**\n\nThere are a lot of ways by which you can achieve this in pre ES2015.\n\nLet us understand the code below by which we achieved setting default parameter value.\n\n**Method 1: Setting default parameter value** \n\n```javascript\nfunction sentEmail(configuration, provider) {\n  // Set default value if user has not passed value for provider\n  provider = typeof provider !== 'undefined' ? provider : 'Gmail'  \n  // Your code logic\n;\n}\n// In this call we are not passing provider parameter value\nsentEmail({\n  from: 'xyz@gmail.com',\n  subject: 'Test Email'\n});\n// Here we are passing Yahoo Mail as a provider value\nsentEmail({\n  from: 'xyz@gmail.com',\n  subject: 'Test Email'\n}, 'Yahoo Mail');\n```\n\n**Method 2: Setting default parameter value** \n\n```javascript\nfunction sentEmail(configuration, provider) {\n  // Set default value if user has not passed value for provider\n  provider = provider || 'Gmail'  \n  // Your code logic\n;\n}\n// In this call we are not passing provider parameter value\nsentEmail({\n  from: 'xyz@gmail.com',\n  subject: 'Test Email'\n});\n// Here we are passing Yahoo Mail as a provider value\nsentEmail({\n  from: 'xyz@gmail.com',\n  subject: 'Test Email'\n}, 'Yahoo Mail');\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Write code for merge two JavaScript Object dynamically?***\n\nLet say you have two objects \n\n```javascript\nvar person = {\n\tname : 'John',\n\tage  : 24\n}\n\nvar address = {\n\taddressLine1 : 'Some Location x',\n\taddressLine2 : 'Some Location y',\n\tcity : 'NewYork'\n} \n```\nWrite merge function which will take two object and add all the own property of second object into first object.\n\n```javascript\nmerge(person , address); \n \n/* Now person should have 5 properties \nname , age , addressLine1 , addressLine2 , city */\n```\n**Method 1: Using ES6, Object.assign method**\n\n```javascript\nconst merge = (toObj, fromObj) =\u003e Object.assign(toObj, fromObj);\n```\n \n**Method 2: Without using built-in function**\n\n```javascript\nfunction merge(toObj, fromObj) {\n  // Make sure both of the parameter is an object\n  if (typeof toObj === 'object' \u0026\u0026 typeof fromObj === 'object') {\n    for (var pro in fromObj) {\n      // Assign only own properties not inherited properties\n      if (fromObj.hasOwnProperty(pro)) {\n        // Assign property and value\n        toObj[pro] = fromObj[pro];\n      }\n    }\n  }else{\n  \tthrow \"Merge function can apply only on object\";\n  }\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is non-enumerable property in JavaScript and how you can create one?***\n\nObject can have properties that don't show up when you iterate through object using for...in loop or using Object.keys() to get an array of property names. This properties is know as non-enumerable properties.\n\nLet say we have following object\n\n```javascript\nvar person = {\n\tname: 'John'\n};\nperson.salary = '10000$';\nperson['country'] = 'USA';\n\nconsole.log(Object.keys(person)); // ['name', 'salary', 'country']\n```\nAs we know that person object properties `name`, `salary` ,`country` are enumerable hence It is shown up when we called Object.keys(person).\n\nTo create a non-enumerable property we have to use **Object.defineProperty()**. This is a special method for creating non-enumerable property in JavaScript.\n\n```javascript\nvar person = {\n\tname: 'John'\n};\nperson.salary = '10000$';\nperson['country'] = 'USA';\n\n// Create non-enumerable property\nObject.defineProperty(person, 'phoneNo',{\n\tvalue : '8888888888',\n\tenumerable: false\n})\n\nObject.keys(person); // ['name', 'salary', 'country']\n```\nIn the example above `phoneNo` property didn't show up because we made it non-enumerable by setting **enumerable:false**\n\nNow Let us try to change value of `phoneNo`\n\n```javascript\nperson.phoneNo = '7777777777'; \n```\nChanging non-enumerable property value will return error in `strict mode`. In non-strict mode it won't through any error but it won't change the value of phoneNo.\n\n**Bonus**\n\n**Object.defineProperty()** is also let you create read-only properties as we saw above, we are not able to modify phoneNo value of a person object.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is Function binding ?***\n\n Function binding falls in advance JavaScript category and this is very popular technique to use in conjunction with event handler and callback function to preserve code execution context while passing function as a parameter.\n\nExample:\n\n```javascript\nvar clickHandler = {\n\tmessage: 'click event handler',\n\thandleClick: function(event) {\n\t\tconsole.log(this.message);\n\t}\n};\n\nvar btn = document.getElementById('myBtn');\n// Add click event to btn\nbtn.addEventListener('click', clickHandler.handleClick);\n```\n\nHere in this example clickHandler object is created which contain message properties and handleClick method.\n\nWe have assigned handleClick method to a DOM button, which will be executed in response of click. When the button is clicked, then handleClick method is being called and console message. Here console.log should log the `click event handler` message but it actually log `undefined`.\n\nThe problem of displaying `undefined` is because of the execution context of clickHandler.handleClick method is not being saved hence `this` pointing to button `btn` object. We can fix this issue using bind method.\n\n```javascript\nvar clickHandler = {\n\tmessage: 'click event handler',\n\thandleClick: function(event) {\n\t\tconsole.log(this.message);\n\t}\n};\n\nvar btn = document.getElementById('myBtn');\n// Add click event to btn and bind the clickHandler object\nbtn.addEventListener('click', clickHandler.handleClick.bind(clickHandler));\n```\n\n`bind` method is available to all the function similar to call and apply method which take argument value of `this`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain how `this` works in JavaScript?***\n\nThe following rules are applied when we use `this` keyword in javascript\n\n1. If the `new` keyword is used when calling the function, `this` inside the function is a brand new object.\n2. If `apply`, `call`, or `bind` are used to call/create a function, `this` inside the function is the object that is passed in as the argument.\n3. If a function is called as a method, such as `obj.method()` — `this` is the object that the function is a property of.\n4. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, `this` is the global object. In a browser, it is the `window` object. If in strict mode (`'use strict'`), `this` will be `undefined` instead of the global object.\n5. If multiple of the above rules apply, the rule that is higher wins and will set the `this` value.\n6. If the function is an ES2015 arrow function, it ignores all the rules above and receives the `this` value of its surrounding scope at the time it is created.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain how prototypal inheritance works?***\n\nAll JavaScript objects have a `prototype` property, that is a reference to another object. 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 `prototype`, and the `prototype`'s `prototype` and so on, until it finds the property defined on one of the `prototype`s or until it reaches the end of the prototype chain.\n\n**Example:**\n\nWe already have a build-in `Object.create`, but if you were to provide a polyfill for it, that might look like:\n\n```javascript\nif (typeof Object.create !== 'function') {\n  Object.create = function (parent) {\n    function Tmp() {}\n    Tmp.prototype = parent;\n    return new Tmp();\n  };\n}\n\nconst Parent = function() {\n  this.name = \"Parent\";\n}\n\nParent.prototype.greet = function() { console.log(\"hello from Parent\"); }\n\nconst child = Object.create(Parent.prototype);\n\nchild.cry = function() {\n  console.log(\"waaaaaahhhh!\");\n}\n\nchild.cry();\n// Outputs: waaaaaahhhh!\n\nchild.greet();\n// Outputs: hello from Parent\n```\n\nThings to note are:\n\n* `.greet` is not defined on the _child_, so the engine goes up the prototype chain and finds `.greet` off the inherited from _Parent_.\n* We need to call `Object.create` in one of following ways for the prototype methods to be inherited:\n  * Object.create(Parent.prototype);\n  * Object.create(new Parent(null));\n  * Object.create(objLiteral);\n  * Currently, `child.constructor` is pointing to the `Parent`:\n\n```javascript\nchild.constructor\nƒ () {\n  this.name = \"Parent\";\n}\nchild.constructor.name\n\"Parent\"\n```\n  * If we'd like to correct this, one option would be to do:\n\n```javascript\nfunction Child() {\n  Parent.call(this);\n  this.name = 'child';\n}\n\nChild.prototype = Parent.prototype;\nChild.prototype.constructor = Child;\n\nconst c = new Child();\n\nc.cry();\n// Outputs: waaaaaahhhh!\n\nc.greet();\n// Outputs: hello from Parent\n\nc.constructor.name;\n// Outputs: \"Child\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other?***\n\nTo understand the differences between the two, Let us look at what each function does.\n\n**`forEach`**\n\n* Iterates through the elements in an array.\n* Executes a callback for each element.\n* Does not return a value.\n\n```javascript\nconst a = [1, 2, 3];\nconst doubled = a.forEach((num, index) =\u003e {\n  // Do something with num and/or index.\n});\n\n// doubled = undefined\n```\n\n**`map`**\n\n* Iterates through the elements in an array.\n* \"Maps\" each element to a new element by calling the function on each element, creating a new array as a result.\n\n```javascript\nconst a = [1, 2, 3];\nconst doubled = a.map(num =\u003e {\n  return num * 2;\n});\n\n// doubled = [2, 4, 6]\n```\n\nThe main difference between `.forEach` and `.map()` is that `.map()` returns a new array. If you need the result, but do not wish to mutate the original array, `.map()` is the clear choice. If you simply need to iterate over an array, `forEach` is a fine choice.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Have you ever used JavaScript templating? If so, what libraries have you used?***\n\nYes. Handlebars, Underscore, Lodash, AngularJS, and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos would go uncaught. JSX is my new favorite as it is closer to JavaScript and there is barely any syntax to learn. Nowadays, you can even use ES2015 template string literals as a quick way for creating templates without relying on third-party code.\n\n```javascript\nconst template = `\u003cdiv\u003eMy name is: ${name}\u003c/div\u003e`;\n```\n\nHowever, do be aware of a potential XSS in the above approach as the contents are not escaped for you, unlike in templating libraries.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is JSON and its common operations?***\n\n**JSON** is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. It is useful when you want to transmit data across a network and it is basically just a text file with an extension of .json, and a MIME type of application/json\nParsing: **Converting a string to a native object\n```javascript\nJSON.parse(text)\n```\nStringification: converting a native object to a string so it can be transmitted across the network\n```javascript\nJSON.stringify(object)\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of array slice method?***\n\nThe **slice()** 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. Some of the examples of this method are,\n```javascript\nlet arrayIntegers = [1, 2, 3, 4, 5];\nlet arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1,2]\nlet arrayIntegers2 = arrayIntegers.slice(2,3); // returns [3]\nlet arrayIntegers3 = arrayIntegers.slice(4); //returns [5]\n```\n*Note: Slice method wonot mutate the original array but it returns the subset as new array*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the purpose of array splice method?***\n\nThe **splice()** method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the option second argument indicates the number of elements to be deleted. Each additional argument is added to the array. Some of the examples of this method are,\n```javascript\nlet arrayIntegersOriginal1 = [1, 2, 3, 4, 5];\nlet arrayIntegersOriginal2 = [1, 2, 3, 4, 5];\nlet arrayIntegersOriginal3 = [1, 2, 3, 4, 5];\n\nlet arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array: [3, 4, 5]\nlet arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array: [1, 2, 3]\nlet arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, \"a\", \"b\", \"c\"); //returns [4]; original array: [1, 2, 3, \"a\", \"b\", \"c\", 5]\n```\n*Note: Splice method modifies the original array and returns the deleted array*.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between slice and splice?***\n\nSome of the major difference in a tabular form\n\n| Slice | Splice |\n|---- | ---------|\n| Doesn't modify the original array(immutable)  | Modifies the original array(mutable) |\n| Returns the subset of original array | Returns the deleted elements as array  |\n| Used to pick the elements from array | Used to insert or delete elements to/from array|\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you compare Object and Map?***\n\n**Objects** are similar to **Maps** 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.\n\n1. The keys of an Object are Strings and Symbols, whereas they can be any value for a Map, including functions, objects, and any primitive.\n2. The keys in Map are ordered while keys added to object are not. Thus, when iterating over it, a Map object returns keys in order of insertion.\n3. 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.\n4. 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.\n5. An Object has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by using map = Object.create(null), but this is seldom done.\n6. A Map may perform better in scenarios involving frequent addition and removal of key pairs.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you redeclare variables in switch block without an error?***\n\nIf you try to redeclare variables in a `switch block` then it will cause errors because there is only one block. For example, the below code block throws a syntax error as below,\n```javascript\nlet counter = 1;\nswitch(x) {\n    case 0:\n      let name;\n      break;\n\n    case 1:\n      let name; // SyntaxError for redeclaration.\n      break;\n}\n```\nTo avoid this error, you can create a nested block inside a case clause will create a new block scoped lexical environment.\n```javascript\nlet counter = 1;\nswitch(x) {\n    case 0: {\n      let name;\n      break;\n    }\n    case 1: {\n      let name; // No SyntaxError for redeclaration.\n      break;\n    }\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to create and trigger events in javascript?***\n\nEvents can be created with the Event constructor as follows:\n```javascript\nvar event = new Event('build');\n\n// Listen for the event.\nelem.addEventListener('build', function (e) { /* ... */ }, false);\n\n// Dispatch the event.\nelem.dispatchEvent(event);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between window.frames window.parent and window.top in JavaScript?***\n\n```\nwindow.frames – the collection of “children” windows (for nested frames).\nwindow.parent – the reference to the “parent” (outer) window.\nwindow.top – the reference to the topmost parent window.\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***In JavaScript, what is the difference between var x = 1 and x = 1?***\n\n'var x = 1' will create a variable within the current scope. Given this is declared in a function, x will not be available outside it, unless explicitly returned.\n\n'x = 1' will create a variable within the global scope. Thus, any other code can access and alter its value. It is generally a bad practice to use variables in a global scope.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is Associative Array? How do we use it?***\n\nAssociative arrays are dynamic objects that  the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array. The `length` attribute has no effect because the variable is not longer of Array type.\n\n**An associative array is declared or dynamically created**  \n```javascript\nvar arr = { \"one\": 1, \"two\": 2, \"three\": 3 }; \n```\n\nUnlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.\nThe content is accessed by keys, whatever the method used to declare the array.\n```javascript\nvar y = arr[\"one\"];\n```\n**An associative array is also an object**  \nwe can create an associative array with the Object reserved word, then and assign keys and values:\n```javascript\nvar obj = new Object();\nobj[\"one\"] = 1;\nobj[\"two\"] = 2;\nobj[\"three\"] = 3;\nfor(var i in obj) {\n     document.write(i + \"=\" + obj[i] + '\u003cbr\u003e');\n}\n```\nOutput\n```\none = 1\ntwo = 2\nthree = 3\n```\n**Attributes of a JavaScript object are also keys**  \n```javascript\nvar oa = new Object();\noa.one = 1;\noa.two = 2;\noa.three = 3;\nfor(var i in oa) {\n     document.write(i + \"=\" + x[i] + '\u003cbr\u003e');\n}\n```\n**An associative array is scanned with for in**  \nWe can not use a simple for loop because the elements are not accessible by an index (besides the fact that we must use a special function to determine the position of the last), but the simpler for in loop is ideal.\n\nKeys are assigned to the variable \"key\", and with the key we access the value.\n```javascript\nvar arr = { \"one\" : 1, \"two\" : 2, \"three\": 3 };  \nfor(var key in arr) {\n  var value = arr[key];\n  document.write(key + \" = \" + value + '\u003cbr\u003e');\n}\n```\n**List of properties**  \n```javascript\nObject.keys(arr)\n\nObject.keys(arr).length\n\nvar a2 = { \"a\":1, \"b\":2, \"c\":3 }\ndocument.write(\"Size=\" + Object.keys(a2).length\n```\n**List of values**  \nWe can transform an associative array, ie an object, into a simple array. With the method that returns the list of keys, and the map method (ECMAScript 1.6), we also obtain the values:\n```javascript\nvar a3 = Object.keys(a2).map(function (k) { return a2[k];})\ndocument.write(a3)\n```\nResult\n```\n1,2,3\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between Classic Inheritance and Prototypical Inheritance?***\n\n**Class Inheritance**: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the new keyword. Class inheritance may or may not use the class keyword from ES6.\n\n**Prototypal Inheritance**: instances inherit directly from other objects. Instances are typically instantiated via factory functions or Object.create(). Instances may be composed from many different objects, allowing for easy selective inheritance.\n\n**Features**  \n\n* Classes: create tight coupling or hierarchies/taxonomies.\n* Prototypes: mentions of concatenative inheritance, prototype delegation, functional inheritance, object composition.\n* No preference for prototypal inheritance \u0026 composition over class inheritance.\n\nThe difference between classical inheritance and prototypal inheritance is that classical inheritance is limited to classes inheriting from other classes while prototypal inheritance supports the cloning of any object using an object linking mechanism. A prototype basically acts as a template for other objects, whether they are extending the base object or not.\n```javascript\nfunction Circle(radius) {\n    this.radius = radius;\n}\nCircle.prototype.area = function () {\n    var radius = this.radius;\n    return Math.PI * radius * radius;\n};\nCircle.prototype.circumference: function () {\n    return 2 * Math.PI * this.radius;\n};\nvar circle = new Circle(5);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between private variable, public variable and static variable? How we achieve this in JS?***\n\nPrivate and public variables are two ways of information hiding. An object can have private and public variables. Private variables can be accessed by all the members (functions and variables) of the owner object but not by any other object. Public variables can be accessed by all the members of the owner as well as other objects that can access the owner.\nStatic variables are related to a class. They come into existence as soon as a class come into existence.\n\nNow, JavaScript natively doesn't support these concepts. But you can use JavaScript's closure techniques to achieve the similar results.\n```javascript\nfunction MyClass () { // constructor function\n  var privateVariable = \"foo\";  // Private variable \n\n  this.publicVariable = \"bar\";  // Public variable \n\n  this.privilegedMethod = function () {  // Public Method\n    alert(privateVariable);\n  };\n}\n\n// Instance method will be available to all instances but only load once in memory \nMyClass.prototype.publicMethod = function () {    \n  alert(this.publicVariable);\n};\n\n// Static variable shared by all instances\nMyClass.staticProperty = \"baz\";\n\nvar myInstance = new MyClass();\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to add and remove properties to object in runtime?***\n\n**Creating an Object**  \nThere are two ways to construct an object in JavaScript:\n* The object literal, which uses curly brackets: {}\n* The object constructor, which uses the new keyword\n```javascript\n// Initialize object literal with curly brackets\nconst objectLiteral = {};\n\n// Initialize object constructor with new Object\nconst objectConstructor = new Object();\n```\nWe can create an example object, contained in the variable employee, to describe a character.\n```javascript\n// Initialize gimli object\nconst employee = {\n    name: \"Gimli\",\n    race: \"dwarf\",\n    weapon: \"axe\",\n    greet: function() {\n        return `Hi, my name is ${this.name}!`;\n    },\n};\n```\n**Accessing Object Properties**  \nThere are two ways to access an object’s properties.\n\n* Dot notation: .\n* Bracket notation: []\n```javascript\n// Retrieve the value of the weapon property\ngimli.weapon;\n\n// Retrieve the value of the weapon property\ngimli[\"weapon\"];\n```\nOutput\n```\n\"axe\"\n```\nIn order to retrieve an object method, you would call it much in the same way you would call a regular function, just attached to the object variable.\n```javascript\nemployee.greet();\n```\nOutput\n```\n\"Hi, my name is Gimli!\"\n```\n**Adding and Modifying Object Properties**  \n```javascript\n// Add new age property to gimli\nemployee.age = 22;\n\n// Add new age property to gimli\nemployee[\"age\"] = 22;\n\nemployee.age;\n```\nOutput\n```\n22\n```\n**Removing Object Properties**  \nIn order to remove a property from an object, you will utilize the delete keyword. delete is an operator that removes a property from an object.\n```javascript\n// Remove weapon from gimli\ndelete employee.weapon;\n```\nOutput\n```\ntrue\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to extend built-in objects?***\n\nAll objects in JS contains a prototype property, even the variables we declare. Since we don’t have access to the JS source code, thus, we cannot insert our custom functionality in String object by fiddling with JS source code, we use the String object’s prototype as another approach to insert our functionality.\n```javascript\nString.prototype.regexIt = function() {\n  /*\n    Since were attaching our custom function to String object,\n    we don't need an argument instead, we use 'this' to access our argument\n    as it points to the String value attached.\n  */\n  var input = this;\n\n  // do something with input and\n\n  return input;\n}\n```\nNow, we can use our regexIt method as shown below:\n```javascript\nvar result = 'Hello World';\nresult.regexIt();\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why extending array is bad idea?***\n\nPolyfilling or shimming standard functionality like `Array.prototype.filter` so that it works in older browsers is a good idea in my opinion. Usually the advice for not extending `Array.prototype` or other native prototypes might come down to one of these:\n1. `for..in` might not work properly\n1. Someone else might also want to extend Array with the same function name\n1. It might not work properly in every browser, even with the shim.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between browser detection and feature detection?***\n\nFeature detection is just a way of determining if a feature exists in certain browsers. A good example is a modern HTML5 feature ‘Location’.\n```javascript\nif (navigator.geolocation) {\n  // detect users location here B-) and do something \n}\n```\nBrowser detection is generally done by reading a property known as `navigator.userAgent` that contains a string with a lot of information about the browser that is currently being used to visit the page.\n\nFeature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:\n```javascript\nif (document.getElementsByTagName) {\n    element = document.getElementById(id);\n}\n```\nChecking the UA string is an old practice and should not be used anymore. You keep changing the UA checks and never benefit from newly implemented features, e.g.:\n```javascript\nif (navigator.userAgent.indexOf(\"MSIE 7\") \u003e -1){\n    //do something\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between Graceful Degradation and Progressive Enhancement?***\n\n**Progressive Enhancement** is when you create a web site that is available to everyone, but then add advanced functionality in layers that improves the experience for those who can access it. For instance, a basic text website can be upgraded to include a design (stylesheets), interactive functionality (javascript), and video (flash). But the website continues to function as just a text-based website.\n\n**Graceful Degradation** is an aspect of `fault-tolerant` systems where your design continues to function even if certain points of the design can't work. For example, HTML5 works in all browsers because HTML parsers themselves don't break if there are unrecognised tags. But since older browsers don't recognise those tags, they also can't provide the functionality associated with them (such as the various new input types like range, number, date, time, color, etc.). Another example is setting color and background-color together in CSS, but possibly overriding the color with an image. If the image doesn't load, you want the text to still be legible, but that might not be the case if you don't ensure that the background colour is one that allows the text to be legible.\n\n**When to use graceful degradation**  \n* You retrofit an old product and you don’t have the time, access or insight to change or replace it.\n* You just don’t have time to finish a product with full progressive enhancement (often a sign of bad planning or running out of budget).\n* The product you have is an edge case, for example very high traffic sites where every millisecond of performance means a difference of millions of dollars.\n* Your product by definition is so dependent on scripting that it makes more sense to maintain a “basic” version rather than enhancing one (Maps, email clients, feed readers).\n\n**When to use progressive enhancement**  \n* Regardless of environment and ability you deliver a product that works.\n* When a new browser comes out or a browser extension becomes widely adopted you can enhance to yet another level without having to touch the original solution — graceful degradation would require you to alter the original solution.\n* You allow technology to be what it is supposed to be — an aid to reach a goal faster than without it, not a “must” to be able to reach a goal in the first place.\n* If you need to add new features, you can do so after checking if they are supported at a certain stage, or you can add it to the most basic level of functionality and make it better in more sophisticated environments. In any case, the maintenance happens at the same spot and not in two different places. Keeping a progressively enhanced product up-to-date is much less work than maintaining two versions.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***In JavaScript, why is the “this” operator inconsistent?***\n\nThe this variable is attached to functions. Whenever you invoke a function, this is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.\n\nThere are four ways to invoke functions in javascript. You can invoke the function as a method, as a function, as a constructor, and with apply.  \n\n**As a Method**  \nA method is a function that's attached to an object\n```javascript\nvar foo = {};\nfoo.someMethod = function(){\n    alert(this);\n}\n```\nWhen invoked as a method, this will be bound to the object the function/method is a part of.  \n\n**As a Function**  \nIf you have a stand alone function, the this variable will be bound to the \"global\" object, almost always the window object in the context of a browser.\n```javascript\nvar foo = function(){\n    alert(this);\n }\n foo();\n ```\n**As a Constructor**  \nWhen invoked as a constructor, a new Object will be created, and this will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and this will be bound to the global object. Use that var that = this; trick/pattern.\n```javascript\nfunction Foo(){\n    this.confusing = 'hell yeah';\n}\nvar myObject = new Foo();\n```\n**With the Apply Method**  \nFinally, every function has a method (yes, functions are objects in Javascript) named apply. Apply lets you determine what the value of this will be, and also lets you pass in an array of arguments.\n```javascript\nfunction foo(a,b){\n    alert(a);\n    alert(b);\n    alert(this);\n}\nvar args = ['ah','be'];\nfoo.apply('omg',args);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What unit testing framework do you use? and why?***\n\nUnit testing is the process of testing the implemented code at a module level. Unit testing allows you to ensure that your developed modules are meeting the requirements specified by the business document. These tests are written for every module as they are created.\n\nUnit testing provides numerous benefits including finding software bugs early, facilitating change, simplifying integration, providing a source of documentation, and many others, which we will look right now with more detail. \n\n1. Makes the Process Agile\n2. Quality of Code\n3. Finds Software Bugs Early\n4. Facilitates Changes and Simplifies Integration\n5. Provides Documentation\n6. Debugging Process\n7. Design\n8. Reduce Costs\n\n**Challenges in JavaScript Unit Testing**  \n1. Many other languages support unit testing in browsers, in the stable as well as in runtime environment but JavaScript can not\n1. You can understand some system actions with other languages, but this is not the case with JavaScript\n1. Some JavaScript are written for a web application may have multiple dependencies\n1. JavaScript is good to use in combination with HTML and CSS rather than on the web\n1. Difficulties with page rendering and DOM manipulation\n\n**JavaScript Unit Testing Frameworks**  \n1. **Unit.js**: It is known as an open source assertion library running on browser and Node.js. It is extremely compatible with other JavaScript Unit Testing frameworks like Mocha, Karma, Jasmine, QUnit, Protractor, etc. Provides the full documented API of assertion list\n\n2. **QUnit**: It is used for both client-side as well as server-side JavaScript Unit Testing. This Free framework is used for jQuery projects. It follows Common JS unit testing Specification for unit testing. It supports the Node Long-term Support Schedule.\n\n3. **Jasmine**: Jasmine is the behavior-driven development framework for JavaScript unit Testing. It is used for testing both synchronous and asynchronous JavaScript Code. It does not require DOM and comes with the easy syntax that can be Written for any test.\n\n4. **Karma**: Karma is an open source productive testing environment. Easy workflow control Running on the command line. Offers the freedom to write the tests with Jasmine, Mocha, and QUnit. You can run the test on real devices with easy debugging.\n\n5. **Mocha**: Mocha runs on Node.js and in the browser. Mocha performs asynchronous Testing in a simpler way. Provides accuracy and flexibility in reporting. Provides tremendous support of rich features such as test-specific timeouts, JavaScript APIs etc.\n\n6. **Jest**: Jest is used by Facebook so far to test all of the JavaScript code. It provides the 'zero-configuration' testing experience. Supports independent and non-interrupting running test without any conflict. Do not require any other setup configuration and libraries.\n\n7. **AVA**: AVA is simple JavaScript Unit Testing Framework. Tests are being run in parallel and serially. Parallel tests run without interrupting each other. AVA Supports asynchronous testing as well. AVA uses subprocesses to run the test.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain the difference between Object.freeze() vs const?***\n\n`const` applies to bindings (\"variables\"). It creates an immutable binding, i.e. you cannot assign a new value to the binding. `const` behaves like let. The only difference is, it defines a variable that cannot be reassigned. Variables declared by const are block scoped and not function scoped like variables declared with var.\n\nThe const keyword applies to bindings and creates an immutable binding.\n```javascript\nlet person = {\n   name: \"Leonardo\"\n};\nlet animal = {\n   species: \"snake\"\n};\nperson = animal;\nconsole.log(person); //output { species: 'snake' }\n```\nIf you change the person object declaration to be a constant the code above won’t work anymore:\n```javascript\nconst person = {\n   name: \"Leonardo\"\n};\nlet animal = {\n   species: \"snake\"\n};\nperson = animal; // ERROR \"person\" is read-only\nconsole.log(person);\n```\nBut you can change its values:\n```javascript\nconst person = {\n   name: \"Leonardo\"\n};\nlet animal = { \n   species: \"snake\"\n};\nperson.name = \"Lima\";\nconsole.log(person); //output { name: 'Lima' }\n```\n\n**Object.freeze**: works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties. `Object.freeze()` takes an object as an argument and returns the same object as an immutable object. This implies that no properties of the object can be added, removed, or changed.\n\nIt works on values and it makes an object immutable, i.e. you cannot change, add or delete its properties, but you can assign another instance.\n```javascript\nlet person = {\n   name: \"Leonardo\"\n};\nlet animal = {\n   species: \"snake\"\n};\nObject.freeze(person);\nperson = animal;\nconsole.log(person); { species: 'snake' }\n```\nEven using Object.freeze() I could assign animal object to to person. Now, let’s try change some property of the person:\n```javascript\nlet person = {\n   name: \"Leonardo\"\n};\nlet animal = {\n   species: \"snake\"\n};\nObject.freeze(person);\nperson.name = \"Lima\"; //TypeError: Cannot assign to read only property 'name' of object\nconsole.log(person);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is generator in JS?***\n\n**Generator-Function**: A generator-function is defined like a normal function, but whenever it needs to generate a value, it does so with the `yield` keyword rather than `return`. The `yield` statement suspends function’s execution and sends a value back to caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last `yield` run.\nSyntax \n```javascript\nfunction* gen() {\n     yeild 1;\n     yeild 2;\n     ...\n     ...\n}\n```\n**Generator-Object**: Generator functions return a generator object. Generator objects are used either by calling the next method on the generator object or using the generator object in a “for in” loop.\n```javascript\nfunction * fun() {\n    yield 10;\n    yield 20;\n    yield 30;\n} \n  \n// Calling the Generate Function\nvar gen = fun();\ndocument.write(gen.next().value);\ndocument.write(\"\u003cbr\u003e\");\ndocument.write(gen.next().value);\ndocument.write(\"\u003cbr\u003e\");\ndocument.write(gen.next().value);\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Describe the Revealing Module Pattern in javascript?***\n\nJavascript does not have the typical 'private' and 'public' specifiers of more traditional object oriented languages like C# or Java. However, you can achieve the same effect through the clever application of Javascript's function-level scoping. The Revealing Module pattern is a design pattern for Javascript applications that elegantly solves this problem.\n\nThe central principle of the Revealing Module pattern is that all functionality and variables should be hidden unless deliberately exposed.\n\nThe Revealing Module Pattern is one of the most popular ways of creating modules. Using the return statement we can return a object literal that ‘reveals’ only the methods or properties we want to be publicly available.\n```javascript\nvar myModule = (function() {\n  'use strict';\n\n  var _privateProperty = 'Hello World';\n  var publicProperty = 'I am a public property';\n\n  function _privateMethod() {\n    console.log(_privateProperty);\n  }\n\n  function publicMethod() {\n    _privateMethod();\n  }\n    \n  return {\n    publicMethod: publicMethod,\n    publicProperty: publicProperty\n  };\n}());\n  \nmyModule.publicMethod();    \t\t        // outputs 'Hello World'   \nconsole.log(myModule.publicProperty);       // outputs 'I am a public property'\nconsole.log(myModule._privateProperty);     // is undefined protected by the module closure\nmyModule._privateMethod();                  // is TypeError protected by the module closure\n```\n**Advantages**  \nThis pattern allows the syntax of our scripts to be more consistent. It also makes it easier to tell at the end of the module which of our functions and variables may be accessed publicly, which eases readability.\n\n**Disadvantages**  \nA disadvantage of this pattern is that if a private function refers to a public function, that public function can’t be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation,and the pattern does not apply to public members, only to functions.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Compare Async-Await and Generators usage to achive same functionality?***\n\n**Generators/Yield**\n\nGenerators are objects created by generator functions — functions with an * (asterisk) next to their name. The yield keyword pauses generator function execution and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.\n```javascript\nconst generator = (function*() {\n  // waiting for .next()\n  const a = yield 5;\n  // waiting for .next()\n  console.log(a); // =\u003e 15\n})();\n\nconsole.log(generator.next()); // =\u003e { done: false, value: 5 }\nconsole.log(generator.next(15)); // =\u003e { done: true, value: undefined }\n```\n**Async/Await**\n\nAsync keyword is used to define an asynchronous function, which returns a `AsyncFunction` object.\n\nAwait keyword is used to pause async function execution until a `Promise` is fulfilled, that is resolved or rejected, and to resume execution of the `async` function after fulfillments. When resumed, the value of the `await` expression is that of the fulfilled `Promise`.\n\n**Key points:**  \n\n1. Await can only be used inside an async function.\n2. Functions with the async keyword will always return a promise.\n3. Multiple awaits will always run in sequential order under a same function.\n4. If a promise resolves normally, then await promisereturns the result. But in case of a rejection it throws the error, just if there were a throw statement at that line.\n5. Async function cannot wait for multiple promises at the same time.\n6. Performance issues can occur if using await after await as many times one statement doesn\\'t depend on the previous one.\n\n```javascript\n\nasync function asyncFunction() {\n\n  const promise = new Promise((resolve, reject) =\u003e {\n    setTimeout(() =\u003e resolve(\"i am resolved!\"), 1000)\n  });\n\n  const result = await promise; \n  // wait till the promise resolves (*)\n\n  console.log(result); // \"i am resolved!\"\n}\n\nasyncFunction();\n```\n\n**Generator and Async-await — Comparison**  \n\n1. Generator functions/yield and Async functions/await can both be used to write asynchronous code that “waits”, which means code that looks as if it was synchronous, even though it really is asynchronous.\n2. Generator function are executed yield by yield i.e one yield-expression at a time by its iterator (the next method) where as Async-await, they are executed sequential await by await.\n3. Async/await makes it easier to implement a particular use case of Generators.\n4. The return value of Generator is always {value: X, done: Boolean} where as for Async function it will always be a promise that will either resolve to the value X or throw an error.\n5. Async function can be decomposed into Generator and promise implementation which are good to know stuff.\n\nGenerators and async functions always return a specific type of object:\n- Generator functions: If you yield/return a value X, it will always return an iteration object with the form {value: X, done: Boolean}\n- Async functions: If you return a value X, it will always return a promise that will either resolve to the value X or throw an error.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain escape() and unescape() functions?***\n\nThe `escape()` [deprecated] function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.\n```javascript\nescape('abc123');     // \"abc123\"\nescape('äöü');        // \"%E4%F6%FC\"\nescape('ć');          // \"%u0107\"\n\n// special characters\nescape('@*_+-./');    // \"@*_+-./\"\n```\n\nThe `unescape()` [deprecated] function computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like escape. Usually, `decodeURI()` or `decodeURIComponent()` are preferred over `unescape()`.\n```javascript\nunescape('abc123');     // \"abc123\"\nunescape('%E4%F6%FC');  // \"äöü\"\nunescape('%u0107');     // \"ć\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What do you understand by Screen objects?***\n\n* **window**: is the execution context and global object for that context's JavaScript\n* **document**: contains the DOM, initialized by parsing HTML\n* **screen**: The screen object contains information about the visitor's screen.\n\n**Properties:**  \n* screen.width\n* screen.height\n* screen.availWidth\n* screen.availHeight\n* screen.colorDepth\n* screen.pixelDepth\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How will you remove duplicates from an array in JavaScript?***\n\n**a.) Using set()**  \n```javascript\nconst names = ['John', 'Paul', 'George', 'Ringo', 'John'];\n\nlet unique = [...new Set(names)];\nconsole.log(unique); // 'John', 'Paul', 'George', 'Ringo'\n```\n**b.) Using filter()**   \n```javascript\nconst names = ['John', 'Paul', 'George', 'Ringo', 'John'];\n\nlet x = (names) =\u003e names.filter((v,i) =\u003e names.indexOf(v) === i)\nx(names); // 'John', 'Paul', 'George', 'Ringo'\n```\n**c.) Using forEach()**  \n```javascript\nconst names = ['John', 'Paul', 'George', 'Ringo', 'John'];\n\nfunction removeDups(names) {\n  let unique = {};\n  names.forEach(function(i) {\n    if(!unique[i]) {\n      unique[i] = true;\n    }\n  });\n  return Object.keys(unique);\n}\n\nremoveDups(names); // // 'John', 'Paul', 'George', 'Ringo'\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain NEGATIVE_INFINITY in JavaScript?***\n\n```javascript\nNumber.NEGATIVE_INFINITY;\n```\n\n- Negative infinity is a number in javascript, which is derived by 'dividing negative number by zero'.\n- A number object needs not to be created to access this static property.\n- The value of negative infinity is the same as the negative value of the infinity property of the global object.\n\n```javascript\nfunction checkNumber(smallNumber) {\n  if (smallNumber === Number.NEGATIVE_INFINITY) {\n    return 'Process number as -Infinity';\n  }\n  return smallNumber;\n}\n\nconsole.log(checkNumber(-Number.MAX_VALUE));\n// expected output: -1.7976931348623157e+308\n\nconsole.log(checkNumber(-Number.MAX_VALUE * 2));\n// expected output: \"Process number as -Infinity\"\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What do you understand by ViewState and SessionState?***\n\n**a.) Session State**: contains information that is pertaining to a specific session (by a particular client/browser/machine) with the server. It is a way to track what the user is doing on the site.. across multiple pages...amid the statelessness of the Web. e.g. the contents of a particular user's shopping cart is session data. Cookies can be used for session state.\n\n* Maintained at session level.\n* Session state value availability is in all pages available in a user session.\n* Information in session state stored in the server.\n* In session state, user data remains in the server.  The availability of the data is guaranteed until either the user closes the session or the browser is closed.\n* Session state is used for the persistence of user-specific data on the server’s end.\n\n**b.) View State**: on the other hand is information specific to particular web page. It is stored in a hidden field so that it is not visible to the user.\n\n* Maintained at page level only.\n* View state can only be visible from a single page and not multiple pages.\n* Information stored on the client’s end only.\n* View state will retain values in the event of a postback operation occurring.\n* View state is used to allow the persistence of page-instance-specific data.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain var self = this in JavaScript?***\n\n`self` is being used to maintain a reference to the original this even as the context is changing. It is a technique often used in event handlers (especially in closures).\n\n`this` is a JavaScript keyword which refers to the current context. Unlike other programming languages, JavaScript does not have block scoping(in C open/close {} curly braces refers to a block). JavaScript has two scopes namely, global and local scope.\n\n```javascript\nfunction Note() {\n  var self = this;\n\n  var note = document.createElement('div');\n  note.className = 'note';\n  note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);\n  note.addEventListener('click', function() { return self.onNoteClick() }, false);\n  this.note = note;\n  // ...\n}\n```\n\n*Note: 'self' should not be used this way anymore, since modern browsers provide a global variable self pointing to the global object of either a normal window or a WebWorker.*\n\nTo avoid confusion and potential conflicts, you can write var thiz = this or var that = this instead.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between append() vs appendChild()?*** \n\n* ParentNode.append() allows you to also append DOMString object, whereas Node.appendChild() only accepts Node objects.\n* ParentNode.append() has no return value, whereas Node.appendChild() returns the appended Node object.\n* ParentNode.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.\n\nThe main difference is that `appendChild()` is a DOM function meanwhile `append()` is a JavaScript function.\n```javascript\ndocument.getElementById(\"yourId\").append(\"Hello\");\n\nvar p = document.createElement(\"p\");\ndocument.getElementById(\"yourId\").appendChild(p);\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between null vs undefined?***\n\n**Null**  \n`Null` means an empty or non-existent value. Null is assigned, and explicitly means nothing.\n```javascript\nvar test = null;\nconsole.log(test); // null\n```\n`null` is also an object. Interestingly, this was actually an error in the original JavaScript implementation:\n```javascript\nconsole.log(typeof test); // object\n```\n**Undefined**  \nUndefined means a variable has been declared, but the value of that variable has not yet been defined. For example:\n```javascript\nvar test2;\nconsole.log(test2); // undefined\n```\nUnlike null, undefined is of the type undefined:\n```javascript\nconsole.log(typeof test2); // undefined\n```\n**Difference**  \n* `null` is an assigned value. It means nothing.\n* `undefined` means a variable has been declared but not defined yet.\n* `null` is an object. `undefined` is of type `undefined`.\n* `null !== undefined` but `null == undefined`.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between array[] vs object()?***\n\n`[]` is declaring an array.\n`{}` is declaring an object.\n\nAn array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === \"object\" to further show you that an array is an object.\n\nThe additional features consist of a magic `.length` property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as `.push()`, `.pop()`, `.slice()`, `.splice()`, etc... You can see a list of array methods here.\n\nAn object gives you the ability to associate a property name with a value as in:\n```javascript\nvar x = {};\nx.foo = 3;\nx[\"whatever\"] = 10;\nconsole.log(x.foo);      // shows 3\nconsole.log(x.whatever); // shows 10\n```\nObject properties can be accessed either via the `x.foo` syntax or via the array-like syntax `x[\"foo\"]`. The advantage of the latter syntax is that you can use a variable as the property name like `x[myvar]` and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the `x.foo` syntax.\n\nAn array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an **ordered**, **sequential** list of numbered indexes starting from `0` and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list `.sort()` or to add or remove things from the list.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between async() or defer() keyword in JavaScript?***\n\n**The async() Attribute**  \nThe async attribute is used to indicate to the browser that the script file can be executed asynchronously. The HTML parser does not need to pause at the point it reaches the script tag to fetch and execute, the execution can happen whenever the script becomes ready after being fetched in parallel with the document parsing.\n```html\n\u003cscript async src=\"script.js\"\u003e\n```\nThis attribute is only available for externally located script files. When an external script has this attribute, the file can be downloaded while the HTML document is still parsing. Once it has been downloaded, the parsing is paused for the script to be executed.\n\n**The defer() Attribute**  \nThe defer attribute tells the browser to only execute the script file once the HTML document has been fully parsed.\n```html\n\u003cscript defer src=\"script.js\"\u003e\n```\nLike an asynchronously loaded script, the file can be downloaded while the HTML document is still parsing. However, even if the file is fully downloaded long before the document is finished parsing, the script is not executed until the parsing is complete.\n\n\nAsynchronous and deferred execution of scripts are more important when the \u003cscript\u003e element is not located at the very end of the document. HTML documents are parsed in order, from the first opening \u003chtml\u003e element to it is close. If an externally sourced JavaScript file is placed right before the closing \u003c/body\u003e element, it becomes much less pertinent to use an async or defer attribute. Since the parser will have finished the vast majority of the document by that point, JavaScript files don not have much parsing left to block.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between async() and await() in ajax?***\n\nWhen an `async()` function is called, it returns a `Promise`. When the `async()` function returns a value, the `Promise` will be resolved with the returned value. When the `async()` function throws an exception or some value, the `Promise` will be rejected with the thrown value.\n\nAn async function can contain an `await()` expression, which pauses the execution of the `async()` function and waits for the passed Promise's resolution, and then resumes the `async()` function's execution and returns the resolved value. \n```javascript\nfunction resolveAfter2Seconds(x) {\n    return new Promise(resolve =\u003e {\n        setTimeout(() =\u003e {\n            resolve(x);\n        }, 2000);\n    });\n}\n\nasync function add1(x) {\n    const a = await resolveAfter2Seconds(20);\n    const b = await resolveAfter2Seconds(30);\n    return x + a + b;\n}\n\nadd1(10).then(v =\u003e {\n    console.log(v); // prints 60 after 4 seconds.\n});\n\nasync function add2(x) {\n    const p_a = resolveAfter2Seconds(20);\n    const p_b = resolveAfter2Seconds(30);\n    return x + await p_a + await p_b;\n}\n\nadd2(10).then(v =\u003e {\n    console.log(v); // prints 60 after 2 seconds.\n});\n```\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is request header in javascript?***\n\nThe `headers` read-only property of the `Request` interface contains the `Headers` object associated with the request.  \nSyntax\n```javascript\nvar myHeaders = request.headers;\n```\nExample\n```javascript\nvar myHeaders = new Headers();\nmyHeaders.append('Content-Type', 'image/jpeg');\n\nvar myInit = { \n  method: 'GET',\n  headers: myHeaders,\n  mode: 'cors',\n  cache: 'default' \n};\n\nvar myRequest = new Request('flowers.jpg', myInit);\nmyContentType = myRequest.headers.get('Content-Type'); // returns 'image/jpeg'\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is rendering in JavaScript?***\n\nJavaScript-powered content needs to be rendered before it can output meaningful code and be displayed for the client.\nThese are the different steps involved in the JavaScript rendering process:\n\n\u003cimg src=\"assets/javascript-stages.png\" alt=\"JavaScript Rendering Process\" /\u003e\n\n1. **JavaScript**: Typically JavaScript is used to handle work that will result in visual changes. \n2. **Style calculations**: This is the process of figuring out which CSS rules apply to which elements. They are applied and the final styles for each element are calculated. \n3. **Layout**: Once the browser knows which rules apply to an element it can begin to calculate how much space it takes up and where it is on screen. \n4. **Paint**: Painting is the process of filling in pixels. It involves drawing out text, colors, images, borders, and shadows, essentially every visual part of the elements. \n5. **Compositing**: Since the parts of the page were drawn into potentially multiple layers they need to be drawn to the screen in the correct order so that the page renders correctly.\n\nThe main responsibility of the rendering engine is to display the requested page on the browser screen.\nRendering engines can display HTML and XML documents and images. \n\nSimilar to the JavaScript engines, different browsers use different rendering engines as well. These are some of the popular ones:\n* **Gecko** — Firefox\n* **WebKit** — Safari\n* **Blink** — Chrome, Opera (from version 15 onwards)\n\n**The process of rendering**\n\nThe rendering engine receives the contents of the requested document from the networking layer.\n\n\u003cimg src=\"assets/rendering-process.png\" alt=\"Rendering Process\" /\u003e\n\n**Constructing the DOM tree**\n\nThe first step of the rendering engine is parsing the HTML document and converting the parsed elements to actual DOM nodes in a DOM tree.\n```html\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\"\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cp\u003e Hello, \u003cspan\u003e World! \u003c/span\u003e \u003c/p\u003e\n    \u003cdiv\u003e \n      \u003cimg src=\"smiley.gif\" alt=\"Smiley face\" height=\"42\" width=\"42\"\u003e\n    \u003c/div\u003e\n  \u003c/body\u003e\n\u003c/html\u003e\n```\nThe DOM tree for this HTML will look like this:\n\n\u003cimg src=\"assets/html-dom-tree.png\" alt=\"HTML DOM Tree\" /\u003e\n\nBasically, each element is represented as the parent node to all of the elements, which are directly contained inside of it. And this is applied recursively.\n\n**Constructing the CSSOM tree**\n\nCSSOM refers to the CSS Object Model. While the browser was constructing the DOM of the page, it encountered a link tag in the head section which was referencing the external theme.css CSS style sheet. Anticipating that it might need that resource to render the page, it immediately dispatched a request for it. Let’s imagine that the theme.css file has the following contents:\n```css\nbody { \n  font-size: 16px;\n}\n\np { \n  font-weight: bold; \n}\n\nspan { \n  color: red; \n}\n\np span { \n  display: none; \n}\n\nimg { \n  float: right; \n}\n```\nAs with the HTML, the engine needs to convert the CSS into something that the browser can work with — the CSSOM. Here is how the CSSOM tree will look like:\n\n\u003cimg src=\"assets/css-dom-tree.png\" alt=\"CSS DOM Tree\" /\u003e\n\nWhen computing the final set of styles for any object on the page, the browser starts with the most general rule applicable to that node (for example, if it is a child of a body element, then all body styles apply) and then recursively refines the computed styles by applying more specific rules.\n\n**Painting the render tree** \n\nIn this stage, the renderer tree is traversed and the renderer’s paint() method is called to display the content on the screen.\nPainting can be global or incremental (similar to layout):\n\n* **Global** — the entire tree gets repainted.\n* **Incremental** — only some of the renderers change in a way that does not affect the entire tree. The renderer invalidates its rectangle on the screen. This causes the OS to see it as a region that needs repainting and to generate a paint event. The OS does it in a smart way by merging several regions into one.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Define the various types of errors which occur in JavaScript programming language?***\n\nWhen an exception occurs, an object representing the error is created and thrown.  The JavaScript language defines seven types of built-in error objects. \n\n**Error**: The “Error” type is used to represent generic exceptions.  This type of exception is most often used for implementing user defined exceptions. \n```javascript\nvar error = new Error(\"error message\");\n```\n**RangeError**: “RangeError” exceptions are generated by numbers that fall outside of a specified range.\n```javascript\nvar pi = 3.14159;\n\npi.toFixed(100000);  // RangeError\n```\n**ReferenceError**: A “ReferenceError” exception is thrown when a non-existent variable is accessed.  These exceptions commonly occur when an existing variable name is misspelled. \n```javascript\nfunction foo() {\n  bar++;  // ReferenceError\n}\n```\n**SyntaxError**: A “SyntaxError” is thrown when the rules of the JavaScript language are broken. \n```javascript\nif (foo) {  // SyntaxError\n  // the closing curly brace is missing\n```\n**TypeError**: A “TypeError” exception occurs when a value is not of the expected type.  Attempting to call a non-existent object method is a common cause of this type of exception. \n```javascript\nvar foo = {};\n\nfoo.bar(); // TypeError\n```\n**URIError**: A “URIError” exception is thrown by methods such as encodeURI() and decodeURI() when they encounter a malformed URI. The following example generates a “URIError” while attempting to decode the string “%”.  The “%” character represents the beginning of a URI escape sequence.  Since nothing follows the “%” in this example, the string is an invalid escape sequence, and therefore a malformed URI component.\n```javascript\ndecodeURIComponent(\"%\"); // URIError\n```\n**EvalError**: “EvalError” exceptions are thrown when the eval() function is used improperly.  These exceptions are not used in the most recent version of the EcmaScript standard.  However, they are still supported in order to maintain backwards compatibility with older versions of the standard.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is unshift() method in JavaScript?***\n\nThe `unshift()` method adds one or more elements to the beginning of an array and returns the new length of the array.\n```javascript\nvar arr = [1, 2, 3];\n\nconsole.log(arr.unshift(4, 5)); // Output: 5\nconsole.log(arr); // Output: Array [4, 5, 1, 2, 3]\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between HTMLCollection and NodeList?***\n\n**HTMLCollection**\n\nAn HTMLCollection is a list of nodes. An individual node may be accessed by either ordinal index or the node’s name or id attributes. Collections in the HTML DOM are assumed to be live meaning that they are automatically updated when the underlying document is changed.\n\n**NodeList**\n\nA NodeList object is a collection of nodes. The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live or static based on the interface used to retrieve them\n\n**Difference**\n\nAn HTMLCollection is a list of webpage elements (div, p, ul, li, img objects, etc…) which form part of the DOM, and are of a specific node type usually referred to as an element node. A NodeList is also a list of nodes, but it can contain a list not only of element nodes, but other types of nodes as well. So it is a more generic list of nodes than HTMLCollection. HTMLCollection tells you that what it contains are webpage elements, specifically.\n\nBoth interfaces are collections of DOM nodes. They differ in the methods they provide and in the type of nodes they can contain. While a NodeList can contain any node type, an HTMLCollection is supposed to only contain Element nodes.\nAn HTMLCollection provides the same methods as a NodeList and additionally a method called namedItem.\n\nCollections are always used when access has to be provided to multiple nodes, e.g. most selector methods (such as getElementsByTagName) return multiple nodes or getting a reference to all children (element.childNodes).\n\n**Attribute Node**\n\nRefers to the attributes of an element node.  \n```javascript\n// html: \u003cdiv id=”my-id” /\u003e \nlet element = document.getElementById(“my-id”); \nlet myIdAttribute = element.getAttributeNode(“id”); \nconsole.log(myIdAttribute); // output: my-id\n```\n**Text Node**\n\nRefers to the text of an element.\n```javascript\n// html: \u003cdiv id=”my-id”\u003e\u003c/div\u003e\nlet element = document.getElementById(“my-id”);\nlet text = document.createTextNode(“Some Text”);\nelement.appendChild(text);\n// updated html: \u003cdiv id=”my-id”\u003eSome Text\u003c/div\u003e\n```\n**Comment Node**\n\n```javascript\n\u003c!-- This is what a comment node looks like --\u003e\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between firstChild and firstElementChild?***\n\n**firstChild**  \nThe firstChild property returns the first child node of the specified node, as a Node object.\n```html\n\u003cul id=\"myList\"\u003e\n    \u003cli\u003eCoffee\u003c/li\u003e\n    \u003cli\u003eTea\u003c/li\u003e\n\u003c/ul\u003e\n```\n```javascript\nvar list = document.getElementById(\"myList\").firstChild.innerHTML; // Coffee\n```\n**firstElementChild**  \nThe firstElementChild property returns the first child element of the specified element.\n```html\n\u003cul id=\"myList\"\u003e\n  \u003cli\u003eCoffee\u003c/li\u003e\n  \u003cli\u003eTea\u003c/li\u003e\n\u003c/ul\u003e\n```\n```javascript\nvar list = document.getElementById(\"myList\").firstElementChild.innerHTML; // Coffee\n```\n\n**Difference**  \nThe difference between this property and firstElementChild, is that firstChild returns the first child node as an element node, a text node or a comment node (depending on which one's first), while firstElementChild returns the first child node as an element node (ignores text and comment nodes).\n\n*Note: Whitespace inside elements is considered as text, and text is considered as nodes*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Name the two functions that are used to create an HTML element dynamically?***\n\n**createElement**  \nIn an HTML document, the `document.createElement()` method creates the HTML element specified by tagName.\nSyntax\n```javascript\nvar element = document.createElement(tagName[, options]);\n```\nHTML\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n  \u003chead\u003e\n      \u003ctitle\u003e||Working with elements||\u003c/title\u003e\n  \u003c/head\u003e\n\u003cbody\u003e\n  \u003cdiv id=\"div1\"\u003eThe text above has been created dynamically.\u003c/div\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\nJavaScript\n```javascript\ndocument.body.onload = addElement;\n\nfunction addElement () { \n  // create a new div element \n  var newDiv = document.createElement(\"div\"); \n  // and give it some content \n  var newContent = document.createTextNode(\"Hi there and greetings!\"); \n  // add the text node to the newly created div\n  newDiv.appendChild(newContent);  \n\n  // add the newly created element and its content into the DOM \n  var currentDiv = document.getElementById(\"div1\"); \n  document.body.insertBefore(newDiv, currentDiv); \n}\n```\n**Create Dynamic Button**  \n```javascript\nvar btn = document.createElement(\"BUTTON\");\nbtn.innerHTML = \"CLICK ME\";\ndocument.body.appendChild(btn);\n```\n**Removing Elements Dynamically**  \n```javascript\nfunction removeElement(elementId) {\n    // Removes an element from the document\n    var element = document.getElementById(elementId);\n    element.parentNode.removeChild(element);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is callback() function in javascript?***\n\nA 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.\n```javascript\nfunction greeting(name) {\n  alert('Hello ' + name);\n}\n\nfunction processUserInput(callback) {\n  var name = prompt('Please enter your name.');\n  callback(name);\n}\n\nprocessUserInput(greeting);\n```\nThe above example is a synchronous callback, as it is executed immediately.\n\n*Note: callbacks are often used to continue code execution after an asynchronous operation has completed — these are called asynchronous callbacks. A good example is the callback functions executed inside a `.then()` block chained onto the end of a promise after that promise fulfills or rejects. This structure is used in many modern web APIs, such as `fetch()`*.\n\nIn JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions. Functions that do this are called `higher-order` functions. Any function that is passed as an argument is called a callback function.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is shallow copy and deep copy in javascript?***\n\n**Shallow copy**\n\nShallow copy is a bit-wise 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.\n\n**Deep copy**\n\nA 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.\n\n\u003cimg src=\"assets/deepcopy.png\" alt=\"Shallow Copy and Deep Copy\" /\u003e\n\nA Shallow copy of the object can be done using `object.assign()` method in javascript.\n```javascript\nlet obj = {\n  a: 1,\n  b: 2,\n};\nlet objCopy = Object.assign({}, obj);\nconsole.log(objCopy); // Result - { a: 1, b: 2 }\n```\nA Deep copy of the object can be done using JSON.parse(JSON.stringify(object));\n```javascript\nlet obj = { \n  a: 1,\n  b: { \n    c: 2,\n  },\n}\nlet newObj = JSON.parse(JSON.stringify(obj));\nobj.b.c = 20;\nconsole.log(obj); // { a: 1, b: { c: 20 } }\nconsole.log(newObj); // { a: 1, b: { c: 2 } } (New Object Intact!)\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is difference between stoppropagation vs stopimmediatepropagation vs preventdefault in javascript?***\n\n**a.) event.stopPropagation()**:  Whenever a event is raised, event will propagate or bubble up till the window object level.\n\n**Example**: Parent Div containing a Child Div and both are registered for click events. When Child Div clicked, event handlers for both Child Div and Parent Div will be fired. To avoid the event bubbling  to top level DOM hierarchy, use the `event.stopPropagation()`.\n\n**b.) event.stopImmediatePropagation()**: The event handlers will be called in the order they have registered. Lets say for a Div element click event is registered from different places. Then when the  Div element is clicked, the click event handler will be fired in all the places.\n\nSince `event.stopPropagation()` will only stop event propagation to parent level and  not at the same element level, so to avoid the event firing at multiple places  we have to use `event.stopImmediatePropagation()`.\n\n**c.) event.preventDefault()**:  Browsers have default behaviors like\n\n* when a anchor tag is clicked, it will load the url specified in the href attribute,\n* when a text content is double clicked it will selected the text.\nSo, to avoid these default browser behavior use `event.preventDefault()`.\n\n**Example**: A click event handler is registered for anchor tag, Based on some logic in the event handler  want to suppress the default browser behavior i.e loading the url.\n\n*Note: Some older versions of IE wont recognize `event.preventDefault()`. So, use `return false`*;\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain array methods [ join(), pop(), push(), shift(), unshift(), concat(), map(), filter(), reduce(), reduceRight(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex(), includes() ]***\n\n**a.) array.join()**: The `join()` method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. \n```javascript\nvar elements = ['Fire', 'Air', 'Water'];\n\nconsole.log(elements.join()); // Output: \"Fire,Air,Water\"\nconsole.log(elements.join('')); // Output: \"FireAirWater\"\nconsole.log(elements.join('-')); // Output: \"Fire-Air-Water\"\n```\n**b.) array.pop()**: The pop() method removes the last element from an array and returns that element. This method changes the length of the array.\n```javascript\nvar plants = ['broccoli', 'cauliflower', 'kale'];\n\nconsole.log(plants.pop()); // Output: \"kale\"\nconsole.log(plants); // Output: Array [\"broccoli\", \"cauliflower\"]\nconsole.log(plants.pop()); // Output: \"cauliflower\"\nconsole.log(plants.pop()); // Output: \"broccoli\"\nconsole.log(plants.pop()); // Output: \"undefined\"\n```\n**c.) array.push()**: The push() method adds one or more elements to the end of an array and returns the new length of the array.\n```javascript\nconst animals = ['pigs', 'goats', 'sheep'];\n\nconst count = animals.push('cows');\nconsole.log(count); // Output: 4\nconsole.log(animals); // Output: Array [\"pigs\", \"goats\", \"sheep\", \"cows\"]\n```\n**d.) array.shift()**: The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.\n```javascript\nvar fruits = [\"Banana\", \"Orange\", \"Apple\", \"Mango\"];\nfruits.shift();\nconsole.log(fruits) // Output: Array [\"Orange\", \"Apple\", \"Mango\"]\n```\n**e.) array.unshift()**: The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.\n```javascript\nvar fruits = [\"Banana\", \"Orange\", \"Apple\"];\nfruits.unshift(\"Mango\",\"Pineapple\");\nconsole.log(fruits); // Output: Array [\"Mango\", \"Pineapple\", \"Banana\", \"Orange\", \"Apple\"]\n```\n**f.) array.concat()**: The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.\n```javascript\nconst array1 = ['a', 'b', 'c'];\nconst array2 = ['d', 'e', 'f'];\n\nconsole.log(array1.concat(array2)); // Output: Array [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"]\n```\n**g.) array.map()**: The map() method creates a new array with the results of calling a provided function on every element in the calling array.\n```javascript\nvar array1 = [1, 4, 9, 16];\n\n// pass a function to map\nconst map1 = array1.map(x =\u003e x * 2); \n\nconsole.log(map1); // Output: Array [2, 8, 18, 32]\n```\n**h.) array.filter()**: The filter() method creates a new array with all elements that pass the test implemented by the provided function.\n```javascript\nvar words = ['spray', 'limit', 'elite', 'exuberant', 'destruction'];\n\nconst result = words.filter(word =\u003e word.length \u003e 6);\n\nconsole.log(result); // Output: Array [\"exuberant\", \"destruction\"]\n```\n**i.) array.reduce()**: The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.\n```javascript\nconst array1 = [1, 2, 3, 4];\nconst reducer = (accumulator, currentValue) =\u003e accumulator + currentValue;\n\nconsole.log(array1.reduce(reducer)); // Output: 10\nconsole.log(array1.reduce(reducer, 5)); // Output: 15\n```\n**j.) array.reduceRight()**: The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.\n```javascript\nconst array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(\n  (accumulator, currentValue) =\u003e accumulator.concat(currentValue)\n);\n\nconsole.log(array1); // Output: Array [4, 5, 2, 3, 0, 1]\n```\n**k.) array.every()**: The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. \n```javascript\nfunction isBelowThreshold(currentValue) {\n  return currentValue \u003c 40;\n}\n\nvar array1 = [1, 30, 39, 29, 10, 13];\nconsole.log(array1.every(isBelowThreshold)); // Output: true\n```\n**l.) array.some()**: The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value. \n```javascript\nvar array = [1, 2, 3, 4, 5];\n\nvar even = function(element) {\n  // checks whether an element is even\n  return element % 2 === 0;\n};\n\nconsole.log(array.some(even)); // Output: true\n``` \n**m.) array.indexOf()**: The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.\n```javascript\nvar beasts = ['ant', 'bison', 'camel'];\n\nconsole.log(beasts.indexOf('camel')); // Output: 2\nconsole.log(beasts.indexOf('giraffe')); // Output: -1\n```\n**n.) array.lastIndexOf()**: The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.\n```javascript\nvar paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';\n\nvar searchTerm = 'dog';\n\nconsole.log('The index of the first \"' + searchTerm + '\" from the end is ' + paragraph.lastIndexOf(searchTerm));\n// Output: \"The index of the first \"dog\" from the end is 52\"\n```\n**o.) array.find()**: The find() method returns the value of the first element in the provided array that satisfies the provided testing function.\n```javascript\nvar array1 = [5, 12, 8, 130, 44];\n\nvar found = array1.find(function(element) {\n  return element \u003e 100;\n});\n\nconsole.log(found); // Output: 130\n```\n**p.) array.findIndex()**: The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.\n```javascript\nvar array1 = [5, 12, 8, 130, 44];\n\nfunction isLargeNumber(element) {\n  return element \u003e 20;\n}\n\nconsole.log(array1.findIndex(isLargeNumber)); // Output: 3\n```\n**q.) array.includes()**: The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.\n```javascript\nvar array1 = [1, 2, 3];\nconsole.log(array1.includes(2)); // Output: true\n\nvar pets = ['cat', 'dog', 'bat'];\nconsole.log(pets.includes('at')); // Output: false\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***When to use function declarations and expressions in JavaScript?***\n\n**Function Declarations**\nA declared function is “saved for later use”, and will be executed later, when it is invoked (called).\n```javascript\n// Function declaration\nfunction add(num1, num2) {\n\treturn num1 + num2;\n}\n```\nfunction is only declared here. For using it, it must be invoked using function name. e.g add(10, 20);  \n\n**Function Expression**   \nA function expression can be stored in a variable:\n```javascript\n// Function expression\nvar add = function (num1, num2) {\n\treturn num1 + num2;\n};\n```\nAfter a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.\n\n**Difference**  \n* `Function declarations` load before any code is executed while `Function expressions` load only when the interpreter reaches that line of code.\n* Similar to the `var` statement, function declarations are hoisted to the top of other code. Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.  \n\n**Benefits of Function Expressions**  \nThere are several different ways that function expressions become more useful than function declarations.\n* As closures\n* As arguments to other functions\n* As Immediately Invoked Function Expressions (IIFE)\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to avoid callback hell in javascript?***\n\n**Callback hell** is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. Some people call it to be the **pyramid of doom**.  \n\nExample\n```javascript\ndoSomething(param1, param2, function(err, paramx){\n    doMore(paramx, function(err, result){\n        insertRow(result, function(err){\n            yetAnotherOperation(someparameter, function(s){\n                somethingElse(function(x){\n                });\n            });\n        });\n    });\n});\n```\n**Techniques for avoiding callback hell**  \n* Write comments\n* Split functions into smaller functions\n* Using Async.js\n* Using Promises\n* Using Async-Await\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Why is eval() considered evil and dangerous?***\n\nThe `eval()` function evaluates JavaScript code represented as a string.\n```javascript\nconsole.log(eval('2 + 2')); // Output: 4\n```\n`eval()` is heavily discouraged because it combines several common issues.\n* **Performance** - eval() runs the interpreter/compiler. If your code is compiled, then this is a big hit, because you need to call a possibly-heavy compiler in the middle of run-time. However, JavaScript is still mostly an interpreted language, which means that calling eval() is not a big performance hit in the general case.\n* **Code injection** - eval() potentially runs a string of code under elevated privileges. For example, a program running as administrator/root would never want to eval() user input, because that input could potentially be \"rm -rf /etc/important-file\" or worse.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is the difference between encryption and hashing?***\n\n**Encryption**  \nEncryption is the process of encoding simple text and other information that can be accessed by the sole authorized entity if it has a decryption key. It will protect your sensitive data from being accessed by cybercriminals. It is the most effective way of achieving data security in modern communication systems. There are a number of encryption systems, where an asymmetric encryption is also known as public-key encryption, symmetric encryption and hybrid encryption are the most common.\n\n* **Symmetric encryption** – Uses the same secret key to encrypt and decrypt the message. The secret key can be a word, a number or a string of random letters.  Both the sender and the receiver should have the key. It is the oldest technique of encryption.\n* **Asymmetric encryption** – It deploys two keys, a public key known by everyone and a private key known only by the receiver. The public key is used to encrypt the message and a private key is used to decrypt it. Asymmetric encryption is little slower than symmetric encryption and consumes more processing power when encrypting data.\n* **Hybrid encryption** – It is a process of encryption that blends both symmetric and asymmetric encryption. It takes advantage of the strengths of the two encryptions and minimizes their weakness.\n\n**Purpose of encryption**  \n* Confidentiality – Encrypted message cannot be read or changed by another person.\n* Encrypt – It transforms data in such a way that only specific individuals can transform the message.\n* Granular access control – Users are limited to what they can see and do.\n* It makes auditing for accountability easy. In the case of message leaked, it is easy to trace who did that and when thus security breaches can be sorted out efficiently.\n* Authentication – the origin of the message received can be traced thus facilitating authentication.\n\n**Hashing**  \nIn hashing, data is converted to the hash using some hashing function, which can be any number generated from string or text. Various hashing algorithms are MD5, SHA256. Data once hashed is non-reversible.\n\nHash function can be any function that is used to map data of arbitrary size to data of fixed size. The data structure hash table is used for storing of data.\n\nFor example: When images are sent to different server and text is sent to a different server for efficiency purposes. So for verifying images that the images are not tampered in between data transfer over the internet, hashing algorithm like `MD5()`, `SHA()` algorithm can be used.\n\n**Purpose of hashing**  \n* Hashing can be used to compare a large amount of data. Hash values can be created for different data, meaning that it is easier comparing hashes than the data itself.\n* It is easy to find a record when the data is hashed.\n* Hashing algorithms are used in cryptographic applications like a digital signature.\n* Hashing is used to generate random strings to avoid duplication of data stored in databases.\n* Geometric hashing – widely used in computer graphics to find closet pairs and proximity problems in planes. It is also called grid method and it has also been adopted in telecommunications.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is Proxies and Reflection in JavaScript?***\n\nJavaScript support for the Proxy and Reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). \n\n**Proxies**  \nThe `Proxy` object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc). For example getting a property on an object:\n```javascript\nvar handler = {\n  get: function(target, name) {\n    return name in target ? target[name] : 42;\n  }\n};\n\nvar p = new Proxy({}, handler);\np.a = 1;\nconsole.log(p.a, p.b); // 1, 42\n```\nThe Proxy object defines a target (an empty object here) and a handler object in which a get trap is implemented. Here, an object that is proxied will not return undefined when getting undefined properties, but will instead return the number 42.\n\n**Reflection**  \nReflection is defined as the ability of a program to inspect and modify its structure and behavior at runtime. `Reflect` is not a function object.\n\n`Reflect` helps with forwarding default operations from the handler to the target.\n```javascript\nReflect.apply(Math.floor, undefined, [1.75]); // 1;\n\nReflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); // \"hello\"\n\nReflect.apply(RegExp.prototype.exec, /ab/, ['confabulation']).index; // 4\n\nReflect.apply(''.charAt, 'ponies', [3]); // \"i\"\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do you check whether an object can be extendable or not?***\n\nThe `Object.isExtensible()` method is used to determine if an object is extensible or not. i.e, Whether it can have new properties added to it or not.\n```javascript\nconst newObject = {};\nconsole.log(Object.isExtensible(newObject)); //true\n```\n*Note: By default, all the objects are extendable. i.e, The new properties can added or modified.*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the different ways to make an object non-extensible?***\n\n\n* `Object.preventExtensions()`\n* `Object.seal()`\n* `Object.freeze()`\n\n```javascript\nvar newObject = {};\n\nObject.preventExtensions(newObject); // Prevent objects are non-extensible\nObject.isExtensible(newObject); // false\n\nvar sealedObject = Object.seal({}); // Sealed objects are non-extensible\nObject.isExtensible(sealedObject); // false\n\nvar frozenObject = Object.freeze({}); // Frozen objects are non-extensible\nObject.isExtensible(frozenObject); // false\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Is enums feature available in javascript?***\n\nNo, javascript does not natively support enums. But there are different kind of solutions to simulate them even though they may not provide exact equivalent. For example, you can use freeze or seal on object,\n\n```javascript\nvar DaysEnum = Object.freeze({\"monday\":1, \"tuesday\":2, \"wednesday\":3, ...})\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How do I modify the url without reloading the page?***\n\nThe `window.localtion.url` property will be helpful to modify the url but it reloads the page. HTML5 introduced the `history.pushState()` and `history.replaceState()` methods, which allow you to add and modify history entries, respectively. Example:\n```javascript\nwindow.history.pushState('newPage', 'Title', '/newPage.html');\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What is throttling and debouncing in javascript?***\n\nDebouncing and throttling techniques are used to limit the number of times a function can execute. These are two widely-used techniques to improve the performance of code that gets executed repeatedly within a period of time.\n\n**Throttling** enforces a maximum number of times a function can be called over time. As in \"execute this function at most once every 100 milliseconds.\"\n\nExample:\n```javascript\n$(\"body\").on('scroll', _.throttle(function() {\n  // Do expensive things\n}, 100));\n```\n**Debouncing** enforces that a function not be called again until a certain amount of time has passed without it being called. As in \"execute this function only if 100 milliseconds have passed without it being called.\"\n\nExample:\n```javascript\n$(window).on('resize', _.debounce(function() {\n  // Do expensive things\n}, 100));\n```\n\n**Example: Use Case**  \n\n* Throttling a button click so we can’t spam click\n* Throttling an API call\n* Throttling a mousemove event handler\n* Debouncing a resize event handler\n* Debouncing a scroll event handler\n* Debouncing a save function in an autosave feature\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to validate JSON Object in javascript?***\n\n```javascript\nfunction isValidJson(json) {\n    try {\n        JSON.parse(json);\n        return true;\n    } catch (e) {\n        return false;\n    }\n}\n\nvar validjson = '{\"firstName\":\"James\",\"lastName\":\"Bond\"}'; \nvar invalidjson = '{\"firstName\"\"James\",\"lastName\":\"Bond\"}'; \n\nconsole.log(\"With Valid JSON Text: \"+isValidJson(validjson)); //true\nconsole.log(\"With inValid JSON Text: \"+isValidJson(invalidjson)); //false\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to check if page is fully loaded using javascript?***\n\n```javascript\nif (document.readyState === 'complete') {\n  // The page is fully loaded\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain browser console logs features?***\n\nThe `Console` method **log()** outputs a message to the web console. The message may be a single string or it may be any one or more JavaScript objects.\n\n**a.) console.table()**\n```javascript\nconst artists = [\n  {\n    first: 'René',\n    last: 'Magritte'\n  },\n  {\n    first: 'Chaim',\n    last: 'Soutine'\n  },\n  {\n    first: 'Henri',\n    last: 'Matisse'\n  }\n];\nconsole.table(artists);\n```\nOutput\n\n\u003cimg src=\"assets/console_table.png\" alt=\"Console Table\"/\u003e\n\n**b.) console.log()**\n\n\u003cimg src=\"assets/console.log.png\" alt=\"Console Log\"/\u003e\n\n**c.) console.warn()**\n\n\u003cimg src=\"assets/console.warn.png\" alt=\"Console Warning\"/\u003e\n\n**d.) console.error()**\n\n\u003cimg src=\"assets/console.error.png\" alt=\"Console Error\"/\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***What are the difference between console.log() and console.dir()?***\n\n* `console.log()` prints the element in an HTML-like tree\nOutput\n\n\u003cimg src=\"assets/console_log.png\" alt=\"Console Log\"/\u003e\n\n* `console.dir()` prints the element in a JSON-like tree\nOutput\n\n\u003cimg src=\"assets/console_dir.png\" alt=\"Console Dir\"/\u003e\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to Copy Text to Clipboard?***\n\n```html\n\u003c!-- The text field --\u003e\n\u003cinput type=\"text\" id=\"inputText\" value=\"Hello World\"\u003e\n\n\u003c!-- The button used to copy the text --\u003e\n\u003cbutton onclick=\"copy()\"\u003eCopy text\u003c/button\u003e\n```\n```javascript\nfunction copy() {\n  /* Get the text field */\n  let copyText = document.getElementById(\"inputText\");\n\n  /* Select the text field */\n  copyText.select();\n  copyText.setSelectionRange(0, 99999); /*For mobile devices*/\n\n  /* Copy the text inside the text field */\n  document.execCommand(\"copy\");\n\n  /* Alert the copied text */\n  alert(\"Copied the text: \" + copyText.value);\n}\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***Explain types of Memory Leaks in JavaScript?***\n\n*[Reference](https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/)*\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How accidental closures might cause memory leaks in IE?***\n\nA closure is a combination of a function and the lexical environment within which that function was declared. A closure is an inner(enclosed) function that has access to the outer (enclosing) function’s variables(scope). Also the inner function will continue to have access to the outer function’s scope even after the outer function is executed.\n\nA memory leak occurs in a closure if a variable is declared in outer function becomes automatically available to the nested inner function and continues to reside in memory even if it is not being used/referenced in the nested function.\n```javascript\nvar newElem;\n \nfunction outer() {\n    var someText = new Array(1000000);\n    var elem = newElem;\n\n    function inner() {\n        if (elem) return someText;\n    }\n\n    return function () {};\n}\n\nsetInterval(function () {\n    newElem = outer();\n}, 5);\n```\nIn the above example, function inner is never called but keeps a reference to elem. But as all inner functions in a closure share the same context, inner shares the same context as function(){} which is returned by outer function. Now in every 5ms we make a function call to outer and assign its new value(after each call) to newElem which is a global variable. As long a reference is pointing to this function(){}, the shared scope/context is preserved and someText is kept because it is part of the inner function even if inner function is never called. Each time we call outer we save the previous function(){} in elem of the new function. Therefore again the previous shared scope/context has to be kept. So in the nth call of outer function, someText of the (n-1)th call of outer cannot be garbage collected. This process continues until your system runs out of memory eventually.\n\n**SOLUTION**: The problem in this case occurs because the reference to function(){} is kept alive. There will be no javascript memory leak if the outer function is actually called(Call the outer function like newElem = outer()();). A small isolated javascript memory leak resulting from closures might not need any attention. However a periodic leak repeating and growing with each iteration can seriously damage the performance of your code.\n\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n\n## Q. ***How to convert Decimal to Binary in JavaScript?***\n\n```javascript\n\nvar val = 10;\n\nconsole.log(val.toString(2)); // 1010  ==\u003e Binary Conversion\n\nconsole.log(val.toString(8)); // 12  ==\u003e Octal Conversion\n\nconsole.log(val.toString(16)); // A  ==\u003e Hexadecimal Conversion\n```\n\u003cdiv align=\"right\"\u003e\n    \u003cb\u003e\u003ca href=\"#\"\u003e↥ back to top\u003c/a\u003e\u003c/b\u003e\n\u003c/div\u003e\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faakashdeveloper%2Fjavascript-interview-question","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faakashdeveloper%2Fjavascript-interview-question","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faakashdeveloper%2Fjavascript-interview-question/lists"}