Questions - JavaScript

Record some JavaScript questions.

Explain event delegation

Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The listener will fire whenever the event is triggered on the descendant elements due to event bubbling up the DOM. The benefits of this technique are:

  • Memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant.
  • There is no need to unbind the handler from elements that are removed and to bind the event for new elements.
1
2
3
4
5
6
7
<ul id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
......
<li>item n</li>
</ul>
1
2
3
4
5
6
7
document.getElementById('list').addEventListener('click', function (e) {
var event = e || window.event;
var target = event.target || event.srcElement;
if (target.nodeName.toLocaleLowerCase === 'li') {
console.log('the content is: ', target.innerHTML);
}
});

Explain how this works in JavaScript

  • If the new keyword is used when calling the function, this inside the function is a brand new object.

    1
    2
    3
    4
    5
    function showThis () {
    console.log(this)
    }
    showThis() // window
    new showThis() // showThis
  • If apply, call, or bind are used to call/create a function, this inside the function is the object that is passed in as the argument.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    var a = {
    name : "Demo",

    func1: function () {
    console.log(this.name)
    },

    func2: function () {
    setTimeout( function () {
    this.func1()
    }.apply(a),100);
    }

    };

    a.func2() // Demo
  • If a function is called as a method, such as obj.method() — this is the object that the function is a property of.

    1
    2
    3
    4
    5
    6
    7
    8
    var name = "windowsName";
    var a = {
    name: "Demo",
    fn : function () {
    console.log(this.name); // Demo
    }
    }
    a.fn();
  • If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, this is the global object. In a browser, it is the window object. If in strict mode (‘use strict’), this will be undefined instead of the global object.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var name = "windowsName";

    function fn() {
    var name = 'Demo';
    innerFunction();
    function innerFunction() {
    console.log(this.name); // windowsName
    }
    }

    fn()
  • If multiple of the above rules apply, the rule that is higher wins and will set the this value.

  • If the function is an ES2015 arrow function, it ignores all the rules above and receives the this value of its surrounding scope at the time it is created.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var name = "windowsName";

    var a = {
    name : "Demo",

    func1: function () {
    console.log(this.name)
    },

    func2: function () {
    setTimeout( () => {
    this.func1()
    },100);
    }

    };

    a.func2() // Demo

    One obvious benefit of arrow functions is to simplify the syntax needed to create functions, without a need for the function keyword. The this within arrow functions is also bound to the enclosing scope which is different compared to regular functions where the this is determined by the object calling it. Lexically-scoped this is useful when invoking callbacks, especially in React components.

What advantage is there for using the arrow syntax for a method in a constructor?

The value of this gets set at the time of the function creation and can’t change after that. So, when the constructor is used to create a new object, this will always refer to that object. For example, let’s say we have a Person constructor that takes a first name as an argument has two methods to console.log that name, one as a regular function and one as an arrow function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const Person = function(firstName) {
this.firstName = firstName;
this.sayName1 = function() { console.log(this.firstName); };
this.sayName2 = () => { console.log(this.firstName); };
};

const john = new Person('John');
const dave = new Person('Dave');

john.sayName1(); // John
john.sayName2(); // John

// The regular function can have its 'this' value changed, but the arrow function cannot
john.sayName1.call(dave); // Dave (because "this" is now the dave object)
john.sayName2.call(dave); // John

john.sayName1.apply(dave); // Dave (because 'this' is now the dave object)
john.sayName2.apply(dave); // John

john.sayName1.bind(dave)(); // Dave (because 'this' is now the dave object)
john.sayName2.bind(dave)(); // John

var sayNameFromWindow1 = john.sayName1;
sayNameFromWindow1(); // undefined (because 'this' is now the window object)

var sayNameFromWindow2 = john.sayName2;
sayNameFromWindow2(); // John

The main takeaway here is that this can be changed for a normal function, but the context always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn’t have to worry about the context changes.
This can be particularly helpful in React class components. If you define a class method for something such as a click handler using a normal function, and then you pass that click handler down into a child component as a prop, you will need to also bind this in the constructor of the parent component. If you instead use an arrow function, there is no need to also bind “this”, as the method will automatically get its “this” value from its enclosing lexical context.

What’s the difference between .call and .apply?

Both .call and .apply are used to invoke functions and the first parameter will be used as the value of this within the function. However, .call takes in comma-separated arguments as the next arguments while .apply takes in an array of arguments as the next argument. An easy way to remember this is C for call and comma-separated and A for apply and an array of arguments.

1
2
3
4
5
function add(a, b) {
return a + b;
}
console.log(add.call(null, 1, 2)); // 3
console.log(add.apply(null, [1, 2])); // 3

Explain how prototypal inheritance works

All JavaScript objects have a prototype property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object’s prototype, and the prototype’s prototype and so on, until it finds the property defined on one of the prototypes or until it reaches the end of the prototype chain. This behavior simulates classical inheritance, but it is really more of delegation than inheritance.
Example of Prototypal Inheritance
We already have a build-in Object.create, but if you were to provide a polyfill for it, that might look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (typeof Object.create !== 'function') {
Object.create = function (parent) {
function Tmp() {}
Tmp.prototype = parent;
return new Tmp();
};
}
const Parent = function() {
this.name = "Parent";
}
Parent.prototype.greet = function() { console.log("hello from Parent"); }
const child = Object.create(Parent.prototype);
child.cry = function() {
console.log("waaaaaahhhh!");
}
child.cry();
// Outputs: waaaaaahhhh!
child.greet();
// Outputs: hello from Parent

Things to note are:
.greet is not defined on the child, so the engine goes up the prototype chain and finds .greet off the inherited from Parent.
We need to call Object.create in one of following ways for the prototype methods to be inherited:

  • Object.create(Parent.prototype);
  • Object.create(new Parent(null));
  • Object.create(objLiteral);
    Currently, child.constructor is pointing to the Parent:
1
2
3
4
5
6
// child.constructor
ƒ () {
this.name = "Parent";
}
// child.constructor.name
// "Parent"

If we’d like to correct this, one option would be to do:

1
2
3
4
5
6
7
8
9
10
11
12
13
function Child() {
Parent.call(this);
this.name = 'child';
}
Child.prototype = Parent.prototype;
Child.prototype.constructor = Child;
const c = new Child();
c.cry();
// Outputs: waaaaaahhhh!
c.greet();
// Outputs: hello from Parent
c.constructor.name;
// Outputs: "Child"

Explain the Prototype Design Pattern

The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype - or sample - object. The Prototype pattern is also referred to as the Properties pattern.
An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.
Classical languages rarely use the Prototype pattern, but JavaScript being a prototypal language uses this pattern in the construction of new objects and their prototypes.

JavaScript is a object-based language.

Prototype

1
2
3
4
5
6
7
8
9
10
11
12
function Cat(name,color) {
this.name = name;
this.color = color;
}
 Cat.prototype.type = "Cats";
 Cat.prototype.eat = function(){alert("eat mouse")};

var cat1 = new Cat("One","yellow");
var cat2 = new Cat("Two","black");
 alert(cat1.type); // Cats
 cat1.eat(); // eat mouse
alert(cat1.eat == cat2.eat); //true

constructor inheritance

1
2
3
function Animal(){
  this.species = "Animals";
 }
  • bind

    1
    2
    3
    4
    5
    6
    7
    function Cat(name,color){
    Animal.apply(this, arguments);
    this.name = name;
       this.color = color;
     }
     var cat1 = new Cat("One","yellow");
     alert(cat1.species); // Animals
  • prototype

    1
    2
    3
    4
    Cat.prototype = new Animal();
    Cat.prototype.constructor = Cat;
    var cat1 = new Cat("One","yellow");
    alert(cat1.species); // Animals
  • direct inherit prototype(save memory but change Animal.prototype.constructor)

    1
    2
    3
    4
    5
    6
    7
    8
    function Animal(){ }
    Animal.prototype.species = "Animals";

    Cat.prototype = Animal.prototype;
    Cat.prototype.constructor = Cat;
    var cat1 = new Cat("One","yellow");
    alert(cat1.species); // Animals
    alert(Animal.prototype.constructor); // Cat
  • use empty object as agent

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    var F = function(){};
    F.prototype = Animal.prototype;
    Cat.prototype = new F();
    Cat.prototype.constructor = Cat;

    function extend(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
    }
    extend(Cat,Animal);
    var cat1 = new Cat("One","yellow");
    alert(cat1.species); // Animals
  • copy

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function Animal(){}
    Animal.prototype.species = "Animals";

    function extend2(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
    c[i] = p[i];
    }
    c.uber = p;
    }

    extend2(Cat, Animal);
    var cat1 = new Cat("One","yellow");
    alert(cat1.species); // Animals

none constructor inheritance

1
2
3
4
5
6
var Chinese = {
nation:'China'
};
var Doctor ={
career:'Doctor'
}
  • object() prototype chain

    1
    2
    3
    4
    5
    6
    7
    8
    function object(o) {
    function F() {}
    F.prototype = o;
    return new F();
    }
    var Doctor = object(Chinese);
    Doctor.career = 'Doctor';
    alert(Doctor.nation); //China
  • shallow copy (parent object can be changed)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    function extendCopy(p) {
    var c = {};
    for (var i in p) {
    c[i] = p[i];
    }
    c.uber = p;
    return c;
    }
    var Doctor = extendCopy(Chinese);
    Doctor.career = 'Doctor';
    alert(Doctor.nation); // China

    Chinese.birthPlaces = ['Beijing','Shanghai','HongKong'];
    var Doctor = extendCopy(Chinese);
    Doctor.birthPlaces.push('Shenzhen');
    alert(Doctor.birthPlaces); //Beijing, Shanghai, HongKong, Shenzhen
    alert(Chinese.birthPlaces); //Beijing, Shanghai, HongKong, Shenzhen
  • deep copy

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    function deepCopy(p, c) {
    var c = c || {};
    for (var i in p) {
    if (typeof p[i] === 'object') {
    c[i] = (p[i].constructor === Array) ? [] : {};
    deepCopy(p[i], c[i]);
    } else {
    c[i] = p[i];
    }
    }
    return c;
    }
    var Doctor = deepCopy(Chinese);
    Chinese.birthPlaces = ['Beijing','Shanghai','HongKong'];
    Doctor.birthPlaces.push('Shenzhen');
    alert(Doctor.birthPlaces); //Beijing, Shanghai, HongKong, Shenzhen
    alert(Chinese.birthPlaces); //Beijing, Shanghai, HongKong

What are the differences between ES6 class and ES5 function constructors?

1
2
3
4
// ES5 Function Constructor
function Person(name) {
this.name = name;
}
1
2
3
4
5
6
// ES6 Class
class Person {
constructor(name) {
this.name = name;
}
}

For simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

1
2
3
4
5
6
7
8
9
10
// ES5 Function Constructor
function Student(name, studentId) {
// Call constructor of superclass to initialize superclass-derived members.
Person.call(this, name);

// Initialize subclass's own members.
this.studentId = studentId;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
1
2
3
4
5
6
7
// ES6 Class
class Student extends Person {
constructor(name, studentId) {
super(name);
this.studentId = studentId;
}
}

What do you think of AMD vs CommonJS?

Both are ways to implement a module system, which was not natively present in JavaScript until ES2015 came along. CommonJS is synchronous while AMD (Asynchronous Module Definition) is asynchronous. CommonJS is designed with server-side development in mind while AMD, with its support for asynchronous loading of modules, is more intended for browsers.

CommonJS

1
2
3
4
5
6
7
8
9
// math.js
var basicNum = 0;
function add(a, b) {
return a + b;
}
module.exports = {
add: add,
basicNum: basicNum
}
1
2
var math = require('./math');
math.add(2, 5);

AMD

1
2
3
4
5
6
define(['./a', './b'], function(a, b) { // require add at first
a.doSomething()
// 100 lines...
b.doSomething()
// ...
})

CMD (Common Module Definition) and sea.js

1
2
3
4
5
6
7
8
define(function(require, exports, module) {
var a = require('./a')
a.doSomething()
// 100 lines...
var b = require('./b') // require near the use
b.doSomething()
// ...
})
1
2
3
4
5
6
7
8
9
10
11
12
13
/** sea.js **/
// define math.js
define(function(require, exports, module) {
var $ = require('jquery.js');
var add = function(a,b){
return a+b;
}
exports.add = add;
});
// use module
seajs.use(['math.js'], function(math){
var sum = math.add(1+2);
});

ES6 Module

1
2
3
4
5
6
/** define math.js **/
var basicNum = 0;
var add = function (a, b) {
return a + b;
};
export { basicNum, add };
1
2
3
4
5
/** use module **/
import { basicNum, add } from './math';
function test(ele) {
ele.textContent = add(99 + basicNum);
}

default

1
2
3
4
5
6
7
8
// export default
export default { basicNum, add };

// import
import math from './math';
function test(ele) {
ele.textContent = math.add(99 + math.basicNum);
}

How can you share code between files?

This depends on the JavaScript environment.

  • On the client (browser environment), as long as the variables/functions are declared in the global scope (window), all scripts can refer to them. Alternatively, adopt the Asynchronous Module Definition (AMD) via RequireJS for a more modular approach.
  • On the server (Node.js), the common way has been to use CommonJS. Each file is treated as a module and it can export variables and functions by attaching them to the module.exports object.
  • ES2015 defines a module syntax which aims to replace both AMD and CommonJS. This will eventually be supported in both browser and Node environments.

What is IIFEs (Immediately Invoked Function Expressions)?

It executes immediately after it’s created:

1
2
3
4
(function IIFE(){
console.log( "Hello!" );
})();
// "Hello!"

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE are not visible outside its scope.

What’s a typical use case for anonymous functions?

They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

1
2
3
(function() {
// Some code here.
})();

As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.

1
2
3
setTimeout(function() {
console.log('Hello world!');
}, 1000);

What’s the difference between a variable that is: null, undefined or undeclared?

undeclared

Undeclared variables are created when you assign a value to an identifier that is not previously created using var, let or const. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a ReferenceError will be thrown when you try to assign to an undeclared variable. Avoid them at all cost!

1
2
3
4
5
function foo() {
x = 1; // Throws a ReferenceError in strict mode
}
foo();
console.log(x); // 1

undefined

A variable that is undefined is a variable that has been declared, but not assigned a value. It is of type undefined. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of undefined. To check for it, compare using the strict equality (===) operator or typeof which will give the ‘undefined’ string.

1
2
3
4
5
6
7
8
var foo;
console.log(foo); // undefined
console.log(foo === undefined); // true
console.log(typeof foo === 'undefined'); // true
console.log(foo == null); // true. Wrong, don't use this to check!
function bar() {}
var baz = bar();
console.log(baz); // undefined

null

A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned.

1
2
3
4
var foo = null;
console.log(foo === null); // true
console.log(typeof foo === 'object'); // true
console.log(foo == undefined); // true. Wrong, don't use this to check!

What is Scope in JavaScript?

In JavaScript, each function gets its own scope. Scope is basically a collection of variables as well as the rules for how those variables are accessed by name. Only code inside that function can access that function’s scoped variables.
A variable name has to be unique within the same scope. A scope can be nested inside another scope. If one scope is nested inside another, code inside the innermost scope can access variables from either scope.

What is a closure, and how/why would you use one?

A closure is the combination of a function and the lexical environment within which that function was declared. The word “lexical” refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Closures are functions that have access to the outer (enclosing) function’s variables—scope chain even after the outer function has returned.

A closure is a function defined inside another function (called parent function) and has access to the variable which is declared and defined in the parent function scope.
The closure has access to variable in three scopes:

  • Variable declared in his own scope
  • Variable declared in parent function scope
  • Variable declared in global namespace
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var globalVar = "abc";
// Parent self invoking function
(function outerFunction (outerArg) { // begin of scope outerFunction
// Variable declared in outerFunction function scope
var outerFuncVar = 'x';
// Closure self-invoking function
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y";
console.log(
"outerArg = " + outerArg + "\n" +
"outerFuncVar = " + outerFuncVar + "\n" +
"innerArg = " + innerArg + "\n" +
"innerFuncVar = " + innerFuncVar + "\n" +
"globalVar = " + globalVar);
// end of scope innerFunction
})(5); // Pass 5 as parameter
// end of scope outerFunction
})(7); // Pass 7 as parameter

innerFunction is closure which is defined inside outerFunction and has access to all variable which is declared and defined in outerFunction scope. In addition to this function defined inside function as closure has access to variable which is declared in global namespace.
Output of above code would be:

1
2
3
4
5
outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

Can you describe the main difference between a .forEach loop and a .map() loop?

forEach

Iterates through the elements in an array.Executes a callback for each element.Does not return a value.

1
2
3
4
5
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
// Do something with num and/or index.
});
// doubled = undefined

map

Iterates through the elements in an array.”Maps” each element to a new element by calling the function on each element, creating a new array as a result.

1
2
3
4
5
const a = [1, 2, 3];
const doubled = a.map(num => {
return num * 2;
});
// doubled = [2, 4, 6]

The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.

Difference between: function Person(){}, var person = Person(), and var person = new Person()?

  • Technically speaking, function Person(){} is just a normal function declaration. The convention is to use PascalCase for functions that are intended to be used as constructors.

  • var person = Person() invokes the Person as a function, and not as a constructor. Invoking as such is a common mistake if the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return undefined and that gets assigned to the variable intended as the instance.

  • var person = new Person() creates an instance of the Person object using the new operator, which inherits from Person.prototype. An alternative would be to use Object.create, such as: Object.create(Person.prototype).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function Person(name) {
    this.name = name;
    }

    var person = Person('John');
    console.log(person); // undefined
    console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined

    var person = new Person('John');
    console.log(person); // Person { name: "John" }
    console.log(person.name); // "john"

What’s the difference between feature detection, feature inference, and using the UA string?

Feature Detection

Feature detection involves working out whether a browser supports a certain block of code, and running different code depending on whether it does (or doesn’t), so that the browser can always provide a working experience rather crashing/erroring in some browsers. For example:

1
2
3
4
5
if ('geolocation' in navigator) {
// Can use navigator.geolocation
} else {
// Handle lack of feature
}

Feature Inference

Feature inference checks for a feature just like feature detection, but uses another function because it assumes it will also exist, e.g.:

1
2
3
if (document.getElementsByTagName) {
element = document.getElementById(id);
}

This is not really recommended. Feature detection is more foolproof.

UA String

This is a browser-reported string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. It can be accessed via navigator.userAgent. However, the string is tricky to parse and can be spoofed. For example, Chrome reports both as Chrome and Safari. So to detect Safari you have to check for the Safari string and the absence of the Chrome string. Avoid this method.

Explain Ajax

Ajax (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send data to and retrieve from a server asynchronously without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly substitute use JSON instead of XML, due to the advantages of JSON being native to JavaScript.
The XMLHttpRequest API is frequently used for the asynchronous communication or these days, the fetch API.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var request = new XMLHttpRequest();

request.onreadystatechange = function () {
if (request.readyState === 4) { // request ready
if (request.status === 200) {
// success get responseText
return request.responseText;
} else {
// fail get error code
return request.status;
}
} else {
// keep request...
}
}

// send request:
request.open('GET', '/api/xxx');
request.send();

Advantages

  • Better interactivity. New content from the server can be changed dynamically without the need to reload the entire page.
  • Reduce connections to the server since scripts and stylesheets only have to be requested once.
  • State can be maintained on a page. JavaScript variables and DOM state will persist because the main container page was not reloaded.

Disadvantages

  • Dynamic webpages are harder to bookmark.
  • Does not work if JavaScript has been disabled in the browser.
  • Some web crawlers do not execute JavaScript and would not see content that has been loaded by JavaScript.

Explain how JSONP works.

JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.
JSONP works by making a request to a cross-origin domain via a <script> tag and usually with a callback query parameter, for example:https://example.com?callback=printData. The server will then wrap the data within a function called printData and return it to the client.

1
2
3
4
5
6
7
8
9
10
<!-- https://mydomain.com -->
<script>
function printData(data) {
console.log(`My name is ${data.name}!`);
}
</script>
<script src="https://example.com?callback=printData"></script>

// File loaded from https://example.com?callback=printData
printData({ name: 'xxx' });

The client has to have the printData function in its global scope and the function will be executed by the client when the response from the cross-origin domain is received.
JSONP can be unsafe and has some security implications. As JSONP is really JavaScript, it can do everything else JavaScript can do, so you need to trust the provider of the JSONP data.

Explain “hoisting”.

Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the var keyword will have their declaration “moved” up to the top of the current scope, which we refer to as hoisting.
Note that the declaration is not actually moved - the JavaScript engine parses the declarations during compilation and becomes aware of declarations and their scopes.

1
2
3
4
// var declarations are hoisted.
console.log(foo); // undefined
var foo = 1;
console.log(foo); // 1
1
2
3
4
// let/const declarations are NOT hoisted.
console.log(bar); // ReferenceError: bar is not defined
let bar = 2;
console.log(bar); // 2

Function declarations have the body hoisted while the function expressions (written in the form of variable declarations) only has the variable declaration hoisted.

1
2
3
4
5
6
7
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
function foo() {
console.log('FOOOOO');
}
console.log(foo); // [Function: foo]
1
2
3
4
5
6
7
// Function Expression
console.log(bar); // undefined
bar(); // Uncaught TypeError: bar is not a function
var bar = function() {
console.log('BARRRR');
};
console.log(bar); // [Function: bar]

What are the differences between variables created using let, var or const?

Variables declared using the var keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. let and const are block scoped, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).

1
2
3
4
5
6
7
8
9
10
11
12
13
function foo() {
// All variables are accessible within functions.
var bar = 'bar';
let baz = 'baz';
const qux = 'qux';

console.log(bar); // bar
console.log(baz); // baz
console.log(qux); // qux
}
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined
1
2
3
4
5
6
7
8
9
10
if (true) {
var bar = 'bar';
let baz = 'baz';
const qux = 'qux';
}
// var declared variables are accessible anywhere in the function scope.
console.log(bar); // bar
// let and const defined variables are not accessible outside of the block they were defined in.
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined

var allows variables to be hoisted, meaning they can be referenced in code before they are declared. let and const will not allow this, instead throwing an error.

1
2
3
4
5
6
console.log(foo); // undefined
var foo = 'foo';
console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization
let baz = 'baz';
console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization
const bar = 'bar';

Redeclaring a variable with var will not throw an error, but ‘let’ and ‘const’ will.

1
2
3
4
5
var foo = 'foo';
var foo = 'bar';
console.log(foo); // "bar"
let baz = 'baz';
let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared

let and const differ in that let allows reassigning the variable’s value while const does not.

1
2
3
4
5
6
// This is fine.
let foo = 'foo';
foo = 'bar';
// This causes an exception.
const baz = 'baz';
baz = 'qux';

What’s the difference between an “attribute” and a “property”?

Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: <input type="text" value="Hello">.

1
2
3
const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello

But after you change the value of the text field by adding “World!” to it, this becomes:

1
2
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello World!

What is the difference between == and ===?

== is the abstract equality operator while === is the strict equality operator. The == operator will compare for equality after doing any necessary type conversions. The === operator will not do type conversion, so if two values are not the same type === will simply return false. When using ==, funky things can happen, such as:

1
2
3
4
5
6
1 == '1'; // true
1 == [1]; // true
1 == true; // true
0 == ''; // true
0 == '0'; // true
0 == false; // true

My advice is never to use the == operator, except for convenience when comparing against null or undefined, where a == null will return true if a is null or undefined.

1
2
3
var a = null;
console.log(a == null); // true
console.log(a == undefined); // true

What is “use strict”?

‘use strict’ is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.

Advantages

  • Makes assignments which would otherwise silently fail to throw an exception.
  • Makes it impossible to accidentally create global variables.
  • Makes attempts to delete undetectable properties throw (where before the attempt would simply have no effect).
  • Requires that function parameter names be unique.
  • this is undefined in the global context.
  • It catches some common coding bloopers, throwing exceptions.
  • It disables features that are confusing or poorly thought out.

Disadvantages:

  • Many missing features that some developers might be used to.
  • No more access to function.caller and function.arguments.
  • Concatenation of scripts written in different strict modes might cause issues.

Explain what a single page app is and how to make one SEO-friendly.

Traditionally, the browser receives HTML from the server and renders it. When the user navigates to another URL, a full-page refresh is required and the server sends fresh new HTML to the new page. This is called server-side rendering.
However, in modern SPAs, client-side rendering is used instead. The browser loads the initial page from the server, along with the scripts and stylesheets required for the whole app. When the user navigates to other pages, a page refresh is not triggered. The URL of the page is updated via the HTML5 History API. New data required for the new page, usually in JSON format, is retrieved by the browser via AJAX requests to the server. The SPA then dynamically updates the page with the data via JavaScript, which it has already downloaded in the initial page load. This model is similar to how native mobile apps work.

Advantages

  • The app feels more responsive and users do not see the flash between page navigation due to full-page refreshes.
  • Fewer HTTP requests are made to the server, as the same assets do not have to be downloaded again for each page load.
  • Clear separation of the concerns between the client and the server; you can easily build new clients for different platforms without having to modify the server code. You can also modify the technology stack on the client and server independently, as long as the API contract is not broken.

Disadvantages

  • Heavier initial page load due to the loading of framework, app code, and assets required for multiple pages.
  • There’s an additional step to be done on your server which is to configure it to route all requests to a single entry point and allow client-side routing to take over from there.
  • SPAs are reliant on JavaScript to render content, but not all search engines execute JavaScript during crawling, and they may see empty content on your page. This inadvertently hurts the Search Engine Optimization (SEO) of your app. However, most of the time, when you are building apps, SEO is not the most important factor, as not all the content needs to be indexable by search engines. To overcome this, you can either server-side render your app or use services such as Prerender to “render your javascript in a browser, save the static HTML, and return that to the crawlers”.

What are the pros and cons of using Promises instead of callbacks?

Pros

  • Avoid callback hell which can be unreadable.
  • Makes it easy to write sequential asynchronous code that is readable with .then().
  • Makes it easy to write parallel asynchronous code with Promise.all().
  • With promises, these scenarios which are present in callbacks-only coding, will not happen:
    • Call the callback too early
    • Call the callback too late (or never)
    • Call the callback too few or too many times
    • Fail to pass along any necessary environment/parameters
    • Swallow any errors/exceptions that may happen

Cons

  • Slightly more complex code (debatable).
  • In older browsers where ES2015 is not supported, you need to load a polyfill in order to use it.

Callback Hell

The asynchronous function requires callbacks as a return parameter. When multiple asynchronous functions are chained together then callback hell situation comes up.
How can you avoid callback hells?

  • break callbacks into independent functions
  • use Promises
  • use yield with Generators

What language constructions do you use for iterating over object properties and array items?

For objects

  • for-in loops

    1
    2
    3
    for (var property in obj) {
    console.log(property);
    }

    However, this will also iterate through its inherited properties, and you will add an obj.hasOwnProperty(property) check before using it.

  • Object.keys()

    1
    2
    3
    Object.keys(obj).forEach(
    function (property) { ... }
    )

    Object.keys() is a static method that will lists all enumerable properties of the object that you pass it.

  • Object.getOwnPropertyNames()

    1
    2
    3
    4
    Object.getOwnPropertyNames(obj).forEach(
    function (property) { ... }
    )
    Object.getOwnPropertyNames() is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it.

For arrays

  • for loops - for (let i = 0; i < arr.length; i++)
  • forEach - arr.forEach(function (el, index) { ... })
  • for-of loops - for (let elem of arr) { ... } ES6 introduces a new loop, the for-of loop, that allows you to loop over objects that conform to the iterable protocol such as String, Array, Map, Set, etc. The advantage of the for loop is that you can break from it, and the advantage of forEach() is that it is more concise than the for loop because you don’t need a counter variable. With the for-of loop, you get both the ability to break from a loop and a more concise syntax.
    Also, when using the for-of loop, if you need to access both the index and value of each array element, you can do so with the ES6 Array entries() method and destructuring:
    1
    2
    3
    4
    const arr = ['a', 'b', 'c'];
    for (let [index, elem] of arr.entries()) {
    console.log(index, ': ', elem);
    }

What is the definition of a higher-order function?

A higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, or returns a function as a result. Higher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is map, which takes an array and a function as arguments. map then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are forEach, filter, and reduce. A higher-order function doesn’t just need to be manipulating arrays as there are many use cases for returning a function from another function. Function.prototype.bind is one such example in JavaScript.

Map

Let say we have an array of names which we need to transform each string to uppercase.

1
const names = ['irish', 'daisy', 'anna'];

The original way will be as such:

1
2
3
4
5
6
7
8
const transformNamesToUppercase = function(names) {
const results = [];
for (let i = 0; i < names.length; i++) {
results.push(names[i].toUpperCase());
}
return results;
};
transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']

Use .map(transformerFn) makes the code shorter and more declarative.

1
2
3
4
const transformNamesToUppercase = function(names) {
return names.map(name => name.toUpperCase());
};
transformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']

Can you give an example for destructuring an object or an array?

Destructuring is an expression available in ES6 which enables a convenient way to extract values of Objects or Arrays and place them into distinct variables.

Array destructuring

1
2
3
4
5
6
// Variable assignment
const foo = ['one', 'two', 'three'];
const [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"
1
2
3
4
5
6
// Swapping variables
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Object destructuring

1
2
3
4
5
// Variable assignment
const o = { p: 42, q: true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true

What are the benefits of using spread syntax and how is it different from rest syntax?

ES6’s spread syntax is very useful when coding in a functional paradigm as we can easily create copies of arrays or objects without resorting to Object.create, slice, or a library function.

1
2
3
4
function putDookieInAnyArray(arr) {
return [...arr, 'dookie'];
}
const result = putDookieInAnyArray(['I', 'really', "don't", 'like']); // ["I", "really", "don't", "like", "dookie"]
1
2
3
4
5
const person = {
name: 'Todd',
age: 29,
};
const copyOfTodd = { ...person };

ES6’s rest syntax offers a shorthand for including an arbitrary number of arguments to be passed to a function. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments.

1
2
3
4
5
6
7
8
9
10
11
function addFiveToABunchOfNumbers(...numbers) {
return numbers.map(x => x + 5);
}
const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15]
const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4]
const { e, f, ...others } = {
e: 1,
f: 2,
g: 3,
h: 4,
}; // e: 1, f: 2, others: { g: 3, h: 4 }