# JavaScript Interview Questions with Answers ## Table of Contents |No.| Questions | |-----|-----------------------------------------------------------------------------------| | 01.|[What is difference between document.getElementById() and document.querySelector()?](#1-what-is-difference-between-documentgetelementbyid-and-documentqueryselector)| | 02.|[When to use reduce(), map(), foreach() and filter() in JavaScript?](#2-when-to-use-reduce-map-foreach-and-filter-in-javascript)| | 03.|[What is Hoisting in JavaScript?](#3-what-is-hoisting-in-javascript)| | 04.|[What are closures?](#4-what-are-closures)| | 05.|[How do you clone an object in JavaScript?](#5-how-do-you-clone-an-object-in-javascript)| | 06.|[What are the possible ways to create objects in JavaScript?](#6-what-are-the-possible-ways-to-create-objects-in-javascript)| | 07.|[What are the javascript data types?](#7-what-are-the-javascript-data-types)| | 08.|[What are global variables?](#8-what-are-global-variables)| | 09.|[What is variable shadowing in javascript?](#9-what-is-variable-shadowing-in-javascript)| | 10.|[What is an event flow?](#10-what-is-an-event-flow)| | 11.|[What is event bubbling?](#11-what-is-event-bubbling)| | 12.|[What is event capturing?](#12-what-is-event-capturing)| | 13.|[What is prototype chain?](#13-what-is-prototype-chain)| | 14.|[What is the difference between Call, Apply and Bind?](#14-what-is-the-difference-between-call-apply-and-bind)| | 15.|[What is the difference between == and === operators?](#15-what-is-the-difference-between--and--operators)| | 16.|[What is a first class function?](#16-what-is-a-first-class-function)| | 17.|[What is a higher order function?](#17-what-is-a-higher-order-function)| | 18.|[What is a unary function?](#18-what-is-a-unary-function)| | 19.|[What is currying function?](#19-what-is-currying-function)| | 20.|[What is a pure function?](#20-what-is-a-pure-function)| | 21.|[What is memoization in JavaScript?](#21-what-is-memoization-in-javascript)| | 22.|[What is a service worker?](#22-what-is-a-service-worker)| | 23.|[How do you manipulate DOM using service worker?](#23-how-do-you-manipulate-dom-using-service-worker)| | 24.|[How do you reuse information across service worker restarts?](#24-how-do-you-reuse-information-across-service-worker-restarts)| | 25.|[What is a post message?](#25-what-is-a-post-message)| | 26.|[What is a web-storage event and its event handler?](#26-what-is-a-web-storage-event-and-its-event-handler)| | 27.|[How to use Web Workers in javascript?](#27-how-to-use-web-workers-in-javascript)| | 28.|[What are the restrictions of web workers on DOM?](#28-what-are-the-restrictions-of-web-workers-on-dom)| | 29.|[What is a promise?](#29-what-is-a-promise)| | 30.|[What is a callback function?](#30-what-is-a-callback-function)| | 31.|[Why do we need callbacks?](#31-why-do-we-need-callbacks)| | 32.|[What is a callback hell?](#32-what-is-a-callback-hell)| | 33.|[What is server-sent events?](#33-what-is-server-sent-events)| | 34.|[What is callback in callback?](#34-what-is-callback-in-callback)| | 35.|[What is promise chaining?](#35-what-is-promise-chaining)| | 36.|[What is promise.all()?](#36-what-is-promiseall)| | 37.|[What is the purpose of race method in promise?](#37-what-is-the-purpose-of-race-method-in-promise)| | 38.|[What is a strict mode in javascript?](#38-what-is-a-strict-mode-in-javascript)| | 39.|[What is the purpose of double exclamation?](#39-what-is-the-purpose-of-double-exclamation)| | 40.|[What is the purpose of delete operator?](#40-what-is-the-purpose-of-delete-operator)| | 41.|[What is typeof operator?](#41-what-is-typeof-operator)| | 42.|[What is undefined property?](#42-what-is-undefined-property)| | 43.|[What is the difference between null and undefined?](#43-what-is-the-difference-between-null-and-undefined)| | 44.|[What is eval?](#44-what-is-eval)| | 45.|[What is the difference between window and document?](#45-what-is-the-difference-between-window-and-document)| | 46.|[How do you access history in javascript?](#46-how-do-you-access-history-in-javascript)| | 47.|[What is isNaN?](#47-what-is-isnan)| | 48.|[What are the differences between undeclared and undefined variables?](#48-what-are-the-differences-between-undeclared-and-undefined-variables)| | 49.|[What is NaN property?](#49-what-is-nan-property)| | 50.|[What is the purpose of isFinite function?](#50-what-is-the-purpose-of-isfinite-function)| | 51.|[How do you submit a form using JavaScript?](#51-how-do-you-submit-a-form-using-javascript)| | 52.|[How do you find operating system details?](#52-how-do-you-find-operating-system-details)| | 53.|[What is the difference between document load and DOMContentLoaded events?](#53-what-is-the-difference-between-document-load-and-domcontentloaded-events)| | 54.|[What is the difference between native, host and user objects?](#54-what-is-the-difference-between-native-host-and-user-objects)| | 55.|[What are the pros and cons of promises over callbacks?](#55-what-are-the-pros-and-cons-of-promises-over-callbacks)| | 56.|[What is the difference between an attribute and a property?](#56-what-is-the-difference-between-an-attribute-and-a-property)| | 57.|[What is same-origin policy?](#57-what-is-same-origin-policy)| | 58.|[What is the purpose of void(0)?](#58-what-is-the-purpose-of-void0)| | 59.|[Is JavaScript a compiled or interpreted language?](#59-is-javascript-a-compiled-or-interpreted-language)| | 60.|[Is JavaScript a case-sensitive language?](#60-is-javascript-a-case-sensitive-language)| | 61.|[What are events?](#61-what-are-events)| | 62.|[What is the use of preventDefault method?](#62-what-is-the-use-of-preventdefault-method)| | 63.|[What is the use of stopPropagation method?](#63-what-is-the-use-of-stoppropagation-method)| | 64.|[What are the steps involved in return false usage?](#64-what-are-the-steps-involved-in-return-false-usage)| | 65.|[What is BOM?](#65-what-is-bom)| | 66.|[What is the use of setTimeout?](#66-what-is-the-use-of-settimeout)| | 67.|[What is the use of setInterval?](#67-what-is-the-use-of-setinterval)| | 68.|[Why is JavaScript treated as Single threaded?](#68-why-is-javascript-treated-as-single-threaded)| | 69.|[What is an event delegation?](#69-what-is-an-event-delegation)| | 70.|[What is the purpose JSON stringify?](#70-what-is-the-purpose-json-stringify)| | 71.|[How do you parse JSON string?](#71-how-do-you-parse-json-string)| | 72.|[What is the purpose of clearTimeout method?](#72-what-is-the-purpose-of-cleartimeout-method)| | 73.|[What is the purpose of clearInterval method?](#73-what-is-the-purpose-of-clearinterval-method)| | 74.|[How do you redirect new page in javascript?](#74-how-do-you-redirect-new-page-in-javascript)| | 75.|[How do you check whether a string contains a substring?](#75-how-do-you-check-whether-a-string-contains-a-substring)| | 76.|[How do you validate an email in javascript?](#76-how-do-you-validate-an-email-in-javascript)| | 77.|[How do you get the current url with javascript?](#77-how-do-you-get-the-current-url-with-javascript)| | 78.|[What are the various url properties of location object?](#78-what-are-the-various-url-properties-of-location-object)| | 79.|[How do get query string values in javascript?](#79-how-do-get-query-string-values-in-javascript)| | 80.|[How do you check if a key exists in an object?](#80-how-do-you-check-if-a-key-exists-in-an-object)| | 81.|[How do you loop through or enumerate javascript object?](#81-how-do-you-loop-through-or-enumerate-javascript-object)| | 82.|[How do you test for an empty object?](#82-how-do-you-test-for-an-empty-object)| | 83.|[What is an arguments object?](#83-what-is-an-arguments-object)| | 84.|[How do you make first letter of the string in an uppercase?](#84-how-do-you-make-first-letter-of-the-string-in-an-uppercase)| | 85.|[What are the pros and cons of for loop?](#85-what-are-the-pros-and-cons-of-for-loop)| | 86.|[How do you display the current date in javascript?](#86-how-do-you-display-the-current-date-in-javascript)| | 87.|[How do you compare two date objects?](#87-how-do-you-compare-two-date-objects)| | 88.|[How do you check if a string starts with another string?](#88-how-do-you-check-if-a-string-starts-with-another-string)| | 89.|[How do you trim a string in javascript?](#89-how-do-you-trim-a-string-in-javascript)| | 90.|[How do you add a key value pair in javascript?](#90-how-do-you-add-a-key-value-pair-in-javascript)| | 91.|[How do you assign default values to variables?](#91-how-do-you-assign-default-values-to-variables)| | 92.|[Can we define properties for functions?](#92-can-we-define-properties-for-functions)| | 93.|[What is the way to find the number of parameters expected by a function?](#93-what-is-the-way-to-find-the-number-of-parameters-expected-by-a-function)| | 94.|[What are break and continue statements?](#94-what-are-break-and-continue-statements)| | 95.|[What are js labels?](#95-what-are-js-labels)| | 96.|[What are the benefits of keeping declarations at the top?](#96-what-are-the-benefits-of-keeping-declarations-at-the-top)| | 97.|[What are the benefits of initializing variables?](#97-what-are-the-benefits-of-initializing-variables)| | 98.|[What are the recommendations to create new object?](#98-what-are-the-recommendations-to-create-new-object)| | 99.|[How do you define JSON arrays?](#99-how-do-you-define-json-arrays)| | 100.|[How do you generate random integers?](#100-how-do-you-generate-random-integers)| | 101.|[Can you write a random integers function to print integers with in a range?](#101-can-you-write-a-random-integers-function-to-print-integers-with-in-a-range)| | 102.|[What are the string methods available in Regular expression?](#102-what-are-the-string-methods-available-in-regular-expression)| | 103.|[What are modifiers in regular expression?](#103-what-are-modifiers-in-regular-expression)| | 104.|[What are regular expression patterns?](#104-what-are-regular-expression-patterns)| | 105.|[What is a RegExp object?](#105-what-is-a-regexp-object)| | 106.|[How do you search a string for a pattern?](#106-how-do-you-search-a-string-for-a-pattern)| | 107.|[What is the purpose of exec method?](#107-what-is-the-purpose-of-exec-method)| | 108.|[How do you change style of a HTML element?](#108-how-do-you-change-style-of-a-html-element)| | 109.|[What is a debugger statement?](#109-what-is-a-debugger-statement)| | 110.|[What is the purpose of breakpoints in debugging?](#110-what-is-the-purpose-of-breakpoints-in-debugging)| | 111.|[Can I use reserved words as identifiers?](#111-can-i-use-reserved-words-as-identifiers)| | 112.|[How do you detect a mobile browser without regexp?](#112-how-do-you-detect-a-mobile-browser-without-regexp)| | 113.|[How do you get the image width and height using JS?](#113-how-do-you-get-the-image-width-and-height-using-js)| | 114.|[How do you make synchronous HTTP request?](#114-how-do-you-make-synchronous-http-request)| | 115.|[How do you make asynchronous HTTP request?](#115-how-do-you-make-asynchronous-http-request)| | 116.|[How do you convert date to another timezone in javascript?](#116-how-do-you-convert-date-to-another-timezone-in-javascript)| | 117.|[What are the properties used to get size of window?](#117-what-are-the-properties-used-to-get-size-of-window)| | 118.|[What is a conditional operator in javascript?](#118-what-is-a-conditional-operator-in-javascript)| | 119.|[Can you apply chaining on conditional operator?](#119-can-you-apply-chaining-on-conditional-operator)| | 120.|[What are the ways to execute javascript after page load?](#120-what-are-the-ways-to-execute-javascript-after-page-load)| | 121.|[What is the difference between proto and prototype?](#121-what-is-the-difference-between-proto-and-prototype)| | 122.|[Give an example where do you really need semicolon?](#122-give-an-example-where-do-you-really-need-semicolon)| | 123.|[What is a freeze method?](#123-what-is-a-freeze-method)| | 124.|[What is the purpose of freeze method?](#124-what-is-the-purpose-of-freeze-method)| | 125.|[Why do I need to use freeze method?](#125-why-do-i-need-to-use-freeze-method)| | 126.|[How do you detect a browser language preference?](#126-how-do-you-detect-a-browser-language-preference)| | 127.|[How to convert string to title case with javascript?](#127-how-to-convert-string-to-title-case-with-javascript)| | 128.|[How do you detect javascript disabled in the page?](#128-how-do-you-detect-javascript-disabled-in-the-page)| | 129.|[What are various operators supported by javascript?](#129-what-are-various-operators-supported-by-javascript)| | 130.|[What is a rest parameter?](#130-what-is-a-rest-parameter)| | 131.|[What happens if you do not use rest parameter as a last argument?](#131-what-happens-if-you-do-not-use-rest-parameter-as-a-last-argument)| | 132.|[What are the bitwise operators available in javascript?](#132-what-are-the-bitwise-operators-available-in-javascript)| | 133.|[How do you determine whether object is frozen or not?](#133-how-do-you-determine-whether-object-is-frozen-or-not)| | 134.|[How do you determine two values same or not using object?](#134-how-do-you-determine-two-values-same-or-not-using-object)| | 135.|[How do you copy properties from one object to other?](#135-how-do-you-copy-properties-from-one-object-to-other)| | 136.|[What are the applications of assign method?](#136-what-are-the-applications-of-assign-method)| | 137.|[What is a proxy object?](#137-what-is-a-proxy-object)| | 138.|[What is the purpose of seal method?](#138-what-is-the-purpose-of-seal-method)| | 139.|[What are the applications of seal method?](#139-what-are-the-applications-of-seal-method)| | 140.|[What are the differences between freeze and seal methods?](#140-what-are-the-differences-between-freeze-and-seal-methods)| | 141.|[How do you determine if an object is sealed or not?](#141-how-do-you-determine-if-an-object-is-sealed-or-not)| | 142.|[How do you get enumerable key and value pairs?](#142-how-do-you-get-enumerable-key-and-value-pairs)| | 143.|[What is the main difference between Object.values and Object.entries method?](#143-what-is-the-main-difference-between-objectvalues-and-objectentries-method)| | 144.|[How can you get the list of keys of any object?](#144-how-can-you-get-the-list-of-keys-of-any-object)| | 145.|[How do you create an object with prototype?](#145-how-do-you-create-an-object-with-prototype)| | 146.|[What is a WeakSet?](#146-what-is-a-weakset)| | 147.|[What are the differences between WeakSet and Set?](#147-what-are-the-differences-between-weakset-and-set)| | 148.|[List down the collection of methods available on WeakSet?](#148-list-down-the-collection-of-methods-available-on-weakset)| | 149.|[What is a WeakMap?](#149-what-is-a-weakmap)| | 150.|[What are the differences between WeakMap and Map?](#150-what-are-the-differences-between-weakmap-and-map)| | 151.|[List down the collection of methods available on WeakMap?](#151-list-down-the-collection-of-methods-available-on-weakmap)| | 152.|[What is the purpose of uneval?](#152-what-is-the-purpose-of-uneval)| | 153.|[How do you encode an URL?](#153-how-do-you-encode-an-url)| | 154.|[How do you decode an URL?](#154-how-do-you-decode-an-url)| | 155.|[How do you print the contents of web page?](#155-how-do-you-print-the-contents-of-web-page)| | 156.|[What is the difference between uneval and eval?](#156-what-is-the-difference-between-uneval-and-eval)| | 157.|[What is an anonymous function?](#157-what-is-an-anonymous-function)| | 158.|[What is the precedence order between local and global variables?](#158-what-is-the-precedence-order-between-local-and-global-variables)| | 159.|[What are javascript accessors?](#159-what-are-javascript-accessors)| | 160.|[How do you define property on Object constructor?](#160-how-do-you-define-property-on-object-constructor)| | 161.|[What is the difference between get and defineProperty?](#161-what-is-the-difference-between-get-and-defineproperty)| | 162.|[What are the advantages of Getters and Setters?](#162-what-are-the-advantages-of-getters-and-setters)| | 163.|[Can I add getters and setters using defineProperty method?](#163-can-i-add-getters-and-setters-using-defineproperty-method)| | 164.|[What is the purpose of switch-case?](#164-what-is-the-purpose-of-switch-case)| | 165.|[What are the conventions to be followed for the usage of swtich case?](#165-what-are-the-conventions-to-be-followed-for-the-usage-of-swtich-case)| | 166.|[What are the different ways to access object properties?](#166-what-are-the-different-ways-to-access-object-properties)| | 167.|[What are the function parameter rules?](#167-what-are-the-function-parameter-rules)| | 168.|[What is an error object?](#168-what-is-an-error-object)| | 169.|[When you get a syntax error?](#169-when-you-get-a-syntax-error)| | 170.|[What are the different error names from error object?](#170-what-are-the-different-error-names-from-error-object)| | 171.|[What are the various statements in error handling?](#171-what-are-the-various-statements-in-error-handling)| | 172.|[What are the two types of loops in javascript?](#172-what-are-the-two-types-of-loops-in-javascript)| | 173.|[What is an Intl object?](#173-what-is-an-intl-object)| | 174.|[How do you perform language specific date and time formatting?](#174-how-do-you-perform-language-specific-date-and-time-formatting)| | 175.|[What is an Iterator?](#175-what-is-an-iterator)| | 176.|[What is a decorator?](#176-what-is-a-decorator)| | 177.|[What are the properties of Intl object?](#177-what-are-the-properties-of-intl-object)| | 178.|[What is an Unary operator?](#178-what-is-an-unary-operator)| | 179.|[How do you sort elements in an array?](#179-how-do-you-sort-elements-in-an-array)| | 180.|[What is the purpose of compareFunction while sorting arrays?](#180-what-is-the-purpose-of-comparefunction-while-sorting-arrays)| | 181.|[How do you reversing an array?](#181-how-do-you-reversing-an-array)| | 182.|[How do you find min and max value in an array?](#182-how-do-you-find-min-and-max-value-in-an-array)| | 183.|[How do you find min and max values without Math functions?](#183-how-do-you-find-min-and-max-values-without-math-functions)| | 184.|[What is an empty statement and purpose of it?](#184-what-is-an-empty-statement-and-purpose-of-it)| | 185.|[How do you get meta data of a module?](#185-how-do-you-get-meta-data-of-a-module)| | 186.|[What is a comma operator?](#186-what-is-a-comma-operator)| | 187.|[What is the advantage of a comma operator?](#187-what-is-the-advantage-of-a-comma-operator)| | 188.|[Explain event delegation?](#188-explain-event-delegation)| | 189.|[Example of Prototypal Inheritance?](#189-example-of-prototypal-inheritance)| | 190.|[What do you think of AMD vs CommonJS?](#190-what-do-you-think-of-amd-vs-commonjs)| | 191.|[Explain why the following does not work as an IIFE: `function foo(){ }();`. What needs to be changed to properly make it an IIFE?](#191-explain-why-the-following-does-not-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife)| | 192.|[What is the difference between a variable that is: `null`, `undefined` or undeclared? How would you go about checking for any of these states?](#192-what-is-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states)| | 193.|[What is a typical use case for anonymous functions?](#193-what-is-a-typical-use-case-for-anonymous-functions)| | 194.|[How do you organize your code? (module pattern, classical inheritance?)](#194-how-do-you-organize-your-code-module-pattern-classical-inheritance)| | 195.|[What is the difference between host objects and native objects?](#195-what-is-the-difference-between-host-objects-and-native-objects)| | 196.|[Difference between: `function Person(){}`, `var person = Person()`, and `var person = new Person()`?](#196-difference-between-function-person-var-person--person-and-var-person--new-person)| | 197.|[What is the difference between `.call` and `.apply`?](#197-what-is-the-difference-between-call-and-apply)| | 198.|[Explain `Function.prototype.bind`?](#198-explain-functionprototypebind)| | 199.|[When would you use `document.write()`?](#199-when-would-you-use-documentwrite)| | 200.|[What is the difference between feature detection, feature inference, and using the UA string?](#200-what-is-the-difference-between-feature-detection-feature-inference-and-using-the-ua-string)| | 201.|[Explain Ajax in detail?](#201-explain-ajax-in-detail)| | 202.|[Explain how JSONP works (and how It is not really Ajax)](#202-explain-how-jsonp-works-and-how-it-is-not-really-ajax)| | 203.|[What is the difference between an 'attribute' and a 'property'?](#203-what-is-the-difference-between-an-attribute-and-a-property)| | 204.|[Why is extending built-in JavaScript objects not a good idea?](#204-why-is-extending-built-in-javascript-objects-not-a-good-idea)| | 205.|[Difference between document `load` event and document `DOMContentLoaded` event?](#205-difference-between-document-load-event-and-document-domcontentloaded-event)| | 206.|[What is the difference between `==` and `===`?](#206-what-is-the-difference-between--and-)| | 207.|[Explain the same-origin policy with regards to JavaScript?](#207-explain-the-same-origin-policy-with-regards-to-javascript)| | 208.|[Why is it called a Ternary expression, what does the word 'Ternary' indicate?](#208-why-is-it-called-a-ternary-expression-what-does-the-word-ternary-indicate)| | 209.|[What is `'use strict';`? What are the advantages and disadvantages to using it?](#209-what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it)| | 210.|[Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?](#210-why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it)| | 211.|[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?](#211-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)| | 212.|[What is the extent of your experience with Promises and/or their polyfills?](#212-what-is-the-extent-of-your-experience-with-promises-andor-their-polyfills)| | 213.|[What are the pros and cons of using Promises instead of callbacks?](#213-what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks)| | 214.|[What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#214-what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript)| | 215.|[What tools and techniques do you use for debugging JavaScript code?](#215-what-tools-and-techniques-do-you-use-for-debugging-javascript-code)| | 216.|[What language constructions do you use for iterating over object properties and array items?](#216-what-language-constructions-do-you-use-for-iterating-over-object-properties-and-array-items)| | 217.|[Explain the difference between mutable and immutable objects?](#217-explain-the-difference-between-mutable-and-immutable-objects)| | 218.|[What is an example of an immutable object in JavaScript?](#218-what-is-an-example-of-an-immutable-object-in-javascript)| | 219.|[How can you achieve immutability in your own code?](#219-how-can-you-achieve-immutability-in-your-own-code)| | 220.|[Explain the difference between synchronous and asynchronous functions?](#220-explain-the-difference-between-synchronous-and-asynchronous-functions)| | 221.|[What is event loop? What is the difference between call stack and task queue?](#221-what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue)| | 222.|[Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}`?](#222-explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function-)| | 223.|[What are the differences between variables created using `let`, `var` or `const`?](#223-what-are-the-differences-between-variables-created-using-let-var-or-const)| | 224.|[What is the definition of a higher-order function?](#224-what-is-the-definition-of-a-higher-order-function)| | 225.|[Can you give an example of a curry function and why this syntax offers an advantage?](#225-can-you-give-an-example-of-a-curry-function-and-why-this-syntax-offers-an-advantage)| | 226.|[How can you share code between files?](#226-how-can-you-share-code-between-files)| | 227.|[Why you might want to create static class members?](#227-why-you-might-want-to-create-static-class-members)| | 228.|[What is the difference between `undefined` and `not defined` in JavaScript?](#228-what-is-the-difference-between-undefined-and-not-defined-in-javascript)| | 229.|[For which value of `x` the results of the following statements are not the same?](#229-for-which-value-of-x-the-results-of-the-following-statements-are-not-the-same)| | 230.|[What is the drawback of declaring methods directly in JavaScript objects?](#230-what-is-the-drawback-of-declaring-methods-directly-in-javascript-objects)| | 231.|[What is “closure” in javascript? Can you provide an example?](#231-what-is-closure-in-javascript-can-you-provide-an-example)| | 232.|[Write a mul function which will work properly when invoked with following syntax?](#232-write-a-mul-function-which-will-work-properly-when-invoked-with-following-syntax)| | 233.|[How to empty an array in JavaScript?](#233-how-to-empty-an-array-in-javascript)| | 234.|[How to check if an object is an array or not?](#234-how-to-check-if-an-object-is-an-array-or-not)| | 235.|[What is `undefined x 1` in JavaScript?](#235-what-is-undefined-x-1-in-javascript)| | 236.|[What is the difference between declaring a function in the formats listed below?](#236-what-is-the-difference-between-declaring-a-function-in-the-formats-listed-below)| | 237.|[In which case the function definition is not hoisted in JavaScript?](#237-in-which-case-the-function-definition-is-not-hoisted-in-javascript)| | 238.|[What is the difference between `typeof` and `instanceof`?](#238-what-is-the-difference-between-typeof-and-instanceof)| | 239.|[Calculate the length of the associative array?](#239-calculate-the-length-of-the-associative-array)| | 240.|[Difference between `Function`, `Method` and `Constructor` calls in JavaScript?](#240-difference-between-function-method-and-constructor-calls-in-javascript)| | 241.|[What are Service Workers and when can you use them?](#241-what-are-service-workers-and-when-can-you-use-them)| | 242.|[What is the difference between a method and a function in javascript?](#242-what-is-the-difference-between-a-method-and-a-function-in-javascript)| | 243.|[What is IIFE (Immediately Invoked Function Expression) and how it can be useful?](#243-what-is-iife-immediately-invoked-function-expression-and-how-it-can-be-useful)| | 244.|[Describe Singleton Pattern In JavaScript?](#244-describe-singleton-pattern-in-javascript)| | 245.|[Singleton Design Pattern Implementation?](#245-singleton-design-pattern-implementation)| | 246.|[Write a function called deepClone which takes an object and creates a object copy of it?](#246-write-a-function-called-deepclone-which-takes-an-object-and-creates-a-object-copy-of-it)| | 247.|[Best way to detect `undefined` object property in JavaScript?](#247-best-way-to-detect-undefined-object-property-in-javascript)| | 248.|[Write a function called `Clone` which takes an object and creates a object copy of it but not copy deep property of object?](#248-write-a-function-called-clone-which-takes-an-object-and-creates-a-object-copy-of-it-but-not-copy-deep-property-of-object)| | 249.|[What are promises and how they are useful?](#249-what-are-promises-and-how-they-are-useful)| | 250.|[How to check whether a key exist in a JavaScript object or not?](#250-how-to-check-whether-a-key-exist-in-a-javascript-object-or-not)| | 251.|[What is NaN, why do we need it, and when can it break the page?](#251-what-is-nan-why-do-we-need-it-and-when-can-it-break-the-page)| | 252.|[How to check if the value of a variable in an array?](#252-how-to-check-if-the-value-of-a-variable-in-an-array)| | 253.|[Best way to detect reference values of any type in JavaScript?](#253-best-way-to-detect-reference-values-of-any-type-in-javascript)| | 254.|[How does Object.create method works JavaScript?](#254-how-does-objectcreate-method-works-javascript)| | 255.|[How to use constructor functions for inheritance in JavaScript?](#255-how-to-use-constructor-functions-for-inheritance-in-javascript)| | 256.|[How we can prevent modification of object in JavaScript?](#256-how-we-can-prevent-modification-of-object-in-javascript)| | 257.|[Write a log function which will add prefix `(your message)` to every message you log using console.log ?](#257-write-a-log-function-which-will-add-prefix-your-message-to-every-message-you-log-using-consolelog)| | 258.|[Write a function which will test string as a literal and as an object ?](#258-write-a-function-which-will-test-string-as-a-literal-and-as-an-object)| | 259.|[What is typical use case for anonymous function in JavaScript?](#259-what-is-typical-use-case-for-anonymous-function-in-javascript)| | 260.|[How to set a default parameter value?](#260-how-to-set-a-default-parameter-value)| | 261.|[Write code for merge two JavaScript Object dynamically?](#261-write-code-for-merge-two-javascript-object-dynamically)| | 262.|[What is non-enumerable property in JavaScript and how you can create one?](#262-what-is-non-enumerable-property-in-javascript-and-how-you-can-create-one)| | 263.|[What is Function binding ?](#263-what-is-function-binding)| | 264.|[Explain how `this` works in JavaScript?](#264-explain-how-this-works-in-javascript)| | 265.|[Explain how prototypal inheritance works?](#265-explain-how-prototypal-inheritance-works)| | 266.|[Can you describe the main difference between a `.forEach` loop and a `.map()` loop and why you would pick one versus the other?](#266-can-you-describe-the-main-difference-between-a-foreach-loop-and-a-map-loop-and-why-you-would-pick-one-versus-the-other)| | 267.|[Have you ever used JavaScript templating? If so, what libraries have you used?](#267-have-you-ever-used-javascript-templating-if-so-what-libraries-have-you-used)| | 268.|[What is JSON and its common operations?](#268-what-is-json-and-its-common-operations)| | 269.|[What is the purpose of array slice method?](#269-what-is-the-purpose-of-array-slice-method)| | 270.|[What is the purpose of array splice method?](#270-what-is-the-purpose-of-array-splice-method)| | 271.|[What is the difference between slice and splice?](#271-what-is-the-difference-between-slice-and-splice)| | 272.|[How do you compare Object and Map?](#272-how-do-you-compare-object-and-map)| | 273.|[How do you redeclare variables in switch block without an error?](#273-how-do-you-redeclare-variables-in-switch-block-without-an-error)| | 274.|[How to create and trigger events in javascript?](#274-how-to-create-and-trigger-events-in-javascript)| | 275.|[What is difference between window.frames window.parent and window.top in JavaScript?](#275-what-is-difference-between-windowframes-windowparent-and-windowtop-in-javascript)| | 276.|[In JavaScript, what is the difference between var x = 1 and x = 1?](#276-in-javascript-what-is-the-difference-between-var-x--1-and-x--1)| | 277.|[What is Associative Array? How do we use it?](#277-what-is-associative-array-how-do-we-use-it)| | 278.|[What is difference between Classic Inheritance and Prototypical Inheritance?](#278-what-is-difference-between-classic-inheritance-and-prototypical-inheritance)| | 279.|[What is difference between private variable, public variable and static variable? How we achieve this in JS?](#279-what-is-difference-between-private-variable-public-variable-and-static-variable-how-we-achieve-this-in-js)| | 280.|[How to add and remove properties to object in runtime?](#280-how-to-add-and-remove-properties-to-object-in-runtime)| | 281.|[How to extend built-in objects?](#281-how-to-extend-built-in-objects)| | 282.|[Why extending array is bad idea?](#282-why-extending-array-is-bad-idea)| | 283.|[What is difference between browser detection and feature detection?](#283-what-is-difference-between-browser-detection-and-feature-detection)| | 284.|[What is difference between Graceful Degradation and Progressive Enhancement?](#284-what-is-difference-between-graceful-degradation-and-progressive-enhancement)| | 285.|[In JavaScript, why is the “this” operator inconsistent?](#285-in-javascript-why-is-the-this-operator-inconsistent)| | 286.|[What unit testing framework do you use? and why?](#286-what-unit-testing-framework-do-you-use-and-why)| | 287.|[Explain the difference between Object.freeze() vs const?](#287-explain-the-difference-between-objectfreeze-vs-const)| | 288.|[What is generator in JS?](#288-what-is-generator-in-js)| | 289.|[Describe the Revealing Module Pattern in javascript?](#289-describe-the-revealing-module-pattern-in-javascript)| | 290.|[Compare Async-Await and Generators usage to achive same functionality?](#290-compare-async-await-and-generators-usage-to-achive-same-functionality)| | 291.|[Explain escape() and unescape() functions?](#291-explain-escape-and-unescape-functions)| | 292.|[What do you understand by Screen objects?](#292-what-do-you-understand-by-screen-objects)| | 293.|[How will you remove duplicates from an array in JavaScript?](#293-how-will-you-remove-duplicates-from-an-array-in-javascript)| | 294.|[Explain NEGATIVE_INFINITY in JavaScript?](#294-explain-negativeinfinity-in-javascript)| | 295.|[What do you understand by ViewState and SessionState?](#295-what-do-you-understand-by-viewstate-and-sessionstate)| | 296.|[Explain var self = this in JavaScript?](#296-explain-var-self--this-in-javascript)| | 297.|[What is difference between append() vs appendChild()?](#297-what-is-difference-between-append-vs-appendchild)| | 298.|[What is difference between null vs undefined?](#298-what-is-difference-between-null-vs-undefined)| | 299.|[What is difference between array[] vs object()?](#299-what-is-difference-between-array-vs-object)| | 300.|[What is difference between async() or defer() keyword in JavaScript?](#300-what-is-difference-between-async-or-defer-keyword-in-javascript)| | 301.|[What is difference between async() and await() in ajax?](#301-what-is-difference-between-async-and-await-in-ajax)| | 302.|[What is request header in javaScript?](#302-what-is-request-header-in-javascript)| | 303.|[What is rendering in JavaScript?](#303-what-is-rendering-in-javascript)| | 304.|[Define the various types of errors which occur in JavaScript programming language?](#304-define-the-various-types-of-errors-which-occur-in-javascript-programming-language)| | 305.|[What is unshift() method in JavaScript?](#305-what-is-unshift-method-in-javascript)| | 306.|[What is the difference between HTMLCollection and NodeList?](#306-what-is-the-difference-between-htmlcollection-and-nodelist)| | 307.|[What is the difference between firstChild and firstElementChild?](#307-what-is-the-difference-between-firstchild-and-firstelementchild)| | 308.|[Name the two functions that are used to create an HTML element dynamically?](#308-name-the-two-functions-that-are-used-to-create-an-html-element-dynamically)| | 309.|[What is callback() function in javascript?](#309-what-is-callback-function-in-javascript)| | 310.|[What is shallow copy and deep copy in javascript?](#310-what-is-shallow-copy-and-deep-copy-in-javascript)| | 311.|[What is difference between stoppropagation vs stopimmediatepropagation vs preventdefault in javascript?](#311-what-is-difference-between-stoppropagation-vs-stopimmediatepropagation-vs-preventdefault-in-javascript)| | 312.|[Explain array methods [join(), pop(), push(), shift(), unshift(), concat(), map(), filter(), reduce(), reduceRight(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex(), includes()]](#312-explain-array-methods-join-pop-push-shift-unshift-concat-map-filter-reduce-reduceright-every-some-indexof-lastindexof-find-findindex-includes)| | 313.|[When to use function declarations and expressions in JavaScript?](#313-when-to-use-function-declarations-and-expressions-in-javascript)| | 314.|[How to avoid callback hell in javascript?](#314-how-to-avoid-callback-hell-in-javascript)| | 315.|[Why is eval() considered evil and dangerous?](#315-why-is-eval-considered-evil-and-dangerous)| | 316.|[What is the difference between encryption and hashing?](#316-what-is-the-difference-between-encryption-and-hashing)| | 317.|[What is Proxies and Reflection in JavaScript?](#317-what-is-proxies-and-reflection-in-javascript)| | 318.|[How do you check whether an object can be extendable or not?](#318-how-do-you-check-whether-an-object-can-be-extendable-or-not)| | 319.|[What are the different ways to make an object non-extensible?](#319-what-are-the-different-ways-to-make-an-object-non-extensible)| | 320.|[Is enums feature available in javascript?](#320-is-enums-feature-available-in-javascript)| | 321.|[How do I modify the url without reloading the page?](#321-how-do-i-modify-the-url-without-reloading-the-page)| | 322.|[What is throttling and debouncing in javascript?](#322-what-is-throttling-and-debouncing-in-javascript)| | 323.|[How to validate JSON Object in javascript?](#323-how-to-validate-json-object-in-javascript)| | 324.|[How to check if page is fully loaded using javascript?](#324-how-to-check-if-page-is-fully-loaded-using-javascript)| | 325.|[Explain browser console logs features?](#325-explain-browser-console-logs-features)| | 326.|[What are the difference between console.log() and console.dir()?](#326-what-are-the-difference-between-consolelog-and-consoledir)| | 327.|[How to Copy Text to Clipboard?](#327-how-to-copy-text-to-clipboard)| | 328.|[Explain types of Memory Leaks in JavaScript?](#328-explain-types-of-memory-leaks-in-javascript)| | 329.|[How accidental closures might cause memory leaks in IE?](#329-how-accidental-closures-might-cause-memory-leaks-in-ie)| | 330.|[How to convert Decimal to Binary in JavaScript?](#330-how-to-convert-decimal-to-binary-in-javascript)|
## 1. What is difference between document.getElementById() and document.querySelector()? * **document.getElementById()** Returns 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. ```javascript element = document.getElementById(id); ``` * **document.querySelector()** Returns the first matching Element node within the node\'s subtree. If no matching node is found, null is returned. ```javascript element = document.querySelector(selectors); ``` * **document.querySelectorAll()** Returns a NodeList containing all matching Element nodes within the node\'s subtree, or an empty NodeList if no matches are found. ```javascript element = document.querySelectorAll(selectors); ``` *Note: `querySelector()` is more useful when we want to use more complex selectors*.
↥ back to top
## 2. When to use reduce(), map(), foreach() and filter() in JavaScript? * **forEach()** It takes a callback function and run that callback function on each element of array one by one. Basically forEach works as a traditional for loop looping over the array and providing array elements to do operations on them. ```javascript var arr = [10, 20, 30]; arr.forEach(function (elem, index){ console.log(elem + ' comes at ' + index); }) ``` Output ``` 10 comes at 0 20 comes at 1 30 comes at 2 ``` * **filter()** The 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. *Note: filter does not update the existing array it will return a new filtered array every time*. ```javascript var arr = [10, 20, 30]; var result = arr.filter(function(elem){ return elem !== 20; }) console.log(result) ``` Output ``` [10, 30] ``` * **map()** map() like filter() & 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. Like 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. ```javascript var arr = [10, 20, 30]; var mapped = arr.map(function(elem) { return elem * 10; }); console.log(mapped) ``` Output ``` [100, 200, 300] ``` * **reduce()** reduce() method of the array object is used to reduce the array to one single value. ```javascript var arr = [10, 20, 30]; var sum = arr.reduce(function(sum, elem) { return sum + elem; }); console.log(sum); // Output: 60 ```
↥ back to top
## 3. What is Hoisting in JavaScript? Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. **Example 01:** Variable Hoisting ```javascript console.log(message); // output : undefined var message = "The variable Has been hoisted"; ``` The above code looks like as below to the interpreter, ```javascript var message; console.log(message); message = "The variable Has been hoisted"; ``` **Example 02:** Function Hoisting ```javascript function hoist() { a = 20; var b = 100; } hoist(); console.log(a); /* Accessible as a global variable outside hoist() function Output: 20 */ console.log(b); /* Since it was declared, it is confined to the hoist() function scope. We can't print it out outside the confines of the hoist() function. Output: ReferenceError: b is not defined */ ``` All 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. ```javascript console.log(a); let a = 3; // Output: ReferenceError: a is not defined ``` They 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. *Note: JavaScript only hoists declarations, not initialisation*
↥ back to top
## 4. What are closures? A 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 * Own scope where variables defined between its curly brackets * Outer function’s variables * Global variables ```javascript function Welcome(name) { var greetingInfo = function(message) { console.log(message+' '+name); } return greetingInfo; } var myFunction = Welcome('John'); myFunction('Welcome '); // Output: Welcome John myFunction('Hello Mr.'); // output: Hello Mr.John ``` As per the above code, the inner `function greetingInfo()` has access to the variables in the outer `function Welcome()` even after outer function has returned.
↥ back to top
## 5. How do you clone an object in JavaScript? Using the object spread operator `...`, the object own enumerable properties can be copied into the new object. This creates a shallow clone of the object. ```javascript const obj = { a: 1, b: 2 } const shallowClone = { ...obj } ``` With 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. Other alternatives include: * **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). * **Object.assign({}, obj)** is another alternative. * **Object.keys(obj).reduce((acc, key) => (acc[key] = obj[key], acc), {})** is another more verbose alternative that shows the concept in greater depth.
↥ back to top
## 6. What are the possible ways to create objects in JavaScript? **a.) Object constructor**: The simpliest way to create an empty object is using Object constructor. Currently this approach is not recommended. ```javascript var object = new Object(); ``` **b.) Object create method**: The create method of Object creates a new object by passing the prototype object as a parameter ```javascript var object = Object.create(null); ``` **c.) Object literal syntax**: The object literal syntax is equivalent to create method when it passes null as parameter ```javascript var object = {}; ``` **d.) Function constructor**: Create any function and apply the new operator to create object instances, ```javascript function Person(name) { var object = {}; object.name = name; object.age = 26; return object; } var object = new Person("Alex"); ``` **e.) Function constructor with prototype**: This is similar to function constructor but it uses prototype for their properties and methods, ```javascript function Person(){} Person.prototype.name = "Alex"; var object = new Person(); ``` This 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. ```javascript function func {}; new func(x, y, z); // **(OR)** // Create a new instance using function prototype. var newInstance = Object.create(func.prototype) // Call the function var result = func.call(newInstance, x, y, z), // If the result is a non-null object then use it otherwise just use the new instance. console.log(result && typeof result === 'object' ? result : newInstance); ``` **f.) ES6 Class syntax**: ES6 introduces class feature to create the objects ```javascript class Person { constructor(name) { this.name = name; } } var object = new Person("Alex"); ``` **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. ```javascript var object = new function() { this.name = "Alex"; } ```
↥ back to top
## 7. What are the javascript data types? Below are the list of javascript data types available 1. Number 2. String 3. Boolean 4. Object 5. Undefined
↥ back to top
## 8. What are global variables? Global variables are those that are available throughout the length of the code without any scope. The var keyword is used to declare a local variable but if you omit it then it will become global variable ```javascript msg = "Hello" // var is missing, it becomes global variable ``` The problem with global variables is the conflict of variable names of local and global scope. It is also difficult to debug and test the code that relies on global variables.
↥ back to top
## 9. What is variable shadowing in javascript? Variable 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. If 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. ```javascript var val = 10; function Hoist(val) { alert(val); } Hoist(20); ``` Output ``` 20 ```
↥ back to top
## 10. What is an event flow? Event flow is the order in which event is received on the web page. When you click an element that is nested in various other elements, before your click actually reaches its destination, or target element, it must trigger the click event each of its parent elements first, starting at the top with the global window object. There are two ways of event flow * Top to Bottom(Event Capturing) * Bottom to Top (Event Bubbling)
↥ back to top
## 11. What is event bubbling? Event bubbling is a type of event propagation where the event first triggers on the innermost target element, and then successively triggers on the ancestors (parents) of the target element in the same nesting hierarchy till it reaches the outermost DOM element. Example: If you click on EM, the handler on DIV runs. ```html
If you click on EM, the handler on DIV runs.
``` * **Stopping bubbling** ```html ```
↥ back to top
## 12. What is event capturing? Event capturing is a type of event propagation where the event is first captured by the outermost element and then successively triggers on the descendants (children) of the target element in the same nesting hierarchy till it reaches the inner DOM element.
↥ back to top
## 13. What is prototype chain? Nearly 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**. **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**. ```javascript function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } //Person class created Person.prototype.getFullName = function() { return this.firstName + " " + this.lastName; } // we have added getFullName method in Person’s prototype. var person = new Person("John", "K", 25); // It will create an instance of the Person class > person.hasOwnProperty("firstName"); // true > person.hasOwnProperty("getFullName"); // false > person.getFullName(); // John K ```
↥ back to top
## 14. What is the difference between Call, Apply and Bind? **a.) call()** The call() method invokes a function with a given `this` value and arguments provided one by one ```javascript var employee1 = {firstName: 'John', lastName: 'Rodson'}; var employee2 = {firstName: 'Jimmy', lastName: 'Baily'}; function invite(greeting1, greeting2) { console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2); } invite.call(employee1, 'Hello', 'How are you?'); // Hello John Rodson, How are you? invite.call(employee2, 'Hello', 'How are you?'); // Hello Jimmy Baily, How are you? ``` **b.) apply()** Invokes the function and allows you to pass in arguments as an array ```javascript var employee1 = {firstName: 'John', lastName: 'Rodson'}; var employee2 = {firstName: 'Jimmy', lastName: 'Baily'}; function invite(greeting1, greeting2) { console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2); } invite.apply(employee1, ['Hello', 'How are you?']); // Hello John Rodson, How are you? invite.apply(employee2, ['Hello', 'How are you?']); // Hello Jimmy Baily, How are you? ``` **c.) bind()** returns a new function, allowing you to pass in an array and any number of arguments ```javascript var employee1 = {firstName: 'John', lastName: 'Rodson'}; var employee2 = {firstName: 'Jimmy', lastName: 'Baily'}; function invite(greeting1, greeting2) { console.log(greeting1 + ' ' + this.firstName + ' ' + this.lastName+ ', '+ greeting2); } var inviteEmployee1 = invite.bind(employee1); var inviteEmployee2 = invite.bind(employee2); inviteEmployee1('Hello', 'How are you?'); // Hello John Rodson, How are you? inviteEmployee2('Hello', 'How are you?'); // Hello Jimmy Baily, How are you? ```
↥ back to top
## 15. What is the difference between == and === operators? JavaScript 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, 1. Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions. 2. Two numbers are strictly equal when they are numerically equal. i.e, Having the same number value. There are two special cases in this, 1. NaN is not equal to anything, including NaN. 2. Positive and negative zeros are equal to one another. 3. Two Boolean operands are strictly equal if both are true or both are false. 4. Two objects are strictly equal if they refer to the same Object. 5. Null and Undefined types are not equal with ===, but equal with ==. i.e, null===undefined --> false but null==undefined --> true **Examples** ```javascript 0 == false // true 0 === false // false 1 == "1" // true 1 === "1" // false null == undefined // true null === undefined // false '0' == false // true '0' === false // false []==[] or []===[] //false, refer different objects in memory {}=={} or {}==={} //false, refer different objects in memory ```
↥ back to top
## 16. What is a first class function? JavaScript 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" **Example:** Assign a function to a variable ```javascript const message = function() { console.log("Hello World!"); } message(); // Invoke it using the variable ``` **Example:** Pass a function as an Argument ```javascript function sayHello() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); ``` **Example:** Return a function ```javascript function sayHello() { return function() { console.log("Hello!"); } } ``` **Example:** Using a variable ```javascript const sayHello = function() { return function() { console.log("Hello!"); } } const myFunc = sayHello(); myFunc(); ``` **Example:** Using double parentheses ```javascript function sayHello() { return function() { console.log("Hello!"); } } sayHello()(); ``` We are using double parentheses `()()` to invoke the returned function as well.
↥ back to top
## 17. What is a higher order function? A Higher-Order function is a function that receives a function as an argument or returns the function as output. For example, `Array.prototype.map()`, `Array.prototype.filter()` and `Array.prototype.reduce()` are some of the Higher-Order functions in javascript. ```javascript const arr1 = [1, 2, 3]; const arr2 = arr1.map(function(item) { return item * 2; }); console.log(arr2); ```
↥ back to top
## 18. What is a unary function? Unary 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. ```javascript const unaryFunction = a => console.log (a + 10); //Add 10 to the given argument and display the value ```
↥ back to top
## 19. What is currying function? Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument. ```javascript function volume(length) { return function(width) { return function(height) { return height * width * length; } } } volume(2)(3)(4); // 24 ``` Curried functions are great to improve code re-usability and functional composition.
↥ back to top
## 20. What is a pure function? Pure 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. **Example** ```javascript function impure(arg) { finalR.s = 90 return arg * finalR.s } ``` The above function is not a pure function because it modified a state `finalR.s` outside its scope. ```javascript function pure(arg) { return arg * 4 } ``` Here is a pure function. It didn’t side effect any external state and it returns an output based on the input. A function must pass two tests to be considered “pure”: 1. Same inputs always return same outputs 1. No side-effects **1. Same Input => Same Output** Compare this: ```javascript const add = (x, y) => x + y; add(2, 4); // 6 ``` To this ```javascript let x = 2; const add = (y) => { x += y; }; add(4); // x === 6 (the first time) ``` **2. Pure Functions = Consistent Results** The first example returns a value based on the given parameters, regardless of where/when you call it. If you pass 2 and 4, you’ll always get 6. Nothing else affects the output. **Benefits** * 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. * The pure functions are easier to parallelize * They also makes maintaining and refactoring code much easier.
↥ back to top
## 21. What is memoization in JavaScript? Memoization 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. ```javascript // A simple memoized function to Add Number const memoizedAdd = () => { let cache = {}; return (number) => { if (number in cache) { console.log('Fetching from cache: '); return cache[number]; } else { console.log('Calculating result: '); let result = number + 10; cache[number] = result; return result; } } } // returned function from memoizedAdd const sum = memoizedAdd(); console.log(sum(10)); // Calculating result: 20 console.log(sum(10)); // Fetching from cache: 20 ```
↥ back to top
## 22. What is a service worker? A 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. Some of the major features of service workers are * Offline first web application development * Periodic background syncs, push notifications * Intercept and handle network requests * Programmatically managing a cache of responses **Lifecycle of a Service Worker** It consists of the following phases: * Download * Installation * Activation **Registering a Service Worker** To register a service worker we first check if the browser supports it and then register it. ```javascript if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/ServiceWorker.js') .then(function(response) { // Service worker registration done console.log('Registration Successful', response); }, function(error) { // Service worker registration failed console.log('Registration Failed', error); } ``` **Installation of service worker** After the controlled page that takes care of the registration process, we come to the service worker script that handles the installation part. Basically, 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 – * Open a cache * Cache the files * Seek confirmation for the required caches and whether they have been successful. ```javascript var CACHENAME = 'My site cache'; var urlstocache = [ '/', '/styles/main1.css', '/script/main1.js' ]; self.addEventListener('install', function(event) { // Performing installation steps event.waitUntil( caches.open(CACHENAME) .then(function(cache) { console.log('Opening of cache'); return cache.addAll(urlstocache); }) ); ``` **Cache and return requests** After 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. ```javascript self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return response if (response) { return response; } return fetch(event.request); } ) ); }); ```
↥ back to top
## 23. How do you manipulate DOM using service worker? Service 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. **Example:** service-worker.html ```html Service Worker (Look in the console.) ``` **service-worker.js** ```javascript self.addEventListener("message", function(event) { //event.source.postMessage("Responding to " + event.data); self.clients.matchAll().then(all => all.forEach(client => { client.postMessage("Responding to " + event.data); })); }); ```
↥ back to top
## 24. How do you reuse information across service worker restarts? The 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.
↥ back to top
## 25. What is a post message? Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).
↥ back to top
## 26. What is a web-storage event and its event handler? The StorageEvent is an event that fires when a storage area has been changed in the context of another document. Whereas onstorage property is an EventHandler for processing storage events. The syntax would be as below ```javascript window.onstorage = functionRef; ``` Let us take the example usage of onstorage event handler which logs the storage key and its values ```javascript if (typeof(Storage) !== "undefined") { window.onstorage = function(e) { console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.'); }; } else { // Browser doesnot support web-storage } ```
↥ back to top
## 27. How to use Web Workers in javascript? **Step 01: Create a Web Workers file**: Write a script to increment the count value. ```javascript // counter.js let i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()",500); } timedCount(); ``` Here `postMessage()` method is used to post a message back to the HTML page. **Step 02: Create a Web Worker Object**: Create a web worker object by checking for browser support. ```javascript if (typeof(w) == "undefined") { w = new Worker("counter.js"); } ``` and we can receive messages from web workers ```javascript w.onmessage = function(event){ document.getElementById("message").innerHTML = event.data; }; ``` **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. ```javascript w.terminate(); ``` **Step 04: Reuse the Web Workers**: If you set the worker variable to undefined you can reuse the code ```javascript w = undefined; ``` Example: ```html

Count numbers:

```
↥ back to top
## 28. What are the restrictions of web workers on DOM? WebWorkers do not have access to below javascript objects since they are defined in an external files 1. Window object 2. Document object 3. Parent object
↥ back to top
## 29. What is a promise? A promise is an object that may produce a single value some time in the future with either a resolved value or a reason that it’s not resolved(for example, network error). It will be in one of the 3 possible states: fulfilled, rejected, or pending. Syntax ```javascript const promise = new Promise(function(resolve, reject) { // promise description }) ``` Promises are used to handle asynchronous operations. They provide an alternative approach for callbacks by reducing the callback hell and writing the cleaner code. Promises have three states: 1. **Pending:** This is an initial state of the Promise before an operation begins 2. **Fulfilled:** This state indicates that specified operation was completed. 3. **Rejected:** This state indicates that the operation did not complete. In this case an error value will be thrown.
↥ back to top
## 30. What is a callback function? A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. ```javascript function callbackFunction(name) { console.log('Hello ' + name); } function outerFunction(callback) { let name = prompt('Please enter your name.'); callback(name); } outerFunction(callbackFunction); ```
↥ back to top
## 31. Why do we need callbacks? The 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. Let us take an example with first function invoking an API call(simulated by setTimeout) and next function which logs the message. ```javascript function firstFunction() { // Simulate a code delay setTimeout( function() { console.log('First function called'); }, 1000 ); } function secondFunction() { console.log('Second function called'); } firstFunction(); secondFunction(); Output // Second function called // First function called ``` As 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.
↥ back to top
## 32. What is a callback hell? Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below, ```javascript async1(function() { async2(function() { async3(function() { async4(function() { .... }); }); }); }); ```
↥ back to top
## 33. What is server-sent events? Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This is been used in Facebook/Twitter updates, stock price updates, news feeds etc. The `EventSource` object is used to receive server-sent event notifications. For example, we can receive messages from server as below, ```javascript if(typeof(EventSource) !== "undefined") { var source = new EventSource("sse_generator.js"); source.onmessage = function(event) { document.getElementById("output").innerHTML += event.data + "
"; }; } ``` Below are the list of events available for server sent events | Event | Description | |------ |--------------| | onopen | It is used when a connection to the server is opened | | onmessage | This event is used when a message is received | | onerror | It happens when an error occurs|
↥ back to top
## 34. What is callback in callback? You can nest one callback inside in another callback to execute the actions sequentially one by one. This is known as callbacks in callbacks. ```javascript loadScript('/script1.js', function(script) { console.log('first script is loaded'); loadScript('/script2.js', function(script) { console.log('second script is loaded'); loadScript('/script3.js', function(script) { console.log('third script is loaded'); // after all scripts are loaded }); }) }); ```
↥ back to top
## 35. What is promise chaining? The process of executing a sequence of asynchronous tasks one after another using promises is known as Promise chaining. ```javascript new Promise(function(resolve, reject) { setTimeout(() => resolve(1), 1000); }).then(function(result) { console.log(result); // 1 return result * 2; }).then(function(result) { console.log(result); // 2 return result * 3; }).then(function(result) { console.log(result); // 6 return result * 4; }); ``` In the above handlers, the result is passed to the chain of .then() handlers with the below work flow, 1. The initial promise resolves in 1 second, 2. After that `.then` handler is called by logging the result(1) and then return a promise with the value of result * 2. 3. After that the value passed to the next `.then` handler by logging the result(2) and return a promise with result * 3. 4. Finally the value passed to the last `.then` handler by logging the result(6) and return a promise with result * 4.
↥ back to top
## 36. What is promise.all()? `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. ```javascript Promise.all([Promise1, Promise2, Promise3]) .then(result) => { console.log(result) }) .catch(error => console.log(`Error in promises ${error}`)); ``` *Note: Remember that the order of the promises(output the result) is maintained as per input order*.
↥ back to top
## 37. What is the purpose of race method in promise? `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 ```javascript var promise1 = new Promise(function(resolve, reject) { setTimeout(resolve, 500, 'one'); }); var promise2 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 'two'); }); Promise.race([promise1, promise2]).then(function(value) { console.log(value); // "two" // Both promises will resolve, but promise2 is faster }); ```
↥ back to top
## 38. What is a strict mode in javascript? Strict 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. Strict mode is useful to write **secure javaScript** by notifying "bad syntax" into real errors. For example, it eliminates accidentally creating a global variable by throwing an error and also throws an error for assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object. The strict mode is declared by adding "use strict"; to the beginning of a script or a function. If declare at the beginning of a script, it has global scope. ```javascript 'use strict'; x = 3.14; // This will cause an error because x is not declared ``` and if you declare inside a function, it has local scope ```javascript x = 3.14; // This will not cause an error. myFunction(); function myFunction() { 'use strict'; y = 3.14; // This will cause an error } ```
↥ back to top
## 39. What is the purpose of double exclamation? The double exclamation or negation(!!) ensures the resulting type is a boolean. If it was falsey (e.g. 0, null, undefined, etc.), it will be false, otherwise, true. For example, you can test IE version using this expression as below, ```javascript let isIE11 = false; isIE11 = !!navigator.userAgent.match(/Trident.*rv[ :]*11\./); console.log(isIE11); // returns true or false ``` If you do not use this expression then it returns the original value. ```javascript console.log(navigator.userAgent.match(/Trident.*rv[ :]*11\./)); // returns either an Array or null ``` *Note: The expression !! is not an operator, but it is just twice of ! operator*.
↥ back to top
## 40. What is the purpose of delete operator? The delete keyword is used to delete the property as well as its value. ```javascript var user= {name: "John", age:20}; delete user.age; console.log(user); // {name: "John"} ```
↥ back to top
## 41. What is typeof operator? You can use the JavaScript typeof operator to find the type of a JavaScript variable. It returns the type of a variable or an expression. ```javascript typeof "John Abraham" // Returns "string" typeof (1 + 2) // Returns "number" ```
↥ back to top
## 42. What is undefined property? The 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. ```javascript var user; // Value is undefined, type is undefined console.log(typeof(user)) //undefined ``` Any variable can be emptied by setting the value to undefined. ```javascript user = undefined ```
↥ back to top
## 43. What is the difference between null and undefined? Below are the main differences between null and undefined, | Null | Undefined | |---- | -----------| | It is an assignment value which indicates that variable points to no object. | It is not an assignment value where a variable has been declared but has not yet been assigned a value. | | Type of null is object | Type of undefined is undefined | | The null value is a primitive value that represents the null, empty, or non-existent reference. | The undefined value is a primitive value used when a variable has not been assigned a value.| | Indicates the absence of a value for a variable | Indicates absence of variable itself | | Converted to zero (0) while performing primitive operations | Converted to NaN while performing primitive operations |
↥ back to top
## 44. What is eval? The eval() function evaluates JavaScript code represented as a string. The string can be a JavaScript expression, variable, statement, or sequence of statements. ```javascript console.log(eval('1 + 2')); // 3 ```
↥ back to top
## 45. What is the difference between window and document? The 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. The 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. | Window | Document | |------- | ---------| | It is the root level element in any web page | It is the direct child of the window object. This is also known as Document Object Model(DOM) | | By default window object is available implicitly in the page | You can access it via window.document or document. | | It has methods like alert(), confirm() and properties like document, location | It provides methods like getElementById(), getElementByTagName(), createElement() etc |
↥ back to top
## 46. How do you access history in javascript? The window.history object contains the browsers history. You can load previous and next URLs in the history using back() and next() methods. ```javascript function goBack() { window.history.back() } function goForward() { window.history.forward() } ``` *Note: You can also access history without window prefix*.
↥ back to top
## 47. What is isNaN? The isNaN() function is used to determine whether a value is an illegal number (Not-a-Number) or not. i.e, This function returns true if the value equates to NaN. Otherwise it returns false. ```javascript isNaN('Hello') //true isNaN('100') //false typeof(NaN) //Number ```
↥ back to top
## 48. What are the differences between undeclared and undefined variables? Below are the major differences between undeclared and undefined variables, | undeclared | undefined | |---- | --------- | These variables do not exist in a program and are not declared | These variables declared in the program but have not assigned any value | | If you try to read the value of an undeclared variable, then a runtime error is encountered | If you try to read the value of an undefined variable, an undefined value is returned. |
↥ back to top
## 49. What is NaN property? The NaN property is a global property that represents "Not-a-Number" value. i.e, It indicates that a value is not a legal number. It is very rare to use NaN in a program but it can be used as return value for few cases ```javascript Math.sqrt(-1) parseInt("Hello") ```
↥ back to top
## 50. What is the purpose of isFinite function? The isFinite() function is used to determine whether a number is a finite, legal number. It returns false if the value is +infinity, -infinity, or NaN (Not-a-Number), otherwise it returns true. ```javascript isFinite(Infinity); // false isFinite(NaN); // false isFinite(-Infinity); // false isFinite(100); // true ```
↥ back to top
## 51. How do you submit a form using JavaScript? You can submit a form using JavaScript use document.form[0].submit(). All the form input information is submitted using onsubmit event handler ```javascript function submit() { document.form[0].submit(); } ```
↥ back to top
## 52. How do you find operating system details? The window.navigator object contains information about the visitor\'s browser os details. Some of the OS properties are avaialble under platform property, ```javascript console.log(navigator.platform); ```
↥ back to top
## 53. What is the difference between document load and DOMContentLoaded events? The `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).
↥ back to top
## 54. What is the difference between native, host and user objects? * `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. * `Host objects` are objects provided by the browser or runtime environment (Node). For example, window, XmlHttpRequest, DOM nodes etc considered as host objects. * `User objects` are objects defined in the javascript code. For example, User object created for profile information.
↥ back to top
## 55. What are the pros and cons of promises over callbacks? Below are the list of pros and cons of promises over callbacks, **Pros:** 1. It avoids callback hell which is unreadable 2. Easy to write sequential asynchronous code with .then() 3. Easy to write parallel asynchronous code with Promise.all() 4. Solves some of the common problems of callbacks(call the callback too late, too early, many times and swallow errors/exceptions) **Cons:** 1. It makes little complex code 2. You need to load a polyfill if ES6 is not supported
↥ back to top
## 56. What is the difference between an attribute and a property? Attributes are defined on the HTML markup whereas properties are defined on the DOM. For example, the below HTML element has 2 attributes type and value, ```html ``` You can retrieve the attribute value as below, ```javascript const input = document.querySelector('input'); console.log(input.getAttribute('value')); // Good morning console.log(input.value); // Good morning ``` And after you change the value of the text field to "Good evening", it becomes like ```javascript console.log(input.getAttribute('value')); // Good morning console.log(input.value); // Good evening ```
↥ back to top
## 57. What is same-origin policy? The same-origin policy is a policy that prevents JavaScript from making requests across domain boundaries. An origin is defined as a combination of URI scheme, hostname, and port number. If you enable this policy then it prevents a malicious script on one page from obtaining access to sensitive data on another web page using Document Object Model(DOM).
↥ back to top
## 58. What is the purpose of void(0)? The `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 `` element. i.e, when you click a link, the browser loads a new page or refreshes the same page. But this behavior will be prevented using this expression. For example, the below link notify the message without reloading the page ```html Click Me! ```
↥ back to top
## 59. Is JavaScript a compiled or interpreted language? JavaScript is an interpreted language, not a compiled language. An interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. Nowadays modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
↥ back to top
## 60. Is JavaScript a case-sensitive language? Yes, JavaScript is a case sensitive language. The language keywords, variables, function & object names, and any other identifiers must always be typed with a consistent capitalization of letters.
↥ back to top
## 61. What are events? Events 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, 1. Web page has finished loading 2. Input field was changed 3. Button was clicked Example: click event for button element ```html ```
↥ back to top
## 62. What is the use of preventDefault method? The preventDefault() method cancels the event if it is cancelable, meaning that the default action or behaviour that belongs to the event will not occur. For example, prevent form submission when clicking on submit button and prevent opening the page URL when clicking on hyper link are some common usecases. ```javascript document.getElementById("link").addEventListener("click", function(event) { event.preventDefault(); }); ``` *Note: Remember that not all events are cancelable*.
↥ back to top
## 63. What is the use of stopPropagation method? The stopPropagation method is used to stop the event from bubbling up the event chain. For example, the below nested divs with stopPropagation method prevents default event propagation when clicking on nested div(Div1) ```html

Click DIV1 Element

DIV 2
DIV 1
```
↥ back to top
## 64. What are the steps involved in return false usage? The return false statement in event handlers performs the below steps, 1. First it stops the browser default action or behaviour. 2. It prevents the event from propagating the DOM 3. Stops callback execution and returns immediately when called. ## 65. What is BOM? The Browser Object Model (BOM) allows JavaScript to "talk to" the browser. It consists of the objects navigator, history, screen, location and document which are children of window. The Browser Object Model is not standardized and can change based on different browsers.
↥ back to top
## 66. What is the use of setTimeout? The 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, ```javascript setTimeout(function() { console.log("Good morning"); }, 2000); ```
↥ back to top
## 67. What is the use of setInterval? The 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, ```javascript setInterval(function() { console.log("Good morning"); }, 2000); ```
↥ back to top
## 68. Why is JavaScript treated as Single threaded? JavaScript is a single-threaded language. Because the language specification does not allow the programmer to write code so that the interpreter can run parts of it in parallel in multiple threads or processes. Whereas languages like java, go, C++ can make multi-threaded and multi-process programs.
↥ back to top
## 69. What is an event delegation? Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it. For example, if you wanted to detect field changes in inside a specific form, you can use event delegation technique, ```javascript var form = document.querySelector('#registration-form'); // Listen for changes to fields inside the form form.addEventListener('input', function (event) { // Log the field that was changed console.log(event.target); }, false); ```
↥ back to top
## 70. What is the purpose JSON stringify? When sending data to a web server, the data has to be in a string format. You can achieve this by converting JSON object into a string using stringify() method. ```javascript var userJSON = {'name': 'John', age: 31} var userString = JSON.stringify(user); console.log(userString); //"{"name":"John","age":31}" ```
↥ back to top
## 71. How do you parse JSON string? When 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. ```javascript var userString = '{"name":"John","age":31}'; var userJSON = JSON.parse(userString); console.log(userJSON);// {name: "John", age: 31} ```
↥ back to top
## 72. What is the purpose of clearTimeout method? The `clearTimeout()` function is used in javascript to clear the timeout which has been set by `setTimeout()` function before that. i.e, The return value of setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer. For example, the below setTimeout method is used to display the message after 3 seconds. This timeout can be cleared by clearTimeout() method. ```javascript var msg; function greeting() { alert('Good morning'); } function start() { msg =setTimeout(greeting, 3000); } function stop() { clearTimeout(msg); } ```
↥ back to top
## 73. What is the purpose of clearInterval method? The `clearInterval()` function is used in javascript to clear the interval which has been set by `setInterval()` function. i.e, The return value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval. For example, the below setInterval method is used to display the message for every 3 seconds. This interval can be cleared by clearInterval() method. ```javascript var msg; function greeting() { alert('Good morning'); } function start() { msg = setInterval(greeting, 3000); } function stop() { clearInterval(msg); } ```
↥ back to top
## 74. How do you redirect new page in javascript? In vanilla javascript, you can redirect to a new page using `location` property of window object. The syntax would be as follows, ```javascript function redirect() { window.location.href = 'newPage.html'; } ```
↥ back to top
## 75. How do you check whether a string contains a substring? There are 3 possible ways to check whether a string contains a substring or not, **a.) Using includes:** ES6 provided `String.prototype.includes` method to test a string contains a substring ```javascript var mainString = "hello", subString = "hell"; mainString.includes(subString) ``` **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. ```javascript var mainString = "hello", subString = "hell"; mainString.indexOf(subString) !== -1 ``` **c.) Using RegEx:** The advanced solution is using Regular expression test method(`RegExp.test`), which allows for testing for against regular expressions ```javascript var mainString = "hello", regex = "/hell/"; regex.test(mainString) ```
↥ back to top
## 76. How do you validate an email in javascript? You 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. ```javascript function validateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\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,}))$/; return re.test(String(email).toLowerCase()); } ``` The above regular expression regular accepts unicode characters.
↥ back to top
## 77. How do you get the current url with javascript? You 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. ```javascript console.log('location.href', window.location.href); // Returns full URL ```
↥ back to top
## 78. What are the various url properties of location object? The below `Location` object properties can be used to access URL components of the page |Properties|Description| |----------|------------| |href |The entire URL| |protocol |The protocol of the URL| |host |The hostname and port of the URL| |hostname |The hostname of the URL| |port |The port number in the URL| |pathname |The path name of the URL| |search |The query portion of the URL| |hash |The anchor portion of the URL|
↥ back to top
## 79. How do get query string values in javascript? You 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, ```javascript const urlParams = new URLSearchParams(window.location.search); const clientCode = urlParams.get('clientCode'); ```
↥ back to top
## 80. How do you check if a key exists in an object? **a.) Using in operator:** You can use the in operator whether a key exists in an object or not ```javascript "key" in obj ``` and If you want to check if a key doesn't exist, remember to use parenthesis, ```javascript !("key" in obj) ``` **b.) Using hasOwnProperty method:** You can use `hasOwnProperty` to particularly test for properties of the object instance (and not inherited properties) ```javascript obj.hasOwnProperty("key") // true ```
↥ back to top
## 81. How do you loop through or enumerate javascript object? You 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. ```javascript var object = { "k1": "value1", "k2": "value2", "k3": "value3" }; for (var key in object) { if (object.hasOwnProperty(key)) { console.log(key + " -> " + object[key]); // k1 -> value1 ... } } ```
↥ back to top
## 82. How do you test for an empty object? **a.) Using Object keys(ECMA 5+):** You can use object keys length along with constructor type. ```javascript Object.keys(obj).length === 0 && obj.constructor === Object ``` **b.) Using Object entries(ECMA 7+):** You can use object entries length along with constructor type. ```javascript Object.entries(obj).length === 0 && obj.constructor === Object ```
↥ back to top
## 83. What is an arguments object? The arguments object is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. For example, let us see how to use arguments object inside sum function, ```javascript function sum() { var total = 0; for (var i = 0, len = arguments.length; i < len; ++i) { total += arguments[i]; } return total; } sum(1, 2, 3) // returns 6 ```
↥ back to top
## 84. How do you make first letter of the string in an uppercase? You 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. ```javascript function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } ```
↥ back to top
## 85. What are the pros and cons of for loop? The for-loop is a commonly used iteration syntax in javascript. It has both pros and cons **Pros** 1. Works on every environment 2. You can use break and continue flow control statements **Cons** 1. Too verbose 2. Imperative 3. You might face one-by-off errors
↥ back to top
## 86. How do you display the current date in javascript? You can use `new Date()` to generate a new Date object containing the current date and time. Example: ```javascript var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! var yyyy = today.getFullYear(); today = mm + '/' + dd + '/' + yyyy; document.write(today); ```
↥ back to top
## 87. How do you compare two date objects? You need to use use date.getTime() method to compare date values instead comparision operators (==, !=, ===, and !== operators) ```javascript var d1 = new Date(); var d2 = new Date(d1); console.log(d1.getTime() === d2.getTime()); //True console.log(d1 === d2); // False ```
↥ back to top
## 88. How do you check if a string starts with another string? You 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, ```javascript "Good morning".startsWith("Good"); // true "Good morning".startsWith("morning"); // false ```
↥ back to top
## 89. How do you trim a string in javascript? JavaScript provided a trim method on string types to trim any whitespaces present at the begining or ending of the string. ```javascript " Hello World ".trim(); //Hello World ``` If your browser(`< IE9`) doesnot support this method then you can use below polyfill. ```javascript if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); } ```
↥ back to top
## 90. How do you add a key value pair in javascript? There are two possible solutions to add new properties to an object. Let us take a simple object to explain these solutions. ```javascript var object = { key1: value1, key2: value2 }; ``` **a.) Using dot notation:** This solution is useful when you know the name of the property ```javascript object.key3 = "value3"; ``` **b.) Using square bracket notation:** This solution is useful when the name of the property is dynamically determined. ```javascript obj["key3"] = "value3"; ```
↥ back to top
## 91. How do you assign default values to variables? You can use the logical or operator `||` in an assignment expression to provide a default value. The syntax looks like as below, ```javascript var a = b || c; ``` As per the above expression, variable 'a 'will get the value of 'c' only if 'b' is falsy (if is null, false, undefined, 0, empty string, or NaN), otherwise 'a' will get the value of 'b'.
↥ back to top
## 92. Can we define properties for functions? Yes, We can define properties for functions because functions are also objects. ```javascript fn = function(x) { //Function code goes here } fn.name = "John"; fn.profile = function(y) { //Profile code goes here } ```
↥ back to top
## 93. What is the way to find the number of parameters expected by a function? You 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, ```javascript function sum(num1, num2, num3, num4){ return num1 + num2 + num3 + num4; } sum.length // 4 is the number of parameters expected. ```
↥ back to top
## 94. What are break and continue statements? The break statement is used to "jumps out" of a loop. i.e, It breaks the loop and continues executing the code after the loop. ```javascript for (i = 0; i < 10; i++) { if (i === 5) { break; } text += "Number: " + i + "
"; } ``` The 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. ```javascript for (i = 0; i < 10; i++) { if (i === 5) { continue; } text += "Number: " + i + "
"; } ```
↥ back to top
## 95. What are js labels? The label statement allows us to name loops and blocks in JavaScript. We can then use these labels to refer back to the code later. For example, the below code with labels avoids printing the numbers when they are same, ```javascript var i, j; loop1: for (i = 0; i < 3; i++) { loop2: for (j = 0; j < 3; j++) { if (i === j) { continue loop1; } console.log('i = ' + i + ', j = ' + j); } } // Output is: // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1" ```
↥ back to top
## 96. What are the benefits of keeping declarations at the top? It is recommended to keep all declarations at the top of each script or function. The benefits of doing this are, 1. Gives cleaner code 2. It provides a single place to look for local variables 3. Easy to avoid unwanted global variables 4. It reduces the possibility of unwanted re-declarations
↥ back to top
## 97. What are the benefits of initializing variables? It is recommended to initialize variables because of the below benefits, 1. It gives cleaner code 2. It provides a single place to initialize variables 3. Avoid undefined values in the code
↥ back to top
## 98. What are the recommendations to create new object? It is recommended to avoid creating new objects using `new Object()`. Instead you can initialize values based on it is type to create the objects. 1. Assign {} instead of new Object() 2. Assign "" instead of new String() 3. Assign 0 instead of new Number() 4. Assign false instead of new Boolean() 5. Assign [] instead of new Array() 6. Assign /()/ instead of new RegExp() 7. Assign function (){} instead of new Function() You can define them as an example, ```javascript var v1 = {}; var v2 = ""; var v3 = 0; var v4 = false; var v5 = []; var v6 = /()/; var v7 = function(){}; ```
↥ back to top
## 99. How do you define JSON arrays? JSON arrays are written inside square brackets and array contain javascript objects. For example, the JSON array of users would be as below, ```javascript "users":[ {"firstName":"John", "lastName":"Abrahm"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Shane", "lastName":"Warn"} ] ```
↥ back to top
## 100. How do you generate random integers? You can use Math.random() with Math.floor() to return random integers. For example, if you want generate random integers between 1 to 10, the multiplication factor should be 10, ```javascript Math.floor(Math.random() * 10) + 1; // returns a random integer from 1 to 10 Math.floor(Math.random() * 100) + 1; // returns a random integer from 1 to 100 ``` *Note: Math.random() returns a random number between 0 (inclusive), and 1 (exclusive)*
↥ back to top
## 101. Can you write a random integers function to print integers with in a range? Yes, you can create a proper random function to return a random number between min and max (both included) ```javascript function randomInteger(min, max) { return Math.floor(Math.random() * (max - min + 1) ) + min; } randomInteger(1, 100); // returns a random integer from 1 to 100 randomInteger(1, 1000); // returns a random integer from 1 to 1000 ```
↥ back to top
## 102. What are the string methods available in Regular expression? Regular Expressions has two string methods: search() and replace(). The search() method uses an expression to search for a match, and returns the position of the match. ```javascript var msg = "Hello John"; var n = msg.search(/John/i); // 6 ``` The replace() method is used return a modified string where the pattern is replaced. ```javascript var msg = "Hello John"; var n = msg.search(/John/i, "Buttler"); // Hello Buttler ```
↥ back to top
## 103. What are modifiers in regular expression? Modifiers can be used to perform case-insensitive and global searches. | Modifier | Description | |---- | -----------------| | i | Perform case-insensitive matching | | g | Perform a global match rather than stops at first match | | m | Perform multiline matching| Example: Global Modifier ```javascript var text = "Learn JS one by one"; var pattern = /one/g; var result = text.match(pattern); // one,one ```
↥ back to top
## 104. What are regular expression patterns? Regular Expressions provided group of patterns in order to match characters. Basically they are categorized into 3 types, **1. Brackets:** These are used to find a range of characters. For example, below are some use cases, * [abc]: Used to find any of the characters between the brackets(a,b,c) * [0-9]: Used to find any of the digits between the brackets * (a|b): Used to find any of the alternatives separated with | **2. Metacharacters:** These are characters with a special meaning For example, below are some use cases, * \d: Used to find a digit * \s: Used to find a whitespace character * \b: Used to find a match at the beginning or ending of a word **3. Quantifiers:** These are useful to define quantities For example, below are some use cases, * n+: Used to find matches for any string that contains at least one n * n*: Used to find matches for any string that contains zero or more occurrences of n * n?: Used to find matches for any string that contains zero or one occurrences of n
↥ back to top
## 105. What is a RegExp object? RegExp object is a regular expression object with predefined properties and methods. ```javascript var regexp = new RegExp('\\w+'); console.log(regexp); // expected output: /\w+/ ```
↥ back to top
## 106. How do you search a string for a pattern? You 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. ```javascript var pattern = /you/; console.log(pattern.test("How are you?")); //true ```
↥ back to top
## 107. What is the purpose of exec method? The purpose of exec method is similar to test method but it returns a founded text as an object instead of returning true/false. ```javascript var pattern = /you/; console.log(pattern.test("How are you?")); //you ```
↥ back to top
## 108. How do you change style of a HTML element? You can change inline style or classname of a HTML element using javascript 1. **Using style property:** You can modify inline style using style property ```javascript document.getElementById("title").style.fontSize = "30px"; ``` 2. **Using ClassName property:** It is easy to modify element class using className property ```javascript document.getElementById("title").style.className = "custom-title"; ```
↥ back to top
## 109. What is a debugger statement? The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect. For example, in the below function a debugger statement has been inserted. So execution is paused at the debugger statement just like a breakpoint in the script source. ```javascript function getProfile() { // code goes here debugger; // code goes here } ```
↥ back to top
## 110. What is the purpose of breakpoints in debugging? You 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.
↥ back to top
## 111. Can I use reserved words as identifiers? No, you cannot use the reserved words as variables, labels, object or function names. ```javascript var else = "hello"; // Uncaught SyntaxError: Unexpected token else ```
↥ back to top
## 112. How do you detect a mobile browser without regexp? You 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, ```javascript function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } } ```
↥ back to top
## 113. How do you get the image width and height using JS? You can programmatically get the image and check the dimensions(width and height) using Javascript. ```javascript var img = new Image(); img.onload = function() { console.log(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif'; ```
↥ back to top
## 114. How do you make synchronous HTTP request? Browsers provide an XMLHttpRequest object which can be used to make synchronous HTTP requests from JavaScript ```javascript function httpGet(theUrl) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReQ.open( "GET", theUrl, false ); // false for synchronous request xmlHttpReQ.send( null ); return xmlHttpReQ.responseText; } ```
↥ back to top
## 115. How do you make asynchronous HTTP request? Browsers provide an XMLHttpRequest object which can be used to make asynchronous HTTP requests from JavaScript by passing 3rd parameter as true. ```javascript function httpGetAsync(theUrl, callback) { var xmlHttpReq = new XMLHttpRequest(); xmlHttpReQ.onreadystatechange = function() { if (xmlHttpReQ.readyState == 4 && xmlHttpReQ.status == 200) callback(xmlHttpReQ.responseText); } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } ```
↥ back to top
## 116. How do you convert date to another timezone in javascript? You 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, ```javascript console.log(event.toLocaleString('en-GB', { timeZone: 'UTC' })); //29/06/2019, 09:56:00 ```
↥ back to top
## 117. What are the properties used to get size of window? You 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, ```javascript var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; ```
↥ back to top
## 118. What is a conditional operator in javascript? The conditional (ternary) operator is the only JavaScript operator that takes three operands which acts as a shortcut for if statement. ```javascript var isAuthenticated = false; console.log(isAuthenticated ? 'Hello, welcome' : 'Sorry, you are not authenticated'); ```
↥ back to top
## 119. Can you apply chaining on conditional operator? Yes, you can apply chaining on conditional operator similar to if … else if … else if … else chain. The syntax is going to be as below, ```javascript function traceValue(someParam) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // The above conditional operator is equivalent to: function traceValue(someParam) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } ```
↥ back to top
## 120. What are the ways to execute javascript after page load? You can execute javascript after page load in many different ways, **a.) window.onload:** ```javascript window.onload = function ... ``` **b.) document.onload:** ```javascript document.onload = function ... ``` **c.) body onload:** ```html ```
↥ back to top
## 121. What is the difference between proto and prototype? The `__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 ```javascript ( new Employee ).__proto__ === Employee.prototype; ( new Employee ).prototype === undefined; ```
↥ back to top
## 122. Give an example where do you really need semicolon? It is recommended to use semicolons after every statement in JavaScript. For example, in the below case it throws an error ".. is not a function" at runtime due to missing semicolon. ```javascript // define a function var fn = function () { //... } // semicolon missing at this line // then execute some code inside a closure (function () { //... })(); ``` and it will be interpreted as ```javascript var fn = function () { //... }(function () { //... })(); ``` In 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.
↥ back to top
## 123. What is a freeze method? The 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. ```javascript const obj = { prop: 100 }; Object.freeze(obj); obj.prop = 200; // Throws an error in strict mode console.log(obj.prop); //100 ``` *Note: It causes a TypeError if the argument passed is not an object*.
↥ back to top
## 124. What is the purpose of freeze method? Below are the main benefits of using freeze method, 1. It is used for freezing objects and arrays. 2. It is used to make an object immutable. ## 125. Why do I need to use freeze method? In 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.
↥ back to top
## 126. How do you detect a browser language preference? You can use navigator object to detect a browser language preference as below, ```javascript var language = navigator.languages && navigator.languages[0] || // Chrome / Firefox navigator.language || // All browsers navigator.userLanguage; // IE <= 10 console.log(language); ```
↥ back to top
## 127. How to convert string to title case with javascript? Title case means that the first letter of each word is capitalized. You can convert a string to title case using the below function, ```javascript function toTitleCase(str) { return str.replace( /\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); } ); } toTitleCase("good morning john"); // Good Morning John ```
↥ back to top
## 128. How do you detect javascript disabled in the page? You can use `