-
Notifications
You must be signed in to change notification settings - Fork 43
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
call
andapply
do the same thing, just different syntaxbind
creates a new function from the given function It is most useful when the function has athis
.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-
-
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
-
Object
vsMap
--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
-
==
&&===
-
===
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
-
let
vsvar
-
let
blocked scoped local variable,var
is 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 Zone
occurs withlet
andconst
but not invar
, when accessinglet
andconst
before declaration causesReferenceError
. The timespan when thatReferenceError
happens 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 -
Classes
are syntactic sugar over JS existing prototype based inheritance -
Closures
the 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 usepostMessage
interface to manipulate the dom because service workers cant access the DOM directly. Service workers gets terminated when not in use. -
IndexDB
lowelevel 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). -
postMessage
enables cross-origin communication between window objects (eg. page and popup it spawned, page and iframe embedded within it.) -
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. - Web workers can't access the window, document and parent object
-
server-sent
event notifications -
promise.race()
method -
strict Mode
to 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 -
typeof
to return type of a variable -
null
vsundefined
, -
eval
evaluates javascript code represented as a string -
window
vsdocument
.window
is the root level element in any webpage.window.document
is the direct child of window object.window
hasalert()
,confirm()
and properties likewindow.location
.document
hasgetElementById
,createElement
etc -
history
you can access browser history bywindow.history.back()
andwindow.history.forward()
- You can detect capslock on mousedown
event.getModifierState("Capslock")
isNaN("hello") === true
-
undeclared
vsundefined
-
global
variables. problematic. is not allowed inuse strict
NaN
isFinite(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 Capturing
andEvent Bubbling
-
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 -
Event Capturing
The event is first captured by the outermost element then successively triggers on the children until it reaches the innermost dom element -
window.navigator.platform
contains information about the visitor's browser OS details -
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 -
native objects
part of javascript language (String, Math, RegExp, Object, Function).host objects
are provided by node or browser likewindow
, dom notes,XMlHttpRequest
. User objects are objects defined in a specific javascript code. -
attribute
are defined in html markup<input type="text" />
whileproperty
is defined in the dom.input.getAttribute("type")
-
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. -
void 0
prevents page from refreshing.<a href="Javascript:void(0);" onclick="alert("well done")"> click me </a>
- Events, things that happen to html ements
-
preventDefault
default behavior of that event will not occur like when submitting a form -
stopPropagation
stops event from bubbling up the event chain - 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 - BOM - browser object model allows the javascript to talk to the browser. it consists of object
navigator
,history
,screen
,location
, anddocument
which 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. -
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 -
clearTimeout
andclearInterval
to kill the event listener and prevent memory leaks - Redirect a new page in javascript
window.location.href = "newPage.html"
-
window.location.href
returns current url full URL -
window.location
has the following properties:href
,protocol
,host
,hostname
,port
,pathname
,search
(query portion of the url),hash
anchor 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
-
polyfill
js code used to provide modern functionality on other browsers that do not natively support it -
jslabels
you 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
,rollup
etc - do not use
eval
it is not safe navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i)
- You can make synchronous and asynchronous http request via
XMLHttpRequest
object that the browser provides - You can get
window.innerWidth
andwindow.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,prototype
is the object that is used to build__proto__
when you create an object ??? -
freeze
method 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.freeze
you 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()
-
WeakSet
collection of weakly references held objectnew WeakSet([iterable])
. weaksets hasadd
,has
,length
,delete
-
weakSet
vsSet
, 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. -
WeakMap
collection of. key value pairs. -
uneval
built in function to create a string representation of an objectuneval(function user() {}) // returns "(function user(){}
-
encodeURI
to 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
-
accessors
areget
andset
on a class -
Object.defineProperty(newObject, 'newProperty', {value: 100, writable: false})
if you donewObject.newProperty = 200
it 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
-
nodejs
server side platform built on chrome's javascript runtime for easily building fast and scalable network applicaions, even-tbased, non blocking, asynchronouse -
Intl
object is the namespace for ecmascript internationalization api, which provides language senstive string comparison, number formating etc. propertiesDateTimeFormat
,Collator
,ListFormat
,NumberFormat
,PluralRules
,RelativeTimeFormat
etc let date = new Date(); console.log(new Intl.DateTimeFormat('en-AU').format(date)
-
event loop
call stack``event queue
-
+
a , the unary operator is used to convert a variable to a number