-
Notifications
You must be signed in to change notification settings - Fork 41
Javascript Interview Questions
Mithi Sevilla edited this page Apr 5, 2021
·
2 revisions
- https://github.com/mithi/old-web-dev-stuff/issues/1
- https://github.com/sudheerj/javascript-interview-questions
- https://github.com/ganqqwerty/123-Essential-JavaScript-Interview-Questions
- https://github.com/learning-zone/javascript-interview-questions
- https://github.com/lydiahallie/javascript-questions
- https://github.com/rohan-paul/Awesome-JavaScript-Interviews
-
Prototype Chain -- Build new types of object based on existing ones. A way of "inheriting" properties but doesn't work the same way as inheritance in a class based language
-
Call, Apply, Bind
callandapplydo the same thing, just different syntaxbindcreates a new function from the given function It is most useful when the function has athis.thiswill refer to the object you pass in as the first argument.
let cat = {name: "Fuku", color: "white" }
function describeCat(prefix, postfix) {
console.log(`${prefix}, ${this.name} the cat is color ${this.color}. ${postfix}`)
}
describeCat.apply(cat, ["Hello!", "Bye!"])
// Hello! Fuku the cat is color white. Bye!
describeCat.call(cat, "start.", "end.")
// start. Fuku the cat is color white. end.
let describeFuku = describeCat.bind(cat)
describeFuku("-START-", "-END-")
// -START- Fuku the cat is color white. -END--
splicearrays Adds item to array or remove item from array. returns removed items and modifies array.
- First argument: position for insertion, deletion
- 2nd argument: (optional) - number of elements to be deleted
- Next arguments, to be added to array
- Check MDN for syntax
-
ObjectvsMap--Objectkeys can only be strings or symbols,Mapany value, like functions and objects --Mapordered keys,objectnot --Maphas a size property, is iterable directly
-
Objecthas prototype,Mapdon't have this
-
==&&===
-
===checks for value and type.==value only
// refers to different objects in memory
{} === {} // false
[] === [] // false
{} == {} // false
[] == [] // false
- Arrow functions
- don't have own this
- can't be called inside it, must be declared first
- pure function, firs order function, higher order function, unary functions, currying function
-
letvsvar
-
letblocked scoped local variable,varis function scoped
console.log(age) // ERROR cannot access age before initialization
let age = 30- For switch statements add curly braces for each case to scope variables
-
Temporal Dead Zoneoccurs withletandconstbut not invar, when accessingletandconstbefore declaration causesReferenceError. The timespan when thatReferenceErrorhappens between the creation of variable's binding and its declaration. - IIFE - Immediately invoked functions, variables declared in IIFE cannot be accessed in the outside world
-
Memoize, cache previously computed results -
Hoisting, variables and functions are moved to the top of scope before execution. Javascript hoists declarations not initializations -
Classesare syntactic sugar over JS existing prototype based inheritance -
Closuresthe inner function has access to the outer or enclosing function variables even if the outer function has already returned -
Scope- the part of the code where you can access particular functions, variables, and objects at runtime -
Service Worker- runs in the background, separate from webpage, that don't need user interaction. example, offline experience, background syncs, push notifications, managing cache. You can usepostMessageinterface to manipulate the dom because service workers cant access the DOM directly. Service workers gets terminated when not in use. -
IndexDBlowelevel API for client-side storage for large structured data like files/blobs. enable high-performance searches of this data - Web storage -you can store key value pairs on your browser (
localStorage,sessionStorage- deletes data when browser tab is closed). -
postMessageenables cross-origin communication between window objects (eg. page and popup it spawned, page and iframe embedded within it.) -
cookiea piece of data stored on your computer to be accessed by browser. Used to remember information like user profile. User visits webpage, user can be stored in the cookie. next time user visits the page, the cookie remembers the user profile. - Web workers can't access the window, document and parent object
-
server-sentevent notifications -
promise.race()method -
strict Modeto prevent certain actions from being taken and throws more exceptions. catches bad syntax like accidentally creating a global variable etc -
!!double exclamation to ensure resulting type is a boolean -
delete- to delete property and value -
typeofto return type of a variable -
nullvsundefined, -
evalevaluates javascript code represented as a string -
windowvsdocument.windowis the root level element in any webpage.window.documentis the direct child of window object.windowhasalert(),confirm()and properties likewindow.location.documenthasgetElementById,createElementetc -
historyyou can access browser history bywindow.history.back()andwindow.history.forward() - You can detect capslock on mousedown
event.getModifierState("Capslock") isNaN("hello") === true-
undeclaredvsundefined -
globalvariables. problematic. is not allowed inuse strict NaNisFinite(Infinity); isFinite(NaN); isFinite(-Infinity)-
Event Flow- order in which event is received in a webpage. When you click an element that is nested in various other elements, before your click actually reaches its destination or target element, is must trigger the click event for each of its parent elements first, starting at the top with the global window object. To ways of event flowEvent CapturingandEvent Bubbling -
Event Bubblingtype of event population where the event first triggers to the inner most target element and then successively triggers on the ancestors (parents) of the target element until it riches the outermost DOM property -
Event CapturingThe event is first captured by the outermost element then successively triggers on the children until it reaches the innermost dom element -
window.navigator.platformcontains information about the visitor's browser OS details -
DOMContentLoadedevent is fired when the initial HTML document has been completely loaded and parsed without waiting for assets (stylesheets, images) finished loading.loadevent is fired when all the the other stuff like stylesheets and images are loaded -
native objectspart of javascript language (String, Math, RegExp, Object, Function).host objectsare provided by node or browser likewindow, dom notes,XMlHttpRequest. User objects are objects defined in a specific javascript code. -
attributeare defined in html markup<input type="text" />whilepropertyis defined in the dom.input.getAttribute("type") -
same-origin policyprevents javascript from making request across domain boundaries (defined by URI scheme, hostname, and port number). to prevent malicious scripts from obtaining access to sensitive data. -
void 0prevents page from refreshing.<a href="Javascript:void(0);" onclick="alert("well done")"> click me </a> - Events, things that happen to html ements
-
preventDefaultdefault behavior of that event will not occur like when submitting a form -
stopPropagationstops event from bubbling up the event chain - returning
falseon event handlers, stops the default action or behavior of the browser. prevents event from propagating the dom. stops callback execution and returns immediately when called - BOM - browser object model allows the javascript to talk to the browser. it consists of object
navigator,history,screen,location, anddocumentwhich are children of the window. it is not standardized and can change based on different browsers -
event delegation, a technique for listening to events where you delegate the parent element as a listener of all the events that happen inside it. For example you can detect the filed changes inside each specific form. -
PWAprogressive web applications, a type of mobile app delivered through the web built with html, css javascript. deployed to servers, accessible through URL, and indexed by search engines -
clearTimeoutandclearIntervalto kill the event listener and prevent memory leaks - Redirect a new page in javascript
window.location.href = "newPage.html" -
window.location.hrefreturns current url full URL -
window.locationhas the following properties:href,protocol,host,hostname,port,pathname,search(query portion of the url),hashanchor portion of the url - app shell model, application shell architecture is one way to build progressive web apps that reliably and instantly loads on your user's screens similar to what you see in native applications. useful for getting some initial html to the screen fast without a network
function sum(a, b, c) { return a + b + c }; sum.length // 4-
polyfilljs code used to provide modern functionality on other browsers that do not natively support it -
jslabelsyou can actually name loops and blocks in javascripts so that if you have nested loops you cancontinue loopName -
tree shaking- eliminating dead code that is not used. implemented ywebpack,rollupetc - do not use
evalit is not safe navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)- You can make synchronous and asynchronous http request via
XMLHttpRequestobject that the browser provides - You can get
window.innerWidthandwindow.innerHeight - You can execute javascript after page load like
window.onload = function....ordocument.onload = function...or<body = onload="script()> -
__proto__vsprototype.__proto__the actual object that is used in the lookup chain to resolve methods,prototypeis the object that is used to build__proto__when you create an object ??? -
freezemethod to NOT allow adding new properties, prevents removing properties etc... to make object immutable - Detect browser language
navigator.language <noscript>Javascript is disabled here</noscript>Object.freeze(myObject); Object.isFrozen(myObject)-
Object.is([], []) // false,Object.is(window, window) //true - Copy object properties with
object.assign -
const p = new Proxy(target, handler)to define custom behavior for fundamental operations ???? -
Object.seal(), changes can be made in the existing properties of the object.freezeyou can't change existing properties.Object.isSealed(myObject) -
Object.values()returns an array of values,Object.entries()returns an array of key, value pairs.Object.keys() -
WeakSetcollection of weakly references held objectnew WeakSet([iterable]). weaksets hasadd,has,length,delete -
weakSetvsSet, sets can stor any value, weaksets can only store collection of objects. weeksets don't have a size property. it does not have methods like clear, keys, values, entries, for each. -
WeakMapcollection of. key value pairs. -
unevalbuilt in function to create a string representation of an objectuneval(function user() {}) // returns "(function user(){} -
encodeURIto encode URLS that has special characters (replaces them),decodeURI -
window.print()prints contents of the window, opens a dialog box that lets you choose between various printing options - Local variables takes precedence over global variables with the same name
-
accessorsaregetandseton a class -
Object.defineProperty(newObject, 'newProperty', {value: 100, writable: false})if you donewObject.newProperty = 200it will return an error. - primitive data types, string, number, boolean, null, undefined, bigint, symbol
- error object.
err.name,err.message - error names
EalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError -
try,catch,throw,finally -
nodejsserver side platform built on chrome's javascript runtime for easily building fast and scalable network applicaions, even-tbased, non blocking, asynchronouse -
Intlobject is the namespace for ecmascript internationalization api, which provides language senstive string comparison, number formating etc. propertiesDateTimeFormat,Collator,ListFormat,NumberFormat,PluralRules,RelativeTimeFormatetc let date = new Date(); console.log(new Intl.DateTimeFormat('en-AU').format(date)-
event loopcall stack``event queue -
+a , the unary operator is used to convert a variable to a number