Skip to content

Javascript Interview Questions

Mithi Sevilla edited this page Apr 5, 2021 · 2 revisions

Start here

  1. 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

  2. Call, Apply, Bind call and apply do the same thing, just different syntax bind creates a new function from the given function It is most useful when the function has a this. this will 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-
  1. splice arrays 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
  1. Object vs Map -- Object keys can only be strings or symbols, Map any value, like functions and objects -- Map ordered keys, object not -- Map has a size property, is iterable directly
  • Object has prototype, Map don't have this
  1. == && ===
  • === checks for value and type. == value only
// refers to different objects in memory
{} === {} // false
[] === [] // false
{} == {} // false
[] == [] // false
  1. Arrow functions
  • don't have own this
  • can't be called inside it, must be declared first
  1. pure function, firs order function, higher order function, unary functions, currying function
  2. let vs var
  • let blocked scoped local variable, var is function scoped
console.log(age) // ERROR cannot access age before initialization 
let age = 30
  1. For switch statements add curly braces for each case to scope variables
  2. Temporal Dead Zone occurs with let and const but not in var, when accessing let and const before declaration causes ReferenceError. The timespan when that ReferenceError happens between the creation of variable's binding and its declaration.
  3. IIFE - Immediately invoked functions, variables declared in IIFE cannot be accessed in the outside world
  4. Memoize, cache previously computed results
  5. Hoisting, variables and functions are moved to the top of scope before execution. Javascript hoists declarations not initializations
  6. Classes are syntactic sugar over JS existing prototype based inheritance
  7. Closures the inner function has access to the outer or enclosing function variables even if the outer function has already returned
  8. Scope - the part of the code where you can access particular functions, variables, and objects at runtime
  9. 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 use postMessage interface to manipulate the dom because service workers cant access the DOM directly. Service workers gets terminated when not in use.
  10. IndexDB lowelevel API for client-side storage for large structured data like files/blobs. enable high-performance searches of this data
  11. Web storage -you can store key value pairs on your browser (localStorage , sessionStorage - deletes data when browser tab is closed).
  12. postMessage enables cross-origin communication between window objects (eg. page and popup it spawned, page and iframe embedded within it.)
  13. cookie a 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.
  14. Web workers can't access the window, document and parent object
  15. server-sent event notifications
  16. promise.race() method
  17. strict Mode to prevent certain actions from being taken and throws more exceptions. catches bad syntax like accidentally creating a global variable etc
  18. !! double exclamation to ensure resulting type is a boolean
  19. delete - to delete property and value
  20. typeof to return type of a variable
  21. null vs undefined,
  22. eval evaluates javascript code represented as a string
  23. window vs document. window is the root level element in any webpage. window.document is the direct child of window object. window has alert(), confirm() and properties like window.location. document has getElementById, createElement etc
  24. history you can access browser history by window.history.back() and window.history.forward()
  25. You can detect capslock on mousedown event.getModifierState("Capslock")
  26. isNaN("hello") === true
  27. undeclared vs undefined
  28. global variables. problematic. is not allowed in use strict
  29. NaN
  30. isFinite(Infinity); isFinite(NaN); isFinite(-Infinity)
  31. 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 flow Event Capturing and Event Bubbling
  32. Event Bubbling type 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
  33. Event Capturing The event is first captured by the outermost element then successively triggers on the children until it reaches the innermost dom element
  34. window.navigator.platform contains information about the visitor's browser OS details
  35. DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed without waiting for assets (stylesheets, images) finished loading. load event is fired when all the the other stuff like stylesheets and images are loaded
  36. native objects part of javascript language (String, Math, RegExp, Object, Function). host objects are provided by node or browser like window, dom notes, XMlHttpRequest. User objects are objects defined in a specific javascript code.
  37. attribute are defined in html markup <input type="text" /> while property is defined in the dom. input.getAttribute("type")
  38. same-origin policy prevents 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.
  39. void 0 prevents page from refreshing. <a href="Javascript:void(0);" onclick="alert("well done")"> click me </a>
  40. Events, things that happen to html ements
  41. preventDefault default behavior of that event will not occur like when submitting a form
  42. stopPropagation stops event from bubbling up the event chain
  43. returning false on 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
  44. BOM - browser object model allows the javascript to talk to the browser. it consists of object navigator, history, screen, location, and document which are children of the window. it is not standardized and can change based on different browsers
  45. 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.
  46. PWA progressive 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
  47. clearTimeout and clearInterval to kill the event listener and prevent memory leaks
  48. Redirect a new page in javascript window.location.href = "newPage.html"
  49. window.location.href returns current url full URL
  50. window.location has the following properties: href, protocol, host, hostname, port, pathname, search (query portion of the url), hash anchor portion of the url
  51. 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
  52. function sum(a, b, c) { return a + b + c }; sum.length // 4
  53. polyfill js code used to provide modern functionality on other browsers that do not natively support it
  54. jslabels you can actually name loops and blocks in javascripts so that if you have nested loops you can continue loopName
  55. tree shaking - eliminating dead code that is not used. implemented y webpack, rollup etc
  56. do not use eval it is not safe
  57. navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)
  58. You can make synchronous and asynchronous http request via XMLHttpRequest object that the browser provides
  59. You can get window.innerWidth and window.innerHeight
  60. You can execute javascript after page load like window.onload = function.... or document.onload = function... or <body = onload="script()>
  61. __proto__ vs prototype. __proto__ the actual object that is used in the lookup chain to resolve methods, prototype is the object that is used to build __proto__ when you create an object ???
  62. freeze method to NOT allow adding new properties, prevents removing properties etc... to make object immutable
  63. Detect browser language navigator.language
  64. <noscript>Javascript is disabled here</noscript>
  65. Object.freeze(myObject); Object.isFrozen(myObject)
  66. Object.is([], []) // false, Object.is(window, window) //true
  67. Copy object properties with object.assign
  68. const p = new Proxy(target, handler) to define custom behavior for fundamental operations ????
  69. Object.seal(), changes can be made in the existing properties of the object. freeze you can't change existing properties. Object.isSealed(myObject)
  70. Object.values() returns an array of values, Object.entries() returns an array of key, value pairs. Object.keys()
  71. WeakSet collection of weakly references held object new WeakSet([iterable]). weaksets has add, has, length, delete
  72. weakSet vs Set, 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.
  73. WeakMap collection of. key value pairs.
  74. uneval built in function to create a string representation of an object uneval(function user() {}) // returns "(function user(){}
  75. encodeURI to encode URLS that has special characters (replaces them), decodeURI
  76. window.print() prints contents of the window, opens a dialog box that lets you choose between various printing options
  77. Local variables takes precedence over global variables with the same name
  78. accessors are get and set on a class
  79. Object.defineProperty(newObject, 'newProperty', {value: 100, writable: false}) if you do newObject.newProperty = 200 it will return an error.
  80. primitive data types, string, number, boolean, null, undefined, bigint, symbol
  81. error object. err.name, err.message
  82. error names EalError , RangeError, ReferenceError, SyntaxError, TypeError, URIError
  83. try, catch, throw, finally
  84. nodejs server side platform built on chrome's javascript runtime for easily building fast and scalable network applicaions, even-tbased, non blocking, asynchronouse
  85. Intl object is the namespace for ecmascript internationalization api, which provides language senstive string comparison, number formating etc. properties DateTimeFormat, Collator, ListFormat, NumberFormat, PluralRules, RelativeTimeFormat etc
  86. let date = new Date(); console.log(new Intl.DateTimeFormat('en-AU').format(date)
  87. event loop call stack``event queue
  88. + a , the unary operator is used to convert a variable to a number
Clone this wiki locally