JS Part 1

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Strings -- fastest way to convert a string to number?

unary plus ( + ) it does not perform any operations on the value if it is already a number. const x = true; console.log(+x) // 1

UTF encoding -- UTF-8 && UTF-16

utf-8 and utf-16 both handle the same unicode characters, they are both variable length encodings that require up to 32 bits per character. utf-8 encodes the common characters including english and numbers using 8-bits utf-16 uses at least 16-bits for every character

Single Responsibility Principle (SRP)

"do one thing and do it well" A class (or object or function...) should only have one responsibility. This doesn't meaan that an object can only do one thing, but it does mean that everything an object does should be part of one resonsibility. A common example is the practice of separating application logic and DOM logic

Function Binding - what are the three methods to help control "this"

( 1 ) call() : calls functions - allows a function belonging to object X to be assigned and called for an object Y -- by using call(), you give the new value of this to the function so that you can write the function once and then inherit it in another object. ( 2 ) apply() : similar to call() - difference is that apply accepts the actual function's arguments as array -- good for merging arrays, identifying min/max, and borrowing functions ( 3 ) bind() : creates a new function whose this keyword sets to the provided value when the function is called. -- most practical use case is when dealing with react https://javascript.plainenglish.io/how-to-control-this-better-in-javascript-dcacd54bcf97

Arrays -- how many ways can you create an array?

( 1 ) creating an instance of array var someArr = new Array() ( 2 ) array constructor() new Array('value1', 'value2') ( 3 ) array literal var someArr = [val1, val2] ( 4 ) Array.from with an array like object Array.from( {'0':'a', '1':'b', '2':'c', 'length':3 } )

Promises -- explain the different states of promises

( 1 ) pending : the initial state or state during execution of promise. -- neither fulfilled nor rejected ( 2 ) fufilled : promise was successful ( 3 ) failure : promise failed.

Closure

** MDN : a closure is a combination of a function bundled together ( enclosed ) with references to its surrounding state - ( gives you access to an outer functions scope from an inner function )** -- closures are created every time a function is created, at function creation time. A closure is a relationship between two functions, an outer function and an inner function. ----------------------------------- *The inner function can be accessed only from statements in the outer function.* The inner function forms a closure: *the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.* This is important for privacy and the module pattern. ------------------------------------ 1. Functions are objects and can be declared anywhere 2. If I declare a function within another function, the inner function has access to the local variables of the outer function 3. Normally when a function exits, all it's local variables are destroyed, but... 4. If I hand on to the inner function in some way, the local variables function are still needed by the inner function 5. They are still in scope, so they are not garbage collected.

Hoisting

Mechanism in which variables and function declarations are moved to the top of their scope before execution. JS only hoists declarations, not initializations.

Tightly Coupled Objects -- what are they and reasons to avoid

-- tightly coupled objects are objects that rely so heavily on each other that removing or changing one will mean that you have to completely change another one. This is related to 'Single resonsibility' but takes a different angle. If we were writing a game and wanted to completely change how the UI worked, we should be able to do that without completely reworking the logic of the game.

Liskov Substitution Principle

Model your classes based on behaviors not on properties model your data based on properties and not on behaviors

Relational operators

<, <=, >, =>

Abstract equality (inequality) operators

== and != convert if their operand types do not match.

Inheritance

A feature of object oriented programming that lets programmers express the idea that some objects in a system are more specialized versions of other objects. We have two objects - both have a talk function that returns string - problem is we are writing the code essentially twice... the way to solve is through inheritance and the prototype chain.

Pure Function

A function which has no side effects. Pure functions only make changes to the calling program through their return values.

Modules

A module is a function or group of similar functions They are grouped together within a file and contain the code to execute a specific task when called into a larger application. ------------------------------------- Separate from the "module pattern", modules are a feature that arrived in ES6. Browser support is slim, it is easy to get around this by making use of the external module bundler.

Singleton

A pattern that allows you to create one instance of an object. The initialization of this object takes place only when it is needed in the program.

Polyfill

A piece of code that is used to provide modern functionality to older browsers that do not natively support it.

Private Variable -- how would you create a private variable?

A private variable is a variable that cannot be accessed outside of the function

Memoization -- pros and cons?

An optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again. If a tree is very deep you will run out of stack space because each delayed computation must be put on the stack

Tabulation

A way of processing information or data by putting it in a table

what are some ways that you would practically implement closures?

Closures give you the ability to access an outer functions scope from an inner function -- creating a closure is nothign but defining a function inside another function and exposing it. ------------------------------------- 1. event handlers : since js is async, this means that events happen at unpredictable times. Network events complete, someone connects to a server, a user clicks a button, submits a form or moves a mouse We want to set up functions to handle these events, but these functions will be called later 2. Self executing functions a.k.a. modules : by converting code into an instantly invoked function expression (just wrap braces and call it right away) the function will be called and local variables inside will remain private, only the published function will be available outside the closure. ------------------------------------- When combing closures and IIFE, there are two main benefits. ( 1 ) the scopes of variables are secured to prevent unexepected behavior. ( 2 ) you can modify variables inside the function from the outside ---- Loop Index -- executing async tasks inside a loop might lead to unexpected results. Closures are great when the values you close over are never intended to change.

Transpiling

Conversion of code from one language to another language of similar abstraction. Or from one version of a language to another version of the language with a similar level of abstraction.

Getters and Setters

Define both on any predefined core object or user-defined object that supports the addition of new properties. Uses objecft literal syntax getter : method that gets the value of a specific property. setter : method that sets the value of a specific property. A difference between using a getter or setter and using a standard function is that getters/setters are automatically invoked on assignment.

Dependency Inversion principle

Dependency injection and inversion of controls means the same thing. DIP is all about handing over control from the function itself to the caller of the function. It is defining who controls the type of parameters the function receives

Encapsulation

Encapsulation means information hiding. It's about hiding as much as possible of the objet's internal parts and exposing minimal public interface. The simplest way to create encapsulation in javascript is using closures. one of the core concepts of Obejct oriented programming refers to the bundling of data, along with the methods that operate on that data, into a single unit, very similar to how a class works. This effectively lets you only expose what is required to achieve the desired functionality,

question : a button is causing the entire application to freeze for exactly 60 seconds, what would you do to identify this bug?

First, ask for a little more clarification - when the ui freezes, does it become completely and totally unresponsive? If it is exactly 60 seconds to the millisecond, then it most likely is not a data access issue... There could be a lot of possibilities from there, especially if it is not exactly 60 seconds. A good first step would be to check where exactly the wait is happening, client or server side. From there, you could isolate the area

.call() -- explain functionality -- how is it different than .apply()

Function.prototype.call() method that calls a function with a given this value and arguments provided individually. Allows for a function or method belonging to one object to be assigned and called for a different object. almost identical to apply() except apply accepts a single array of arguments & call() accepts an argument list. i.e. arguments.call()

Open Closed Principle

Means our javascript modules should be open to extension, but closed to modification.

IIFE - what are some use cases for IIFE's ?

Immediately Invoked Function Expression : a function that runs as soon as it's defined. The Grouping Operator : fundamental to making the IIFE work. -- } () ) use cases : ( 1 ) function scoping vs. block scoping -- local variables declared using var are scoped to the enclosing function - if no function exists, variables will be created as global variables instead, thus polluting the global scope. To prevent this, create an IIFE function wrapper for local variables. ( 2 ) closures and private data ( 3 ) optimization for minification -- aliasing variable names can also be used to optimize code such that it can be minified more efficiently ( function (window, doc, undefined) { )(window, doc) }

Javascript Runtime -- how does it work

JS runtime consists of a few parts Heap : a large mostly unstructured region of memory, where variables are allocated. Call Stack : where function calls form a stack of frames. Queue : a list of messages to be processed. Each message has an associated function that gets called to handle the message. Functions from call stack are executred according to the "First in, First out" rule meaning that the function on top will be executed first.

JSON -- what is it? -- what are its common operations?

JSON : text based data format following javascript object syntax useful for transmitting data across a network ( 1 ) Parsing : converting a string to a native object JSON.parse(text) ( 2 ) Stringification : converting a native object to a string so it can be transmitted across the network. JSON.stringify(object)

Javascript Programming Paradigms

Javascript is a multi-paradigm language Supports imperative/procedurazl OOP/functional OOP w/ prototypal inheritance

Prototypal Inheritance -- three ways to implement it?

Language feature every object inherits properties and methods from its prototype object.

Nested Functions -- how are they different from closures?

Nested Functions are a side effect of closures Closures refer to the technique of preserving variables used in both the outer and inner scopes. This in turn leaves you with a nested function ( a function defined within a function )

Object oriented programming -- Is JS OOP? -- what makes a language OOP?

OOP means binding data to behavior. JS is not OOP. Javascript is a prototypal object oriented language. This means that objects in js directly inherit from other objects. Therefore we don't need classes, all we need is a way to create and extend objects. Javascript uses prototypes to define object properties, including methods and inheritance. --------------------------------- The key characteristic of an OOP language would be that it supports polymorphism. Secondly would be encapsulation (bundling of data with methods that operate on that data) Thirdly is inheritance, (specifically implementation inheritance), which javascript does provide but it is at the expense of encapsulation. If your criteria to decide whether or not a language is OOP based on the three reasons above, then javascript does not pass. ---------------------------------- programming paradigm that is about modeling a system as a collection of objects, which each prepresent some particular aspect of the system. Objects contain both function (methods) and data. An object provides a public interface to other code that wants to use it, but it maintains its own private internal state

Prototype & prototype chain

Prototypes are the mechanism by which javascript objects inherit features from one antoher. Every object has a built in property which is called prototype. The prototype itself is an object, so the prototype will have its own prototype, making what is known as the prototype chain. The chain ends when we reach a prototype that has null for its own prototype.

Coercion

the concept of forcing a value to be a certain data type. the conversion of a value from one type to another. Applies to every data type present in JS

Scope

Scope refers to the current context of code and the accessibility of variables. There exists three types of scope - local, function, and global global variables are those declared outside of a block Set of rules for looking up variables by their identifier name. It is the ability to store values and pull values out of variables Without scope, there would be no state, and without state a program would be very limited in terms of performance ( mainly # of tasks )

Lexical Scope

Scope that is defined by the JS programmer at the time of writing the code. It all comes down to where you choose to place varibales, functions, blocks, ect. This placement tells the JS engine where it should perform its LHS & RHS lookups -- (the chain of scopes it needs to move up through to find a variable)

Web Workers

Scripts that run in the background without the page needing to wait for it to complete. Useful for when you have a heavy-cost, slow operation running in your app as it wont block the js runtime while its running and allow a user to interact with the page.

Array -- how to check if an object is an array?

Since Arrays are not Primtive Data types it is not possible to use the "typeof" operator on an array directly. The best option is to use the Array.isArray([]) method.

Array Methods : sort()

Sorts the elements of an array in place. The default order is ascending - built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Logical Operators

there are three in total - they all evaluate from left to right and short circuit(...for second operator in logical statement to even be looked at - the first operand must be true). ( 1 ) AND && : operator finds the first false expression in its operands and returns it. ( 2 ) OR || : finds the first truthy expression & returns. ( 3 ) NOT ! :

SOLID principles

The basic pillars of OOP Single Responsibility Open/Closed Liskov Substitution Interface Segregation Dependency Inversion

Promises -- how to create a promise

The constructor accepts a function called the executor. the executor accepts two parameters : resolve and reject

Map object

The map objec

Promises -- what are they

The promise object represents the eventual completion or failure of an asynchronous operation. ** they are not callbacks. During async operations, they can promise to do something when that operation finishes

Data Types -- what are they?

There are 8 data types in JS, seven of which are called 'primitive' because their values only contain one thing, and that one thing is immutable. The object type is the only one that is not primitive. Objects are used to store collections of data and more complex entities. Symbol is used to create unique identifiers for objects but it is primtive. Primitive types undefined - lack of existence null - lack of existence boolean - true&false (logical) number - integer&floating string symbol - new to ES6 bigInt

Concatenate Arrays

There are several methods, some of them mutate the target array, others leave all input arrays unchanged and return new array. The clear winner is concat() while using the spread operator is superior when cloning arrays, concat is nearly 50% quicker ( 1 ) push() : mutates the target array ( 2 ) concat() : non-mutating - returns new array - can accept any amount of arguments [].concat(...arrays); ( 3 ) spread syntax in array literal : may be unsuitable for copying multidimensional arrays, as it only goes one level deep when copying the array -- recommended to use concat()

Scope : how it works

Three main processes ( 1 ) Engine : responsible for start-to-finsih compilation and execution ( 2 ) Compiler : works with engine, handles dirty work of parsing and code-generation ( 3 ) Scope : works with engine, collects and maintains a look-up list of all the declared identifiers (variables) - enforces a strict set of rules as to how these are accessible to currently executing code.

Modules -- Revealing Module Pattern Design

Variation of the module pattern Purpose is to maintain ecapsulation and reveal certain variables and methods returned in an object literal

Recursion

When a function calls itself.

Arrays -- Value of empty array

[ ] = false;

Bottleneck

a bottleneck occurs when the capacity of an algorithm or application is limited by a single component

Methods -- what are they?

a method is a bit of functionality that is built into the language or into specifc data types. They are functions stored as object properties and they implicitly pass the object on which they are called. object = { methodName: function() { // content }} object.methodName()

first-class function

a programming language is said to have first class functions when functions in that language are treated like any other variable -- they can be called within other functions

How to check that a number is NaN

isNaN(parseFloat("geoff"))

Type coercion, type conversion, typecasting, type juggling

all different names that refer to the process of converting one data type into another. type coercion : only coerces to the 'string', number, and Boolean primitive tyeps --- There is no way in Js to coerce a value type to object or function

Async/Await

an async function is a modification to the syntax used in writing promises. async functions return a promise -- if the function returns a value, the promise will be resolved with the value, but if the async function throws an error, the promise is rejected with that value

Pointer

an object that stores a memory address

Reduce method

array method - executes a user supplied 'reducer' callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element

ES6 features -- list them

arrow functions classes template strings destructuring default value spread operator let, const, var

Undefined vs null

both are falsy values null : the intentional absence of a value for an identifier or prop which has already been created. undefined : the absense of value, such as before identifier or obejct property has even been created or is in the period between creation. ------------------------------ null : object || intential undefined : data type || variable not declared or defined

Break and continue statements -- what do they do?

break : "jumps out" of a loop. - ends a loop or switch - with label reference, the break statement can be used to jump out of any { code block; } continue : "jumps over" one iteration in the loop. - breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration of a loop. break and continue are the only javascript statements that can "jump out of" a code block.

Classes -- what are the different methods to make classes?

class user { cosnt userClass = class { export default class User { export class User {

Execution context

concept which holds information about the environment within which the code is being executed. ( 1 ) creation phase : when the js engine executes a script for the first time, it create global execution context. ( GEC ) ( 2 ) execution phase : the engine executes the code line by line, assigns the values to variables, and executes the function calls. For each function call, the engine creates a new function exection context. ( FEC ) FEC is similar to GEC, but instead of creating the global object, the egine creates the arguments object that is a reference to all the parameters of the function.

Number -- how to check if num is integer?

const isInt = (num) => num % 1 === 0;

Classes -- Initialization : constructor

constructor() is a special method in the body of a class that intitializes the instance. contains one parameter (name), used to set the initial value of the field this.name Inside of constructors -- "this" is equal to the newly created instance.

Filter method

creates new array with all elements that pass the test implemented by the provided function

Object-oriented Programming

designing a program by discovering objects, their properties, and their relationships

Var, const, and let -- explain the differences

the biggest difference is how they are scoped. var is scoped globally const & let are block scoped - meaning they can only be accessed within the block that they are declared

Look-ups : LHS & RHS

don't think of it as left/right hand side assignment -- think of it as storing the value into memory and retrieving it later. e.g. when you type b in the chrome console, it starts the RHS look-up and if value is not found it returns a reference error. in contrast - if you type b = 2 into chome console, it starts LHS look-up LHS look-up (container lookup) : occurs when a variable appears on the left hand side of an assignment operation RHS look-up (value lookup) : variable appears on the right hand side.

Higher-order functions

function that receives function as an argument or returns the function as output function that accepts a function as an argument

Anonymous Functions

functions without names not accessible after initial creation, therefore, you often need to assign it to a variable let x = function() {

e.stopPropagation() vs e.preventDefault()

https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault stopPropagation prevents further propagation of the current event in the capturing and bubbling phases propagation in programming refers to the nchanging existing application code and spreading copies of the altered code to other users preventDefault prevents the default action the browser makes on that event

Callback functions - what are the two types of callbacks?

https://www.javascripttutorial.net/javascript-callback/ Functions are Objects, meaning you can pass a function to another function as an argument. There are two types of callbacks: synchronous & asynchronous synchronous: executed during the execution of the higher-order function that uses the callback asynchronous : when you use a callback to continue code execution after an asynchronous operation, the callback is called an asynchronous callback.

What are some of the downfalls of using constructors?

if you aren't careful, it can be easy to introduce bugs - - while they look just like regular functions, they do not behave like regular functions at all.

runtime binding

if your code calls a method that the compiler knows about at compile time, then it is called compile time binding. A runtime binding is something that the compiler has no idea where the method comes from.

implicit vs explicit coercion

implicit : happens when Js coerces the value type to the expected type under the hood. -- i.e. you do not notice it explicit : we want to coerce the value type to a specific type. Most of the time, explicit coercion in Js happens using built in functions such as String(), Number(), & Boolean() -- i.e. you control&manipulate into action ----------- whenever we create operations using different data types, js coerces the data for us implicitly. Most developers will avoid this and whenever possible use explicit coercion because the results can become unexpected

Objects - Explain some nuances of JS Objects

in computer science, an object is a value in memory which is possibly referenced by an identifier. In JS - Objects can be seen as a collection of properties. There are two types of object properties ( 1 ) data property : associates a key with a value ( 2 ) accessor property : associates a key with one of two accessor functions ( get & set) to retrieve or store a value.

this -- how is the value of this determined?

in most cases, it is determined by how a function is called (runtime binding) it cannot be set by assignment during execution, and it may be different each time the function is called

innerHTML -- what are some alternativaes?

innerText property for setting the value of a text node : works more or less the same as innerhtml just as a configurable text value. document.createElement : method can be used with additional methods like document.createTextNode and el.appendChild to do the same thing as innerHTML

Why learn javascript?

javascript is clear, simple, obvious, and very easily testible. Of course much of this depends on the complexity. The main reason I learned javascript is because of its ability to traverse both the front and backends of an app. Node.js is extremely powerful and well maintained, not to mention it includes the mount olympus of package managers in npm. It is built on the most reliable runtime engine ( chrome ) and the sheer amount of community resources alone make it the obvious choice if you are looking for any type of job protection. Anything that can be written in javascript, will eventually be written in javascript.

Let vs Var

let : allows you to declare variables that are limited in scope to the block, statement, or expression on which it is being used. var : defines a variable globally, or locally to an entire function regardless of block scope.

Linked list

like arrays - linked lists are linear data structures - the key difference is that linked list elements are not stored at a contiguous location; the elements are linked using pointers. -- why use them? arrays have limitations 1) the size of arrays is fixed, we must know the upper limit on the number of elements in advance. 2) inserting a new element in an array of elements is expensive because the room has to be created for the new elements and to create room - existing elements have to be shifted In linked lists - if we have the head node then we can traverse to any node through it and insert new nodes at the required position.

Javascript is a loosely typed, dynamic language -- what does this mean?

loosely typed : when you dont have to explicitly specify types of variables and objects. i.e. you dont have to tell that a string is a string, nor can you require a function to accept an integer as its parameter. dynamic languages : allow run time modification (changing the structure of a program while running) dynamic languages sacrifice efficiency for productivity. Basic variable declarations arent required to be predefined by their type.

Classes -- background

new to ES6 (along with modules) introduced as a way to expand prototype-based inheritance by adding some object oriented concepts. Created with optional constructor method ( if you want to set up default internal values ) however if you do not make explicitly call one, JS will make one by default.

parseInt() && integers

parseInt() function parses a string argument and returns an integer of specific radix(base) ---------------------------- let n = [95] let x = parseInt(n) console.log(typeof x); ---------------------------- in javascript, all numbers are floating point. floating point : a positive or negative whole number with a decimal point. 5.5 == floating point 5 == not floating point. ----------------------------- Integers are floating point numbers without a fraction

Function composition

process of combining two or more functions to produce a new function. functions f & g can be defined as f(g(x))

Reduce Method -- vs reducer function

reducer method of the array object used to reduce the array to one single value. The method executes a reducer function on each member of the array resulting in a single output value the reducer function takes four arguments : ( 1 ) accumulartor ( 2 ) current value ( 3 ) current index ( 4 ) source array reducer function return value is assigned to the accumulator, whose value is remembered across each iteration throughout the array until it utltimately becomes the final, single resulting value.

Namespacing

refers to the programming paradigm of providing scope to the identifiers (names of functions ,variables, types, ect.) to prevent collisions. namespace is context for identifiers, a logical grouping of names.

Array [1,2,3] --> [1,2,3,1,2,3]

return arr.concat(arr);

Scope chain - explain how block scope has made an impact

scope chain : always flows downwards ( func --> glob ) in Js, a variable can be accessed if it exists in the current lexical environment or in the preceding lexical environment chain which extends on to the global context. Every search ends in the Global context. Traditionally there were global and local scopes -- anything declared inside a function had local scope & anything outside had global. With the introduction of let and const in es2015 -- the scope of the variables is reduced to the block level they exist in A block -- anything wrapped in {}

Array -- how to empty an array?

set array = to empty array array = []

innerHTML -- why should you avoid it?

slow : innerhtml content is slowly built, it also causes already parsed content or content in the process of parsing to re-render along with the innerhtml element content is replace everywhere : this goes for adding, appending, delting, or modyfing content, also all of the DOM nodes inside that element are reparsed and recreated. can break the document : there is no proper validation provided by innerhtml, so any valid html code can be used. This may break the document of javascript specifically cross-site scripting : can easily be used by malicious users to manipulate and display undesirable or harmful elements within other HTML tags.

Stack

stack is a data structure with two principle operations : ( 1 ) push : add element to collection ( 2 ) pop : remove the most recent element added The two remove and add according to the last in first out principle

Event Capturing

when an event occurs on a DOM element, that event does not entirely occur on just that one element. In capturing phase, the event starts from the window all the way down to the element that triggered the event

Interface Segregation

you shouldn't create bloated interfaces. wherever you expose a module for outside use, make sure only the bare essentials are required and the rest are optional.


Ensembles d'études connexes

Algebra 2B Rational Functions Practice - Algebra 2B U3L7 Rational Functions Unit Review

View Set

Health Assessment Chapter 17 Breasts and Regional Lymphatics

View Set

Taxes, Retirement, and Other Insurance Concepts

View Set