JavaScript Flashcards
Explain prototypes in JavaScript.
When you call any property on any JavaScript object, the interpreter will first look for that property in the object itself. If it does not find it there, it will look in the object’s prototype (which is pointed to by the object’s internal __proto__ property).
If it does not find the property in the prototype, it will recursively look at the prototype’s __proto__ property to continue up the prototype chain. How does the chain stop? Object.prototype.__proto__ == *null, so eventually the chain ends.
Explain closures
Closure allows a function to access variables from an enclosing scope — environment — even after it leaves the scope in which it was declared. Closures allow for factory functions.
function dwightJob(title) { return function(prefix) { return prefix + ' ' + title; }; }
var sales = dwightJob('Salesman'); var manager = dwightJob('Manager');
alert(sales(‘Top’)); // Top Salesman
Explain Context
Refers to how a function is invoked, and refers to ‘this’.
Explain scope
visibility of variables.
Explain call, apply, bind
All 3 are used to attach ‘this’ into function
var say = function(greeting){ alert(greeting + ', ' + this.name); }; //person1 becomes 'this' say.call(person1, 'Hello');
1) call is used list of argument
2) apply is for array of arguments
3) bind returns a new function, with a certain context and parameters. It is usually used when you want a function to be called later with a certain context.
const Snow = {surename: 'Snow'} const char = { surename: 'Stark', knows: function(arg, name) { console.log(`You know ${arg}, ${name} ${this.surename}`);} } const whoKnowsNothing = char.knows.bind(Snow, 'nothing'); whoKnowsNothing('Jon'); // You know nothing, Jon Snow
Explain EventLoop
JavaScript is single-threaded. Functions are processed using a callstack. Async functions need to be processed a little bit differently. JavaScript moves Async functions to a task-queue and from there it sits until the entire callstack is empty. Then JS dequeues and processes the async functions.
Pros: Non-blocking. Browser doesn’t freeze while events are processing.
Function Declaration vs Function Expression?
Function Expression:
var myFunction = function name {
statements
};
Function Declaration: function sum (a,b){ return a + b; }
Expression allows for annonymous functions to exist. Pros: Can be used as IIFE
What is this in JS? What are some common pitfalls with this?
‘this’ refers to the current context. In the global scope, this refers to the window. ‘this’ can also reference the context inside a function or object.
== vs. ===
== is equality with co-ersion. === checks for strict equality