⏱ 0:01est. 19 min
Misc
// https://github.com/yining1023/algorithm-questions
// https://app.codility.com/programmers/lessons/1-iterations/
// https://www.twilio.com/blog/5-ways-to-make-http-requests-in-node-js-using-async-await
const fetch = require('node-fetch');
(async () => {
try {
const response = await fetch('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY')
const json = await response.json()
console.log(json.url);
console.log(json.explanation);
} catch (error) {
console.log(error.response.body);
}
})();
const request = require('request')
// https://stackoverflow.com/questions/38428027/why-await-is-not-working-for-node-request-module
function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode == 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
// Usage:
async function main() {
let res = await doRequest(url);
console.log(res);
}
main();
// https://github.com/h5bp/Front-end-Developer-Interview-Questions/blob/master/src/questions/javascript-questions.md
// Javascript
// Explain event delegation.
// - Event delegation is one of the most potent events handling patterns. It allows users to append a single event listener to a parent element that adds it to all of its present and future descendants that match a selector.
// 1. Add a handler on a container
// 2. Add the event.target source element on the handler
// 3. Handle the event
// Explain how this works in JavaScript.
// Can you give an example of one of the ways that working with this has changed in ES6?
// Explain how prototypal inheritance works.
// What's the difference between a variable that is: null, undefined or undeclared?
// How would you go about checking for any of these states?
// What is a closure, and how/why would you use one?
// - A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)
// In other words, a closure gives you access to an outer function’s scope from an inner function.
// In JavaScript, closures are created every time a function is created, at function creation time.
// To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.
// What language constructions do you use for iterating over object properties and array items?
// Can you describe the main difference between the Array.forEach() loop and Array.map() methods and why you would pick one versus the other?
// - forEach() — executes a provided function once for each array element.
// - map() — creates a new array with the results of calling a provided function on every element in the calling array.
// What's a typical use case for anonymous functions?
// What's the difference between host objects and native objects?
// - Host Objects are objects supplied by a certain environment. They are not always the same because each environment differs and contains host objects that accommodates execution of ECMAScript. Example, browser environment supplies objects such as window. While a node.js/server environment supplies objects such as NodeList.
// - Native Objects or Built-in Objects are standard built-in objects provided by Javascript. Native objects is sometimes referred to as ‘Global Objects’ since they are objects Javascript has provided natively available for use.
// - https://medium.com/@rlynjb/js-interview-question-what-s-the-difference-between-host-objects-and-native-objects-b395f7c5fbf1#:~:text=From%20what%20I%20understand%2C%20objects,supplied%20by%20a%20certain%20environment.&text=Native%20Objects%20or%20Built%2Din,in%20objects%20provided%20by%20Javascript.
// Explain the difference between: function Person(){}, var person = Person(), and var person = new Person()?
// Explain the differences on the usage of foo between function foo() {} and var foo = function() {}
// Can you explain what Function.call and Function.apply do? What's the notable difference between the two?
// - call and apply are very similar—they invoke a function with a specified this context, and optional arguments. The only difference between call and apply is that call requires the arguments to be passed in one-by-one, and apply takes the arguments as an array.
// https://www.taniarascia.com/this-bind-call-apply-javascript
// Explain Function.prototype.bind.
// What's the difference between feature detection, feature inference, and using the UA string?
// Explain "hoisting".
// Describe event bubbling.
// Describe event capturing.
// What's the difference between an "attribute" and a "property"?
// -
// - https://javascript.info/dom-attributes-and-properties
// What are the pros and cons of extending built-in JavaScript objects?
// What is the difference between == and ===?
// Explain the same-origin policy with regards to JavaScript.
// Why is it called a Ternary operator, what does the word "Ternary" indicate?
// What is strict mode? What are some of the advantages/disadvantages of using it?
// What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?
// What tools and techniques do you use debugging JavaScript code?
// Explain the difference between mutable and immutable objects.
// What is an example of an immutable object in JavaScript?
// What are the pros and cons of immutability?
// How can you achieve immutability in your own code?
// Explain the difference between synchronous and asynchronous functions.
// What is event loop?
// What is the difference between call stack and task queue?
// What are the differences between variables created using let, var or const?
// What are the differences between ES6 class and ES5 function constructors?
// Can you offer a use case for the new arrow => function syntax? How does this new syntax differ from other functions?
// What advantage is there for using the arrow syntax for a method in a constructor?
// What is the definition of a higher-order function?
// Can you give an example for destructuring an object or an array?
// Can you give an example of generating a string with ES6 Template Literals?
// Can you give an example of a curry function and why this syntax offers an advantage?
// What are the benefits of using spread syntax and how is it different from rest syntax?
// How can you share code between files?
// Why you might want to create static class members?
// What is the difference between while and do-while loops in JavaScript?
// What is a promise? Where and how would you use promise?
// https://glider.ai/resources/interview-questions/software-engineering/front-end-web-developer-interview-questions
// Which Javascript engines are you familiar with?
// -v8
// Elaborate event loop?
// How are the objects passed- by reference or by value?
// What is a closure?
// Explain Function.prototype.bind.
// How do you organize your Javascript code?
// Do you have an idea that you want to try out quickly? Mention the tools you would use to prototype it.
// What is the main difference between a .map() loop and a forEach loop?
// What is “use strict”;? What are the pros and cons of using this?
// Web
// Which HTTP status code classes are used to designate client error, server error, and success, respectively?
// When do Load and DOMContentLoaded events get fired?
// Explain event propagation (bubbling phase) in your own words. Do you know any other phase in the DOM Event flow?
// Why is HTML5 History API essential for all single page applications?
// Explain the same-origin policy as a part of the web browser security model.
// Name some storage options that modern browsers provide?
// Why do you think Page Visibility API is useful?
// Mention some steps that constitute the Critical Rendering Path for web browsers.
// Give the basic overview of the Push web technologies that are available today?
// HTML/CSS
// Explain why you would use "instead of" ?
// What is doctype for?
// Explain progressive rendering.
// Mention some new features in HTML5.
// What is the difference between a sessionStorage, localStorage and a cookie?
// What will you consider while designing a multilingual site?
function Person() {
return 2;
}
var p = Person();
var p1 = new Person();
console.log(p);
console.log(p1);
function duplicate(arr) {
return [...arr, ...arr]
}
console.log(duplicate([1,2,3,4,5])); // [1,2,3,4,5,1,2,3,4,5]
// https://stackoverflow.com/questions/30048388/javascript-recursive-array-flattening
function flatten(array, result) {
if (array.length === 0) {
return result
}
var head = array[0]
var rest = array.slice(1)
if (Array.isArray(head)) {
return flatten(head.concat(rest), result)
}
result.push(head)
return flatten(rest, result)
}
console.log(flatten([], []))
console.log(flatten([1], []))
console.log(flatten([1,2,3], []))
console.log(flatten([1,2,[3,4]], []))
console.log(flatten([1,2,[3,[4,5,6]]], []))
console.log(flatten([[1,2,3],[4,5,6]], []))
console.log(flatten([[1,2,3],[[4,5],6,7]], []))
console.log(flatten([[1,2,3],[[4,5],6,[7,8,9]]], []))
// ------------------------------------
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
// https://javascript.info/recursion
alert( pow(2, 3) ); // 8
// ----------------------------------------
//Q Now let’s say we want a function to get the sum of all salaries. How can we do that?
// https://javascript.info/recursion
let company = { // the same object, compressed for brevity
sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }],
development: {
sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
internals: [{name: 'Jack', salary: 1300}]
}
};
return department.reduce((prev, current) => prev+current.salary, 0)
// The function to do the job
function sumSalaries(department) {
if (Array.isArray(department)) { // case (1)
return department.reduce((prev, current) => prev + current.salary, 0); // sum the array
} else { // case (2)
let sum = 0;
for (let subdep of Object.values(department)) {
sum += sumSalaries(subdep); // recursively call for subdepartments, sum the results
}
return sum;
}
}
alert(sumSalaries(company)); // 7700
// -----
function sumSalaries(department) {
let sum =0;
for (let subdep of Object.values(department)) {
sum += subdep.reduce((prev, curr) => prev+curr.salary, 0)
}
return sum;
}
sumSalaries({ sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 1600 }], sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }])
// --------
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#:~:text=A%20closure%20is%20the%20combination,state%20(the%20lexical%20environment).&text=In%20JavaScript%2C%20closures%20are%20created,created%2C%20at%20function%20creation%20time.
// A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
// https://javascript.info/recursion#recursive-structures
function sumTo(n) {
if (n == 1) return 1;
return n + sumTo(n - 1);
}
alert( sumTo(100) );
function factorial(n) {
return n ? n * factorial(n - 1) : 1;
}
alert( factorial(5) ); // 120
function fib(n) {
return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
alert( fib(3) ); // 2
alert( fib(7) ); // 13
// fib(77); // will be extremely slow!
// ----
function fib(n) {
let a = 1;
let b = 1;
for (let i = 3; i <= n; i++) {
let c = a + b;
a = b;
b = c;
}
return b;
}
alert( fib(3) ); // 2
alert( fib(7) ); // 13
alert( fib(77) ); // 5527939700884757
// ----
function sumAll(...args) { // args is the name for the array
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
alert( sumAll(1) ); // 1
alert( sumAll(1, 2) ); // 3
alert( sumAll(1, 2, 3) ); // 6
// ------
function showName(firstName, lastName, ...titles) {
alert( firstName + ' ' + lastName ); // Julius Caesar
// the rest go into titles array
// i.e. titles = ["Consul", "Imperator"]
alert( titles[0] ); // Consul
alert( titles[1] ); // Imperator
alert( titles.length ); // 2
}
showName("Julius", "Caesar", "Consul", "Imperator");
// https://javascript.info/closure