javaScript
What are arrow functions?
Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. var obj1 = { valueOfThis: function(){ return this; } } var obj2 = { valueOfThis: ()=>{ return this; } } obj1.valueOfThis(); // Will return the object obj1 obj2.valueOfThis(); // Will return window/global object The biggest difference between the traditional function expression and the arrow function, is the handling of the this keyword. By general definition, the this keyword always refers to the object that is calling the function. As you can see in the code above, obj1.valueOfThis() returns obj1, since this keyword refers to the object calling the function. In the arrow functions, there is no binding of the this keyword. The this keyword inside an arrow function, does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.
How does the event loop work in relation to the call stack with asynchronous events?
Asynchronous behavior happens on its own empty function call stack. SO without a promise to stop the call stack from emptying, any exception thrown by an asynchronous event will not be caught by any catch handlers. try { setTimeout(() => { throw new Error("Woosh"); }, 20); } catch (_) { // This will not run console.log("Caught!"); }
Difference between " == " and " === " operators.
Both are comparison operators. The difference between both the operators is that,"==" is used to compare values whereas, " === " is used to compare both value and types.
What ways can a promise be rejected?
By calling the Reject(method) new Promise.reject() or const x = "false" new Promise(resolve, reject) => { if (x === false) { reject()} } OR throwing an Error BE CAREFUL const A = new Error("error A); is just an object so i would be a resolve throw A would be how we trigger .catch
What is the use of a constructor function in javascript?
Constructor functions are used to create objects in javascript. function Person(name,age,gender){ this.name = name; this.age = age; this.gender = gender; } var person1 = new Person("Vivek", 76, "male"); console.log(person1); var person2 = new Person("Courtney", 34, "female"); console.log(person2);
What is the DOM
DOM stands for Document Object Model. DOM is a programming interface for HTML and XML documents. When the browser tries to render a HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.
What is a Call Stack Frame
Each entry in the stack is called a stack frame. A stack frame contains the information of the function call such as arguments of the function call, locals of the function, return address (where the return value will be consumed), and other information of the function.
Explain the event loop
Event Que - Only job is to check the message(callback queue). Goes to sleep when nothing in queue. When it finds something it sends it put its on the JAVASCRIPT call stack
Talk me through what Fetch('user.json') .then(response => response.json()) .then(data => console.log(data)) is doing
Fetch is outside of JavaScript. However it does know how promises are strucuted due to them being part of JS SO, when the http call responds with its payload it will call Promise.resolve(payload) we use our first .then to access the response.json() and return it that first .then wraps that return in a new promise so we can call another .then if we so chooose which we do, and use to console log that data.
Why can we use a function as parameter of another function??
Functions are what we call First Class Objects. Which means they essentially just objects. 1) they can be assigned variables and properties 2) passed as args into funcs 3) return as values from functions!
What are callbacks?
Functions that are used as an argument to another function are called callback functions. function divideByHalf(sum){ console.log(Math.floor(sum / 2)); } function multiplyBy2(sum){ console.log(sum * 2); } function operationOnSum(num1,num2,operation){ var sum = num1 + num2; operation(sum); } operationOnSum(3, 3, divideByHalf); // Outputs 3 operationOnSum(5, 5, multiplyBy2); // Outputs 20
Higher-order functions
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
Explain Implicit Type Coercion in javascript.
Implicit type coercion in javascript is automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types. String coercion String coercion takes place while using the ' + ' operator. When a number is added to a string, the number type is always converted to the string type.
Explain passed by value and passed by reference.
In JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference. var y = #8454; // y pointing to address of the value 234 var z = y; var z = #5411; // z pointing to a completely new address of the value 234 // Changing the value of y y = 23; console.log(z); // Returns 234, since z points to a new address in the memory so changes in y will not effect z var obj = { name: "Vivek", surname: "Bisht" }; var obj2 = obj; var obj = #8711; // obj pointing to address of { name: "Vivek", surname: "Bisht" } var obj2 = obj; var obj2 = #8711; // obj2 pointing to the same address // changing the value of obj1 obj1.name = "Akki"; console.log(obj2); // Returns {name:"Akki", surname:"Bisht"} since both the variables are pointing to the same address.
What is the thread of execution?
It is the parsing and executing of code line by line. Which means we are synchronous and Single threaded.
.then method, what does it return? WHY ?
It returns another promise, which resolves to the value that the handler function returns or, if that returns a promise, waits for that promise and then resolves to its result. so sessientally .then ( value => CODE(value)) is really .then ( value => promise.resolve(CODE value)) This way we can daisy chain .then and .then (value => { // use that value in some async code to return something else // return VALUE 2 }) =>>> now we have a new promise(value2) to call another . then on .then (value => { consoe.log(value)}
Is javascript a statically typed or a dynamically typed language?
JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to statically typed language, where the type of a variable is checked during compile-time. Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.For example, a variable which is assigned a number type can be converted to a string type:
What is the call Stack and how does it work?
Last in First out structure. That holds execution Context. What function is currently being run and where to return to after an execution context is popped off the stack. One global execution context, mulitple function context if we are in a function context and it executes another function, we are now in a new function context to we must add that new function to the top of the stack.
1. What is the difference btw let and var const ?
Let - locally scoped mutatble & resassigable var const - locally scoped mutable but not reassigable var - function scoped mutable/reassiganble var
Function Context
Memory allocated just for the things inside a function. Each functions has its own Local Function execution context!
what is the MVC
Model - manages data and rules of app, COMPONENT View - the output, the RENDER Controller - takes user input and converts it into commands for the model, Onclick/events/buttons ects
What is NaN property in JavaScript?
NaN property represents "Not-a-Number" value. It indicates a value which is not a legal number.typeof of a NaN will return a Number . To check if a value is NaN, we use the isNaN() function,
What happens to the event loop/call stack when a promise is made?
No when our promise is made it is executed asynchronusly, after the event loop turn in which .then is called with a fresh stack
What is Object Destructuring?
Object destructuring is a new way to extract elements from an object or an array. const classDetails = { strength: 78, benches: 39, blackBoard:1 } const {strength, benches,blackBoard} = classDetails; or arry version const arr = [1, 2, 3, 4]; const [first,second,third,fourth] = arr;
Non Primitive vs Primitive data types
Primitive Boolean Number String BigInt null undefined symbol non Prim object
Explain what is promise and what is a callback?
Promise - object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Callback - a function that is passed into another function.
What happens when a promise in Promise.all() is Rejected
Promise.all() itself is rejected
What are the 4 types of documentation
SDC - self describing code. good naming! ILC - in line comment, what was reasoning around the logic. Github Comments - leave comments when doing pull reqs, commits ect Detailed story of functionality - Description of major architectural choices and why. Why we structured the app that way.
What is a Temporal Dead Zone
Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords.It is a behaviour where we try to access a variable before it is initialized. x = 23; // Gives reference error let x; function anotherRandomFunc(){ message = "Hello"; // Throws a reference error let message; } anotherRandomFunc();
Explain the Job Que
The job que is the same as the message que, but its for promises and has priority over the message que.
WHAT is a promise, how is it made, and what is it used for
A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively. Promises are used to handle asynchronous operations like server requests,
What is Hoisting?
All declarations are dragged to the top of the scope Hoisting drags the var/func DECLERATION to the top of the scope, while the INITIALIZATION is not, so its initialized to undefined. LET / CONST gets DEFINED and hoisted but does not get initialized AT ALL. so you'll get a reference error. === ONLY WORKS WITH VAR keyword of functions ==== not let/const console.log(x); // undefined var x = 1; console.log(x); // 1 y = 1 console.log(y) // 1 var y = 2 ;
How do exceptions work in Javascript?
An exception can be any value. Raising one somewhat resembles a super-charged return from a function: it jumps out of not just the current function but also its callers, all the way down to the first call that started the current execution.
What JS feature 'unwinds the stack'
An exception when thrown will zoom down the stack, throwing away all the call contexts it encounter
What is a higher Order Function(what can they do) and Why do we use them?
a higher order function is a function that either Takes in a function or return a function. Take a function as a parameter - helps generalize the function and allows you to insert code where a normal primitive value as a parameter would not suffice. (you're passing different operations) .map .fitler .reduce ect..... setTimeout( ) Returns a function - ex a Functions factory would create function DEFENTIONS, so you want similar functions but cannot call them(Eg a click handler right?). So you make a function that makes slightly different functions to assign to a click handler. instead of function that takes a PARAM at EXECUTION. that PARAM is baked into the func. // we dont want to call () => func(1px) @ onClick cuz its expensive // thats why we make click handlers right?> <btn onClick={clickhandler1} /> <btn onClick={clickhandler2} /> <btn onClick={clickhandler3} /> // but were not writing 3 diff funcs ... no thats dumb const clickHandler1 = makeClickHandler(1) const clickHandler2 = makeClickHandler(12) const clickHandler3 = makeClickHandler(14) // function factory is the answer function makeClickHandler(size) { return function() { doc.body.style.fontSize = `${size}px` } }
What is a Stack Trace
a list of methods that were called before the exception occurred. So Chrome Dev tools will print out what the whole stack looked like before that exception. so first function would be on the bottom, which would be the global aka (anonymous), shows the line it was executed on.
What are the two results of a promise
a rejection or a resolve
Difference between continue and break
break stop execution and jumps out of the loop/block continue jumps to next iteration
call()
call() method allows an object to use the method (function) of another object. function sayHello(){ return "Hello " + this.name; } var obj = {name: "Sandy"}; sayHello.call(obj); // Returns "Hello Sandy" var person = { age: 23, getAge: function(){ return this.age; } } var person2 = {age: 54}; person.getAge.call(person2); // Returns 54
apply()
call() method takes arguments separately whereas, apply() method takes arguments as an array.
Explain the DOM
document object model , allows to to add delete and change info on HTML page document - html document objects - the html elememts model - the hierarchy that describes how objects(html elements) are laid out node - dom sees elemnts as nodes and the text inside as a node
What is an execution context
going through our thread of execution in combination with the things we save in memory. We have different execution contexts! Global, function which are called inside of another To many layers. JavaScript keeps track of this with THE CALL STACK
what is the .catch method and when is its handler invoked
it registers a handler to be called when a promise is rejected. new Promise((_, reject) => reject(new Error("Fail"))) .then(value => console.log("Handler 1")) .catch(reason => { console.log("Caught failure " + reason); return "nothing"; }) .then(value => console.log("Handler 2", value)); // → Caught failure Error: Fail // → Handler 2 nothing
What is node.js?
jallows us to use JS outside of a browser, uses chromes v8 engine, single threaded and used mainly for server side applicaitons.
What is the difference btw javascript and node.js?
javascript is a programming langauge node.js is a javascript runtime environment RTE (where complied code is ran)
What is the difference btw null and undefined?
null - something we use to state that there is nothing inside a varriable/binding undefined - there is nothing there, no value has been set/returned
So What is the difference between a function and an object
only real difference is that a function can be invoked!
setTimeout(() => { }, 2000); setTimeout(() => { }, 2000); set Timeout ( () => { setTimeout (() => { }, 2000) }, 2000) HOW Do these differ, one after another or chained if we output the time stamps would they be different and WHY!
so the first blockwould both go out to WEB API then into messaque completed and then event loop would put them onto the Call stack in JS one after another First one would print first second one second HOWEVER THE TIME at which they printed they ran would be identical, BC they were both sent to the web api and it ran both at nearly identical time (smaller than ms difference) the second one that inner set timout would only run once the first had been out to the api thru the message que and took by the event loop onto the callstack and RAN ! then it would itslef go into the Web api so the printed time would be the outer one and then the inner one 2 seconds later!
CLASS vs constructor function
syntax: class syntax is cleaner, keeping everything together under a single class block and handling a lot of the boilerplate for you. safety: Code run in class definitions is always in strict mode. You also can't accidentally call a class constructor as a function or an error will be thrown. built-ins support/initialization: class initialization starts at the base class and works down to the derived class. This allows base classes to define the this (the new instance) which in turn allows class syntax to correctly support extending built-ins like Array. Alternatively, function constructors create the instance in the derived class and pass it up to the base for initialization so a base class has no influence over what this is. feature support: class syntax can support features that function constructors don't, in particular private members. The upcoming support for decorators is also only for class syntax.
What is Promise.all()
takes an array of promises and returns an array of all values that returned from each promise.
What is the meaning of the keyword this in javascript?
this Object instance OR In a method, this refers to the owner object. Alone, this refers to the global object. In a function, this refers to the global object. In a function, in strict mode, this is undefined. In an event, this refers to the element that received the event. Methods like call(), and apply() can refer this to any object.
What is prototype in javascript?
to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. Your prototype can also have a prototype which is called a Prototype Chain
const promise1 = Promise.resolve(value) explain how this works when passed a value and when passed a promise how do you access the value passed?
when passed a value it will return a NEW promise. when passed a promise it will return that same promise, cuz why would you need to promise a promise? doesnt make sense. The value passed is accessed with the .then method which takes a callback function in which the argument is our value.
bind()
This method returns a new function, where the value of "this" skeyword will be bound to the owner object, which is provided as a parameter. var bikeDetails = { displayDetails: function(registrationNumber,brandName){ return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName; } } var person1 = {name: "Vivek"}; var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet"); // Binds the displayDetails function to the person1 object detailsOfPerson1(); // Returns Vivek, bike details: TS0452, Thunderbird
Rest parameter ( ... )
Using the rest parameter syntax, we can create functions that can take a variable number of arguments. fucntion ABC(...args) {}
What is A Web API
Web api's are how JavaScript gets around being single threaded. THEY ARE PROVIDED BY THE BROWSER. When the JavaScript's async code is handled by Web APIS, AJAX, set Timeout, DOM events ect. These Web Apis take a callback function to be run when the async is done. Once async is done it sends the callback to the Message(callback) que/
Explain the Message Que or Callback Que
When we write a callback for some Web Api, lets say AJAX or set Timeout, or dom events. That function will go to that API's Stack and once its done with its Async Actions, i will send that Async action to the Message que for the event loop to handle.
Explain settimeout in javascript?
When you call the setTimeout(), the JavaScript engine creates a new function execution context and places it on the call stack. The setTimeout() executes and creates a timer in the Web APIs component of the web browser. When the timer expires, the callback function that was passed in the setTimeout() is placed to the callback queue. The event loop monitors both the call stack and the callback queue. It removes the callback function from the callback queue and places it to call stack when the call stack is empty. Once the callback function is on the call stack, it is executed.
Local Memory
Where our variables/ functions and function vars are stored. This is where we look when our functions and variables/objects are instantiated/used.
How do you prevent and Exception from throwing away your entire call stack?
With a try Catch Block! making a function call with an exception in should be contained by a try catch block where you would want the program to continue if that exception were to be thrown.
What is closure?
a func can access its parents scope => parents parents scope; its why we can chain array.map(==item== => array.filter(notItem => notItem < ==item==)) func1 (a,b,c) => { return func2 (z,x,y) => { return a + b + c + z + x + y; } } const colsure = func1(1,2,3) colsure(4,5,6) => 1+2+3+4+5+6