fejes713 / 30-seconds-of-interviews
- суббота, 2 июня 2018 г. в 00:15:39
JavaScript
A curated collection of common interview questions to help you prepare for your next interview.
Interviews are daunting and can make even the most seasoned expert forget things under pressure. Review and learn what questions are commonly encountered in interviews curated by the community that's answered them and go prepared for anything they'll ask. By bringing together experience and real-world examples, you can go from being nervous to being prepared for that next big opportunity.
All financial support on Patreon will be equally split between core colaborators on projects in the way of purchasing educational materials and courses.
30 seconds of interviews is a community effort, so feel free to contribute in any way you can. Every contribution helps!
Do you have an excellent idea or know some cool questions that aren't on the list? Read the contribution guidelines and submit a pull request.
Join our Gitter channel to help with the development of the project.
==
and ===
?0.1 + 0.2 === 0.3
evaluate to?map()
and forEach()
?#
except for the last four (4) characters.null
and undefined
?pipe
that performs left-to-right function composition by returning a function that accepts one argument.this
keyword and how does it work?'use strict'
do and what are some of the key benefits to using it?var
, let
, const
and no keyword statements?defer
and async
attributes on a <script>
tag?<header>
elements? What about <footer>
elements?<header>
, <article>
,<section>
, <footer>
localStorage
and sessionStorage
.alt
attribute on images?rel="noopener"
attribute used?col-{n} / 12
ratio of the container.@media
properties?==
and ===
?Triple equals (===
) checks for strict equality, which means both the type and value must be the same. Double equals (==
) on the other hand first performs type coercion so that both operands are of the same type and then applies strict comparison.
==
can have unintuitive results.A Promise
is in one of these states:
A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called.
fs.readFile(filePath, function(err, data) {
if (err) {
// handle the error, the return is important here
// so execution stops here
return console.log(err)
}
// use the data object
console.log(data)
})
Advantages include:
As you can see from below example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an Error object, which then becomes the callback's only parameter. The callback function allows a user to easily know whether or not an error occurred.
This practice is also called the Node.js error convention, and this kind of callback implementations are called error-first callbacks.
var isTrue = function(value, callback) {
if (value === true) {
callback(null, "Value was true.")
} else {
callback(new Error("Value is not true!"))
}
}
var callback = function(error, retval) {
if (error) {
console.log(error)
return
}
console.log(retval)
}
isTrue(false, callback)
isTrue(true, callback)
/*
{ stack: [Getter/Setter],
arguments: undefined,
type: undefined,
message: 'Value is not true!' }
Value was true.
*/
Even though two different objects can have the same properties with equal values, they are not considered equal when compared using ==
or ===
. This is because they are being compared by their reference (location in memory), unlike primitive values which are compared by value.
In order to test if two objects are equal in structure, a helper function is required. It will
iterate through the own properties of each object to test if they have the same values, including nested objects.
Optionally, the prototypes of the objects may also be tested for equivalence by passing true
as the 3rd argument.
Note: this technique does not attempt to test equivalence of data structures other than plain objects, arrays, functions, dates and primitive values.
function isDeepEqual(obj1, obj2, testPrototypes = false) {
if (obj1 === obj2) {
return true
}
if (typeof obj1 === "function" && typeof obj2 === "function") {
return obj1.toString() === obj2.toString()
}
if (obj1 instanceof Date && obj2 instanceof Date) {
return obj1.getTime() === obj2.getTime()
}
const prototypesAreEqual = testPrototypes
? isDeepEqual(
Object.getPrototypeOf(obj1),
Object.getPrototypeOf(obj2),
true
)
: true
const obj1Props = Object.getOwnPropertyNames(obj1)
const obj2Props = Object.getOwnPropertyNames(obj2)
return (
obj1Props.length === obj2Props.length &&
prototypesAreEqual &&
obj1Props.every(prop => isDeepEqual(obj1[prop], obj2[prop]))
)
}
The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.
<head>
with a defer
attribute, or inside a DOMContentLoaded
event listener. Scripts that manipulate DOM nodes should be run after the DOM has been constructed to avoid errors.document.getElementById()
and document.querySelector()
are common functions for selecting DOM nodes.innerHTML
property to a new value runs the string through the HTML parser, offering an easy way to append dynamic HTML content to a node.XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application. This is often achieved when the application does not validate user input and freely injects dynamic HTML content.
For example, a comment system will be at risk if it does not validate or escape user input. If the comment contains unescaped HTML, the comment can inject a <script>
tag into the website that other users will execute against their knowledge.
textContent
instead of innerHTML
prevents the browser from running the string through the HTML parser which would execute scripts in it.Event delegation is a technique of delegating events to a single common ancestor. Due to event bubbling, events "bubble" up the DOM tree by executing any handlers progressively on each ancestor element up to the root that may be listening to it.
DOM events provide useful information about the element that initiated the event via Event.target
. This allows the parent element to handle behavior as though the target element was listening to the event, rather than all children of the parent or the parent itself.
This provides two main benefits:
Instead of:
document.querySelectorAll("span").forEach(span => {
span.addEventListener("click", handleSpanClick)
})
Event delegation involves using a condition to ensure the child target matches our desired element:
document.addEventListener("click", e => {
if (e.target.matches("span")) {
handleSpanClick()
}
})
Initialize an empty array of length n
. Use Array.prototype.reduce()
to add values into the array, using the sum of the last two values, except for the first two.
const fibonacci = n =>
[...Array(n)].reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
)
0.1 + 0.2 === 0.3
evaluate to?It evaluates to false
because JavaScript uses the IEEE 754 standard for Math and it makes use of 64-bit floating numbers. This causes precision errors when doing decimal calculations, in short, due to computers working in Base 2 while decimal is Base 10.
0.1 + 0.2 // 0.30000000000000004
A solution to this problem would be to use a function that determines if two numbers are approximately equal by defining an error margin (epsilon) value that the difference between two values should be less than.
const approxEqual = (n1, n2, epsilon = 0.0001) => Math.abs(n1 - n2) < epsilon
approxEqual(0.1 + 0.2, 0.3) // true
map()
and forEach()
?Both methods iterate through the elements of an array. map()
maps each element to new element by invoking the callback function on each element and returns a new array. On the other hand, forEach()
invokes the callback function for each element but does not return a new array. forEach()
is generally used when causing a side effect on each iteration, whereas map()
is a common functional programming technique.
forEach()
if you need to iterate over an array and cause mutations to the elements without needing to return values to generate a new array.map()
is the right choice to keep data immutable where each value of the original array is mapped to a new array.var foo = 1
var foobar = function() {
console.log(foo)
var foo = 2
}
foobar()
Due to hoisting, the local variable foo
is declared before the console.log
method is called. This means the local variable foo
is passed as an argument to console.log()
instead of the global one declared outside of the function. However, since the value is not hoisted with the variable declaration, the output will be undefined
, not 2
.
strict
modeHoisting is a JavaScript mechanism where variable and function declarations are put into memory during the compile phase. This means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
However, the value is not hoisted with the declaration.
The following snippet:
console.log(hoist)
var hoist = "value"
is equivalent to:
var hoist
console.log(hoist)
hoist = "value"
Therefore logging hoist
outputs undefined
to the console, not "value"
.
Hoisting also allows you to invoke a function declaration before it appears to be declared in a program.
myFunction() // No error; logs "hello"
function myFunction() {
console.log("hello")
}
But be wary of function expressions that are assigned to a variable:
myFunction() // Error: `myFunction` is not a function
var myFunction = function() {
console.log("hello")
}
This technique is very common in JavaScript libraries. It creates a closure around the entire contents of the file which creates a private namespace and thereby helps avoid potential name clashes between different JavaScript modules and libraries. The function is immediately invoked so that the namespace (library name) is assigned the return value of the function.
const myLibrary = (function() {
var privateVariable = 2
return {
publicMethod: () => privateVariable
}
})()
privateVariable // ReferenceError
myLibrary.publicMethod() // 2
#
except for the last four (4) characters.mask("123456789") // "#####6789"
There are many ways to solve this problem, this is just one one of them.
Using String.prototype.slice()
, we can grab a portion of the string from index 0
(first character) to index -4
(5th last character) and calculate the resulting length, using String.prototype.repeat()
to repeat the mask character that many times. Then, using String.prototype.slice()
once more, we can concatenate the last 4 characters by passing -4
as an argument.
const mask = (str, maskChar = "#") =>
maskChar.repeat(str.slice(0, -4).length) + str.slice(-4)
Callbacks are functions passed as an argument to another function to be executed once an event has occurred or a certain task is complete, often used in asynchronous code. Callback functions are invoked later by a piece of code but can be declared on initialization without being invoked.
As an example, event listeners are callbacks that are only executed when a specific event occurs.
function onClick() {
console.log("The user clicked on the page.")
}
document.addEventListener("click", onClick)
null
and undefined
?In JavaScript, two values discretely represent nothing - undefined
and null
. The concrete difference between them is that null
is explicit, while undefined
is implicit. When a property does not exist or a variable has not been given a value, the value is undefined
. null
is set as the value to explicitly indicate “no value”. In essence, undefined
is used when the nothing is not known, and null
is used when the nothing is known.
typeof undefined
evaluates to "undefined"
.typeof null
evaluates "object"
. However, it is still a primitive value and this is considered an implementation bug in JavaScript.undefined == null
evaluates to true
.Often used to store one occurrence of data.
const person = {
name: "John",
age: 50,
birthday() {
this.age++
}
}
person.birthday() // person.age === 51
Often used when you need to create multiple instances of an object, each with their own data that other instances of the class cannot affect. The new
operator must be used before invoking the constructor or the global object will be mutated.
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.birthday = function() {
this.age++
}
const person1 = new Person("John", 50)
const person2 = new Person("Sally", 20)
person1.birthday() // person1.age === 51
person2.birthday() // person2.age === 21
Creates a new object similar to a constructor, but can store private data using a closure. There is also no need to use new
before invoking the function or the this
keyword. Factory functions usually discard the idea of prototypes and keep all properties and methods as own properties of the object.
const createPerson = (name, age) => {
const birthday = () => person.age++
const person = { name, age, birthday }
return person
}
const person = createPerson("John", 50)
person.birthday() // person.age === 51
Object.create()
Sets the prototype of the newly created object.
const personProto = {
birthday() {
this.age++
}
}
const person = Object.create(personProto)
person.age = 50
person.birthday() // person.age === 51
A second argument can also be supplied to Object.create()
which acts as a descriptor for the new properties to be defined.
Object.create(personProto, {
age: {
value: 50,
writable: true,
enumerable: true
}
})
Parameters are the variable names of the function definition, while arguments are the values given to a function when it is invoked.
function myFunction(parameter1, parameter2) {
console.log(arguments[0]) // "argument1"
}
myFunction("argument1", "argument2")
arguments
is an array-like object containing information about the arguments supplied to an invoked function.myFunction.length
describes the arity of a function (how many parameters it has, regardless of how many arguments it is supplied).JavaScript always passes by value. However, with objects, the value is a reference to the object.
Using the object spread operator ...
, the object's own enumerable properties can be copied
into the new object. This creates a shallow clone of the object.
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.The Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
An example can be the following snippet, which after 100ms prints out the result string to the standard output. Also, note the catch, which can be used for error handling. Promise
s are chainable.
new Promise((resolve, reject) => {
setTimeout(() => {
resolve("result")
}, 100)
})
.then(console.log)
.catch(console.error)
Promise
s!In the classical inheritance paradigm, object instances inherit their properties and functions from a class, which acts as a blueprint for the object. Object instances are typically created using a constructor and the new
keyword.
In the prototypal inheritance paradigm, object instances inherit directly from other objects and are typically created using factory functions or Object.create()
. Finally, object instances can be composed from many different objects, allowing for selective inheritance.
const a = [1, 2, 3]
const b = [1, 2, 3]
const c = "1,2,3"
console.log(a == c)
console.log(a == b)
The first console.log
outputs true
because JavaScript's compiler performs type conversion and therefore it compares to strings by their value. On the other hand, the second console.log
outputs false
because Arrays are Objects and Objects are compared by reference.
function greet() {
return
{
message: "hello"
}
}
Because of JavaScript's automatic semicolon insertion (ASI), the compiler places a semicolon after return
keyword and therefore it returns undefined
without an error being thrown.
Synchronous means each operation must wait for the previous one to complete.
Asynchronous means an operation can occur while another operation is still being processed.
In JavaScript, all code is synchronous due to the single-threaded nature of it. However, asynchronous operations not part of the program (such as XMLHttpRequest
or setTimeout
) are processed outside of the main thread because they are controlled by native code (browser APIs), but callbacks part of the program will still be executed synchronously.
alert
block the main thread so that no user input is registered until the user closes it.typeof typeof 0
It evaluates to "string"
.
typeof 0
evaluates to the string "number"
and therefore typeof "number"
evaluates to "string"
.
The latest ECMAScript standard defines seven data types, six of them being primitive: Boolean
, Null
, Undefined
, Number
, String
, Symbol
and one non-primitive data type: Object
.
Symbol
data typeArray
, Date
and function
are all of type object
var
, let
, const
and no keyword statements?When no keyword exists before a variable assignment, it is either assigning a global variable if one does not exist, or reassigns an already declared variable. In non-strict mode, if the variable has not yet been declared, it will assign the variable as a property of the global object (window
in browsers). In strict mode, it will throw an error to prevent unwanted global variables from being created.
var
was the default statement to declare a variable until ES2015. It creates a function-scoped variable that can be reassigned and redeclared. However, due to its lack of block scoping, it can cause issues if the variable is being reused in a loop that contains an asynchronous callback because the variable will continue to exist outside of the block scope.
Below, by the time the the setTimeout
callback executes, the loop has already finished and the i
variable is 10
, so all ten callbacks reference the same variable available in the function scope.
for (var i = 0; i < 10; i++) {
setTimeout(() => {
// logs `10` ten times
console.log(i)
})
}
/* Solutions with `var` */
for (var i = 0; i < 10; i++) {
// Passed as an argument will use the value as-is in
// that point in time
setTimeout(console.log, 0, i)
}
for (var i = 0; i < 10; i++) {
// Create a new function scope that will use the value
// as-is in that point in time
;(i => {
setTimeout(() => {
console.log(i)
})
})(i)
}
let
was introduced in ES2015 and is the new preferred way to declare variables that will be reassigned later. Trying to redeclare a variable again will throw an error. It is block-scoped so that using it in a loop will keep it scoped to the iteration.
for (let i = 0; i < 10; i++) {
setTimeout(() => {
// logs 0, 1, 2, 3, ...
console.log(i)
})
}
const
was introduced in ES2015 and is the new preferred default way to declare all variables if they won't be reassigned later, even for objects that will be mutated (as long as the reference to the object does not change). It is block-scoped and cannot be reassigned.
const myObject = {}
myObject.prop = "hello!" // No error
myObject = "hello" // Error
let
and const
there is a concept called the temporal dead zone (TDZ). While the declarations are still hoisted, there is a period between entering scope and being declared where they cannot be accessed.var
and how let
can solve it, as well as a solution that keeps var
.var
should be avoided whenever possible and prefer const
as the default declaration statement for all variables unless they will be reassigned later, then use let
if so."Mutability" means a value is subject to change. "Immutability" means a value cannot change.
Objects are mutable, while primitive values (strings, numbers, etc) are immutable. This means any operation performed on a primitive value does not change the original value.
All String.prototype
methods do not have an effect on the original string and return a new string. On the other hand, while some methods of Array.prototype
do not mutate the original array reference and produce a fresh array, some cause mutations.
const myString = "hello!"
myString.replace("!", "") // returns a new string, cannot mutate the original value
const originalArray = [1, 2, 3]
originalArray.push(4) // mutates originalArray, now [1, 2, 3, 4]
originalArray.concat(4) // returns a new array, does not mutate the original
NaN
(Not-a-Number) is the only value not equal to itself when comparing with any of the comparison operators. NaN
is often the result of meaningless math computations, so two NaN
values make no sense to be considered equal.
isNaN()
and Number.isNaN()
const isNaN = x => x !== x
Big O notation is used in Computer Science to describe time complexity of an algorithm. The best algorithms will execute the fastest and have the simplest complexity.
Algorithms don't always perform the same and may vary based on the data they are supplied. While in some cases they will execute quickly, in other cases they will execute slowly, even with the same number of elements to deal with.
In these examples, the base time is 1ms
to make it more familiar.
arr[arr.length - 1]
Constant time complexity. No matter how many elements the array has, it will theoretically take (excluding real-world variation) the same amount of time to execute.
1ms
arr.filter(fn)
Linear time complexity. The execution time will increase linearly with the number of elements the array has. If the array has 1000 elements and the function takes 1ms to execute, 7000 elements will take 7ms to execute. This is because the function must iterate through all elements of the array before returning a result.
1000ms
arr.some(fn)
1ms <= x <= 1000ms
The execution time varies depending on the data supplied to the function, it may return very early or very late. The best case here is O(1) and the worst case is O(N).
arr.sort(fn)
Browsers usually implement the quicksort algorithm for the sort()
method which is logN time complexity. This is very efficient for large collections.
3ms
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
// ...
}
}
The execution time rises quadratically with the number of elements. Usually the result of nesting loops.
1000000ms
const permutations = arr => {
if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr
return arr.reduce(
(acc, item, i) =>
acc.concat(
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
item,
...val
])
),
[]
)
}
The execution time rises extremely fast with even just 1 addition to the array.
1000 elements = Infinity
(practically) ms
A pure function is function that satisfies these two conditions:
Pure functions can mutate local data within the function as long as it satisfies the two conditions above.
const a = (x, y) => x + y
const b = (arr, value) => arr.concat(value)
const c = arr => [...arr].sort((a, b) => a - b)
const a = (x, y) => x + y + Math.random()
const b = (arr, value) => (arr.push(value), arr)
const c = arr => arr.sort((a, b) => a - b)
setInnerHTML
).Recursion is the repeated application of a process. In JavaScript, recursion involves functions that call themselves repeatedly until they reach a base condition. The base condition breaks out of the recursion loop because otherwise the function would call itself indefinitely. Recursion is very useful when working with data structures that contain nesting where the number of levels deep is unknown.
For example, you may have a thread of comments returned from a database that exist in a flat array but need to be nested for display in the UI. Each comment is either a top-level comment (no parent) or is a reply to a parent comment. Comments can be a reply of a reply of a reply... we have no knowledge beforehand the number of levels deep a comment may be. This is where recursion can help.
const nest = (items, id = null, link = "parent_id") =>
items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }))
const comments = [
{ id: 1, parent_id: null, text: "First reply to post." },
{ id: 2, parent_id: 1, text: "First reply to comment #1." },
{ id: 3, parent_id: 1, text: "Second reply to comment #1." },
{ id: 4, parent_id: 3, text: "First reply to comment #3." },
{ id: 5, parent_id: 4, text: "First reply to comment #4." },
{ id: 6, aprent_id: null, text: "Second reply to post." }
]
nest(comments)
/*
[
{ id: 1, parent_id: null, text: "First reply to post.", children: [...] },
{ id: 6, parent_id: null, text: "Second reply to post." children: [] }
]
*/
In the above example, the base condition is met if filter()
returns an empty array. The chained map()
won't invoke the callback function which contains the recursive call, thereby breaking the loop.
getData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
getMoreData(c, function(d) {
getMoreData(d, function(e) {
// ...
})
})
})
})
})
Refactoring the functions to return promises and using async/await
is usually the best option. Instead of supplying the functions with callbacks that cause deep nesting, they return a promise that can be await
ed and will be resolved once the data has arrived, allowing the next line of code to be evaluated in a sync-like fashion.
The above code can be restructured like so:
async function asyncAwaitVersion() {
const a = await getData()
const b = await getMoreData(a)
const c = await getMoreData(b)
const d = await getMoreData(c)
const e = await getMoreData(e)
// ...
}
There are lots of ways to solve the issue of callback hells:
A closure is a function defined inside another function and has access to its lexical scope even when it is executing outside its lexical scope. The closure has access to variables in three scopes:
In JavaScript, all functions are closures because they have access to the outer scope, but most functions don't utilise the usefulness of closures: the persistence of state. Closures are also sometimes called stateful functions because of this.
In addition, closures are the only way to store private data that can't be accessed from the outside in JavaScript. They are the key to the UMD (Universal Module Definition) pattern, which is frequently used in libraries that only expose a public API but keep the implementation details private, preventing name collisions with other libraries or the user's own code.
Static methods belong to a class and don't act on instances, while instance methods belong to the class prototype which is inherited by all instances of the class and acts on them.
Array.isArray // static method of Array
Array.prototype.push // instance method of Array
In this case, the Array.isArray
method does not make sense as an instance method of arrays because we already know the value is an array when working with it.
Instance methods could technically work as static methods, but provide terser syntax:
const arr = [1, 2, 3]
arr.push(4)
Array.push(arr, 4)
Event-driven programming is a paradigm that involves building applications that send and receive events. When the program emits events, the program responds by running any callback functions that are registered to that event and context, passing in associated data to the function. With this pattern, events can be emitted into the wild without throwing errors even if no functions are subscribed to it.
A common example of this is the pattern of elements listening to DOM events such as click
and mouseenter
, where a callback function is run when the event occurs.
document.addEventListener("click", function(event) {
// This callback function is run when the user
// clicks on the document.
})
Without the context of the DOM, the pattern may look like this:
const hub = createEventHub()
hub.on("message", function(data) {
console.log(`${data.username} said ${data.text}`)
})
hub.emit("message", {
username: "John",
text: "Hello?"
})
With this implementation, on
is the way to subscribe to an event, while emit
is the way to publish the event.
this
keyword and how does it work?The this
keyword is an object that represents the context of an executing function. Regular functions can have their this
value changed with the methods call()
, apply()
and bind()
. Arrow functions implicitly bind this
so that it refers to the context of its lexical environment, regardless of whether or not its context is set explicitly with call()
.
Here are some common examples of how this
works:
this
refers to the object itself inside regular functions if the object precedes the invocation of the function.
Properties set as this
do not refer to the object.
var myObject = {
property: this,
regularFunction: function() {
return this
},
arrowFunction: () => {
return this
},
iife: (function() {
return this
})()
}
myObject.regularFunction() // myObject
myObject["regularFunction"]() // my Object
myObject.property // NOT myObject; lexical `this`
myObject.arrowFunction() // NOT myObject; lexical `this`
myObject.iife() // NOT myObject; lexical `this`
const regularFunction = myObject.regularFunction
regularFunction() // NOT myObject; lexical `this`
this
refers to the element listening to the event.
document.body.addEventListener("click", function() {
console.log(this) // document.body
})
this
refers to the newly created object.
class Example {
constructor() {
console.log(this) // myExample
}
}
const myExample = new Example()
With call()
and apply()
, this
refers to the object passed as the first argument.
var myFunction = function() {
return this
}
myFunction.call({ customThis: true }) // { customThis: true }
this
Because this
can change depending on the scope, it can have unexpected values when using regular functions.
var obj = {
arr: [1, 2, 3],
doubleArr() {
return this.arr.map(function(value) {
// this is now this.arr
return this.double(value)
})
},
double() {
return value * 2
}
}
obj.doubleArr() // Uncaught TypeError: this.double is not a function
this
is the global object (window
in browsers), while in strict mode global this
is undefined
.Function.prototype.call
and Function.prototype.apply
set the this
context of an executing function as the first argument, with call
accepting a variadic number of arguments thereafter, and apply
accepting an array as the second argument which are fed to the function in a variadic manner.Function.prototype.bind
returns a new function that enforces the this
context as the first argument which cannot be changed by other functions.this
context to be changed based on how it is called, you must use the function
keyword. Use arrow functions when you want this
to be the surrounding (lexical) context.Functional programming is a paradigm in which programs are built in a declarative manner using pure functions that avoid shared state and mutable data. Functions that always return the same value for the same input and don't produce side effects are the pillar of functional programming. Many programmers consider this to be the best approach to software development as it reduces bugs and cognitive load.
.map
, .reduce
etc.)Memoization is the process of caching the output of function calls so that subsequent calls are faster. Calling the function again with the same input will return the cached output without needing to do the calculation again.
A basic implementation in JavaScript looks like this:
const memoize = fn => {
const cache = new Map()
return value => {
const cachedResult = cache.get(value)
if (cachedResult !== undefined) return cachedResult
const result = fn(value)
cache.set(value, result)
return result
}
}
The main purpose is to avoid manipulating the DOM directly and keep the state of an application in sync with the UI easily. Additionally, they provide the ability to create components that can be reused when they have similar functionality with minor differences, avoiding duplication which would require multiple changes whenever the structure of a component which is reused in multiple places needs to be updated.
When working with DOM manipulation libraries like jQuery, the data of an application is generally kept in the DOM itself, often as class names or data
attributes. Manipulating the DOM to update the UI involves many extra steps and can introduce subtle bugs over time. Keeping the state separate and letting a framework handle the UI updates when the state changes reduces cognitive load. Saying you want the UI to look a certain way when the state is a certain value is the declarative way of creating an application, instead of the imperative way of manually updating the UI to reflect the new state.
'use strict'
do and what are some of the key benefits to using it?Including 'use strict'
at the beginning of your JavaScript source file enables strict mode, which enfores more strict parsing and error handling of JavaScript code. It is considered a good practice and offers a lot of benefits, such as:
eval()
and arguments
.this
coercion, throwing an error when this
references a value of null
or undefined
.delete
.pipe
that performs left-to-right function composition by returning a function that accepts one argument.const square = v => v * v
const double = v => v * 2
const addOne = v => v + 1
const res = pipe(square, double, addOne)
res(3) // 19; addOne(double(square(3)))
Gather all supplied arguments using the rest operator ...
and return a unary function that uses Array.prototype.reduce()
to run the value through the series of functions before returning the final value.
const pipe = (...fns) => x => fns.reduce((v, fn) => fn(v), x)
The virtual DOM (VDOM) is a representation of the real DOM in the form of plain JavaScript objects. These objects have properties to describe the real DOM nodes they represent: the node name, its attributes, and child nodes.
<div class="counter">
<h1>0</h1>
<button>-</button>
<button>+</button>
</div>
The above markup's virtual DOM representation might look like this:
{
nodeName: "div",
attributes: { class: "counter" },
children: [
{
nodeName: "h1",
attributes: {},
children: [0]
},
{
nodeName: "button",
attributes: {},
children: ["-"]
},
{
nodeName: "button",
attributes: {},
children: ["+"]
}
]
}
The library/framework uses the virtual DOM as a means to improve performance. When the state of an application changes, the real DOM needs to be updated to reflect it. However, changing real DOM nodes is costly compared to recalculating the virtual DOM. The previous virtual DOM can be compared to the new virtual DOM very quickly in comparison.
Once the changes between the old VDOM and new VDOM have been calculated by the diffing engine of the framework, the real DOM can be patched efficiently in the least time possible to match the new state of the application.
The event loop handles all async callbacks. Callbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received.
Browsers have a cache to temporarily store files on websites so they don't need to be re-downloaded again when switching between pages or reloading the same page. The server is set up to send headers that tell the browser to store the file for a given amount of time. This greatly increases website speed and preserves bandwidth.
However, it can cause problems when the website has been changed by developers because the user's cache still references old files. This can either leave them with old functionality or break a website if the cached CSS and JavaScript files are referencing elements that no longer exist, have moved or have been renamed.
Cache busting is the process of forcing the browser to download the new files. This is done by naming the file something different to the old file.
A common technique to force the browser to re-download the file is to append a query string to the end of the file.
src="js/script.js"
=> src="js/script.js?v=2"
The browser considers it a different file but prevents the need to change the file name.
<header>
elements? What about <footer>
elements?Yes to both. The W3 documents state that the tags represent the header(<header>
) and footer(<footer>
) areas of their nearest ancestor "section". So not only can the page <body>
contain a header and a footer, but so can every <article>
and <section>
element.
<header>
, <article>
,<section>
, <footer>
<header>
is used to contain introductory and navigational information about a section of the page. This can include the section heading, the author’s name, time and date of publication, table of contents, or other navigational information.
<article>
is meant to house a self-contained composition that can logically be independently recreated outside of the page without losing it’s meaining. Individual blog posts or news stories are good examples.
<section>
is a flexible container for holding content that shares a common informational theme or purpose.
<footer>
is used to hold information that should appear at the end of a section of content and contain additional information about the section. Author’s name, copyright information, and related links are typical examples of such content.
<form>
and <table>
alt
attribute on images?The alt
attribute provides alternative information for an image if a user cannot view it. If the image is for decorative purposes only, the alt
attribute should be empty. On the other hand, if image contains information the alt
attribute should describe image.
alt
tagdefer
and async
attributes on a <script>
tag?If neither attribute is present, the script is downloaded and executed synchronously, and will halt parsing of the document until it has finished executing (default behavior). Scripts are downloaded and executed in the order they are encountered.
The defer
attribute downloads the script while the document is still parsing but waits until the document has finished parsing before executing it, equivalent to executing inside a DOMContentLoaded
event listener. defer
scripts will execute in order.
The async
attribute downloads the script during parsing the document but will pause the parser to execute the script before it has fully finished parsing. async
scripts will not necessarily execute in order.
Note: both attributes must only be used if the script has a src
attribute (i.e. not an inline script).
<script src="myscript.js"></script>
<script src="myscript.js" defer></script>
<script src="myscript.js" async></script>
defer
script in the <head>
allows the browser to download the script while the page is still parsing, and is therefore a better option than placing the script before the end of the body.defer
.async
.defer
if the DOM must be ready and the contents are not placed within a DOMContentLoaded
listener.The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.
<head>
with a defer
attribute, or inside a DOMContentLoaded
event listener. Scripts that manipulate DOM nodes should be run after the DOM has been constructed to avoid errors.document.getElementById()
and document.querySelector()
are common functions for selecting DOM nodes.innerHTML
property to a new value runs the string through the HTML parser, offering an easy way to append dynamic HTML content to a node.HTML specifications such as HTML5
define a set of rules that a document must adhere to in order to be “valid” according to that specification. In addition, a specification provides instructions on how a browser must interpret and render such a document.
A browser is said to “support” a specification if it handles valid documents according to the rules of the specification. As of yet, no browser supports all aspects of the HTML5
specification (although all of the major browser support most of it), and as a result, it is necessary for the developer to confirm whether the aspect they are making use of will be supported by all of the browsers on which they hope to display their content. This is why cross-browser support continues to be a headache for developers, despite the improved specificiations.
HTML5
defines some rules to follow for an invalid HTML5
document (i.e., one that contains syntactical errors)Some of the key differences are:
<DOCTYPE>
checked="checked"
instead of checked
)rel="noopener"
attribute used?The rel="noopener"
is an attribute used in <a>
elements (hyperlinks). It prevents pages from having a window.opener
property, which would otherwise point to the page from where the link was opened and would allow the page opened from the hyperlink to manipulate the page where the hyperlink is.
rel="noopener"
is applied to hyperlinks.rel="noopener"
prevents opened links from manipulating the source page.localStorage
and sessionStorage
.With HTML5, web pages can store data locally within the user’s browser. The data is stored in name/value pairs, and a web page can only access data stored by itself.
Differences between localStorage
and sessionStorage
regarding lifetime:
localStorage
is permanent: it does not expire and remains stored on the user’s computer until a web app deletes it or the user asks the browser to delete it.sessionStorage
has the same lifetime as the top-level window or browser tab in which the data got stored. When the tab is permanently closed, any data stored through sessionStorage
is deleted.Differences between localStorage
and sessionStorage
regarding storage scope:
Both forms of storage are scoped to the document origin so that documents with different origins will never share the stored objects.
sessionStorage
is also scoped on a per-window basis. Two browser tabs with documents from the same origin have separate sessionStorage
data.localStorage
, the same scripts from the same origin can't access each other's sessionStorage
when opened in different tabs.The BEM methodology is a naming convention for CSS classes in order to keep CSS more maintainable by defining namespaces to solve scoping issues. BEM stands for Block Element Modifier which is an explanation for its structure. A Block is a standalone component that is reusable across projects and acts as a "namespace" for sub components (Elements). Modifiers are used as flags when a Block or Element is in a certain state or is different in structure or style.
/* block component */
.block {
}
/* element */
.block__element {
}
/* modifier */
.block__element--modifier {
}
Here is an example with the class names on markup:
<nav class="navbar">
<a href="/" class="navbar__link navbar__link--active"></a>
<a href="/" class="navbar__link"></a>
<a href="/" class="navbar__link"></a>
</nav>
In this case, navbar
is the Block, navbar__link
is an Element that makes no sense outside of the navbar
component, and navbar__link--active
is a Modifier that indicates a different state for the navbar__link
Element.
Since Modifiers are verbose, many opt to use is-*
flags instead as modifiers.
<a href="/" class="navbar__link is-active"></a>
These must be chained to the Element and never alone however, or there will be scope issues.
.navbar__link.is-active {
}
CSS preprocessors add useful functionality that native CSS does not have, and generally make CSS neater and more maintainable by enabling DRY (Don't Repeat Yourself) principles. Their terse syntax for nested selectors cuts down on repeated code. They provide variables for consistent theming (however, CSS variables have largely replaced this functionality) and additional tools like color functions (lighten
, darken
, transparentize
, etc), mixins, and loops that make CSS more like a real programming language and gives the developer more power to generate complex CSS.
col-{n} / 12
ratio of the container.<div class="row">
<div class="col-2"></div>
<div class="col-7"></div>
<div class="col-3"></div>
</div>
Set the .row
parent to display: flex;
and use the flex
shorthand property to give the column classes a flex-grow
value that corresponds to its ratio value.
.row {
display: flex;
}
.col-2 {
flex: 2;
}
.col-7 {
flex: 7;
}
.col-3 {
flex: 3;
}
@media
properties?all
, which applies to all media type devicesprint
, which only applies to printersscreen
, which only applies to screens (desktops, tablets, mobile etc.)speech
, which only applies to screenreadersCSS sprites combine multiple images into one image, limiting the number of HTTP requests a browser has to make, thus improving load times. Even under the new HTTP/2 protocol, this remains true.
Under HTTP/1.1, at most one request is allowed per TCP connection. With HTTP/1.1, modern browsers open multiple parallel connections (between 2 to 8) but it is limited. With HTTP/2, all requests between the browser and the server are multiplexed on a single TCP connection. This means the cost of opening and closing multiple connections is mitigated, resulting in a better usage of the TCP connection and limits the impact of latency between the client and server. It could then become possible to load tens of images in parallel on the same TCP connection.
However, according to benchmark results, although HTTP/2 offers 50% improvement over HTTP/1.1, in most cases the sprite set is still faster to load than individual images.
To utilize a spritesheet in CSS, one would use certain properties, such as background-image
, background-position
and background-size
to ultimately alter the background
of an element.
background-image
, background-position
and background-size
can be used to utilize a spritesheet.Assuming the browser has already determined the set of rules for an element, each rule is assigned a matrix of values, which correspond to the following from highest to lowest specificity:
When two selectors are compared, the comparison is made on a per-column basis (e.g. an id selector will always be higher than any amount of class selectors, as ids have higher specificity than classes). In cases of equal specificity between multiple rules, the rules that comes last in the page's style sheet is deemed more specific and therefore applied to the element.
A focus ring is a visible outline given to focusable elements such as buttons and anchor tags. It varies depending on the vendor, but generally it appears as a blue outline around the element to indicate it is currently focused.
In the past, many people specified outline: 0;
on the element to remove the focus ring. However, this causes accessibility issues for keyboard users because the focus state may not be clear. When not specified though, it causes an unappealing blue ring to appear around an element.
In recent times, frameworks like Bootstrap have opted to use a more appealing box-shadow
outline to replace the default focus ring. However, this is still not ideal for mouse users.
The best solution is an upcoming pseudo-selector :focus-visible
which can be polyfilled today with JavaScript. It will only show a focus ring if the user is using a keyboard and leave it hidden for mouse users. This keeps both aesthetics for mouse use and accessibility for keyboard use.
fs.readFile(filePath, function(err, data) {
if (err) {
// handle the error, the return is important here
// so execution stops here
return console.log(err)
}
// use the data object
console.log(data)
})
Advantages include:
As you can see from below example, the callback is called with null as its first argument if there is no error. However, if there is an error, you create an Error object, which then becomes the callback's only parameter. The callback function allows a user to easily know whether or not an error occurred.
This practice is also called the Node.js error convention, and this kind of callback implementations are called error-first callbacks.
var isTrue = function(value, callback) {
if (value === true) {
callback(null, "Value was true.")
} else {
callback(new Error("Value is not true!"))
}
}
var callback = function(error, retval) {
if (error) {
console.log(error)
return
}
console.log(retval)
}
isTrue(false, callback)
isTrue(true, callback)
/*
{ stack: [Getter/Setter],
arguments: undefined,
type: undefined,
message: 'Value is not true!' }
Value was true.
*/
REST (REpresentational State Transfer) is a software design pattern for network architecture. A RESTful web application exposes data in the form of information about its resources.
Generally, this concept is used in web applications to manage state. With most applications, there is a common theme of reading, creating, updating, and destroying data. Data is modularized into separate tables like posts
, users
, comments
, and a RESTful API exposes access to this data with:
Here is an example of the URL and HTTP method with a posts
resource:
/posts/
=> GET/posts/new
=> POST/posts/:id
=> PUT/posts/:id
=> DELETEgetData(function(a) {
getMoreData(a, function(b) {
getMoreData(b, function(c) {
getMoreData(c, function(d) {
getMoreData(d, function(e) {
// ...
})
})
})
})
})
Refactoring the functions to return promises and using async/await
is usually the best option. Instead of supplying the functions with callbacks that cause deep nesting, they return a promise that can be await
ed and will be resolved once the data has arrived, allowing the next line of code to be evaluated in a sync-like fashion.
The above code can be restructured like so:
async function asyncAwaitVersion() {
const a = await getData()
const b = await getMoreData(a)
const c = await getMoreData(b)
const d = await getMoreData(c)
const e = await getMoreData(e)
// ...
}
There are lots of ways to solve the issue of callback hells:
The event loop handles all async callbacks. Callbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received.
XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application. This is often achieved when the application does not validate user input and freely injects dynamic HTML content.
For example, a comment system will be at risk if it does not validate or escape user input. If the comment contains unescaped HTML, the comment can inject a <script>
tag into the website that other users will execute against their knowledge.
textContent
instead of innerHTML
prevents the browser from running the string through the HTML parser which would execute scripts in it.MIT. Copyright (c) Stefan Feješ.