Interview
function User(name) { this.name = name || "JsGeeks"; } var person = new User("xyz")["location"] = "USA"; console.log(person);
"USA", new User object with location property assigned as USA is initialized, but the assignment itself returns the rightmost value
deprecated lifecycle methods
(3) will methods componentWillMount(), componentWillReceiveProps(), componetWillUpdate(), with the exception of componentWillUnmount() which singlehandedly comprises the destruction section of the component, inherently requires to occur before the end of the component's life
how to empty an array
1) arrayList = [] 2) arrayList.length = 0 3) arrayList.splice(0, arrayList.length); 4) while(arrayList.length) { arrayList.pop(); }
var bar = true; console.log(bar + 0); console.log(bar + "xyz"); console.log(bar + true); console.log(bar + false);
1, "truexyz", 2, 1 Number + Number -> Addition Boolean + Number -> Addition Boolean + Boolean -> Addition Number + String -> Concatenation String + Boolean -> Concatenation String + String -> Concatenation
2way data binding vs 1way data flow
1way is deterministic, 2way can cause side effects making it harder to follow/understand, react is a good example of 1way, angular uses 2way
const x = 1; const output = (function() {delete x; return x+3;})(); what does console.log(output) output? what is x?
4, x is a global variable
var trees = ["xyz", "xxxx", "test", "ryan", "apple"]; delete trees[3]; console.log(trees.length);
5
const output = (function(x) {delete x; return x+3;})(5); what does console.log(output) output? what is x?
8, x is a local variable
concatenative inheritance
? object.assign(), mixins
functional inheritance
? uses functions to create closures for private state/encapsulation
React vs Angular
Angular approaches building an application by extending HTML markup and injecting various constructs (e.g. Directives, Controllers, Services) at runtime, as a result Angular is opinionated about the greater architecture of the application whereas React, by representing just the view in MVC, is flexible
Microservice cons
As you're building a new microservice architecture, you're likely to discover lots of cross-cutting concerns that you did not anticipate at design time. A monolithic app could establish shared magic helpers or middleware to handle such cross-cutting concerns without much effort. In a microservice architecture, you'll either need to incur the overhead of separate modules for each cross-cutting concern, or encapsulate cross-cutting concerns in another service layer that all traffic gets routed through. Eventually, even monolthic architectures tend to route traffic through an outer service layer for cross-cutting concerns, but with a monolithic architecture, it's possible to delay the cost of that work until the project is much more mature. Microservices are frequently deployed on their own virtual machines or containers, causing a proliferation of VM wrangling work. These tasks are frequently automated with container fleet management tools.
Principle of least astonishment
If a necessary feature has a high astonishment factor, it may be necessary to redesign the feature
hoisting
JavaScript's default behavior of moving declarations to the top
functional language examples
Lisp (one of first 1958), ML, Haskell, Erlang, Clojure, Elm F Sharp, OCaml
Microservice pros
Microservice architectures are typically better organized, since each microservice has a very specific job, and is not concerned with the jobs of other components. Decoupled services are also easier to recompose and reconfigure to serve the purposes of different apps (for example, serving both the web clients and public API). They can also have performance advantages depending on how they're organized because it's possible to isolate hot services and scale them independent of the rest of the app.
Monolithic cons
Monolithic app services tend to get tightly coupled and entangled as the application evolves, making it difficult to isolate services for purposes such as independent scaling or code maintainability. Monolithic architectures are also much harder to understand, because there may be dependencies, side-effects, and magic which are not obvious when you're looking at a particular service or controller.
Calculate the length of the associative array
Object.keys(associativeArray).length;
What is the drawback of declaring methods directly in JavaScript objects?
One of the drawback of declaring methods directly in JavaScript objects (example: model objects) is that they are very memory inefficient. When you do that, a new copy of the method is created for each instance of an object. SAME GOES FOR true private methods in javascript
var salary = "1000$"; (function () { console.log("Original salary was " + salary); var salary = "5000$"; console.log("My New Salary " + salary); })();
Original salary was undefined My New Salary 5000$
What is React?
React is an open-source JavaScript library created by Facebook for building complex, interactive UIs in web and mobile applications
two way data binding
UI fields are bound to model data dynamically such that when a UI field changes, the model data changes with it and vice-versa
programming paradigm
a classification of programming languages based on features
JSX
a dialect of Javascript that embeds raw HTML templates inside Javascript code, cannot be read by browser, requires transpiling by Babel and Webpack into traditional Javascript. More declarative and reduces code complexity
pure function
a function who return value is the same for the same arguments and has no side effects
declarative programming
a programming paradigm that expresses logic of computation without describing its control flow
functional programming
a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data
object oriented programming (OOP)
a programming paradigm that uses objects (which may contain data in the form of fields (attributes)) and code (in the form of procedures (methods))
procedural programming
a programming paradigm that uses procedures the contain a series of computational steps to be carried out
imperative programming
a programming paradigm that uses statements that change a program's state
prototypal inheritance
a style of oop in which behavior reuse (inheritance) is performed via a process of reusing existing objects via delegation that serve as prototypes, instances are typically instantiated by factory functions like Object.create() and can be composed from many different objects
What are Service Workers and when can you use them?
a technology that allows your web application to use cached resources first, and provide default experience offline, before getting more data from the network later. This principle is commonly known as Offline First. actively use promises. A Service Worker has to be installed,activated and then it can react on fetch, push and sync events.
undefined vs not defined (javascript)
a variable is not defined until it is declared: let x; it is then undefined until it is defined/assigned: x=0; a variable neither declared nor defined with throw a referenceerror
object composition
a way to combine simple objects or data types into more complex ones
function composition
an act or mechanism to combine simple functions to build more complicated ones
lambda
an anonymous function
expression vs statement
an expression calculates a combination of variables and functions and returns a value, a statement performs an action or command.
var bar = function() { return 12; }; typeof bar();
anonymous function
closure
any function which closes over the environment in which it was defined a function defined inside another function (called parent function) and has access to the variable which is declared and defined in parent function scope (has 3 scopes total when including global namespace)
monolithic architecture
app is written as one cohesive unit of code whose components are designed to work together, sharing the same memory space and resources
when is classical inheritance an appropriate choice
apparently never/almost never, multi level class inheritance is an antipattern, single level is ok (React.Component), prefer object composition to class inheritance
Convention Over Configuration
attempt to decrease the number of decisions that a developer using the framework is required to make without necessarily losing flexibility
functional programming pros
avoids shared state/side effects, eliminating bugs caused by multiple functions competing for the same resources, functions tend to be simplified and easily recomposed for more reusable code compared to OOP, favors declarative/denotational style which doesn't spell out step by step instructions but rather focuses on what to do letting functions take care of how to do it, this allows for wider range of refactoring and performance optimization, (ex: replacing entire algorithms with more efficient ones with very little code change), computation of pure functions is more easily scalable without resource conflicts, race conditions, immutability makes features like undo/redo, rewind/replay, and time travel debugging easier
synchronous programming
barring conditionals and function calls, code is executed sequentially from top-to-bottom, blocking on long-running tasks such as network requests and disk I/O
call() (javascript)
calls a function with a given this value and arguments provided individually
what does "favor object composition over class inheritance" mean?
code reuse should be achieved by assembling smaller units of functionality into new objects instead of inheriting from classes and creating object taxonomies. basically use composition. quote from "Design Patterns: Elements of Reusable Object-Oriented Software", avoid class hierarchies, brittle base class problem, tight coupling, rigid taxonomy (forced is-a relationships), gorilla banana problem.
React Lifecycle - Destruction
componentWillUnmount()
Crash-only software
computer programs that handle failures by simply restarting, without attempting any sophisticated recovery
React Lifecycle - Initialization
constructor(), static getDerivedStateFromProps(), render(), componentDidMount()
composition
creates a has-a, uses-a, or can-do relationship as opposed to the is-a relationship created with class inheritance
Inversion of control
custom-written portions of a computer program receive the flow of control from a generic framework
delete operator (js)
deletes a property from an object
Single version of the truth
describes the data warehousing ideal of having either a single centralised database, or at least a distributed synchronised database, which stores all of an organisation's data in a consistent and non-redundant form
DRY
don't repeat yourself
OOP pros
easy to understand concept of objects and to interpret meaning of method calls, tends to use imperative over declarative style, thus reads like a straightforward set of instructions for computer to follow
features that support functional purity
first class functions, higher order functions, functions as arguments/values
function vs method vs constructor
function - simply a function method - property of an object that is function type constructor - uses new keyword, creates a brand new object and passes it as the value of this, and implicitly returns the new object as its result, primary role is to initialize the object
var foo = function() { // Some code } vs function bar () { // Some code }
function foo is defined at run-time and is called function expression, whereas function bar is defined at parse time and is called function statement. foo cannot be called before the line it is declared on is run.
write a multiplication function that will work properly invoked with the following syntax: console.log(mul(2)(3)(4)); // output : 24 console.log(mul(4)(3)(4)); // output : 48
function mul (x) { return function (y) { // anonymous function return function (z) { // anonymous function return x * y * z; }; }; }
function bar() { return 12; }; typeof bar();
function statement named bar
first class function
functions treated as first class citizens, implies the language supports passing functions as arguments to other functions, returning them as values from other functions, and assigning them to variables/storing them in data structures
React Lifecycle
highest level - Initialization, State/Prop Update, Destruction
how to check if an object is an array or of a certain type?
if(Object.prototype.toString.call(arrayList) === '[object Array]') { console.log('Array!'); }
classical inheritance vs protoypal inheritance
in JS, protypal inheritance is simpler and more flexible than classical inheritance
When is prototypal inheritance an appropriate choice?
in situations where modules or functional programming don't provide an obvious solution, when you need to compose objects from multiple sources, and any time you need inheritance
class inheritance
instances inherit from classes (like a blueprint), create subclass relationships (hierarchical class taxonomies) instead of from another object (the prototype) instances are typically instantiated via constructor functions with 'new' keyword, creates tight coupling
Flux
is an architectural pattern that enforces unidirectional data flow — its core purpose is to control derived data so that multiple components can interact with that data without risking pollution
KISS
keep it simple, stupid
Monolithic Pros
most apps typically have a large number of cross-cutting concerns, such as logging, rate limiting, and security features such audit trails and DOS protection, When everything is running through the same app, it's easy to hook up components to those cross-cutting concerns. There can also be performance advantages, since shared-memory access is faster than inter-process communication (IPC).
flux vs mvc
mvc problems, poorly defined data flow: The cascading updates which occur across views often lead to a tangled web of events which is difficult to debug, and lack of data integrity: Model data can be mutated from anywhere, yielding unpredictable results across the UI
functional programming cons
over exploitation of features like point free style and large composition reduces readability because code is more abstract less concrete, harder learning curve than OOP
react stateless components
pure functions that render DOM based solely on the properties provided to them
Worse is better
quality does not necessarily increase with functionality
real dom vs virtual dom (React)
real dom - updates slow, can directly update html, creates new DOM if updates, Dom manipulation is expensive, significant memory waste. virtual dom - updates faster, can't directly update html, updates JSX if element updates, DOM manipulation is easy, no memory waste
var foo = function bar() { return 12; }; typeof bar();
reference error. this is named twice.
delegation
refers to evaluating a property or method of one object (receiver) in the context of another original object (sender)
Separation of concerns
separate a computer program into distinct sections, such that each section addresses a separate concern
React Lifecycle - Updating
static getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate(), componentDidUpdate()
microservice architecture
that your app is made up of lots of smaller, independent applications capable of running in their own memory space and scaling independently from each other across potentially many separate machines
flux pattern
the Store is the central authority for all data; any mutations to the data must occur within the store. Changes to the Store data are subsequently broadcast to subscribing Views via events. Views then update themselves based on the new state of received data, To request changes to any Store data, Actions may be fired. These Actions are controlled by a central Dispatcher; Actions may not occur simultaneously, ensuring that a Store only mutates data once per Action, The strict unidirectional flow of this Flux pattern enforces data stability, reducing data-related runtime errors throughout an application
asynchronous programming
the engine runs in an event loop. When a blocking operation is needed, the request is started, and the code keeps running without blocking for the result. When the response is ready, an interrupt is fired, which causes an event handler to be run, where the control flow continues. In this way, a single program thread can handle many concurrent operations
one way data flow
the model is the single source of truth, ghanges in the UI trigger messages that signal user intent to the model (or "store" in React). only the model has the access to change the app's state, the effect is that data always flows in a single direction, which makes it easier to understand
side effect
the modification of some state outside the local environment of the function that causes it
Single source of truth
the practice of structuring information models and associated data schema such that every data element is stored exactly once
event handling
the receipt of an event at some event handler from an event producer and subsequent processes
Occam's razor
the simplest solution tends to be the right one
What is React's core purpose?
to build UI components, often referred to as the V in MVC architecture, thus has no opinions on other pieces of the tech stack and is integrated seamlessly into any app
typeof vs instanceof
typeof is an operator that returns a string with the type of whatever you pass, checks if a value belongs to one of the seven basic types: number, string, boolean, object, function, undefined or Symbol. instanceof tests to see if the right operand appears anywhere in the prototype chain of the left, checks the current object and returns true if the object is of the specified type ex: var dog = new Animal(); dog instanceof Animal; //true var name = new String("xyz"); name instanceof String; //true
OOP cons
typically depends on shared state, objects and behaviors and tacked together on same entity which may be accessed at random by any number of functions with non-deterministic order, which may lead to undesirable behavior such as race conditions, resistant to change compared to FP equivalent
var z = 1, y = z = typeof y; console.log(y);
undefined var z; z = 1; var y; z = typeof y; y = z; var z and var y (declaration) occur first respectively because of hoisting variable = (definition/assignment) occurs right ot left because of associativity of the assignment operator
var x = { foo : 1}; var output = (function() { delete x.foo; return x.foo; })(); what does console.log(output) output? what is foo?
undefined. foo is a property of the object 'x'.
for which value of x are the following statements not the same: (x <= 100) and !(x> 100)
values that return NaN such as undefined, [1, 2, 4], {a: 22}
flux testing
very easy to test the state of any react component just by updating the store, instead of using a tool like selenium to perform very specific scenarios
tight coupling
when a component makes use of knowledge of separate components
blocking
when the execution of additional code in the process must wait until another operation complete
var Employee = { company: 'xyz' } var emp1 = Object.create(Employee); delete emp1.company what does console.log(emp1.company) output?
xyz. delete does not work on a prototype property. company is not emp1's own property, we can delete the company property from the Employee object using delete Employee.company or from emp1 object using delete emp1.___proto__.company
var foo = function bar() { // is foo is visible here? // is bar is visible here? console.log(typeof bar()); // Works here :) }; // is foo is visible here? // is bar is visible here?
yes, yes, yes, no bar is undefined
YAGNI
you aren't gonna need it
Law of Demeter
• Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. • Each unit should only talk to its friends; don't talk to strangers. • Only talk to your immediate friends.
things to check for when evaluating a react component
• does the constructor pass its props to the super class with super(props)? • are the functions properly scoped and bound?