JS.Node Flashcards
What is a common error made when storing data as JSON ?
stringifying the data more than once before storage or not stringifying it at all.
what does array.filter() do?
filters an existing array and returns a new array that contains only the filtered values.
what does array.foreach() do?
Much like a for loop, it loops through each item in an array and performs a specified opperation on each item.
What does array.map() do?
Performs an opperation on each value within an array and returns a new array that contains the new mapped values.
What does array.reduce() do?
reduces the values in a given array to a single value.
What does it mean when we say that node uses “non-blocking I/O”?
It means that Node is asynchronous.
What are the two most common JSON commands?
JSON.stringify() and JSON.parse()
What does JSON.stringify do?
turns an object into a JSON object by adding double quotes to the keys and values in objects.
What does JSON.parse() do?
turns JSON objects into objects by removing the double quotes from the keys in an object.
Which module is used to work with files in node?
fs
Which module is used to provide colourful feedback in the console?
chalk
How does the V8 engine works
Node itself is written in C++ and the V8 engine is embedded into it. When writing javascript. The javascript and it’s c++ bindings are passed into the V8 engine which converts it to machine language which can be run on a machine like a computer or a server.
The javascript engine used by Chrome
V8
The javascript engine used by Edge
Chakra
The javascript engine used by Firefox
Spidermonkey
The javascript engine used by Edge
Javascriptcore
What is a javascript engine?
A program that compiles javascript down to machine language
What is the difference between an AOT and JIT compiler?
AOT (ahead of time) compilers, will compile the entire program into machine code ahead of time.
JIT (Just in time) compilers used a combination of interpretation and compilation and will compile blocks of code just before it is neede.
JIT is slower than AOT but it makes it easier to debug and maintain code.
The V8 engine is multi-threaded. What are the 4 main threads and what are there functions?
- Main thread: Fetch - compile -execute
- Compiler thread: Codegen(ignition): converts to
machine code Crankshaft(turbofan): optimizes hot
code - Profiler thread: Monitors code and finds “hot” sections
- Garbage collection thread: Garbage collection
How does crankshaft optimize code?
1. inlining: All the function in the "hot" path are replaced by the actual code from the function to improve performance 2. Hidden classes: The compiler generates hidden classes that maintains the pointers to every object property in a class structure so that it need not be looked up everytime 3. inline caching: A cache of the object type that is most likely to be passed to a function is maintained so that unnecessary lookups are avoided
what is a “method”?
Methods are functions defined as a propertie of an object or class. methods are executed using the dot notation.
Why are arrow functions not well suited for use as methods in an object?
Because arrow functions do not bind their own “this” value, instead they access the “this” value of the context they were created in. This can make it difficult to access properties within objects. Instead it would be better to use an anonymous function which binds its own “this” value
What are arrow functions best used for?
callback functions
What should we use in the place of array.filter() when looking for a single item in a large array? Why?
Array.find()
Array.filter() will look through each item in a list one at a time. It will continue to do so even if the item we are looking for has been found.
Example. In a list of 1000 items, if the item we are looking for is at index 89, it will continue to look through the remaining 911 items before stopping.
Array.find() will stop after it finds the first instance of the desired item.
Array.find()
Looks for item in an array an returns the item (not new array) when found.
Returns “undefined” when nothing is found
How can I use chrome as a debugging tool?
add debugger to script
run “node inspect app.js commands” in terminal
navigate to chrome://inspect in the chrome browser
add folders to project
press esc to toggle console
press run top right hand corner
look at values in the right hand pane.
What are the 6 catagories of errors in javascript?
EvalError: Raised when the eval() functions is used in an incorrect manner.
RangeError: Raised when a numeric variable exceeds its allowed range.
ReferenceError: Raised when an invalid reference is used. Like when you use a variable that has not been declared
SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
TypeError: Raised when the type of a variable is not as expected. Like when you call .toUpperCase() on an integer
URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.
Javascript generates an error object when an error occurs. Which two propperties does it contain?
name
message
What is a stack trace?
A stack trace is a list of the functions, in order, that lead to a given point in a software program.A stack trace is essentially a breadcrumb trail for your software.It helps us understand the steps that lead to the error.
What is the biggest problem with anonymous functions?
They make it difficult to debug as they show up in the stack trace as anonymous.
console.trace()
A command that can be placed inside a function which then generates a stack trace for that funciton in the console or terminal.
Format of a stack trace
Error name function name, file, line number, column number
Which async function can be used to time the execution of a function?
setTimeout(callback, time in milliseconds)
Call stack
a call stack is a stack data structure which is based on the LIFO or last in first out principle. It uses four opperations namely push (to add data), pop (to remove data), peek (to return the value of the top item), isEmpty (returns true if stack is empty). Stacks emulate real life stacks like a stack of books or a can of tennis balls.
Whe a script runs, it wraps all of the code in the main() function. The main function gets pusched onto the call stack and executes, then any function called by main gets pushed onto the call stack on top of main. when the function has finished running it is poped of the call stack. and right at the end of the script the main funciton is popped of the stack.
Callback que
a que used by node to keep track of callback functions that are waiting to run.
Event loop
Adds functions waiting in the call back cue to the call stack when the stack is empty.
Explain what happens in the background when running asyncronous scripts?
Function gets pushed onto the callstack, the async event gets registered with the node api, when it is ready or complete it is moved to the callback cue where it waits for the event loop to add it to the call stack as soon as the call stack is empty. Once it is in the call stack it get executed.
How to initialize a new project as an NPM project?
run “npm init -y” in the root of the folder
package.json file
holds the metadata and information about dependencies and project configuration. It is generated automatically as soon as a project is initialized using npm init
Which npm module can be used ot make http requests?
request
simplest way to make an http request using request?
request({url:url,json:true},(error,response)=>{
console.log(response)
});
Which chrome extension presents json data in a more readable format?
JSON formatter
What are query strings?
a query string is the part of a uniform resource locator (URL) which assigns values to specified parameters. The query string commonly includes fields added to a base URL
query string format base_url?key=value&key=value
Which api provides geocoding or location based information?
Mapbox.
How can errors be handled when using the npm request module to make http requests?
if(error){ console.log("cannot connect) }else if(response.body.error){ console.log("cannot find info") }else{ console.log(response.body) }
What is defensive programming?
Anticipating possible errors and pre-emptively writing code that solves the anticipated problem
A common example is the try/catch statements
What is a call back function?
A callback is a function that is to be executed after another function has finished executing
Functions that do this are called higher-order functions.
Any function that is passed as an argument is called a callback function.
What is a higher order function?
Any function that calls another function or that takes another funciton as an argument
What is a common convention used for callback functions?
someFunction(arg,(error,data)=>{
})
which function helps to parse user input into a valid URI component?
encodeURIComponent()
In which folder should code be placed that make api calls or HTTP requests?
utils
What is callback chaining?
chaining together a number of functions via callbacks while passing arguments (data) between them.
What is callback hell?
When so many functions have been chained together that it becomes unreadable and difficult to understand.
What is object destructuring?
A method that extracts values from an object
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {label, price} = book
How to rename a property during object destructuring?
currentName:newName
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {label:title, price:cost} = book
How to set defualt values for properties when they don’t exist in an object during destructuring?
Using the assignment operator
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
const {title, cost = 100} = book
How to destructure an object passed in as an argument into a function?
by using curly braces.
const book = { label:"To the moon and back", price:56, author:"Ryan holiday" }
function inventory(type, {label, price, author}){ some code here }