js
arrow functions and Hoisting
Arrow functions do not work the way function declarations do, thus will lead to a ReferenceError if referenced before declaration
Ternary Operator
let userName = if(1 >0) ? 'Andrew' : 'boxman';
navigator object
User OS and browser info
Default values to functions
The only value being passed in that will not overwrite the default value is undefined. Any other value such as null, 0, etc will override the default argument
What does splice do?
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
-What is the difference between for(let num of arr) and for(let num in arr)?
-for(let num of arr) will return the actual elements in the array wheres for(let num in arr) will just return the index numbers of the elements position
How does splice work?
-let hobbies = ['soccer', 'snowboarding', 'barbecuing']; splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) let newArr = hobbies.splice(0,2) // start at index 9 and remove two elements. Returns ['soccer', 'snowboarding'] //hobbies will now just be barbecuing. Note, splice modifies the original array
Reflect API
A newer version of the Object. methods. It provides two main advantages 1) better error messages 2) groups all object methods and has some that Object. doesnt such as deleteProperty
What is ESLint?
A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.
Private fields
Accessible ONLY inside of the class/Object Add #symbol in front of field class ProductList { #products = []; } Private properties are only available in the class in which you defined them, not in base class or sub-class
Why would you convert array like objects to arrays to use splice()?
Because splice() only works on real arrays, not array like objects
setTimeout()
Timeout value is the minimum time. It could take longer if something is blocking the event loop and if the stack is not empty
How do you add two arrays together?
arr.concat(newArr) //will add all items of newArr into arr
instanceof operator
class Person = { name = 'Max' } const p = new Person() p instanceof Person //true
Is it included?
const array1 = [5, 12, 8, 130, 44]; arr.includes(item) returns true or false
Class Syntax
is just syntactic sugar
How do you convert from a String to an Int in JS?
parseInt(str)
Determining Browser Support
MDN, Caniuse, Kangax compat table: https://kangax.github.io/compat-table/es6/
reduce()
let arr = [1,2,3,4,5]; let sum = arr.reduce((prevVal, currVal) => { return prevVal + currVal; }); // sum 15 //Returns value. DOES NOT MODIFY ARRAY
Coercion vs Conversion?
-Coercion is essentially temporarily generating a value(or boolean) behind the scenes to use in a comparison but not actually converting the value: -i.e. let userInput = "Max"; if(userInput) { //is really userInput === true, thus javascript uses coercion to generate a temporary boolean related to userInput
Import paths
./ current folder (relative path) ../ up one folder (relative path) / (absolute path)
What is the difference between undefined and null?
If a variable has not been assigned with any value, then it is referred to as undefined. A null value is a value that is assigned to any variable which states that the variable is empty. undefined is a state. When we declare a variable but never initialize it with a value, then it's called undefined. It's the default value used by JavaScript to initialize variables. It's also an empty value. null is a user-assigned value and is an empty value.
Difference between Maps and Objects
Maps can use Any values(and types and objects) as keys whereas Objects can only use strings, numbers, or symbols as keys. Maps provide better performance for large quantities of data and better performance and when adding + removing data frequently whereas Objects are perfect for small/medium-sized sets of data and they are easier to create(typically less expensive than maps to create)
Transpiling code
-When you have core JS features such as const or arrow functions that a browser doesn't support and you can't add a polyfill, use feature detection, etc. -Traspilation is the process or converting('transpiling') modern code to "older" code -Use a third-party tool like Babel to convert your code to code that works in older browsers as well. -Use babel-loader for webpack integration -Babel able to automatically add Polyfills(sick) through using a package under the hood called core-js(which is a collection of polyfills) but still need to install core-js and regerator-runtime(another polyfill library babel uses that core-js does not have) -presets: [ ['@babel/preset-env', {useBuiltIns: 'usage', corejs : {version: 3} ] Babel does not check third party packages so might be a good option to import all polyfills with changing useBuiltIns: 'entry' and then importing 'core-js/stable' and 'regenerator-runtime/runtime'
What is NaN property in JS
-represents Not-a-Number value. It indicates a value which is not a legal number. -To check if value is NaN, we use the isNaN() functions. -**Note-isNaN() function converts the given value to a Number type, and then equates to NaN.
How do you convert "Array-like Objects" to Arrays?
-use Array.from() // <= takes in an array like object such as a nodeList or a String and converts it to an array i.e. let strToArray = Array.from('Bali') // returns ['B','a','l','i']
map()
//Returns new array. DOES NOT MODIFY let arr = [1,2,3]; arr.map(item => { return item *= 2; }) //[2, 4, 6]
Difference between --save and --save-dev
--save The package installed is core dependency. All core dependency is listed under dependencies in package.json. --save-dev The package installed is not a core rather development dependency. All development dependency is listed under devDependencies in package.json.
This overview
1) this in Global Context (i.e. outside of any function) function something() { ... } console.log(this); // logs global object (window in browser) - ALWAYS (also in strict mode)! 2) this in a Function (non-Arrow) - Called in the global context function something() { console.log(this); } something(); // logs global object (window in browser) in non-strict mode, undefined in strict mode 3) this in an Arrow-Function - Called in the global context const something = () => { console.log(this); } something(); // logs global object (window in browser) - ALWAYS (also in strict mode)! 4) this in a Method (non-Arrow) - Called on an object const person = { name: 'Max', greet: function() { // or use method shorthand: greet() { ... } console.log(this.name); } }; person.greet(); // logs 'Max', "this" refers to the person object 5) this in a Method (Arrow Function) - Called on an object const person = { name: 'Max', greet: () => { console.log(this.name); } }; person.greet(); // logs nothing (or some global name on window object), "this" refers to global (window) object, even in strict mode
Bubbling and Capturing
<section> <div> <button> Capturing works from top down, so section to button for events handlers. Bubbling is intuitive, it bubbles up so it works from button to section, or bottom up. //By default, all event listeners are registered in the Bubbling Phase Capturing/Bubbling starts/ends with the body To change to capturing phase, add argument to eventListener. element.addEventListener('click', function, true) //default is false to not add to Capturing phase
Classes
A Class is essentially just a function syntax: class Product { title = 'DEFAULT'; imageURL; } //create new product new Product Constructor method constructor(title, image, desc, price) { this.title = title; this.imageURL = image this.desc = desc; this.price = price; } // this refers to the object being created
Pure Functions & Side-Effects
A Pure Function is a function that given the same input, always produces the same output and has no side effects(does not change anything "outside" of the function) Pure Function function add(num1, num2) { return num1 + num2; } Impure Function function addRandom(num) { return num + Math.random(); } //impure because for the same input, you get an unknown different output
What is Webpack?
A bundling tool. Takes entry file, analyzes that file and its imports, resolve all dependencies of that file and all dependencies of the imported files. import files without .js extension as webpack will add this automatically Need to split between development and production mode
What is a WeakSet?
A collection of objects only. They cannot contain arbitrary values of any type, as Set s can. The WeakSet is weak, meaning references to objects in a WeakSet are held weakly. If no other references to an object stored in the WeakSet exist, those objects can be garbage collected. So if you had let person = {name: 'Max}; const persons = new WeakSet(); persons.add(person); // ... some operations person = null; //this would allow js garbage collector to delete person from the set as there is no other reference to it other than from within the set
What is JavaScript?
A dynamic, weakly typed programming language which is compiled at run time
Factory Function
A factory function is any function which is not a class or constructor that returns a (presumably new) object. In JavaScript, any function can return an object. When it does so WITHOUT the new keyword, it's a factory function. Ex: function createTaxCalculator(tax) { function calculateTax(amount) { return amount * tax; } return calculateTax; } const calculateVatAmount = createTaxCalculator(0.19); const calculateIncomeTaxAmount = createTaxCalculator(0.25);
Difference between a Node and an Element
A node is the generic name for any type of object in the DOM hierarchy. A node could be one of the built-in DOM elements such as document or document.body, it could be an HTML tag specified in the HTML such as <input> or <p> or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node is any DOM object. An element is one specific type of node as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...). The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. Nodes: Objects that make up the DOM HTML tags are "element nodes" (or just "elements") Text creates "text nodes" Attributes create "attribute nodes" Elements: Elements are one type of nodes Special properties and methods to interact with the elements Available methods and properties depend on the kind of element Can be selected in various different ways (via JavaScript) Can be created and removed via JavaScript
What is a Promise?
A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved. A promise may be in one of 3 possible states: fulfilled, rejected, or pending (or a 4th settled where you can add a finally block after all then/catch which will run no matter if you resolved or rejected before). function somePromise = () => { const promise = new Promise((resolve, reject) => { ...resolve ...reject return promise; }) }
What is a Polyfill?
A third party package thats adds some functionality which otherwise might be missing in a browser A polyfill is essentially the specific code (or plugin) that would allow you to have some specific functionality that you expect in current or "modern" browsers to also work in other browsers that do not have the support for that functionality built in. Can use Caniuse and under resources will show polyfill if available
What is TypeScript?
Adds static types, adds some new features, and compiles next-gen JS to "old JS"
Numbers in JS
All numbers are stored as Floats in JS, specifically 64 Bit Floating Points. One bit is designed for identifying positive or negative, and the other 63 bits is there to represent the number and where the dot is Min and Max numbers: Number.MAX_SAFE_INTEGER //Math.pow(2, 53)-1 Number.MAX_SAFE_INTEGER //-(Math.pow(2, 53)-1) Number.MAX_VALUE //1.7976931348623157e+308 largest decimal value allowed There are limits when working with these large or precise numbers JS always works with the binary system and then uses the decimal system when outputting that number(how strange numbers are output)
What are the 3 main iterables in JS?
Arrays, maps, and sets
Attributes vs Properties
Attributes(placed in HTML code, on element tags) are then converted to properties (automatically added on created DOM objects) Ex: <input id="input-1" class="input-default" value="Enter text..."> live-sync: if you change the attribute, the property will change. If you change the property, the attribute will change id: 1:1 mapping(+live-sync) input.id class: Different names(but live-sync) input.className value: 1:1 mapping(1-way live-sync where changing value updates property but not attribute to keep original value if needed by developer) input.value
CORS(Cross Origin Resource Sharing)
By default in the browser, only requests to the same origin(domain) are allowed. i.e. your own server where you hosted the website Always on the backend to give access through headers in NodeJS res.setHeader('Access-Control-Allow-Origin, 'allowedDomain') res.setHeader('Access-Control-Allow-Methods, 'POST, GET, OPTIONS') //For POST requests, Browser sends OPTIONS request first so need to make sure to add it. res.setHeader('Access-Control-Allow-Headers,'Content-Type')
Default Exports
Can only select one default export per file. These are exports with no name but can use export default class { ...//some content } import cmp from './Component.js'
Benefit of formData()
Can send text, files, etc. More dynamic then JSON const fd = new FormData(form); fd.append('someFile', actualFile' ,'optionalFileName')
Feature Detection
Check for feature by seeing if(feature) {...logic} else{show error} If feature is not available, it will be undefined when calling it and then show error
Children, Descendants, Parent & Ancestors
Child: Direct child node or element <div> <p> A <em>test!</em> </p> </div> <p> is a child of <div>. <em> isn't! Descendant: Direct or indirect child node or element <p> is a descendant of <div>. So is <em>! Parent: Direct parent node or element <div> is a parent of <p> but not of <em>! Ancestor: Direct or indirect parent node/ element <divV is an ancestor of <p> and of <em>!
Connect Classes
Connect Classes in a cleve way.
What is Inhertiance
Conveniently share code amongst Objects. You have some base class and want to extend that base class class ShoppingCart extends Component *You can only extend from one class. Extending from multiple classes is not allows in JS Super keyworkd. Add to constructor to call parent constructor method Call super() first before rest of base class code in constructor function
HTTP Only
Cookies is only accessible by the server, not by browser-side javascript
Proxy API
Create "traps" for object operations Step in and execute code, i.e. when someone wants to retrieve a property from your object Control code usage/impact const courseHandler = { get(obj, propertyName) { //do something when a getProperty request is executed } } const pCourse = new Proxy(course, handlerObject); //where course is the object that you want to wrap with the Proxy object
What are Web Components?
Custom HTML Elements Shadow DOM - A separate DOM node tree behind your custom element for your HTML elements(including scoped CSS styles) Templates & Slots - Define core structure behind custom element and entry points(pass data into custom element) HTML Imports - Import HTML Filed ** Not Continued **
What are Objects?
Data structures made up of key-value pairs of properties and methods. Properties are variables in an Object and methods are functions in an Object. Methods are the actions on an Object and are still key value pairs.
Spread vs Destructuring vs Rest
Destructuring is used to create variables from array items or object properties. Spread syntax is used to unpack iterables such as arrays, objects, and function calls. Rest parameter syntax will create an array from an indefinite number of values.
What is the DOM
Document Object Model It is a Web API that allows JS to work with the parsed HTML document
Difference between Document and Window
Document is a global window object and is a property of the Window global object. Document is the root DOM Node(top most entry point to access html code) and provides access to element querying, DOM content, etc Window is the real top most global object. It represents the active Browser Tab/Window and acts as global storage for script, also provides access to window-specific properties and methods alert() is a property of Window object and browsers always parse your code and add Window.function if function name is not found, i.e. Window.alert();
Order of Classes
Does not matter.
connectedCallback()
Element attached to DOM DOM Initializations
What is a WeakMap?
Essentially the same concept as a WeakSet. A WeakMap is a collection of key/value pairs whose keys must be objects, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a WeakMap does not prevent the object from being garbage collected.
The DOM and Prototype Chain
EventTarget -- Node -- Element -- HTMLElement (works right to left)
Closure
Every function is a closure Inner functions can use all the variables or parameters of the outer function and global scope but not vice versa This means that every function has its own Lexical Environment Ex: let multiplier = 1.1; function createTaxCalculator(tax) { function calculateTax(amount) { return amount * tax * multiplier; } return calculateTax; } const calculateVatAmount = createTaxCalculator(0.19); const calculateIncomeTaxAmount = createTaxCalculator(0.25); multiplier = 1.2; console.log(calculateVatAmount(100)); //will use 1.2 as multiplier because only tax is locked in, multiplier will change dynamically as the function reflects that change(i.e the latest value) functions remember the surrounding variables
Fields vs Properties
Fields are created as properties upon Object creation. class Product { title = 'DEFAULT'; imageURL; } //above are fields //create new product new Product Constructor method constructor(title, image, desc, price) { this.title = title; this.imageURL = image this.desc = desc; this.price = price; } //above fields in constructor are properties
What is a generator?
Generators are a special class of functions that simplify the task of writing iterators. A generator is a function that produces a sequence of results instead of a single value, i.e you generate a series of values. In JavaScript, a generator is a function which returns an object on which you can call next(). Every invocation of next() will return an object of shape — { value: Any,done: true|false} [Symbol.iterator]: function* employeeGenerator() { //need to have yield someValue which is the same as using the next() function } Symbol.iterator with generator function allows you to use for of loop with object
Creating & Inserting Elements
HTML string: innerHTML - Add(render) HTML string insertAdjacentHTML() - Add(render) HTML string in specific position: beforebegin, afterbegin, beforeend, afterend, and then element insertAdjacentHTML('afterend', '<p>Some content</p>'); ul.innerHTML = ul.innerHTML + '<li>Item 4</li>' This has two problems. 1) Causes the browser to reparse and rerender 2) Removes user input and Event Listeners textContent only updates text. innerHTML will render new elements. JS document.createElement('tagName') //const li = document.createElement('li') appendChild() / append(): Append new DOM element/node .append('Some text') will append a text node. However, more common use case is element.append(item) or element.append(item1, item2, item3) Insert new DOM element/node in specific position prepend(): The Element.prepend() method inserts a set of Node objects or DOMString objects before the first child of the Element. DOMString objects are inserted as equivalent Text nodes. before(): The Element.before() method inserts a set of Node or DOMString objects in the children list of this Element's parent, just before this Element. DOMString objects are inserted as equivalent Text nodes. after(): The Element.after() method inserts a set of Node or DOMString objects in the children list of the Element's parent, just after the Element. DOMString objects are inserted as equivalent Text nodes. insertBefore(): The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node. Note, if the element already exists in the DOM, then inserting will remove it from its current position to the new position. replaceChild(), replaceWith(): Replace existing DOM element/node with new one replaceWith(): The Element.replaceWith() method replaces this Element in the children list of its parent with a set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes. replaceChild(): The replaceChild() method of the Node element replaces a child node within the given (parent) node. ***insertAdjacentElement beforebegin, afterbegin, beforeend, afterend is the way to go as before and after are not supported on Safari. downside to using insertAdjacentHTML is you don't have direct access to the elements and then will have to add another query to get access, creating two steps when it should be one.
[object object]
Happens bc the browser calls object.toString() so you need to run JSON.parse(object)
Object properties order
If keys are strings, then the order will be the order in which they were added. If they are numbers, then they will be sorted in ascending order.
XSS
If using .innerHTML and using elements such as `<h2>${product.title}</h2> <p>${product.price}</p> ` Make sure to sanitize user input
Memory Leaks
If you remove a DOM node, you need to also remove all references to it. Otherwise, it will cause a memory leak and a detached elelment.
Arrow Function and Event Listeners and this
If you want to use to arrow functions with eventListeners, you need to use bind(this) when adding the eventListener to have access to the element. However, you will have access to the event regardless with element.addEventListener('click', event => { console.log(event); })
Constructor Function
In JavaScript, a constructor function is used to create objects. function Person() { this.age = 30; this.name = 'Bryce'; this.greet = function() { console.log(this.name + ' ' + this. age) } } const p = new Person() p.greet(); When adding the new keyword, what is effectively happening is: function Person() { this = {}; this.age = 30; this.name = 'Bryce'; this.greet = function() { console.log(this.name + ' ' + this. age) } return this; }
Strict Mode and this
In Strict Mode, this leads to undefined in a function instead of Global Window if this is not specifically defined.
What is the Event Loop?
It is part of the hosted environment, not part of JS i.e. it is part of the browser. It's job is so synchronize the call stack and the engine with message queue. Checks if the call stack is empty and if so, pushes the next message from the queue onto the stack https://www.educative.io/edpresso/what-is-an-event-loop-in-javascript
Closures & Memory Management
JS Engine will get rid of unused variables do don't need to worry about functions locking in too many variables and being inefficient
How to convert JS data to JSON and vice versa?
JSON.stringify(jsData) converts JS data to JSON JSON.parse(jsonData) converts JSON data to JS
When comparing two objects with the same properties, == or === will return false. How would you compare if two objects are the same?
JSON.stringify(one) === JSON.stringify(two); // true *However, order of the keys matter so if they are different the above would return false Or use Lodash _.isEqual(k1, k2); // true
Lexical Scope
Lexical scoping (sometimes known as static scoping ) is a convention used with many programming languages that sets the scope (range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined. The scope is determined when the code is compiled
Module Scope
Module have their own scope and is not shared globally unless specifically set with globalThis.someValue = '' and then you have to access with globalThis.
Dynamic Hosting
Need dynamic host (able to execute server-side Node.js). Server needs to host + execute files (server-side)
When to use classes
No! Great for general data grouping, objects which you only create once Quick & easy to create, no overhead But also consider classes! Great when you re-create the same type of object over and over again More overhead initially but easy "object duplication" thereafter
Static Hosting
Only HTML, CSS, and JS. Just handles HTTP requests and serves HTML, CSS, and JS files and images, etc,
Note about Traversing DOM
Only use Traversal techniques when you know the relationship wont change i.e. li will always be under ul.
event.preventDefault()
Prevents the browser from executing the default action of the event
What are symbols?
Primitive value Used as object property identifiers Built-in and createable by developers Uniqueness is guaranteed Mainly used for building libraries and exposing code Ex: //Library Land const uid = Symbol('uid'); //'uid' is optional and just a name used for debugging purposes const user = { [uid]: 'p1', name: 'Max', age:30 } can change it within backend such as user[uid] = 'p3' //app land => using the library user.id = 'p2' //this should not be possible console.log(Symbol('uid') === Symbol('uid'))' //false
What are the two types of values in JavaScript?
Primitive values and Reference values
Primitive values vs Objects
Primitive values are the core building blocks that hold your data, objects (and arrays) are helpful for organizing and working with that data.
How do you fix Callback Hell?
Promise chaining(step after step instead of step inside of step) or Async/Await
Event Delegation
Put the eventListener on a parent element to avoid putting it on all elements. i.e. you have a ul and li several items and you want to toggle the li background and color on click, you could add the event listener on the ul and then set the event.target.classList.toggle('bg') as this event will propagate up to the parent ul. or event.target.closest('li') if you have p or other elements within the li.
Propogation
Refers to how events propagate through the DOM tree for Capturing phase or through an elements ancestors in the Bubbling phase event.stopPropagation(); event.stopImmediatePropagation(); stops propagation after the first eventListener runs
Cookies
Servers can set cookies with headers on their responses. If you don't set an expiry, it will normally expire when the browser session expires although it is up to the browser. max-age expires in seconds expires takes a date
Static Properties, Fields, & Methods
Static Fields /Property/ Method Defined with Static Keyword Only accessible on class itself, without instantiation Typically used in helper classes, global configuration etc Instance Field / Property / Method Defined without static keyword Only accessible on instances (objects) based on classes Used for core, re-usable logic
Is JS synchronous or asynchronous?
Synchronous. JS is a single-threaded, blocking language
Testing Setup
Test Runner: Execute your tests, summarize results - Mocha Assertion Library: Define testing logic, conditions - Chai Jest is both of these - Test Runner and Assertion Library Headless Browser - Simulates browser interaction Puppeteer
What is the difference between localStorage and sessionStorage?
That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site. For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.
Understanding how the DOM is created
The browser parses the HTML file and creates an Object representation of your document. The browser doesn't work with text, but instead objects that are stored in memory
What is an iterator?
The iterable protocol allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a for...of construct. Some built-in types are built-in iterables with a default iteration behavior, such as Array or Map, while other types (such as Object) are not. In order to be iterable, an object must implement the @@iterator method, meaning that the object (or one of the objects up its prototype chain) must have a property with a @@iterator key which is available via constant Symbol.iterator: A function, with either zero arguments or one argument, that returns an object with at least the following two properties. If the next() method is called with one argument, that argument will be available to the next() method being invoked. done (boolean) Has the value false if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. valueAny JavaScript value returned by the iterator. Can be omitted when done is true. The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a TypeError ("iterator.next() returned a non-object value") will be thrown. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
What is the difference between a callback and a promise?
The main difference between Callback Functions and Promises is that we attach a callback to a Promise rather than passing it. So we still use callback functions with Promises, but in a different way (chaining). A key difference between the two is when using the callback approach, we'd normally just pass a callback into a function that would then get called upon completion in order to get the result of something. In promises, however, you attach callbacks on the returned promise object.
Traversing DOM - Children
The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes. So if you have ul with three li, to get second li: const ul = document.querySelector('ul'); ul.children[1] To get first or last, can use firstElementChild or firstChild(returns all nodes including text nodes) and similarly lastElementChild or lastChild(also returns text nodes). You'll want to use elementChilds in most cases. Could also use querySelector('ul li:last-of-type')
Why are IIFE not really necessary anymore
The old patterns only had var and had to use something like this to lock in the var scope which has function scope: (function() { var age = 30; console.log(age); // 30 })() Nowadays, this is not needed with the introduction of let and const that have block scope
Impure vs Pure Functions
Try to keep functions predictable and pure and minimize the use of Impure Functions. Keep names clear about what the function is doing and imply whether the function is pure or impure
Paint Flashing
Use Paint Flashing to see DOM updating
Network Tab
Use it in Chrome to find when files aren't loading
<template>
Use template tag to separate HTML from JS and as code inside template html is not shown initially. Can then call it in JS and set content as needed
<noscript>...content</noscript>
Use to throw error when JS is disabled in the browser
Styling DOM Elements
Via Style Property Directly target individual CSS styles and controls styles as inline styles on the element via className Directly set the CSS classes assigned to the element Set/Control all classes at once Via classList Conveniently add, remove, or toggle CSS classes
Object properties
When accessing property that has not been created, you will not get an error. It will just return undefined. Also, to delete a property, use delete object.propertyName which will set it to undefined and remove the key from the object
When Does Module Code Execute
When it is imported for the first time
Callback Hell
Where you have many nested callbacks within each other and your code gets very difficult to understand and maintain
Does removing an element remove event listeners?
Yes, in most modern browsers.
import
You can either import the functions such as { function1, function2 } from './utils/util.js' Or as an Object import * as util from './utils/util.js'
Error object
const customError = new Error('Some error message'); can also set custom properties like customError.coder = 404; throw customError; //prints message and stack trace
getElementsByTagName
const listItemElements = document.getElementsByTagName('li') //returns live list
Getters and Setters
const newMovie = { info: { set title(val) { this._title = val; } get title() { return this._title; } } } Then when you set and access the value, the setter and getter are executed such as newMovie.title = 'test'; //setter is called console.log(newMovie.title) //getter is called
Object Property Descriptors
const person = { name: 'Max' greet() { console.log(this.name); } } Object.getOwnPropertyDescriptors(person) //returns greet: {...same values as below} name: { configurable: true, enumerable: true, value: 'Max', writable: true } //configurable is to delete, enumerable is to loop through on for loops, and writable is editable To set one of the properties, you need to pass in all again otherwise they will be set to false if you leave them out Object.defineProperty(object, key, values) Object.defineProperty(person, 'name', { configurable: true, enumerable: true, value: 'Max', writable: false //can't edit }
Object.assign()
const person = {name: 'Max'}; const person2 = Object.assign({}, person); Can pass in empty array or existing array and merge with person properties
Loading Scripts Dynamically
const script = document.createElement('script'); script.src='...'; script.defer=true; document.head.append(script); Call above when you want to load script instead of on page load initially.
Measuring Performance
const startTime = performance.now() const endTime = performance.now() Broswer DevTools jsperf.com webpagetest.com lighthouse audit report in Chrome DevTools developers.google for docs for DevTools https://web.dev/performance-optimizing-content-efficiency/ https://developer.chrome.com/docs/devtools/evaluate-performance/reference/ https://web.dev/optimize-javascript-execution/ https://developer.chrome.com/docs/devtools/memory-problems/ Server Side Compression: https://github.com/expressjs/compression Caching: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control https://web.dev/http-cache/ https://wp-rocket.me/blog/different-types-of-caching/ HTTP/2: https://web.dev/performance-http2/ Add third-party libraries to bundle instead of via CDN Minify Code
Setting Timer and Intervals
const timerId = setTimeout(cbFunction,3000, optional array of arguments to function) -Run asynchronously -clearTimeout(timerId) const intervalId = setInterval(cbFunction, 2000, optional array of arguments to function) clearInterval(intervalId);
Well Known Symbols
const user = { [uid]: 'p1', name: 'Max', age:30, [Symbol.toStringTag]: 'User' } console.log(user.toString()); //[object user]
how to toggle class
element.classList.toggle('class');
cloneNode
element.cloneNode(bool) default bool is false but boolean determines whether a deep clone should be created with all child and descendant elements should be copied or not.
Removing Elements
element.remove() or element.innerHTML = ''; or element.parentNode.removeChild(someElement) //oldest but provides the broadest browser support
scrollIntoView
element.scrollIntoView({behavior: 'smooth'}) //scroll to element //Chrome and Firefox support behavior smooth scroll
Sync + Async Code - The Execution Order
function trackUserHandler() { navigator.geolocation.getCurrentPosition(posData => { console.log(posData) },error => { console.log(error } }); console.log('Getting position'); } console.log('Getting position') will always run first because the async code will have to be called through the browser API and go through the event loop and message queue.
Getters and Setters in Classes
get and set field name();
promise chaining key notes
getPosition() .then(posData => { return someData; } .then().... //someData does NOT have to be a promise. It can be any value. However, if not already a promise, it will be converted to one.
Why do two objects with the same properties not equal each other, i.e.
let a = { 'name': 'Bob' } let b = { 'name': 'Bob' } a === b // returns false -Because a and b are really just pointers and they are pointing to different objects on the heap. Thus, you are really comparing memory address and not properties. This is the same for Arrays.
LocalStorage vs Cookies vs IndexedDB
localStorage, sessionStorage: -simple key-value store -Manage user preferences or basic user-data -Can be cleared by the user and via JS Cookies: -simple key-value store(some config options such as expiry, etc) -Manage user preferences or basic user-data -Can be cleared by the user and via JS -Sent to server with outgoing HTTP requests. Main difference between local/session storage and cookies IndexedDB (in browser database) -Relatively Sophisticated, client-side db -Manage complex data your web add needs -Can be cleared by the user and via JS -Great for complex (non-critical) data needs
location and history object
location object is all about page and url information can change page with location.url='//...' or location.replace('//...') //can't use back button with this history.back()
Traversing DOM - Parent
parentElement or parentNode refer to the nearest parent element. All elements have only parent. Use parentElement closest('ancenstor') will find the closest ancestor anywhere up in the element tree. *Note is has to wrap the element. It will not find siblings.
Traversing DOM - Sibling
previousElementSibling or previousSibling for sibling before and nextElementSibling or nextElementSibling for next sibling after
Querying Elements in the DOM
querySelector(), getElementsById() Return single elements, different ways of querying elements(by CSS selector, or by ID) Direct reference to DOM element is returned querySelectorAll(), getElementsByTagName() Return collections of elements(array-like objects): NodeList Different ways of querying elements(by CSS selector, by tag name, by CSS class) querySelectorAll() returns a non-live NodeList, getXByY return live NodeLists *Live NodeList means if you add or remove elements, you will see reflected in the list. In some cases, the NodeList is live, which means that changes in the DOM automatically update the collection. For example, Node.childNodes is live: const parent = document.getElementById('parent'); let child_nodes = parent.childNodes; console.log(child_nodes.length); // let's assume "2" parent.appendChild(document.createElement('div')); console.log(child_nodes.length); // outputs "3" Static NodeLists In other cases, the NodeList is static, where any changes in the DOM does not affect the content of the collection. The ubiquitous document.querySelectorAll() method returns a static NodeList.
How to create a Promise
return new Promise((resolve, reject) => { if(somethingSuccesfulHappened) { const successObject = { msg: 'Success', data,//...some data we got back } resolve(successObject); } else { const errorObject = { msg: 'An error occured', error, //...some error we got back } reject(errorObject); } });
Event Handler Functions & this
this refers to the event current target, or the element that you registered the eventListener on
Arrow Functions and this
this refers to what it outside of the object, in the global object or main script Example const members = { teamName: 'Blue Rockets', people: ['Max', 'Manuel'], getTeamMembers() { this.people.forEach(function(p) { console.log(this); //window object console.log(p + ' - ' + this.teamName); }); } } members.getTeamMembers(); Window is printed Max - undefined Window is printed Manuel - undefined The reason is because functions created with the functions keyword bind this inside of them. This function is executed by forEach by the browser and the Window object is bound The solution Use an arrow function. An arrow function doesn't change the binding of this. const members = { teamName: 'Blue Rockets', people: ['Max', 'Manuel'], getTeamMembers() { this.people.forEach(p => { console.log(this); //window object console.log(p + ' - ' + this.teamName); }); } } Outside of the forEach function is the getTeamMembers function where the binding of this in getTeamMembers function is the Object
data-*attributes
to access, use element.dataset.keyName - it will get converted to camelCase. You can also use it to set data attributes, i.e. element.dataset.keyName = 'test';
Fields are translated to properties after the constructor ran
true
prototype is only part of constructor functions
true
Check for Property Existance
use in keyword if (property in object)
Dynamic Object properties
use object[dynamicKey] = ...
Difference between value and text content
value is for form elements to get the value of the form element. textContent is for other elements to get the content of the element.
Adding async keyword
wraps entire function and returns a promise Note, code below try catch block will wait for try code because it really just adds a .then() to the code below. await is only available in async functions
Finding index of item/ last index of
Both return first index found or -1 if item not found arr.indexOf(item)//search from left arr.lastIndexOf(item)//search from right
Keys in dictionaries:
All are cooerced into strings. You can use numbers but not with dot notation, i.e const persion = { 1.5 = 'hello' } //person[1.5] = 'hello'; //valid
JavaScript naming conventions:
Allowed -best practice: camelCase -can use $ and _ anywhere in the variable name, including the beginning -only digits and letters -Not Allowed -bad practice: snake_case (i.e. as in Python) -starting variable name with digitis i.e. 21players -using -, i.e. let user-b. -keywords. i.e. let
filter()
let arr = [1,2,3,4,5] let filteredArr = arr.filter(item => { return item > 3; }) // filteredArr [4,5] //Returns new array. DOES NOT MODIFY
Why does: const hobbies = ['football']; hobbies.push('running'); work?
It does not throw an error because you are not changing the reference, i.e. hobbies which is stored on the stack. You are only dynamically changing the memory on the heap. However, setting: hobbies = ['football', 'running']; would throw an error because you changing the memory reference of hobbies and pointing it to a new object on the heap.
Name the 7 primitive types in JS
1) String 2) Number: Can be written with or without decimals 3) BigInt: Can store numbers above the limitation of numbers. Used with an n to an integer literal 4) Boolean 5) Undefined: When a variable is declared but not assigned, it has the value of undefined and type of undefined 6) Null: It represents a non-existent or invalid value 7) Symbol: New data type introduced in ES6 and stores an anonymous and unique value. *Note - All other non primitive types in JavaScripts are objects.
Indirect vs Direct Function Execution
-() invokes a function immediately. -i.e.add(num1, num2) -just function name such as add will not execute the function immediately as it is parsed. It will wait to execute at some point in the future: -such btn.addEventListener('click', add); -Note: btn.addEventListener('click', add()) would be wrong as this would execute immediately
Are Boolean values lower or upper case?
-Boolean values are lowercase: false and true
Which data can you store in Arrays?
Can store mixed or same type. Can store numbers, string, objects, nested arrays, etc
What is the difference between function declaration and function expressions?
Function Declaration: function multiply(a,b) { return a * b; } Function Expression: const multiply = function(a,b) { return a * b; } Both are technically hoisted, but function declarations are initialized and can be called from anywhere in the file whereas function expressions are hoisted but not initialized/defined, this throwing a cannot access 'multiply' before initilization error if access before the expression.
How are properties ordered?
Keep the order in which they are added Exception: If keys are all numbers then they will be sorted in asc.
Diff between Statically typed languages vs Dynamically typed languages
Statically typed languages do type checking at compile-time and dynamically typed languages do type checks at runtime
How do you remove an element from the end of an array?
array.pop() // returns the element that was removed from the end
Function Statement vs Function Expression?
-Function statements are defined with the function keyword and then the function name: i.e. function add(x,y) { return x + y; } -Function statements are hoisted unlike function expressions which behave like a normal assignment statement. -Function expressions are assigning a function to a variable name: i.e. const add = function(x,y) { return x + y; }
What is a first-class citizen?
-Functions are objects which are first-class citizens in javaScript. -fcc is an entity that supports all the operations available to the other entities. In this case, it means that functions can be assigned to a value, passed in to a function as an argument, returned from a function, and also modified.
Rest Parameter
-Allows you to pass in any number of arguments to a function and all will be combined into an array. i.e. let sum = (...numbers) => { let result = 0; for(const num of numbers) { result += num; } return result; } -You SHOULD only have one parameter, and you cannot have anything after such as ...numbers, a as all arguments will be combined into a single array and you will get rest parameter must be last formal parameter -If you have additional parameters before the rest parameter such as a, ...numbers then a will not be included in the ...numbers array and thus the sum calculation.
Explain call(), apply(), and bind() methods
-Call() invokes a method(function) by specifying the object. -The only difference between call and apply is how you pass arguments. Instead of passing in arguments for the call() method individually, you pass the arguments as a list for apply(). -bind(). Instead of directly invoking the function, bind will return a method with "this" bound to the owner object passed in. The bind() method creates a new function that, when called, has its this keyword set to the provided value. var pokemon = { firstName: 'Pika', lastName: 'Chu ', }; var pokemonName = function() { console.log(this.firstName + ' ' + this.lastName + ' I choose you!'); }; var logPokemon = pokemonName.bind(pokemon); // creates new object and binds pokemon. 'this' of pokemon === pokemon now logPokemon(); // 'Pika Chu I choose you!' The call() method calls a function with a given this value and arguments provided individually. The main differences between bind() and call() is that the call() method: 1) Accepts additional parameters as well 2) Executes the function it was called upon right away. 3) The call() method does not make a copy of the function it is being called on. call() and apply() serve the exact same purpose. The only difference between how they work is that call() expects all parameters to be passed in individually, whereas apply() expects an array of all of our parameters var pokemon = { firstname: 'Pika', lastname: 'Chu ', getPokeName: function() { var fullname = this.firstname + ' ' + this.lastname; return fullname; } }; var pokemonName = function(snack, hobby) { console.log(this.getPokeName() + ' loves ' + snack + ' and ' + hobby); }; pokemonName.call(pokemon,'sushi', 'algorithms'); // Pika Chu loves sushi and algorithms pokemonName.apply(pokemon,['sushi', 'algorithms']); // Pika Chu loves sushi and algorithms 2) Function borrowing. The apply() method allows an object to borrow the method of another object without duplicating the code. const computer = { name: 'MacBook', isOn: false, turnOn() { this.isOn = true; return `The ${this.name} is On`; }, turnOff() { this.isOn = false; return `The ${this.name} is Off`; } }; const server = { name: 'Dell PowerEdge T30', isOn: false }; let result = computer.turnOn.apply(server); console.log(result); //The Dell PowerEdge T30 is On
What is the difference between an expression and a statement?
-Expression results in a value. It is something you could use on the right side of an equals side. All expressions are statements -An if statement does not return a result. For example, if statements such as if(userName) or for loop statements are commands that do not return a value.
What are Higher Order Functions?
-Functions that operate on other functions, either by accepting them as arguments or returning them. -Functions are a first class citizen in JS(can pass them in as arguments, return them from functions, and assign them to variables, etc) function higherOrder(fn) { fn(); } higherOrder(function() { console.log("Hello world") }); function higherOrder2() { return function() { return "Do something"; } } var x = higherOrder2(); x() // Returns "Do something"
Explain passed by value and passed by reference
-In JS, primitive data types are passed by value and non-primitive data types are passed by reference. -Primitive values are stored on the stack whereas Non Primitive types are stored on the heap. For example, var z = 221 is stored on the stack. If you then had var y = z, var y is a new variable with a new address on the stack with the same value. However, these do not point to the same memory address. So changing z will not affect y. However, if you had an object such as let dict = {a: 'b'}, this is stored on the heap. So let dictCopy = dict and then dictCopy[a] = 'c' would change dict because they both point to the same memory address.
What is strict mode?
-It is a restricted variant that was introduced in ES5 -All modern browsers support "use strict" except Internet Explorer 9 and lower -You can define it at a level for the entire script or a specific function. However, modules and classes are strict by default. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export to see what modules are in js and how default/named exports work. -To define, write 'use strict' as a string literal at the top;
Is JS pass by value or pass by reference?
-It is always pass by value. But for objects the value of the variable is a reference. So when changing object members, those will exist outside of the function. function changeObject(x) { x = { member: "bar" }; console.log("in changeObject: " + x.member); } function changeMember(x) { x.member = "bar"; console.log("in changeMember: " + x.member); } var x = { member: "foo" }; console.log("before changeObject: " + x.member); changeObject(x); console.log("after changeObject: " + x.member); /* change did not persist */ console.log("before changeMember: " + x.member); changeMember(x); console.log("after changeMember: " + x.member); /* change persists */
So why did the change occur to where let and const were introduced?
-Let and const were introduced to encourage cleaner and more well defined code that gets rid of poor coding standards when using var and additional errors with having access to data where you shouldn't in the program
Define the 3 types of scope in JS
-Lexical(Global) scope: An inner function has access to all variables and functions in its outer parents scope. -Function(local) scope-variables defined in function are contained within that function. Includes var, let and const. -Block scope: let and const are contained to that block, however, var is not and these variables can be accessed outside of that scope. Note that var is hoisted outside of the block scope to the parent lexical scope
Arrow Functions
-No arguments/parameters: () => { ... } empty pair of parentheses is required -Exactly one argument/parameter: arg => { ... } empty pair of parentheses can be omitted -Exactly one expression in function body: (a,b) => a + b curly braces can be omitted, result is returned -More than one expression in the function body: (a, b) => { a *= 2; return a + b } curly braces and return statement required
Creating Arrays
-Normal way: -let numbers = [4,5,6] -Can use new Array() -note, if you pass in more than one argument, behaves just like [] -However, if you pass in one argument and it is a number, then it will return an array with that much length allocated. i.e. const moreNumbers = newop Array(5) //returns an array with length 5
What's an "Array-like Object"?
-Objects that have a length property and use indexes to access items -Not every array-like object is an array! Other array-likes are (for example): Nodelist, String
The Slice() method:
-Returns a copy - works like other languages with starting index is included and up to but not including. Can also just set a starting index and it will go until the end of the iterable. i.e. let food = [ "gyros", "spaghetti", "salmon"]]; let foodCopy = food.slice(0,2); //results in [ "gyros", "spaghetti"];
DOES NOT MODIFY IN PLACE - Only returns a copy
-Slice() -Concat() -Map() -Filter() -Reduce() -.split() -.join(' ')
Modifies in Place***
-Splice -Push() -Pop() -Unshift() -Shift() -sort() -reverse()
JS specific stack and heap notes
-The browser decides what data ends up where(i.e. on the stack or on the heap) -Primitive values are copied by value. Objects are copied by reference -The stack stores static data such as primitive values(i.e. number, string, boolean, undefined, null) and references (to functions and objects you have created) -Functions and Objects are stored on the heap
What is a Closure?
-The closure is a function that accesses its lexical scope even executed outside of its lexical scope. -Simpler, the closure is a function that remembers the variables from the place where it is declared, regardless of where it is executed later. -In JavaScript, closures are created every time a function is created, at function creation time. -A closure is a stateful function -In other words, a closure gives you access to an outer function's scope from an inner function.
How do you create a deep copy of an object?
-The spread operator -let copyObject = {...a} //this also works for arrays. i,e, [...a] let copyObject = JSON.parse(JSON.stringify(a)); //make a deep copy of a
How is JavaScript executed?
-There is a built in js Engine in the Browser(V8 for Chrome and SpiderMonkey for Firefox). Order: -Code All within JS Engine -Parse Code -Compile to Machine Code -Execute Machine Code Effect Web Page End JS Engine *Note, JS code runs in a single thread
What is the difference between var and let/const?
-Var has function/global scope, meaning that it will be confined to being accessed in a function if defined there. -On the other hand, let and const have block/global scope, meaning that any time they are defined within {} their scope will be limited to inside the curly braces ex: function greet() { var age = 30; //age is defined to this function } console.log(age); // will throw ReferenceError: age is not defined however, if you had { var age = 30; } console.log(age); //this will work and print 30 to the console.
Explain the difference between shallow/deep copies and what is the difference when creating a copy of variable that points to a primitive value vs copying a variable that points to an object?
-Variables who's value are a primitive type will be stored on the stack. As an example, let a = 15; If you did: let b = a; This would create a new value(copy the value) on the stack where b = 15. -So, if you then did b = 30, a would still be 15 as b was pointing to it's own value since first setting b = a. -However, this is different when dealing with objects. -If you have, let a = { 'name': 'Bob' } -and then you had, -let b = a; -You just created a shallow copy, which means that a and b both exist on the stack but are references(pointers) to the same object that exists on the heap. -So, changing a property on B would also reflect on A and vice versa as they are referring to the same object. -As an example, b.name = 'Max' -Would also change a.name. -***note that Object.assign(a) creates a shallow copy, not a deep copy -If you want to create a new object on the heap that has the same properties as a and b can refer to this new object, you would have to create a deep copy
Explain "this" keyword?
-Whatever is in front of the function call or with eventListeners, it is the event. -"this" refers to the object in which it is bound, or refers to the object that the function is a property of. -Window in Browser and Global Object in NodeJS. "This" keyword refers to the object that is executing the current piece of code.
How do you add an element to the end of an array?
-array.push(item) //adds it to the end and returns the new length of the array
How to you remove an element from the beginning of an array?
-array.shift() //returns the element from the beginning of the array. The new array completely removes the old element and the length is updated accurately.
How do you add an element to the beginning of an array?
-array.unshift(item) // returns length of the new array. Think unshift because each element shifts all elements to the right. The new array accurrately reflects the new element and has the updated new lengths
Second version of Splice i.e. replace
-let hobbies = ['soccer', 'snowboarding', 'barbecuing', 'coding']; let newArray = hobbies.splice(1, 3, 'Netflix'); // ["snowboarding", "barbecuing", 'coding'] //hobbies will be ["soccer", "Netflix"] -Note*** if you have: -let hobbies = ['soccer', 'snowboarding', 'barbecuing', 'coding']; hobbies.splice(1, 0, 'Netflix') //returns empty array //hobbies now equals ["soccer", "Netflix", "snowboarding", "barbecuing", 'coding] Also, if you have: -let hobbies = ['soccer', 'snowboarding', 'barbecuing', 'coding']; hobbies.splice(0, 0, 'Netflix') // returns empty array also like above //hobbies now equals ["soccer", "Netflix", "snowboarding", "barbecuing", 'coding] -Can add as many elements as you want when splicing i.e. hobbies.splice(1,0,'Running', 'Scuba Diving'); -Can also use negative indexes and go from the right: -let hobbies = ['soccer', 'snowboarding', 'barbecuing', 'coding']; hobbies.splice(-2,1) // returns barbecuing but leaves coding // hobbies is now ['soccer', 'snowboarding', 'coding']
Dynamic properties
-use [] to dynamically access as well as set properties const userChosenKeyName = 'level'; person = { [userChosenKeyName] = '...', // keyname will be level age: 31 } person['age'] // 31
-All values except what are truthy values.
0, 0n, -0, '', null, undefined and NaN values.
What does strict mode do?
1) Have to define variables with a valid keyword such as var, let, or const. userName = 'Max'; console.log(userName); // ReferenceError thrown. Without use strict, js engine would automatically add a var before when defining. 2) Makes assignments that would otherwise fail silently throw an error // Assignment to a non-writable global var undefined = 5; // throws a TypeError var Infinity = 5; // throws a TypeError // Assignment to a non-writable property var obj1 = {}; Object.defineProperty(obj1, 'x', { value: 42, writable: false }); obj1.x = 9; // throws a TypeError 3) Attempts to delete undeletable properties throws an error where as before would have no effect -delete Object.prototype; // throws a TypeError 4) Parameter names must be unique -function sum(a, a, c) { // !!! syntax error 5) Forbids a 0 prefixed Octal literal or octal escape sequence -Outside strict mode, a number starting with 0 if all numbers are less than 8 will be interpreted as an octal number. Ex: -0644 === 420 -Similarly, octal escape sequences such as "/45" equals '%' as represented by Extended ASCII character code numbers in octal. -In strict mode, the two above throws an error. To define an octal literal or string sequence, you must use 0o such as: -var a = 0o10; // ES2015: Octal. This is valid. 6) ES5 forbids setting properties on primitive values. i.e.: -false.true = ''; // TypeError
What is the memory life cycle?
1) Memory allocation 2) Memory use/accessing data 3) Memory release/deallocation
Difference between == and ===
== compares values whereas === compares values and type var x = 2; var y = "2"; (x == y) // Returns true since the value of both x and y is the same (x === y) // Returns false since the typeof x is "number" and typeof y is "string"
What is a callback function?
A function that is passed into another function as an argument to be executed later. In essence, it is just a reference or a pointer to another function as you pass it in without the () to execute it.
What is an immediately Invoked Function? IIFE?
A function that runs as soon as it is defined IIFE (function () { /* ... */ })(); Arrow function IIFE (() => { /* ... */ })(); async IIFE (async () => { /* ... */ })();
What is an anonymous function?
A function without a name
What is the difference between methods and functions?
A method is a function attached to an object whereas a function is not associated to one object
Spread Operator
Can copy all elements into a new array. i.e. const elements = ['earth', 'wind', 'fire'] const copiedElements = [...elements] Can also assign variables directly to items in the array called Array Destructuring: const [earth, wind, fire] = [...elements]; //earth is 'earth', etc Can also use the spread operator for Objects with Object Destructuring let obj1 = { foo: 'bar', x: 42 }; let clonedObj = { ...obj1 }; // Object { foo: "bar", x: 42 } Can also directly assign variables from spread operator const { foo, x } = obj1
What is currying in JS?
Currying is transforming a function with multiple arguments into a sequence of arguments with a single argument -Can use bind or function currying function add(a) { return function(b) { return a + b; } } function multiply(a) { return function(b) { return a * b; } } add(2)(3); //5 Can use bind in two ways with the above; const add2 = add.bind(this, 2); add2()(3); //5 Or Change function to function add(a,b) { return a + b; } const add2 = add.bind(this, 2); add2(3); //5
Why would you consider adding a name to a function?
For debugging purposes as if an error is thrown, the name of the function will get added which can help with debugging, especially if the line numbers don't add up as can happen with compressed files
How does Garbage Collection work?
In V8, the garbage collector periodically checks heap for unused objects(objects without reference) and removes them. -i.e. let person = {name: 'Max'}; person = null; or if person is not used anywhere in your code. It will remove the object {name: 'Max'}; *************You can add memory leaks by adding an anonymous function to an event listener multiple times as the garbage collector will not know how to clean up the duplicate objects as it won't be able to tell that the anonymous function is the same.
Hoisting DECLARATIONS vs Initializations
Hoisting only works for DECLARATIONS, not initializations. Initialization does not occur until the actual associated line is executed. Essentially, hoisting just moves the declaration to the top of the code but leaves the initialization as is. ------------------------------------------------------------ console.log(num); // Returns 'undefined' from hoisted var declaration (not 6) var num = 6; // Initialization and declaration. console.log(num); // Returns 6 after the line with initialization is executed. ------------------------------------------------------------ console.log(num); // Throws ReferenceError exception - the interpreter doesn't know about `num`. num = 6; // Initialization
How do you know if a language is single threaded?
If the language has a single call stack. That means that functions are pushed and popped off the stack one by one, implying instructions are executed synchronously.
Type Cooercion
Refers to the process of automatic or implicit conversion of values from one data type to another
What is Hoisting?
Refers to the process of where the interpreter appears to move the declaration of variables, functions, and classes to the top of their scope prior to code being executed
Working with Sets
T o create a new set, you can pass in an iterable for the initial creation const set = new Set([1,2,3]) add: set.add(4) has: set.has(4) // returns true or false size: set.size //4 set.entries() returns value twice, i.e. SetIterator {1 => 1, 2 => 2, 3 => 3} to keep inline with map.entries. However, use set.values to just get values: SetIterator {1, 2, 3} delete: set.delete(4) //returns true or false whether it was in set and deleted or not
What is an Iterable?
Technical: Objects that implement the "iterable" protocol and have an @@iterator method (i.e. Symbol.iterator) Simple: Objects where you can use the for-of loop. Note: Not every iterable is an array. Other iterables are (for example): NodeList, String, Map, Set
let and const Hoisting
Technically they are hoisted as well but are not initialized with undefined, thus will lead to a ReferenceError as the variable value is uninitialized console.log(num); // Throws ReferenceError: Cannot access num before initialization exception as the variable value is uninitialized. Note that this is different from ReferenceError: num is not defined which is what would be thrown if the variable was not defined anywhere in the file. let num = 6;// Initialization
What is scope chain?
The JS engine will use scope chain to determine the order in which is checks for a variable. First it checks local scope, then outer scope, then global scope. If it is not found in either, then a reference error is thrown.
What happens if you have an array with a length of 2 and then set arr[5] = 'some_value'
The array will now have a length of 6 and positions 2,3,4 will all be undefined.
Explain Implicit Type Coercion in JS
The 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: Occurs with the '+' operator. When a number is added to a string the number type is always converted to the string type. Type coercion also takes place when using the '-' operator, but the difference while using '-' is that a string is converted to a number and then subtraction takes place. Boolean Coercion takes place when using logical operators, ternary operators, if statements and loop checks. Truthy values are those which will be converted(coerced) to true.
What is a hosted language in regards to js?
The browser provides an environment to run js. It provides an engine which parses the code and executes it in the end. The browser also provided many APIs which allows JavaScript to interact with the rendered HTML code.
Primitive Types
The lowest level of data built into a program and contain a single value with a fixed allocation in memory. The values themselves are immutable
What is the difference between the Rest Operator and the Spread Operator?
The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. But the spread syntax expands iterables into individual elements.
split() and join()
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and RETURNS the array. const data = 'new york;10.99;2000' const transformedData = data.split(';'); The join() method creates and RETURNS a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. const name = ['Bryce', 'Di Geronimo'] const output = name.join(' ');
-How is code Parsed and executed?
Your source code is loaded by the interpreter in the browser(built in JS engine), transforms it to byte code, and then starts to execute it line by line in an unoptimized way. Simultaneously, while the code starts running, the interpreter hands off the byte code to the JIT(just in time compiler) also built into the browser- called TurboFan in Chrome. The compilation happens side by side with the interpreter execution. Once the compilation to machine code is done, it is handed off to your computer to run in the most efficient manner. There are also some optimizations such as if the file hasn't changed, then there is no need to recompile and your computer can automatically run the most recent version of the script without recompiling.
Diff between Strongly typed languages vs Weakly typed languages?
Weakly typed languages make conversions between unrelated types implicitly; whereas, Strongly typed languages don't allow implicit conversions between unrelated types.
sort()ing and reverse()ing
When sorting an array, all values are converted to a string but then for strings, only the first character is compared by default, hence it's not '10' > '3', but '1' < '3' let prices = [10.99, 5.99, 3.99, 6.59] prices.sort((a,b) => { if(a > b) { return 1; } else if(a === b) { return 0; } else { return -1 } } However, you cannot pass a function into reverse. You just call it with arr.reverse(); *Both methods modify in place
Is JavaScript case sensitive?
Yes
-What is defer and async? When would you use both of them?
async tells the browser to execute your JavaScript asynchronously The script is fetched asynchronously, and when its ready the HTML parsing is paused to executed the script then its resumed defer tells the browser to fetch the scrypt asynchronously, and its executed on after the HTML parsing is done. If you specify both, async takes precedence on the modern browsers, while older browsers that support defer but not async will fallback to defer Link: https://medium.com/@kudzanayi/html-defer-and-async-66e4f21c2fa5
How do you delete a property in an object?
delete i.e. delete person.age; //sets it to undefined -Note, if you directly set the property to undefined, the property will still be.
Is JS a statically typed or dynamically typed language?
dynamically typed language as the type of a variable is checked during run-time in contrast to statically typed languages where the type of a variables is checked during compile-time Since JS is a dynamically typed language, variables in JS are not associated with any type. A variable can hold the value of any data type and switch as needed.
Finding items
find() const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10;); console.log(found); // expected output: 12 findIndex() const array1 = [5, 12, 8, 130, 44]; console.log(array1.findIndex(element) => element > 13;); // expected output: 3
How do you convert from a String to a Float in JS?
parseFloat(str)
-isNaN(var)
returns true or false if input is Not a Number or not