Competitive Programming - Bit Shifting, Formulas, and More., Python Language & ML Libs (Pandas, SciKit Learn, NumPy), Mental Math, Important Math for CS (Notation, Linear Algebra, Number Theory, Foundations, Calculus, etc), Codewars in JS, Machine Le...

Competitive Programming - Bit Shifting, Formulas, and More., Python Language & ML Libs (Pandas, SciKit Learn, NumPy), Mental Math, Important Math for CS (Notation, Linear Algebra, Number Theory, Foundations, Calculus, etc), Codewars in JS, Machine Le...

memorize.aimemorize.ai (lvl 286)
Section 1

Preview this deck

Scalar official definition?

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

3

All-time users

4

Favorites

0

Last updated

4 years ago

Date created

Mar 1, 2020

Cards (488)

Section 1

(50 cards)

Scalar official definition?

Front

(of a quantity) having only magnitude, not direction.

Back

Can you assign to a const after declaring the const?

Front

No. A const promises that we won't change the value of the variable for the rest of its life and this is considered a reassignment or rewrite.

Back

The sum of powers of two is...

Front

2^(n+1) - 1

Back

How to check if a number is a power of two?

Front

(n & (n - 1)) == 0 this works because every power of 2 has just one 1 in binary

Back

pandas.DataFrame.loc

Front

Purely label-location based indexer for selection by label. .loc[] is primarily label based, but may also be used with a boolean array. Allowed inputs are: A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. A slice object with labels, e.g. 'a':'f' (note that contrary to usual python slices, both the start and the stop are included!). A boolean array. A callable function with one argument (the calling Series, DataFrame or Panel) and that returns valid output for indexing (one of the above) .loc will raise a KeyError when the items are not found.

Back

X || Y equivalent?

Front

X ∨ Y (called Vee)

Back

Bitwise Swap Intuition x = x xor y y = x xor y x = x xor y

Front

On line 1 we combine x and y (using XOR) to get this "hybrid" and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again. So, this is exactly what we do on line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped. On the last line, x still has the hybrid value. We XOR it yet again with y (now with x's original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete! The mathematics are fairly simple and work because XOR has a useful property, when you XOR A and B, you get a value C. If you XOR C and A you'll get B back, if you XOR C and B you'll get A back.

Back

Subtract one to n using bit ops

Front

~-n

Back

What does the R mean in matrices?

Front

The set of all rows x columns matrices

Back

How to detect if two integers have opposite signs?

Front

int x, y; // input values to compare signs bool f = ((x ^ y) < 0); // true iff x and y have opposite signs

Back

Divisible by 3?

Front

Add up all digits and see if divisble by 3. If so, the number is divisible by 3.

Back

How to swap two values a,b using bits?

Front

a ^= b; b ^= a; a ^= b; OR (easier to memorize) x = x xor y y = x xor y x = x xor y

Back

Import the linear regression class from Scikit

Front

from sklearn.linear_model import LinearRegression

Back

What is a vector in linear algebra?

Front

A vector is a list of numbers (can be in a row or column) - think Array. n x 1 matrix (https://en.wikipedia.org/wiki/Row_and_column_vectors)

Back

Nth term of geometric series?

Front

a_n = a_1 * r^(n-1)

Back

The sum of an arithmetic sequence?

Front

S_n = (n(a_1 + a_n))/2

Back

Get absolute value of n using bit ops?

Front

(n ^ (n >> 31)) - (n >> 31);

Back

What is an octet? Why do we use the term?

Front

An octet is a unit of digital information in computing and telecommunications that consists of eight bits. The term is often used when the term byte might be ambiguous, since historically there was no standard definition for the size of the byte.

Back

In 8-bit Two's Complement what is -1 in binary, what about -127?

Front

1111 1111

Back

pandas.Series.describe

Front

Generate various summary statistics, excluding NaN values. For numeric dtypes, it will include: count, mean, std, min, max, and lower, 50, and upper percentiles. For object dtypes (e.g. timestamps or strings), the index will include the count, unique, most common, and frequency of the most common. Timestamps also include the first and last items. For mixed dtypes, the index will be the union of the corresponding output types. Non-applicable entries will be filled with NaN. Note that mixed-dtype outputs can only be returned from mixed-dtype inputs and appropriate use of the include/exclude arguments. If multiple values have the highest count, then the count and most common pair will be arbitrarily chosen from among those with the highest count.

Back

How to toggle a bit?

Front

number ^= 1 << x;

Back

X && Y equivalent?

Front

X ∧ Y (called wedge)

Back

Divisible by 4?

Front

Check last two digits, if divisible by 4 then it is divisible by 4. Also note that all divisble by 4 numbers end in 0,4,8,2,6

Back

How to clear a bit

Front

number &= ~(1 << x);

Back

Find nth term of an arithmetic sequence?

Front

a_n = a_1 + (n-1)d

Back

How to check if the nth bit is set?

Front

if (x & (1 << n)) { //set } else { //not-set }

Back

What is left associativity?

Front

a Q b Q c If Q is left associative, then it evaluates as (a Q b) Q c And if it is right associative, then it evaluates as a Q (b Q c)

Back

pandas.DataFrame.fillna

Front

Fill NA/NaN values using the specified method - returns the filled DataFrame

Back

Commutative Property

Front

3 2 = 2 3, 5 + 3 = 3 + 5 The word "commutative" comes from "commute" or "move around", so the Commutative Property is the one that refers to moving stuff around. For addition, the rule is "a + b = b + a"; in numbers, this means 2 + 3 = 3 + 2. For multiplication, the rule is "ab = ba"; in numbers, this means 2×3 = 3×2. Any time they refer to the Commutative Property, they want you to move stuff around; any time a computation depends on moving stuff around, they want you to say that the computation uses the Commutative Property.

Back

Sum of geometric series?

Front

S_n = a_1(1-r^n)/(1-r)

Back

local variables

Front

varaibles defined inside a pair of curly braces and exist only while executing the part of the program within those braces.

Back

Matrix scalar multiplication rules?

Front

Multiply the scalar against each number in the matrix.

Back

Front

Back

How do you change the sign of an integer?

Front

~x + 1

Back

What is a nibble in Computer Programming?

Front

Half an octet, 4-bit aggregation 0xF

Back

lowercase letter convention in reference to matrices?

Front

lowercase indicates vectors, uppercase indicates matrices

Back

character literals in C++

Front

completely distinct from string literals - and always enclosed in single quotes whereas strings are always enclosed in double quotes.

Back

Matrix Addition & Subtraction rules?

Front

Two matrices may be added or subtracted only if they have the same dimension; that is, they must have the same number of rows and columns. Addition or subtraction is accomplished by adding or subtracting corresponding elements. For example, consider matrix A and matrix B.

Back

Front

Back

Explain Two's Complements

Front

Back

Nth term of arithmetic sequence?

Front

a_n = a_1 + (n-1)d

Back

What is a stream?

Front

In computer science, a stream is a sequence of data elements made available over time. A stream can be thought of as items on a conveyor belt being processed one at a time rather than in large batches Streams are processed differently from batch data - normal functions cannot operate on streams as a whole, as they have potentially unlimited data, and formally, streams are codata (potentially unlimited), not data (which is finite). Functions that operate on a stream, producing another stream, are known as filters, and can be connected in pipelines, analogously to function composition. Filters may operate on one item of a stream at a time, or may base an item of output on multiple items of input, such as a moving average. - processed one at a time rather than in batches

Back

when does a stream stop writing

Front

whitespace encounter

Back

How to set any bit?

Front

number |= 1 << x;

Back

How to fill first byte with 1's to a variable x?

Front

x |= (0xFF)

Back

Add one to n using bit ops

Front

-~n

Back

Get Max Int (Bit Ops)

Front

int maxInt = ~(1 << 31); int maxInt = (1 << 31) - 1; int maxInt = (1 << -1) - 1;

Back

How are matrices denoted? Columns then rows or rows then columns?

Front

rows x columns

Back

Get Min Int (Bit Ops)

Front

int minInt = 1 << 31; int minInt = 1 << -1;

Back

Sum of an arithmetic sequence?

Front

S_n = terms(a_1 + a_n) / 2

Back

Section 2

(50 cards)

Target Function definition?

Front

Target function: In predictive modeling, we are typically interested in modeling a particular process; we want to learn or approximate a particular function that, for example, let's us distinguish spam from non-spam email. The target function f(x) = y is the true function f that we want to model. The target function is the (unknown) function which the learning problem attempts to approximate.

Back

Classifier?

Front

Classifier: A classifier is a special case of a hypothesis (nowadays, often learned by a machine learning algorithm). A classifier is a hypothesis or discrete-valued function that is used to assign (categorical) class labels to particular data points. In the email classification example, this classifier could be a hypothesis for labeling emails as spam or non-spam. However, a hypothesis must not necessarily be synonymous to a classifier. In a different application, our hypothesis could be a function for mapping study time and educational backgrounds of students to their future SAT scores.

Back

Partial derivative notation?

Front

The partial derivative of z with respect to x. Remember that the partial derivative is a derivative of one variable wiht others held in constant.

Back

Front

contains as a member, "ni"

Back

Find the partial derivative of 3x-2y^4 with respect to x and with respect to y.

Front

you treat everything else as a constant f_x = 3 f_y = -8y^3

Back

What is an identity matrix?

Front

In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere. Multiplying by the identity matrix I doesn't change anything, just like multiplying a number by 1 doesn't change anything. This property is why I and 1 are each called the "multiplicative identity". But while there is only one "multiplicative identity" for regular numbers (namely the number 1), there are lots of different identity matrices.

Back

Supervised learning

Front

Supervised learning is a type of machine learning algorithm that uses a known dataset (called the training dataset) to make predictions. The training dataset includes input data and response values. From it, the supervised learning algorithm seeks to build a model that can make predictions of the response values for a new dataset. A test dataset is often used to validate the model. Using larger training datasets often yield models with higher predictive power that can generalize well for new datasets. Called Supervised learning BECAUSE the data is labeled with the "correct" responses.

Back

∀ meaning?

Front

for all..

Back

Front

is in, element of..

Back

Define the properties of two matrices and those particular of square matrices

Front

All Matrices Not commutative, Distributive over matrix addition Scalar multiplication is compatible with matrix multiplication, Transpose Complex Conjugate Conjugate Transpose Traces Square Matrices Identity Element - If A is a square matrix, then AI = IA = A where I is the identity matrix of the same order. Inverse Matrix - ?? Determinants - if A and B are square matrices of the same order, the determinant of their product AB equals the product of their determinants:

Back

Differential vs derivatives?

Front

Back

Regression vs Classification?

Front

Regression: the output variable takes continuous values. - Price of house given a size. Classification: the output variable takes class labels, or discrete value output - Breast cancer, malignant or benign? Almost like quantitative vs categorical

Back

What is differential calculus?

Front

In mathematics, differential calculus is a subfield of calculus concerned with the study of the rates at which quantities change. It is one of the two traditional divisions of calculus, the other being integral calculus. The primary objects of study in differential calculus are the derivative of a function, related notions such as the differential, and their applications. The derivative of a function at a chosen input value describes the rate of change of the function near that input value. The process of finding a derivative is called differentiation. Geometrically, the derivative at a point is the slope of the tangent line to the graph of the function at that point, provided that the derivative exists and is defined at that point. For a real-valued function of a single real variable, the derivative of a function at a point generally determines the best linear approximation to the function at that point.

Back

transpose matrix

Front

In linear algebra, the transpose of a matrix A is another matrix AT (also written A′, Atr, tA or At) created by any one of the following equivalent actions: reflect A over its main diagonal (which runs from top-left to bottom-right) to obtain AT write the rows of A as the columns of AT write the columns of A as the rows of AT Formally, the i th row, j th column element of AT is the j th row, i th column element of A: {\displaystyle [\mathbf {A} ^{\mathrm {T} }]_{ij}=[\mathbf {A} ]_{ji}} [\mathbf {A} ^{\mathrm {T} }]_{ij}=[\mathbf {A} ]_{ji} If A is an m × n matrix then AT is an n × m matrix.

Back

What does this hypothesis represent? h_theta(x) = theta_0 + theta_1 x

Front

univariate linear regression model

Back

Properties of matrix multiplication?

Front

Associative Trace Determinant: For square matrices only, the determinant of a product is the product of determinants:

Back

When is Matrix Multiplication commutative?

Front

... one matrix is the Identity matrix. ... one matrix is the Zero matrix. ... both matrices are rotation matrices. (basically case #2) ... both matrices are Diagonal matrices.

Back

Synonym for Input variable?

Front

Features

Back

Cocktail party effect/problem

Front

The cocktail party effect is the phenomenon of being able to focus one's auditory attention on a particular stimulus while filtering out a range of other stimuli, much the same way that a partygoer can focus on a single conversation in a noisy room. Example of source separation.

Back

Front

superset of or equal to

Back

why did they name this subject calculus?

Front

It's from the Latin meaning reckon or account (like calculate), which came from using pebbles (calx) to count with.

Back

Cost function vs Gradient Descent?

Front

A cost function is something you want to minimize. For example, your cost function might be the sum of squared errors over your training set. Gradient descent is a method for finding the minimum of a function of multiple variables. So you can use gradient descent to minimize your cost function. If your cost is a function of K variables, then the gradient is the length-K vector that defines the direction in which the cost is increasing most rapidly. So in gradient descent, you follow the negative of the gradient to the point where the cost is a minimum. If someone is talking about gradient descent in a machine learning context, the cost function is probably implied (it is the function to which you are applying the gradient descent algorithm).

Back

Differentials?

Front

Back

A square matrix that is not invertible is called ..

Front

singular or degenerate

Back

Does the order of operations matter in Matrices?

Front

yes

Back

What is a zero matrix?

Front

n mathematics, particularly linear algebra, a zero matrix or null matrix is a matrix with all its entries being zero. Acts as the additive identity.

Back

Check for even or odd number using bits

Front

x&1 ? "odd" : "even"

Back

Learning algorithm?

Front

Learning algorithm: Again, our goal is to find or approximate the target function, and the learning algorithm is a set of instructions that tries to model the target function using our training dataset. A learning algorithm comes with a hypothesis space, the set of possible hypotheses it can come up with in order to model the unknown target function by formulating the final hypothesis

Back

Derivatives?

Front

a derivative is the rate of change of a function with respect to changes in its variable

Back

Simplify 2(3x), and justify your steps.

Front

2(3x) original (given) statement (2×3)x by the Associative Property 6x simplification (2×3 = 6)

Back

Training sample definition?

Front

Training sample: A training sample is a data point x in an available training set that we use for tackling a predictive modeling task. For example, if we are interested in classifying emails, one email in our dataset would be one training sample. Sometimes, people also use the synonymous terms training instance or training example.

Back

Why is the following true? 2(x + y) = 2x + 2y

Front

Since they distributed through the parentheses, this is true by the Distributive Property.

Back

What is Leibniz's notation for differentiation and antidifferentiation? What is Newton's notation?

Front

Back

Partial derivative?

Front

In mathematics, a partial derivative of a function of several variables is its derivative with respect to one of those variables, with the others held constant (as opposed to the total derivative, in which all variables are allowed to vary). Partial derivatives are used in vector calculus and differential geometry.

Back

Differential calculus intuition

Front

It answers the question how fast things are changing (instantaneous) at a certain point in time rather than across a long period of time. This is where we attempt to find the slope at a point by using a tangent line. Because we cannot find the slope at a particular point to be precise, we do this by approaching a difference of zero when finding rise over run.

Back

Front

subset of or equal to

Back

Find the odd int - Given an array, find the int that appears an odd number of times. There will always be only one integer that appears an odd number of times.

Front

function findOdd(A) { var searched = []; for (let i = 0; i < A.length; i++){ var index = searched.findIndex((val) => A[i] ===val[0]); if (index === -1){ var pair = []; pair.push(A[i]); //element pair.push(1); //count searched.push(pair); } else { searched[index][1]++; } }; console.log(searched); for (let i = 0; i < searched.length; i++){ if (searched[i][1] % 2 === 1) return searched[i][0]; } return 0; }

Back

What is "hypothesis" in machine learning?

Front

Hypothesis: A hypothesis is a certain function that we believe (or hope) is similar to the true function, the target function that we want to model. In context of email spam classification, it would be the rule we came up with that allows us to separate spam from non-spam emails.

Back

Model definition?

Front

Model: In machine learning field, the terms hypothesis and model are often used interchangeably. In other sciences, they can have different meanings, i.e., the hypothesis would be the "educated guess" by the scientist, and the model would be the manifestation of this guess that can be used to test the hypothesis.

Back

Matrix multiplication?

Front

The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix. And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix. remember matrix multiplication does not have the commutative property. Use the Dot Product to get each value for matrix multiplication.

Back

Distributive Property

Front

The Distributive Property is easy to remember, if you recall that "multiplication distributes over addition". Formally, they write this property as "a(b + c) = ab + ac". In numbers, this means, that 2(3 + 4) = 2×3 + 2×4. Any time they refer in a problem to using the Distributive Property, they want you to take something through the parentheses (or factor something out); any time a computation depends on multiplying through a parentheses (or factoring something out), they want you to say that the computation used the Distributive Property.

Back

Clustering

Front

a method of unsupervised learning - a good way of discovering unknown relationships in datasets. Cluster analysis or clustering is the task of grouping a set of objects in such a way that objects in the same group (called a cluster) are more similar (in some sense or another) to each other than to those in other groups (clusters). It is a main task of exploratory data mining, and a common technique for statistical data analysis, used in many fields, including machine learning, pattern recognition, image analysis, information retrieval, bioinformatics, data compression, and computer graphics. Cluster analysis itself is not one specific algorithm, but the general task to be solved. It can be achieved by various algorithms that differ significantly in their notion of what constitutes a cluster and how to efficiently find them. Popular notions of clusters include groups with small distances among the cluster members, dense areas of the data space, intervals or particular statistical distributions. Clustering can therefore be formulated as a multi-objective optimization problem. The appropriate clustering algorithm and parameter settings (including values such as the distance function to use, a density threshold or the number of expected clusters) depend on the individual data set and intended use of the results. Cluster analysis as such is not an automatic task, but an iterative process of knowledge discovery or interactive multi-objective optimization that involves trial and failure. It is often necessary to modify data preprocessing and model parameters until the result achieves the desired properties.

Back

3x4 matrix * 4x1 vector result is...

Front

3x1 matrix

Back

∂ meaning?

Front

partial, often used for partial differentials

Back

Associative Property

Front

The word "associative" comes from "associate" or "group";the Associative Property is the rule that refers to grouping. For addition, the rule is "a + (b + c) = (a + b) + c"; in numbers, this means 2 + (3 + 4) = (2 + 3) + 4. For multiplication, the rule is "a(bc) = (ab)c"; in numbers, this means 2(3×4) = (2×3)4. Any time they refer to the Associative Property, they want you to regroup things; any time a computation depends on things being regrouped, they want you to say that the computation uses the Associative Property.

Back

Use the Distributive Property to rearrange: 4x - 8

Front

Back

Unsupervised learning

Front

Unsupervised learning is the machine learning task of inferring a function to describe hidden structure from unlabeled data. Since the examples given to the learner are unlabeled, there is no error or reward signal to evaluate a potential solution. This distinguishes unsupervised learning from supervised learning and reinforcement learning. Unsupervised learning is closely related to the problem of density estimation in statistics.[1] However unsupervised learning also encompasses many other techniques that seek to summarize and explain key features of the data.

Back

Synonym for output variable?

Front

Targets

Back

What is ceteris paribus?

Front

All other things equal, all else unchanged, etc (think partial derivative)

Back

Front

therefore

Back

Section 3

(50 cards)

Linear regression formula?

Front

Back

ATTRIBUTE_NODE example?

Front

e.g. class="funEdges"

Back

Convex functions?

Front

In mathematics, a real-valued function defined on an interval is called convex (or convex downward or concave upward) if the line segment between any two points on the graph of the function lies above or on the graph, in a Euclidean space (or more generally a vector space) of at least two dimensions. Equivalently, a function is convex if its epigraph (the set of points on or above the graph of the function) is a convex set. Well-known examples of convex functions include the quadratic function {\displaystyle x^{2}} x^{2} and the exponential function {\displaystyle e^{x}} e^{x} for any real number x. Convex functions play an important role in many areas of mathematics. They are especially important in the study of optimization problems where they are distinguished by a number of convenient properties. For instance, a (strictly) convex function on an open set has no more than one minimum.

Back

What is SSE?

Front

The sum of squared error

Back

DOCUMENT_NODE example?

Front

window.document

Back

"Batch" Gradient Descent (BGD or GD)

Front

Each step of gradient descent uses all the training examples. batch GD - This is different from (SGD - stochastic gradient descent or MB-GD - mini batch gradient descent) In GD optimization, we compute the cost gradient based on the complete training set; hence, we sometimes also call it batch GD. In case of very large datasets, using GD can be quite costly since we are only taking a single step for one pass over the training set -- thus, the larger the training set, the slower our algorithm updates the weights and the longer it may take until it converges to the global cost minimum (note that the SSE cost function is convex).

Back

Inflection points

Front

Inflection points are where the function changes concavity. Since concave up corresponds to a positive second derivative and concave down corresponds to a negative second derivative, then when the function changes from concave up to concave down (or vise versa) the second derivative must equal zero at that point. So the second derivative must equal zero to be an inflection point. But don't get excited yet. You have to make sure that the concavity actually changes at that point.

Back

Derive SSE

Front

Given a linear regression model, the difference at each predicted point with the correct point is given by diff = y_i - (mx + b)

Back

DOCUMENT_TYPE_NODE

Front

<!DOCTYPE html>

Back

What are first order methods in numerical analysis?

Front

In numerical analysis, methods that have at most linear local error are called first order methods. They are frequently based on finite differences, a local linear approximation.

Back

What is the purpose of the DOM?

Front

to provide a programatic interface for scripting (removing, adding, replacing, eventing, modifiying) this live document using JavaScript.

Back

What is the downside of using an alpha (learning rate) that is too big?

Front

Gradient descent can overshoot the minimum and it may fail to converge or even diverge.

Back

Gradient Descent algorithm

Front

Image result for gradient descent Gradient descent is a first-order optimization algorithm. To find a local minimum of a function using gradient descent, one takes steps proportional to the negative of the gradient (or of the approximate gradient) of the function at the current point. used with simultaneous updates of the parameters of success Susceptible to falling into local optimum depending on initialization.

Back

What is overfitting?

Front

In statistics and machine learning, one of the most common tasks is to fit a "model" to a set of training data, so as to be able to make reliable predictions on general untrained data. In overfitting, a statistical model describes random error or noise instead of the underlying relationship. Overfitting occurs when a model is excessively complex, such as having too many parameters relative to the number of observations. A model that has been overfit has poor predictive performance, as it overreacts to minor fluctuations in the training data. how to avoid overfitting? cross-validation, regularization, early stopping, pruning, Bayesian priors on parameters or model comparison and more!

Back

What happens if you initialize a parameter at a local minimum and attempt to use gradient descent on it?

Front

The derivative turns out to be zero because the tangent is a flat line meaning that regardless of alpha it is multiplied by zero, indicating no change.

Back

What letter is typically used to depict a cost function?

Front

Function J

Back

multivariate linear regression

Front

ask: why is the notation shorter and what does that convenience notation indicate?

Back

What is the downside of using an alpha (learning rate) that is too small?

Front

Gradient descent can be way too slow.

Back

What is feature scaling?

Front

Feature scaling is a method used to standardize the range of independent variables or features of data. In data processing, it is also known as data normalization and is generally performed during the data preprocessing step. The range of values of raw data varies widely, in some machine learning algorithms, objective functions will not work properly without normalization[citation needed]. For example, the majority of classifiers calculate the distance between two points by the Euclidean distance[citation needed]. If one of the features has a broad range of values, the distance will be governed by this particular feature[citation needed]. Therefore, the range of all features should be normalized so that each feature contributes approximately proportionately to the final distance[citation needed]. Another reason why feature scaling is applied is that gradient descent converges much faster with feature scaling than without it[citation needed]. Some methods are rescaling, standardization, scaling to unit length.

Back

What is cross-validation?

Front

Cross-validation, sometimes called rotation estimation,[1][2][3] is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly used in settings where the goal is prediction, and one wants to estimate how accurately a predictive model will perform in practice. In a prediction problem, a model is usually given a dataset of known data on which training is run (training dataset), and a dataset of unknown data (or first seen data) against which the model is tested (testing dataset).[4] The goal of cross validation is to define a dataset to "test" the model in the training phase (i.e., the validation dataset), in order to limit problems like overfitting, give an insight on how the model will generalize to an independent dataset (i.e., an unknown dataset, for instance from a real problem), etc.

Back

Why is it unnecessary to change alpha over time to ensure that the gradient descent converges to a local minimum?

Front

As we approach a local minimum, the gradient descent will take smaller steps because of the change of the derivative or the steepness of the cost function J. Don't need to worry about divergence.

Back

TEXT_NODE example?

Front

text characters in an html document including carriage returns and white space

Back

What does theta typically represent in stat/ML?

Front

quite often θ stands for the set of parameters of a distribution.

Back

Node.appendChild()

Front

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). Returns the appended child. var addCourseToDom = function addCourseToDom(course){ var li = document.createElement("li"); var text = document.createTextNode(course.title); li.appendChild(text); var placeToAdd = document.getElementById("courses"); placeToAdd.appendChild(li); return "added " + li; }

Back

x^i_j notation in ML means?

Front

an index into a training set for the ITH training example and JTH feature (input variable)

Back

What is the structure of node objects in the DOM typically compared to?

Front

A Tree

Back

3D Surface Plot - how can it be used to plot the cost function?

Front

Theta 0 and Theta 1 in a univariate linear regression can be plotted on the x and y axes. the Z axis will indicate the actual cost

Back

Why do we square instead of using the absolute value when calculating variance and standard deviation?

Front

First I'll answer the mathematical question asked in the question details, which I'm going to restate because I think it is stated wrong: The short answer is "Because of Jensen's inequality." See http://en.wikipedia.org/wiki/Jen... and the rest of the article for context. It says in particular that for a concave function What about the more general question, "Why variance?" I don't believe there is any compelling conceptual reason to use variance as a measure of spread. If forced to choose, my guess is that most people would say more robust measures like interquartile range or MAD better capture the concept of "spread" in most cases. But variance (and more generally "sum of squares") has some attractive properties, many of which flow from the Pythagorean theorem one way or another. Here some of them, without much math: We can decompose sums of squares into meaningful components like "between group variance" and "within-group variance." To generalize the above point, when a random variable Y Y is partly explained by another random variable X X there is a useful decomposition of the variance of Y Y into the part explained by X X and the unexplained part. (See http://en.wikipedia.org/wiki/Law...). If we think more broadly about mean squared error, this too can be decomposed into the sum of variance and squared bias. It is easy to interpret this total error as the sum of "systematic error" and "noise." Often we want to minimize our error. When the error is a sum of squares, we are minimizing something quadratic. This is easily accomplished by solving linear equations. So yes, variance and mean squared error are conveniences rather than conceptual necessities. But they are convenient conveniences.

Back

What does J(Theta) increasing tell you about ur gradient descent?

Front

it's not working lol. use a bigger alpha. on the other end if you use too big of an alpha you'll end up with a bowl shaped curve and you might be moving farther away from convergence.

Back

What is the formula for theta in a normal equation?

Front

Back

Higher derivatives?

Front

Let f be a differentiable function, and let f ′(x) be its derivative. The derivative of f ′(x) (if it has one) is written f ′′(x) and is called the second derivative of f. Similarly, the derivative of a second derivative, if it exists, is written f ′′′(x) and is called the third derivative of f. Continuing this process, one can define, if it exists, the nth derivative as the derivative of the (n-1)th derivative. These repeated derivatives are called higher-order derivatives. The nth derivative is also called the derivative of order n.

Back

What does it mean for an algorithm to converge?

Front

An iterative algorithm is said to converge when as the iterations proceed the output gets closer and closer to a specific value. In some circumstances, an algorithm will diverge; its output will undergo larger and larger oscillations, never approaching a useful result. The "converge to a global optimum" phrase in your first sentence is a reference to algorithms which may converge, but not to the "optimal" value (e.g. a hill-climbing algorithm which, depending on initial conditions, may converge to a local maximum, never reaching the global maximum).

Back

hypothesis model

Front

remember that the HYPOTHESIS MODEL or SET is what is depicted with h(theta)

Back

What is a nodeType in regards to DOM nodes?

Front

The nodeType property can be used to distinguish different kind of nodes, such that elements, text and comments, from each other. -- basically a number system for the types of nodes there are.

Back

SSE formula?

Front

observation - mean for each observation squared.

Back

What are contour plots?

Front

A contour plot is a graphical technique for representing a #D surface by plotting constant z slices, called contours onto a 2Dimensional format. That is, given a value for z, lines are drawn for connecting the x,y, coordinates twhere that z value occurs. The circles in a contour plot are called level sets - the function J is equal here.The center of the contour plot is the minimum of the cost function typically in ML.

Back

DOCUMENT_FRAGMENT_NODE

Front

e.g. document.createDocumentFragment() The DocumentFragment interface represents a minimal document object that has no parent. It is used as a light-weight version of Document to store well-formed or potentially non-well-formed fragments of XML. DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node. Doing so allows developers to produce structure without doing so within the visible DOM -- an increase of speed is the true advantage. Let me show you how DocumentFragments are used!

Back

why use features that are on a similar scale?

Front

contour plots with differently scaled features will be extremely thin or extremely fat resulting in a very slow gradient descent (convergence is slower) get them to a -1 <= x <= 1 scale. poorly scaled is too large -100 to 100 or -0.00001 or 0.00001

Back

K-Fold?

Front

In k-fold cross-validation, the original sample is randomly partitioned into k equal sized subsamples. Of the k subsamples, a single subsample is retained as the validation data for testing the model, and the remaining k − 1 subsamples are used as training data. The cross-validation process is then repeated k times (the folds), with each of the k subsamples used exactly once as the validation data. The k results from the folds can then be averaged to produce a single estimation. The advantage of this method over repeated random sub-sampling (see below) is that all observations are used for both training and validation, and each observation is used for validation exactly once. 10-fold cross-validation is commonly used,[7] but in general k remains an unfixed parameter. When k=n (the number of observations), the k-fold cross-validation is exactly the leave-one-out cross-validation. In stratified k-fold cross-validation, the folds are selected so that the mean response value is approximately equal in all the folds. In the case of a dichotomous classification, this means that each fold contains roughly the same proportions of the two types of class labels. Ultimately this helps fix the problem that we want to maximize both the training and test sets in cross-validation.

Back

For a sufficiently small alpha...

Front

J(Theta) should decrease EVERY iteration

Back

Standardization vs normalization

Front

Normalization rescales the values from to a range of [0,1]. This might useful in some cases where all parameters need to have the same positive scale, but outliers from data set are lost. Xchanged = (X - Xmin)/(Xmax-Xmin) Standardization rescales data to have a mean of 0 and standard deviation of 1 (unit variance). Xchanged = (x-mean)/sd For most applications standardization is recommended. In the business world, "normalization" typically means that the range of values are "normalized to be from 0.0 to 1.0". "Standardization" typically means that the range of values are "standardized" to measure how many standard deviations the value is from its mean. However, not everyone would agree with that. It's best to explain your definitions before you use them. In any case, your transformation needs to provide something useful.

Back

What to do when J(Theta) is moving up and down in waves ?

Front

Use a smaller Alpha!!

Back

How to make sure gradient descent is working properly?

Front

create an automatic convergence test - declare convergence based on amount of decrease of J(Theta) plot on graph, y axis being J and axis being number of iterations.

Back

Cubic functions...

Front

Back

What is a simple linear regression?

Front

In statistics, simple linear regression is the least squares estimator of a linear regression model with a single explanatory variable. In other words, simple linear regression fits a straight line through the set of n points in such a way that makes the sum of squared residuals of the model (that is, vertical distances between the points of the data set and the fitted line) as small as possible. minimize squared error

Back

What is normalization?

Front

In statistics and applications of statistics, normalization can have a range of meanings.[1] In the simplest cases, normalization of ratings means adjusting values measured on different scales to a notionally common scale, often prior to averaging. In more complicated cases, normalization may refer to more sophisticated adjustments where the intention is to bring the entire probability distributions of adjusted values into alignment. In the case of normalization of scores in educational assessment, there may be an intention to align distributions to a normal distribution. A different approach to normalization of probability distributions is quantile normalization, where the quantiles of the different measures are brought into alignment.

Back

ELEMENT_NODE example?

Front

<body>, <a>, <p>, <script>, <style>, <html>, <h1>

Back

Definition of stochastic?

Front

randomly determined; having a random probability distribution or pattern that may be analyzed statistically but may not be predicted precisely.

Back

What does the derivative of a function tell us?

Front

The derivative of a function of a real variable measures the sensitivity to change of a quantity (a function value or dependent variable) which is determined by another quantity (the independent variable). Derivatives are a fundamental tool of calculus. For example, the derivative of the position of a moving object with respect to time is the object's velocity: this measures how quickly the position of the object changes when time is advanced. The derivative of a function of a single variable at a chosen input value, when it exists, is the slope of the tangent line to the graph of the function at that point. The tangent line is the best linear approximation of the function near that input value. For this reason, the derivative is often described as the "instantaneous rate of change", the ratio of the instantaneous change in the dependent variable to that of the independent variable.

Back

Gradient Descent for linear regression?

Front

(Review again)

Back

Section 4

(50 cards)

What is a side effect?

Front

In computer science, a function or expression is said to have a side effect if it modifies some state or has an observable interaction with calling functions or the outside world. For example, a particular function might modify a global variable or static variable, modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions. In the presence of side effects, a program's behaviour may depend on history; that is, the order of evaluation matters. Understanding and debugging a function with side effects requires knowledge about the context and its possible histories

Back

AJS: With function?

Front

The with statement extends the scope chain for a statement. One way to create dynamic scope "with is typically explained as a short-hand for making multiple property references against an object without repeating the object reference itself each time." Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks.

Back

AJS: What scope does JS have as specifically as possible?

Front

Lexical scoping with function scope.

Back

EventTarget.addEventListener()

Front

The EventTarget.addEventListener() method registers the specified listener on the EventTarget it's called on. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest). target.addEventListener(type, listener[, options]); target.addEventListener(type, listener[, useCapture]); type A string representing the event type to listen for. listener The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be an object implementing the EventListener interface, or simply a JavaScript function.

Back

Document.createElement()

Front

var element = document.createElement(tagName); element is the created Element object. tagName is a string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don't use qualified names (like "html:a") with this method.

Back

why use Array.prototype.forEach when iterating with side effects?

Front

forEach has an "undefined" return value always. MAP, being a functional programming method is much better suited when creating a pure function. For non-pure iterative functions forEach makes sense. The predicate here should produce a side effect. immutability is promoted with FP and can be exhibited when using map. That is map doesnt mutate the given array, only creates a new array as a copy of the given and then modifies it. example: function logValue(v) {console.log(v);} forEach(arr,logValue);

Back

When were React and ReactDOM split?

Front

React and ReactDOM were only recently split into two different libraries. Prior to v0.14, all ReactDOM functionality was part of React. This may be a source of confusion, since any slightly dated documentation won't mention the React / ReactDOM distinction. As the name implies, ReactDOM is the glue between React and the DOM. Often, you will only use it for one single thing: mounting with ReactDOM.render(). Another useful feature of ReactDOM is ReactDOM.findDOMNode() which you can use to gain direct access to a DOM element. (Something you should use sparingly in React apps, but it can be necessary.) If your app is "isomorphic", you would also use ReactDOM.renderToString() in your back-end code. For everything else, there's React. You use React to define and create your elements, for lifecycle hooks, etc. i.e. the guts of a React application. The reason React and ReactDOM were split into two libraries was due to the arrival of React Native. React contains functionality utilised in web and mobile apps. ReactDOM functionality is utilised only in web apps. [UPDATE: Upon further research, it's clear my ignorance of React Native is showing. Having the React package common to both web and mobile appears to be more of an aspiration than a reality right now. React Native is at present an entirely different package.] See the blog post announcing the v0.14 release: https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html

Back

Document.createElement

Front

In an HTML document, the Document.createElement() method creates the specified HTML element or an HTMLUnknownElement if the given element name isn't a known one.

Back

Node.insertBefore()

Front

The Node.insertBefore() method inserts the specified node before the reference node as a child of the current node.

Back

AJS: What's the difference between undeclared and undefined?

Front

Undefined IS a value -- empty placeholder -- indicates that there was a declared variable. Undeclared means it hasnt been registered in the scope when the compiler runs through in phase 1.

Back

How to access component properties?

Front

this.props

Back

AJS: IIFE mainstream use?

Front

Used to hide things in anonymous functions within a function expression. The compiler will treat it as a function expression. Recommended to name IIFE for stack tracing purposes. Because the point of the parens or coercing operators is to disambiguate between function expressions and function declarations, they can be omitted when the parser already expects an expression (but please see the

Back

What is the difference between a deep copy and a shallow copy?

Front

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Back

Document.createTextNode(data)

Front

Back

AJS: What is the official transpiler for TC39?

Front

Traceur maintained by Google. But it only features ES.next features and not future feature sets like Babel does.

Back

What is a lambda expression?

Front

lambda expression in computer programming, also called anonymous function, a function (or a subroutine) defined, and possibly called, without being bound to an identifier Lambda Expressions are nameless functions given as constant values. They can appear anywhere that any other constant may, but are typically written as a parameter to some other function. The canonical example is that you'll pass a comparison function to a generic "sort" routine, and instead of going to the trouble of defining a whole function (and incurring the lexical discontinuity and namespace pollution) to describe this comparison, you can just pass a lambda expression describing the comparison. HOWEVER, this misses one of the most important features of Lambda Expressions, which is that they execute in the context of their appearance. Therefore, they can use the values of the variables that are defined in that context. This differentiates function-pointers from true lambda expressions. In languages supporting mutable variables, proper lambda expressions offer the power change the values of those variables. Lambda expressions are rooted in lambda calculus.

Back

Nobody complains when you mop the floor.

Front

Do work that is undesired. Don't ask. It's an asset.

Back

AJS: What are the four ways that the <this> keyword can be called?

Front

1. New Keyword 2. Explicit/Hard Binding 3. Implicit Binding Rule: turns into the object that invoked the function -- o2 = {bar: "bar2", foo: foo}; 4 (least precedence). normal function call : default binding rule - if you are in strict mode, this is undefined if not, then this is the global object. 1. Default Binding - (catch all) - plain, un-decorated function reference - goes to global or undefined depending on strict mode settings 2. Implicit Binding - calling a function off an object obj1.foo() where foo can be defined anywhere - goes to the object that is calling it 3a. Explicit Binding - explicitly defining the this reference using call or apply ``` function foo(){ console.log(this.a); } var obj = { a: 2 }; foo.call(obj); ``` how does "boxing" work? 3b. Hard Binding - solves the possibility of explicit or any binding losing its intended binding - you can implement using Function.prototype.bind, a helper function, function wrapping or any other mechanism ``` function foo(){ console.log(this.a); } var obj = { a : 2; }; var bar = function(){ foo.call( obj); }; bar(); // 2 setTimeout(bar, 100); //2 bar.call(window); // 2 ``` 4. New Keyword - As a new object created via constructor call hijacking via "new"

Back

AJS: What are the different ways to create a new scope?

Front

Catch blocks, curly braces with <let> in ES6, functions.

Back

How to iterate across an object with side effects?

Front

use the for... in loop while checking .hasOwnProperty because for...in will check parents as well.

Back

Document.querySelector(String selector)

Front

returns the first element node within the document in document order that matches the specified selectors.

Back

How to remove elements from the DOM?

Front

Back

Why use one line functions?

Front

Don't be scared of 1-line functions! A lot of programmers seem to have a mental block about 1-line functions, you shouldn't. If it makes the code clearer and cleaner, extract the line into a function. Performance probably won't be affected. Any decent compiler made in the last decade (and perhaps further) will automatically inline a simple 1-line function. Also, 1-line of C can easily correspond to many lines of machine code. You shouldn't assume that even in the theoretical case where you incur the full overhead of a function call that this overhead is significant compared to your "one little line". Let alone significant to the overall performance of your application. Abstraction Leads to Better Design. (Even for single lines of code) Functions are the primary building blocks of abstract, componentized code, they should not be neglected. If encapsulating a single line of code behind a function call makes the code more readable, do it. Even in the case where the function is called once. If you find it important to comment one particular line of code, that's a good code smell that it might be helpful to move the code into a well-named function. Sure, that code may be 1-line today, but how many different ways of performing the same function are there? Encapsulating code inside a function can make it easier to see all the design options available to you. Maybe your 1-line of code expands into a call to a webservice, maybe it becomes a database query, maybe it becomes configurable (using the strategy pattern, for example), maybe you want to switch to caching the value computed by your 1-line. All of these options are easier to implement and more readily thought of when you've extracted your 1-line of code into its own function. Maybe Your 1-Line Should Be More Lines. If you have a big block of code it can be tempting to cram a lot of functionality onto a single line, just to save on screen real estate. When you migrate this code to a function, you reduce these pressures, which might make you more inclined to expand your complex 1-liner into more straightforward code taking up several lines (which would likely improve its readability and maintainability).

Back

AJS: IIFE syntax ways

Front

(function(){ / code / })(); - ben alman and many others (function(){ / code / }()); - crockford

Back

AJS: What type of scoping rule(s) does JS have? What are the exceptions?

Front

Lexical, exceptions being <eval> and <with>

Back

AJS: <with> keyword

Front

The with statement extends the scope chain for a statement.

Back

How do event handlers work?

Front

http://stackoverflow.com/questions/7575589/how-does-javascript-handle-ajax-responses-in-the-background/7575649#7575649 it uses a queue - event loop other systems often use the polling mechanism and/or observer pattern

Back

AJS: What is lexical scope? (Kyle Simpson)

Front

Lexical scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by you, at write time, and thus is mostly set in stone by the time the lexer processes the code.

Back

AJS: Why is the <let> keyword stylistically good for <for> loops?

Front

Because <let> indicates in the code that the variable being created is meant to only exist within that loop. For example, counters like (var i = 0; i < whatever; i++) indicates that, but does not functionally restrict access to i within that loop or block.

Back

Array.prototype.slice vs Array.prototype.slice is a good demonstration of what?

Front

A pure function vs a non-pure function. arr.slice([begin[, end]]) --> begin is zero-indexed, end is zero-indexed but is not included in the slice. slice does NOT alter the given array. It returns a shallow copy of elements from the original array. array.splice(start, deleteCount[, item1[, item2[, ...]]]) --> start is the beginning index to start changing the array, deleteCount is the number of elements to delete, items are anything to be added var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; // removes 0 elements from index 2, and inserts 'drum' var removed = myFish.splice(2, 0, 'drum'); // myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removed is [], no elements removed // myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon'] // removes 1 element from index 3 removed = myFish.splice(3, 1); // myFish is ['angel', 'clown', 'drum', 'surgeon'] // removed is ['mandarin'] // myFish is ['angel', 'clown', 'drum', 'surgeon'] // removes 1 element from index 2, and inserts 'trumpet' removed = myFish.splice(2, 1, 'trumpet'); // myFish is ['angel', 'clown', 'trumpet', 'surgeon'] // removed is ['drum'] // myFish is ['angel', 'clown', 'trumpet', 'surgeon'] // removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue' removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue'); // myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removed is ['angel', 'clown'] // myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon'] // removes 2 elements from index 2 removed = myFish.splice(myFish.length -3, 2); // myFish is ['parrot', 'anemone', 'surgeon'] // removed is ['blue', 'trumpet']

Back

Array.prototype.concat - does it mutate the given array?

Front

Nah, creates a new one. See specs: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.4

Back

AJS: How to avoid pollution of namespace while hiding some variables?

Front

IIFE

Back

What does Document.createElement() return?

Front

the element that is created.

Back

AJS: (function ($) { $(document).ready(function () { // my code }); })(jQuery);

Front

this technique is used to rename different globals appropriately, i.e. conflict of prototype and JQuery using $

Back

React.createClass accepts?

Front

one argument, an object of which the only property required is the render function

Back

How to set an attribute on an element in Pure JS DOM?

Front

Element.setAttribute() -- element.setAttribute(name, value); name is the name of the attribute as a string. value is the desired new value of the attribute.

Back

Kyle Simpson's public API classic Module way?

Front

have a variable called publicAPI that is returned as an object. it holds a reference this way and is clear on what is happening. this way you can modify at runtime. whereas if you had an anonymous return value you cannot do so.

Back

Who founded Lambda Calculus?

Front

Alonzo Church (1930)

Back

Node.appendChild()

Front

Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

Back

Document.getElementsByClassName()

Front

var elements = document.getElementsByClassName(names); // or: var elements = rootElement.getElementsByClassName(names); elements is a live HTMLCollection of found elements. names is a string representing the list of class names to match; class names are separated by whitespace getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.

Back

Pure Function conditions

Front

In computer programming, a function may be considered a pure function if both of the following statements about the function hold: The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change while program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices (usually—see below). Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices (usually—see below).

Back

AJS: Why use .call(this) for IIFE's?

Front

function Foo() { (function () { console.log(this); // > Foo }).call(this); (function () { console.log(this); // > undefined in strict mode, or Window in non strict mode })(); } var bar = new Foo; Also here (Non-iife): function identify() { return this.name.toUpperCase(); } function speak() { var greeting = "Hello, I'm " + identify.call(this); console.log(greeting); } var me = { name: "Kyle" } identify.call(me)

Back

AJS: Eval function? What's it do? Why is it good or bad?

Front

The eval() function evaluates JavaScript code represented as a string. It's a way to cheat Lexical Scope "The eval(..) function in JavaScript takes a string as an argument, and treats the contents of the string as if it had actually been authored code at that point in the program. " Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks. "function foo(str, a) { eval( str ); // cheating! console.log( a, b ); } var b = 2; foo( "var b = 3;", 1 ); // 1, 3" Excerpt From: Riley Gelwicks. "You Dont Know JS by Kyle Simpson." iBooks.

Back

AJS: Two keywords that cheat lexical scope?

Front

eval, with

Back

AJS: What feature had block scope back in ES3?

Front

Try and Catch Blocks. Specifically, just the catch blocks. Unfortunately, JSLint and JSHint and many other linters don't pick up on this and may throw errors.

Back

What is a Node?

Front

A Node is an interface from which a number of DOM types inherit and allow these various types to be treated or tested similarly.

Back

What are the mutative array functions in Javascript?

Front

push, pop, shift, unshift, sort, reverse, splice and delete (kind of).

Back

AJS: What is the definition of Closure (Kyle Simpson's)?

Front

Closure is when a function remembers its lexical scope even when the function is executed outside of that lexical scope.

Back

What function should you use when intentionally iterating with a predicate that produces side effects?

Front

Array.prototype.foreach(predicate) -- as recommended by Kyle Simpson

Back

Classic Module Pattern characteristics

Front

must be an IIFE or an outer function that gets executed. second characteristic, one or more functions that get returned from the function call that have a closure over the inner private scope.

Back

Section 5

(50 cards)

Haskell: What character denotes function application?

Front

Whitespace

Back

JQUERY: event.which

Front

For key or mouse events, this property indicates the specific key or button that was pressed.

Back

body

Front

document data displayed to users by client browser

Back

Object.prototype.__proto__

Front

Points to the object which was used as prototype when the object was instantiated.

Back

What is lazy evaluation?

Front

In programming language theory, lazy evaluation, or call-by-need[1] is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations (sharing).[2][3] The sharing can reduce the running time of certain functions by an exponential factor over other non-strict evaluation strategies, such as call-by-name.[citation needed] The benefits of lazy evaluation include: The ability to define control flow (structures) as abstractions instead of primitives. The ability to define potentially infinite data structures. This allows for more straightforward implementation of some algorithms. Performance increases by avoiding needless calculations, and error conditions in evaluating compound expressions.

Back

Haskell: how to get type of expression in GHCI?

Front

:type expr

Back

Haskell: What do back quotes do for operators?

Front

Makes the operator infix

Back

Self contained modules

Front

everything with my module is in my module no global variables if a module manages more than one thing it should be broken up

Back

Object.assign

Front

Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object. Object.create(proto[, propertiesObject])

Back

Object.create

Front

The Object.create() method creates a new object with the specified prototype object and properties. Object.create(proto[, propertiesObject]) // Example where we create an object with a couple of sample properties. // (Note that the second parameter maps keys to property descriptors.) o = Object.create(Object.prototype, { // foo is a regular 'value property' foo: { writable: true, configurable: true, value: 'hello' }, // bar is a getter-and-setter (accessor) property bar: { configurable: false, get: function() { return 10; }, set: function(value) { console.log('Setting `o.bar` to', value); } /* with ES5 Accessors our code can look like this get function() { return 10; }, set function(value) { console.log('setting `o.bar` to', value); } */ } });

Back

What is [[Prototype]]?

Front

The mechanism by which objects can point to their successors. Basically a reference to another object. Written in the spec, not public

Back

Haskell: whitespace is not significant in Haskell T or F?

Front

whitespace is significant in Haskell

Back

What is the dunder proto?

Front

__proto__

Back

Properties of the Object built-in-type?

Front

1. Object.length Has a value of 1. 2. Object.prototype Allows the addition of properties to all objects of type Object.

Back

In Javascript/jQuery what does (e) mean?

Front

e is the short var reference for event object which will be passed to event handlers. The event object essentially has lot of interesting methods and properties that can be used in the event handlers. jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.

Back

Haskell: Sum up list, length of list, product, reverse, append two lists

Front

sum [1,2,3,4,5], product, [1,2,3,4,5] ++ [6,7,8], reverse

Back

First FP programming language?

Front

Lisp -- this is important because Lisp is often used as a good comparison and frequently referenced.

Back

Haskell: Generalizations of <head> and <tail>?

Front

<take> and <drop>

Back

Is Haskell lazy or strict?

Front

Haskell is often described as a lazy language. However, the language specification simply states that Haskell is non-strict, which is not quite the same thing as lazy.

Back

Haskell: Select 2nd element of a list

Front

[1,2,3,4,5] !! 2 note that this is not a constant time operation because lists are not arrays in Haskell

Back

Separation of concerns - Single Responsibility Principle

Front

SOC: Divide your app into distinct features with as little overlap in functionality as possible. SRP: The single responsibility principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. Robert C. Martin expresses the principle as follows:[1] A class should only have one reason to change.

Back

what does jQuery() return?

Front

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example). More importantly, you can also apply jQuery functions against all the selected elements. The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().

Back

Haskell: Are functions first class citizens?

Front

yes

Back

html

Front

root element

Back

Haskell: Select first N elements of a list

Front

take 3 [1,2,3,4,5]

Back

What are polymorphic types in Haskell?

Front

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a. Lists of integers (e.g. [1,2,3]), lists of characters (['a','b','c']), even lists of lists of integers, etc., are all members of this family. (Note, however, that [2,'b'] is not a valid example, since there is no single type that contains both 2 and 'b'.)

Back

Does Javascript have function overloading?

Front

No, you cannot double-define functions in the same scope.

Back

Object.freeze()

Front

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

Back

head

Front

document metadata used by browsers and search engines

Back

Privileged vs Private vs Public

Front

http://javascript.crockford.com/private.html Public function Constructor(...) { this.membername = value; } Constructor.prototype.membername = value; Private function Constructor(...) { var that = this; var membername = value; function membername(...) {...} } Note: The function statement function membername(...) {...} is shorthand for var membername = function membername(...) {...}; Privileged function Constructor(...) { this.membername = function (...) {...}; }

Back

Object.prototype.hasOwnProperty()

Front

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

Back

32

Front

Back

Haskell: :t length returns length :: [a] -> Int => wtf is the [a]?

Front

alpha type, meaning its polymorphic

Back

jQuery( selector [, context ] ) is equivalent to

Front

$(); not to be confused with Chrome's default

Back

Haskell: Remove first element from a list

Front

tail [1,2,3,4,5];

Back

Object.defineProperty() Needs MUCH MORE ELABORATION

Front

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

Back

Object.prototype.isPrototypeOf()

Front

Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.

Back

Object.prototype.constructor

Front

Specifies the function that creates an object's prototype.

Back

doctype

Front

declaration of standards compliance

Back

Haskell: do strings exist in Haskell?

Front

Nah, lists of chars do though [Char] single chars can be written with single quotes while list of chars can be written with double quotes

Back

What was the significant advance of ML?

Front

Type inference - compiler would infer types based on code.

Back

Haskell: What operator has highest priority?

Front

function application

Back

Haskell: What does null do

Front

null checks if a list is empty. If it is, it returns True, otherwise it returns False. Use this function instead of xs == [] (if you have a list called xs)

Back

Haskell: how to convert infix operator to prefix?

Front

2 + 2 ---> (+) 2 2

Back

What are the three configurable or not so configurable Object properties?

Front

Enumerable: I can access to all of them using a for..in loop. Also, enumerable property keys of an object are returned using Object.keys method. Writable: I can modify their values, I can update a property just assigning a new value to it: ob.a = 1000; Configurable: I can modify the behavior of the property, so I can make them non-enumerable, non-writable or even non-cofigurable if I feel like doing so. Configurable properties are the only ones that can be removed using the delete operator.

Back

JQUERY: event.type

Front

Describes the nature of the event. -- mouseclick,

Back

Haskell: convention meaning: xs, ns, nss

Front

list of type s, list of type n, list of lists of type s

Back

Haskell 98?

Front

In late 1997, the series culminated in Haskell 98, intended to specify a stable, minimal, portable version of the language and an accompanying standard library for teaching, and as a base for future extensions. The committee expressly welcomed creating extensions and variants of Haskell 98 via adding and incorporating experimental features.

Back

Haskell: double colon <::> means

Front

has the type <type>

Back

Object.getPrototypeOf()

Front

The Object.getPrototypeOf() method returns the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object.

Back

Section 6

(50 cards)

push()

Front

pushes an item onto the end of an array

Back

Dependencies vs devdependencies in package.json?

Front

The packages listed under dependencies are essential to running the application. The devDependencies are only necessary to develop the application. They can be excluded from production installations as in this example: $npm install my-application --production

Back

What is the root of an Angular 2 App?

Front

AppComponent is the root of the application

Back

pop()

Front

removes the last position of an array and returns it

Back

test()

Front

tests a string for a matching pattern, used with regular expression

Back

Move forward one word

Front

w

Back

@angular/upgrade

Front

Set of utilities for upgrading Angular 1 application2

Back

system.js

Front

A dynamic module loader compatible with the ES2015 module specification. There are other viable choices including the well-regarded webpack. SystemJS happens to be the one we use in the documentation samples. It works.

Back

Write a file my-module.js that exports a function Cubed and a const foo. Then import the two into another file. Use Named Exports

Front

// module "my-module.js" export function cube(x) { return x x x; } const foo = Math.PI + Math.SQRT2; export { foo }; -------- import { cube, foo } from 'my-module'; console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888

Back

@angular/core

Front

@angular/core - Critical runtime parts of the framework needed by every application. Includes all metadata decorators, Component, Directive, dependency injection, and the component lifecycle hooks.

Back

RequireJS

Front

Used mainly in the browser. Packages everything into file and helps you manage how JS is loading.

Back

Webpack?

Front

Webpack is a powerful module bundler. A bundle is a JavaScript file that incorporate assets that belong together and should be served to the client in a response to a single file request. A bundle can include JavaScript, CSS styles, HTML, and almost any other kind of file. Webpack roams over your application source code, looking for import statements, building a dependency graph, and emitting one (or more) bundles. With plugin "loaders" Webpack can preprocess and minify different non-JavaScript files such as TypeScript, SASS, and LESS files. We determine what Webpack does and how it does it with a JavaScript configuration file, webpack.config.js.

Back

Add a "//" to multiple lines at once

Front

<C-v> + I + // + esc

Back

@angular/platform-browser

Front

@angular/platform-browser - Everything DOM and browser related, especially the pieces that help render into DOM. This package also includes the bootstrapStatic method for bootstrapping applications for production builds that pre-compile templates offline.

Back

What are all of String.prototype properties?

Front

String.prototype.constructor - specifies the function that creates an object's prototype. String.prototype.length, N (Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of length. These properties are read-only.), constructor

Back

Front

Back

Erase until and including character

Front

df charactef

Back

ES6: export

Front

The export statement is used to export functions, objects or primitives from a given file (or module). export { name1, name2, ..., nameN }; export { variable1 as name1, variable2 as name2, ..., nameN }; export let name1, name2, ..., nameN; // also var export let name1 = ..., name2 = ..., ..., nameN; // also var, const export default expression; export default function (...) { ... } // also class, function* export default function name1(...) { ... } // also class, function* export { name1 as default, ... }; export * from ...; export { name1, name2, ..., nameN } from ...; export { import1 as name1, import2 as name2, ..., nameN } from ...;

Back

What is the essential structure of an ng2 Component?

Front

One or more import statements to reference the things we need. A @Component decorator that tells Angular what template to use and how to create the component. A component class that controls the appearance and behavior of a view through its template.

Back

select()

Front

highlights text in the textarea object

Back

match()

Front

similar to search, but sends back array of matched text instead of index position

Back

unshift()

Front

adds given value to the front of an array array will get bigger

Back

valueOf()

Front

returns the primitive value of the String object

Back

getDate()

Front

returns the calendar day number

Back

getDay()

Front

returns day of the week

Back

@angular/http

Front

Angular's http client

Back

search()

Front

searches a string for text and returns an index position if found

Back

jQuery

Front

javascript library

Back

String.fromCharCode()

Front

The static String.fromCharCode() method returns a string created by using the specified sequence of Unicode values.

Back

trim()

Front

white space is removed from both sides of string original string is not altered

Back

String comparison - strcmp equivalent?

Front

<, > var a = 'a'; var b = 'b'; if (a < b) { // true console.log(a + ' is less than ' + b); } else if (a > b) { console.log(a + ' is greater than ' + b); } else { console.log(a + ' and ' + b + ' are equal.'); }

Back

What are the three package categories in the dependencies section of package.json?

Front

Features - Feature packages provide our application with framework and utility capabilities. Polyfills - Polyfills plug gaps in the browser's JavaScript implementation. Other - Other libraries that support the application such as bootstrap for HTML widgets and styling.

Back

replace()

Front

receives 2 arguments, first the string to be replaced, then the replacement text

Back

shift()

Front

removes the first position of an array and returns it

Back

split()

Front

splits a string and returns an array of substrings

Back

What are the ways to do character access in JS?

Front

return 'cat'.charAt(1); // returns "a" return 'cat'[1]; // returns "a"

Back

Erase until and excluding character

Front

dt character

Back

String.prototype.charAt()

Front

The charAt() method returns the specified character from a string.

Back

toString()

Front

returns a string value of the regular expression

Back

@angular/common

Front

@angular/common - The commonly needed services, pipes and directives provided by the Angular team.

Back

@angular/router

Front

Component router.

Back

What are the two types of Exports?

Front

Named exports: export { myFunction }; // exports a function declared earlier export const foo = Math.sqrt(2); // exports a constant Default exports (only one per script): export default function() {} // or 'export default class {}' // there is no semi-colon here

Back

class Student { fullName: string; constructor(public firstName, public middleInitial, public lastName) { this.fullName = firstName + " " + middleInitial + " " + lastName; } } interface Person { firstName: string; lastName: string; } function greeter(person : Person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user); Typescript -> ES5 compiles to....?

Front

var Student = (function () { function Student(firstName, middleInitial, lastName) { this.firstName = firstName; this.middleInitial = middleInitial; this.lastName = lastName; this.fullName = firstName + " " + middleInitial + " " + lastName; } return Student; }()); function greeter(person) { return "Hello, " + person.firstName + " " + person.lastName; } var user = new Student("Jane", "M.", "User"); document.body.innerHTML = greeter(user);

Back

String.fromCodePoint()

Front

The static String.fromCodePoint() method returns a string created by using the specified sequence of code points.

Back

Write a file my-module.js that exports a default function cube! Then import it in another file. Use Default Exports

Front

// module "my-module.js" export default function cube(x) { return x x x; } import cube from 'my-module'; console.log(cube(3)); // 27

Back

getTime()

Front

returns milliseconds since 1970

Back

Tsconfig.json?

Front

The tsconfig.json file specifies the root files and the compiler options required to compile the project.

Back

@angular/platform-browser-dynamic

Front

@angular/platform-browser-dynamic - Providers and a bootstrap method for applications that compile templates on the client. don't use offline compilation. We use this package for boostrapping during development and for boostrapping plunker samples

Back

@angular/compiler

Front

@angular/compiler - Angular's Template Compiler. It understand templates and can convert them to code that makes the app run and render. Developers typically don't interact with the compiler directly. They use it indirectly via platform-browser-dynamic or the offline template compiler.

Back

String.prototype.anchor()

Front

The anchor() method creates an <a> HTML anchor element that is used as a hypertext target.

Back

Section 7

(50 cards)

String.prototype.search()

Front

The search() method executes a search for a match between a regular expression and this String object. str.search(regexp)

Back

String.prototype.substr()

Front

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters. str.substr(start[, length])

Back

Object definition in OOP

Front

An instance of a class.

Back

String.prototype.concat()

Front

The concat() method combines the text of two or more strings and returns a new string.

Back

String.prototype.lastIndexOf()

Front

The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found. str.lastIndexOf(searchValue[, fromIndex])

Back

String.prototype[@@iterator]()

Front

The [@@iterator]() method returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value. string[Symbol.iterator]

Back

When code is executed, an execution context is created. What is created within this execution context ALWAYS?

Front

Global object, <this>

Back

Class definition

Front

Defines the object's characteristics. A class is a template definition of an object's properties and methods.

Back

ES6: The spread operator is also called...

Front

spread, rest, gather

Back

Namespace definition

Front

A container which lets developers bundle all functionality under a unique, application-specific name.

Back

Encapsulation definition

Front

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination[1][2] thereof: A language mechanism for restricting direct access to some of the object's components.[3][4] A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6] Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object-oriented programming, while other programming languages which provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation. The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition. The features of encapsulation are supported using classes in most object-oriented programming languages, although other alternatives also exist.

Back

ES6: Why the hell are there classes in ES6?

Front

JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

Back

String.prototype.charCodeAt()

Front

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index (the UTF-16 code unit matches the Unicode code point for code points representable in a single UTF-16 code unit, but might also be the first code unit of a surrogate pair for code points not representable in a single UTF-16 code unit, e.g. Unicode code points > 0x10000). If you want the entire code point value, use codePointAt().

Back

String.prototype.indexOf()

Front

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. str.indexOf(searchValue[, fromIndex])

Back

String.prototype.startsWith()

Front

The startsWith() method determines whether a string begins with the characters of another string, returning true or false as appropriate. str.startsWith(searchString[, position])

Back

ES6: Spread operator

Front

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected. it is practical for fixing cases where you have to use .apply in "hacky" sort of ways particularly when you are manipulating or using the <arguments> object and want to use arguments as an array.

Back

String.prototype.repeat()

Front

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together. str.repeat(count)

Back

What is a Privileged Method?

Front

A privileged method is able to access the private variables and methods, and is itself accessible to the public methods and the outside. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

Back

String.prototype.link()

Front

The link() method creates a string representing the code for an <a> HTML element to be used as a hypertext link to another URL. str.link(url)

Back

String.prototype.slice()

Front

The slice() method extracts a section of a string and returns a new string. str.slice(beginSlice[, endSlice])

Back

Variables that are created within code and not within a function is always attached to...

Front

The global object

Back

Inheritance definition

Front

A class can inherit characteristics and capabilities from another class.

Back

String.prototype.codePointAt()

Front

The codePointAt() method returns a non-negative integer that is the Unicode code point value.

Back

String.prototype.substring()

Front

The substring() method returns a subset of a string between one index and another, or through the end of the string. str.substring(indexStart[, indexEnd])

Back

String.prototype.toString()

Front

The toString() method returns a string representing the specified object. str.toString()

Back

String.prototype.toUpperCase()

Front

The toUpperCase() method returns the calling string value converted to uppercase. str.toUpperCase()

Back

ES6: Difference between function declarations and class declarations for OOP JS?

Front

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError: var p = new Polygon(); // ReferenceError class Polygon {}

Back

String.prototype.split()

Front

The split() method splits a String object into an array of strings by separating the string into substrings. str.split([separator[, limit]])

Back

String.prototype.toLowerCase()

Front

The toLowerCase() method returns the calling string value converted to lowercase. str.toLowerCase()

Back

ES6: let name = 'Bob'; String.raw`Hi
${name}!`; returns?

Front

"Hi
Bob!"

Back

String.prototype.valueOf()

Front

The valueOf() method returns the primitive value of a String object. str.valueOf() The valueOf() method of String returns the primitive value of a String object as a string data type. This value is equivalent to String.prototype.toString(). This method is usually called internally by JavaScript and not explicitly in code.

Back

ES6: Why is the scope of the arrow function particularly useful?

Front

Typically, Javascript functions create new scopes with a new this binding. Arrow functions support "lexical" this meaning that a new "this" is not binded, instead it uses the "This" of the function that encloses it. Problem: function Person() { // The Person() constructor defines `this` as an instance of itself. this.age = 0; setInterval(function growUp() { // In non-strict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } var p = new Person(); Old fix: function Person() { var self = this; // Some choose `that` instead of `self`. // Choose one and be consistent. self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); }

Back

String.prototype.toLocaleUpperCase()

Front

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings. str.toLocaleUpperCase()

Back

String.prototype.endsWith()

Front

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate. str.endsWith(searchString[, position])

Back

String.prototype.replace()

Front

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. str.replace(regexp|substr, newSubStr|function)

Back

ES6: What there's a constructor keyword now?

Front

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

Back

String.prototype.includes()

Front

The includes() method determines whether one string may be found within another string, returning true or false as appropriate. str.includes(searchString[, position])

Back

String.raw()

Front

The static String.raw() method is a tag function of template literals, similar to the r prefix in Python or the @ prefix in C# for string literals (yet there is a difference: see explanations in this issue). It's used to get the raw string form of template strings (that is, the original, uninterpreted text). String.raw(callSite, ...substitutions) String.raw`templateString`

Back

String.prototype.match()

Front

The match() method retrieves the matches when matching a string against a regular expression. str.match(regexp)

Back

ES6: var a = 5; var b = 10; console.log("Fifteen is " + (a + b) + " and
not " + (2 * a + b) + "."); // "Fifteen is 15 and // not 20." rewrite using ES6 template literals

Front

var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`); // "Fifteen is 15 and // not 20."

Back

console.log("string text line 1
"+ "string text line 2"); rewrite this using ES6 template literals

Front

console.log(`string text line 1 string text line 2`);

Back

ES6: This is used to work around the <this> bindings in JS What ES6 feature fixes this? and how can it be rewritten? let sum = function(){ return Array.prototype.reduce.call(arguments,(prev,curr) => {prev+curr}); } sum(2,3,4,5);

Front

let sum = function(...args){ return args.reduce((prev,curr) => prev + curr); }

Back

String.prototype.trim()

Front

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). str.trim()

Back

Polymorphism defintiion

Front

Poly means "many" and morphism means "forms". Different classes might define the same method or property.

Back

Abstraction definition

Front

The conjunction of an object's complex inheritance, methods, and properties must adequately reflect a reality model.

Back

ES6: Template Literals

Front

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting.

Back

String.prototype.normalize()

Front

The normalize() method returns the Unicode Normalization Form of a given string (if the value isn't a string, it will be converted to one first). str.normalize([form])

Back

String.prototype.localeCompare()

Front

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent. referenceStr.localeCompare(compareString[, locales[, options]])

Back

Constructor definition

Front

A method called at the moment an object is instantiated. It usually has the same name as the class containing it.

Back

String.prototype.toLocaleLowerCase()

Front

The toLocaleLowerCase() method returns the calling string value converted to lower case, according to any locale-specific case mappings. str.toLocaleLowerCase()

Back

Section 8

(50 cards)

What are the three sources of Node modules?

Front

Built in modules, your own project files, third party modules

Back

What is the Christmas Tree problem?

Front

A problem of asynchronous code due to severe nesting of callbacks.

Back

How to implement inheritance in Javascript?

Front

Inheritance is a way to create a class as a specialized version of one or more classes (JavaScript only supports single inheritance). The specialized class is commonly called the child, and the other class is commonly called the parent. In JavaScript you do this by assigning an instance of the parent class to the child class, and then specializing it. In modern browsers you can also use Object.create to implement inheritance.

Back

Router

Front

Our server will need to answer differently to requests, depending on which URL the request was asking for, thus we need some kind of router in order to map requests to request handlers

Back

Router vs Request Handlers?

Front

The Router routes the URL the requests are coming in for and routes these requests to the Request Handlers.

Back

Ctrl+B (⌘B) or Ctrl+Click (⌘-Click)

Front

Navigate to declaration: Ctrl+B (⌘B) or Ctrl+Click (⌘-Click) You can instantly jump to the function or method definition or a variable, class, component, or CSS style declaration: just Ctrl-click on it, or place the caret on it and press Ctrl+B. This shortcut can also help you jump to the referenced file or imported module:

Back

What is libuv?

Front

libuv is a multi-platform support library with a focus on asynchronous I/O. It was primarily developed for use by Node.js, but it's also used by Luvit, Julia, pyuv, and others.

Back

Shift + CMD + A

Front

Find Action

Back

What are the three core components of NodeJS?

Front

Libuv, V8 Engine, C++/JS Custom Code

Back

Create a property firstName within a class Person

Front

var Person = function (firstName) { this.firstName = firstName; }; //instantiation: var person1 = new Person('Alice');

Back

What is the equivalent of a constructor in JS?

Front

The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript the function serves as the constructor of the object, therefore there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation. The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.

Back

Create a Student class that inherits from a Person Class

Front

// Define the Person constructor var Person = function(firstName) { this.firstName = firstName; }; // Add a couple of methods to Person.prototype Person.prototype.walk = function(){ console.log("I am walking!"); }; Person.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName); }; // Define the Student constructor function Student(firstName, subject) { // Call the parent constructor, making sure (using Function#call) // that "this" is set correctly during the call Person.call(this, firstName); // Initialize our Student-specific properties this.subject = subject; } // Create a Student.prototype object that inherits from Person.prototype. // Note: A common error here is to use "new Person()" to create the // Student.prototype. That's incorrect for several reasons, not least // that we don't have anything to give Person for the "firstName" // argument. The correct place to call Person is above, where we call // it from Student. Student.prototype = Object.create(Person.prototype); // See note below // Set the "constructor" property to refer to Student Student.prototype.constructor = Student; // Replace the "sayHello" method Student.prototype.sayHello = function(){ console.log("Hello, I'm " + this.firstName + ". I'm studying " + this.subject + "."); }; // Add a "sayGoodBye" method Student.prototype.sayGoodBye = function(){ console.log("Goodbye!"); }; // Example usage: var student1 = new Student("Janet", "Applied Physics"); student1.sayHello(); // "Hello, I'm Janet. I'm studying Applied Physics." student1.walk(); // "I am walking!" student1.sayGoodBye(); // "Goodbye!" // Check that instanceof works correctly console.log(student1 instanceof Person); // true console.log(student1 instanceof Student); // true

Back

What does AMD stand for?

Front

Asynchronous module definition (AMD) is a JavaScript specification that defines an API for defining code modules and their dependencies, and loading them asynchronously if desired. Implementations of AMD provide the following benefits: Website performance improvements.

Back

Alt+Click

Front

Multiple Cursor or Multiline edit

Back

What does the URL module do?

Front

The url module provides methods which allow us to extract the different parts of a URL (like e.g. the requested path and query string), and querystring can in turn be used to parse the query string for request parameters:

Back

Import a single property bar of a module named foo into a file

Front

const bar = require('foo').bar;

Back

Import a node module named foo into a file

Front

const foo = require('foo');

Back

The Node - King Analogy

Front

That's right, everything runs in parallel, except your code. To understand that, imagine your code is the king, and node is his army of servants. The day starts by one servant waking up the king and asking him if he needs anything. The king gives the servant a list of tasks and goes back to sleep a little longer. The servant now distributes those tasks among his colleagues and they get to work. Once a servant finishes a task, he lines up outside the kings quarter to report. The king lets one servant in at a time, and listens to things he reports. Sometimes the king will give the servant more tasks on the way out. Life is good, for the king's servants carry out all of his tasks in parallel, but only report with one result at a time, so the king can focus. *

Back

Files and modules in Node are in one to one correspondence. What does this mean?

Front

Each js file is its own module. //foo.js const circle = require('./circle.js'); console.log( `The area of a circle of radius 4 is ${circle.area(4)}`); //circle.js const PI = Math.PI; exports.area = (r) => PI r r; exports.circumference = (r) => 2 PI r;

Back

Does resetting the prototype constructor in a subclass matter?

Front

Yes and no. In ES5 and earlier, JavaScript itself didn't use constructor for anything. It defined that the default object on a function's prototype property would have it and that it would refer back to the function, and that was it. Nothing else in the specification referred to it at all. That changed in ES2015 (ES6), which started using it in relation to inheritance hierarchies. For instance, Promise#then uses the constructor property of the promise you call it on (via SpeciesConstructor) when building the new promise to return. It's also involved in subtyping arrays. Note that in the places the ES2015 spec uses it, it's set automatically for you (you can't subclass Promise or arrays except via class, and class handles it for you). Outside of the language itself, sometimes people would use it when trying to build generic "clone" functions or just generally when they wanted to refer to what they believed would be the object's constructor function. My experience is that using it is rare, but sometimes people do use it. It's there by default, you only need to put it back when you replace the object on a function's prototype property: Student.prototype = Object.create(Person.prototype); If you don't do this: Student.prototype.constructor = Student; ...then Student.prototype.constructor inherits from Person.prototype which (presumably) has constructor = Person. So it's misleading. It's okay if nothing in your code (or library code you use) uses it. I've always ensured it was correctly wired up. Of course, with ES2015 (aka ES6)'s class keyword, most of the time we would have used it, we don't have to anymore, because it's handled for us when we do class Student extends Person { }

Back

SOLID

Front

SRP - Single Responsibility Principle (https://www.youtube.com/watch?v=Ib-gxqF6Wuk)

Back

HTTP Server

Front

The HTTP Server "serves" content located in the server, this includes HTML, images, flash and any file related. The server is not restricted to server static content, it also serves dynamic content generated on fly from a database or similar. We want to serve web pages, therefore we need an HTTP server

Back

How does JS define classes?

Front

JavaScript uses functions as constructors for classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person with an empty constructor. var Person = function () {};

Back

Create a method sayHello on a class Person using the prototype design pattern

Front

var Person = function (firstName) { this.firstName = firstName; }; Person.prototype.sayHello = function() { console.log("Hello, I'm " + this.firstName); };

Back

What is the difference between Object.create() and new?

Front

The object used in Object.create actually forms the prototype of the new object, whereas in the new Function() form, the declared properties/functions do not form the prototype. With constructor functions, the newly created object inherits from the constructor's prototype when using new. var o = new SomeConstruct(); --> inheriting from SomeConstructor.prototype.

Back

In JS OOP, what's a namespace?

Front

In JavaScript a namespace is just another object containing methods, properties, and objects. (The idea behind creating a namespace in JavaScript is simple: create one global object, and all variables, methods, and functions become properties of that object. Use of namespaces also reduces the chance of name conflicts in an application, since each application's objects are properties of an application-defined global object.)

Back

Why add methods using prototype as opposed to using this?

Front

Methods that inherit via the prototype chain can be changed universally for all instances, for example: function Class () {} Class.prototype.calc = function (a, b) { return a + b; } // Create 2 instances: var ins1 = new Class(), ins2 = new Class(); // Test the calc method: console.log(ins1.calc(1,1), ins2.calc(1,1)); // -> 2, 2 // Change the prototype method Class.prototype.calc = function () { var args = Array.prototype.slice.apply(arguments), res = 0, c; while (c = args.shift()) res += c; return res; } // Test the calc method: console.log(ins1.calc(1,1,1), ins2.calc(1,1,1)); // -> 3, 3 ) Notice how changing the method applied to both instances? This is because ins1 and ins2 share the same calc() function. In order to do this with public methods created during construction, you'd have to assign the new method to each instance that has been created, which is an awkward task. This is because ins1 and ins2 would have their own, individually created calc() functions. Another side effect of creating methods inside the constructor is poorer performance. Each method has to be created every time the constructor function runs. Methods on the prototype chain are created once and then "inherited" by each instance. On the flip side of the coin, public methods have access to "private" variables, which isn't possible with inherited methods. var YourClass = function(){ var privateField = "somevalue"; this.publicField = "somevalue"; this.instanceMethod1 = function(){ //you may access both private and public field from here: //in order to access public field, you must use "this": alert(privateField + "; " + this.publicField); }; } YourClass.prototype.instanceMethod2 = function(){ //you may access only public field 2 from this method, but not private fields: alert(this.publicField); //error: drawaback of prototype methods: alert(privateField); }; When you define methods via prototype, they are shared among all YourClass instances. As a result the total size of such instances is less than if you define methods in constructor; There are tests that show how method definition via prototype decrease the total size of html page and as a result a speed of its loading. another advantage of methods, defined via prototype - is when you use inherited classes, you may override such methods and in the overriden method of the derived class you may invoke the method of base class with the same name, but with methods defined in constructor, you cannot do this.

Back

SOLID

Front

LSP - Liskov Substitution Principle Derived classes must be substitutable by their base classes.

Back

SOLID

Front

DIP - Dependency Inversion Principle (In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details. The principle states:[1] A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions.)

Back

Import a constructor from a module named Bar

Front

const Bar = require('bar'); notice the casing

Back

Request Handlers

Front

To fulfill the requests that arrived at the server and have been routed using the router, we need actual request handlers

Back

What are Node's built in modules?

Front

exports._builtinLibs = ['assert', 'buffer', 'child_process', 'cluster', 'crypto', 'dgram', 'dns', 'events', 'fs', 'http', 'https', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'string_decoder', 'tls', 'tty', 'url', 'util', 'vm', 'zlib'];

Back

Prototype-based programming

Front

Prototype-based programming is an OOP model that doesn't use classes, but rather it first accomplishes the behavior of any class and then reuses it (equivalent to inheritance in class-based languages) by decorating (or expanding upon) existing prototype objects. (Also called classless, prototype-oriented, or instance-based programming.)

Back

The NodeJS Docs have stability indexes. What does this mean?

Front

The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned. Stability 0 - 3. Only use features from Stability 2-3 if you really want to have consistent and compatible code

Back

SOLID

Front

OCP - Open Closed Principle (Open for extension, closed for modification)

Back

CMD + O

Front

Go to class

Back

Create a global namespace called MYAPP, then create a sub namespace called event

Front

//global namespace var MYAPP = MYAPP || {}; // sub namespace MYAPP.event = {};

Back

Browserify allows you to use CommonJS or AMD or RequireJS?

Front

CommonJS in the browser! Remember RequireJS implements the AMD api.

Back

Why is writing code for Node different?

Front

Highly dependent on using callbacks to take full advantage of asynchronous (non-blocking) pattern and event loops.

Back

SOLID

Front

ISP - Interface Segregation Principle (The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.)

Back

Synchronous vs Asynchronous code?

Front

//example 1 var result = database.query("SELECT * FROM hugetable"); console.log("query finished"); console.log("Next line"); //example 2 database.query("SELECT * FROM hugetable", function(result) { console.log("query finished"); }); console.log("Next line"); query finished Next line Next line query finished

Back

Does Node implement CommonJS or AMD?

Front

CommonJS. RequireJS IMPLEMENTS the AMD api

Back

What is Node's execution model?

Front

Asynchronous, single-threaded, event-driven execution model.

Back

What is the equivalent to the global object, Window, in Node?

Front

process

Back

Your code (king) gives node (servants) the two tasks to read and write a file, and then goes to sleep. Once node has completed a task, the callback for it is fired. But there can only be one callback firing at the same time. Until that callback has finished executing, all other callbacks have to wait in line. In addition to that, there is no guarantee on the order in which the callbacks will fire.

Front

var fs = require('fs') , sys = require('sys'); fs.readFile('treasure-chamber-report.txt', function(report) { sys.puts("oh, look at all my money: "+report); }); fs.writeFile('letter-to-princess.txt', '...', function() { sys.puts("can't wait to hear back from her!"); });

Back

What is an error-first callback?

Front

Error-first callbacks are used to pass errors and data. The first argument is always an error object that the programmer has to check if something went wrong. Additional arguments are used to pass data. (fs.readFile(filePath, function(err, data) { if (err) { //handle the error } // use the data object });)

Back

Double Shift

Front

Search everywhere

Back

How do we create an instance or object of a class named Person?

Front

var person1 = new Person();

Back

Say there are four DB Queries, one takes 200ms, the second takes 400ms, the third takes 600 ms, the fourth takes 800ms - how does node shine in this case?

Front

With node, you can execute all your queries at once, reducing the response time to the duration it takes to execute the slowest query. -- 800MS - whereas in other non asynchronous platforms it would take 200+400+600+800 unless specifically made to run in parallel

Back

Alt+Enter or ⌥-Enter

Front

WebStorm has a great number of intentions to help you quickly apply fixes, generate code, or change some project settings. Place the caret on highlighted or underlined code, and press Alt+Enter to see the list of available intention actions. For example:

Back

Section 9

(50 cards)

How do they differ from each other?

Front

Each method differs in how this is initialized.

Back

The callback pattern for async code is more... The event pattern for async code is more...

Front

Request/Reply -- no results until all results -- Publish/Subscribe -- act on results as they come in -- so the .on is kind of like a subscription when an event occurs.

Back

Rewrite the following async code that utilizes callbacks to using events getThem(param, function(err, items) { //check for err //operate on array of items }

Front

var results = getThem(param); results.on('item', function(i){ //do something with this one item }); results.on('done', function(){ //no more items }); results.on('error', function(err){ //react to error }); Request/Reply -- no results until all results -- either error or results Publish/Subscribe -- act on results as they come in -- partial results before error -- the .on is kind of like a subscription when an event occurs.

Back

var foo = function bar() { // statements go here }; What are the three ways to recursively call this named function expression?

Front

bar() arguments.callee() foo()

Back

What is the value of "this" when used in a function?

Front

it is the object that "owns" the function.

Back

what is "main" in NPM package.json?

Front

The entry point of the module. It is what is executed when someone requires the module.

Back

function multiply(a, b = 1) { return a*b; } multiply(5); // 5 What ES6 feature does this demonstrate?

Front

Default parameters

Back

Quadratic function form?

Front

f(x) = ax2 + bx + c

Back

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); Value of fn_inside?

Front

a function that adds 3 to whatever you give it.

Back

map(function(x) {return x x x}, [0, 1, 2, 5, 10]); --> function expression or declaration?

Front

function expression

Back

Import a module foo in the current directory

Front

const foo = require('./foo');

Back

Demonstration of how a quadratic model might not fit housing size as a feature to predict housing prices. Why would the price go down as size goes up...? Why not use a square root function instead?

Front

Back

What is a computer thread??

Front

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of its variables at any given time. Systems with a single processor generally implement multithreading by time slicing: the central processing unit (CPU) switches between different software threads. This context switching generally happens very often and rapidly enough that users perceive the threads or tasks as running in parallel. On a multiprocessor or multi-core system, multiple threads can execute in parallel, with every processor or core executing a separate thread simultaneously; on a processor or core with hardware threads, separate software threads can also be executed concurrently by separate hardware threads.

Back

Write function map(f,a) {};

Front

function map(f,a){ var result =[], i; for (i = 0; i != a.length; i++){ result[i] = f(a[i]); } return result; }

Back

AMD vs CommonJS advantages and disadvantages summary and where does ES6 modules play into this?

Front

From Reddit: AMD is dead (was killed by Node-compatible bundlers). CommonJS is dead (was killed by Node). Node uses something that looks like CommonJS and is commonly called CommonJS but isn't actually CommonJS (there's a spec for CommonJS imports and Node knowingly violates good chunks of it). ES6 imports aren't currently natively supported in any JS engine I know of. They can however be translated to Node-style "CommonJS" and there are bundlers that support them directly. As for what CommonJS is: CommonJS was an effort to define common standards for the various competing server-side JavaScript environments that existed at the time (including well-known but now mostly obsolete stuff like Rhino as well as a few lesser known alternatives to Node that have died out). Node mostly won, so the new common standard is "whatever Node does". One of the reasons AMD failed was that it is a lot more complex than the alternative. AMD is intended to be asynchronous at runtime. This means it not only defines dependencies, it also conflates the issue of lazy loading dependency bundles. As it turned out, lazy loading dependency bundles at runtime is a difficult, rare and heterogeneous enough problem that a module system can't easily solve it. But having this kind of complexity in it meant that it was effectively overengineered for the more common simple problems. That said, if you write code today, just use either Node-style imports directly or a tool like Babel that translates ES6 imports to Node-style ones.

Back

Import a module foo in the subdirectory bar

Front

const foo = require('./bar/foo');

Back

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); result = fn_inside(5); result1 = outside(3)(5); Explain how result1 returns its value.

Front

outside(3) returns a function that adds 3 to whatever it is given because of the closure. That is, the inside function has access to the arguments and variables of the outside function. Thus, when outside(3) returns it calls the 'add 3 to whatever' function with the value (5) thus returning 8. (Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible. This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.)

Back

Is the current directory dot necessary when importing modules in Node?

Front

Yes.

Back

Cubic functions and properties

Front

Back

True or false? In a nested function, the inner function has access to the outer function's variables and arguments

Front

True

Back

Export a module that sums up the area of a square

Front

module.exports = (width) => { return { area: () => width * width }; }

Back

How to change a linear regression to better fit a data using the same features?

Front

Change the order of the polynomial model by taking the order of the polynomial model and just applying it to the features you do have.

Back

What does AMD stand for?

Front

Asynchronous module definition designed with browser in mind

Back

What's different about ES6 and Anonymous Function Expressions?

Front

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. However, in ES6, they do!!! Well, most of the time. (As of ES6, though, a lot of "anonymous" function expressions create functions with names, and this was predated by various modern JavaScript engines being quite smart about inferring names from context. In ES6, your anonymous function expression results in a function with the name boo. This is strewn throughout the spec rather than being defined in one place with a bunch of rules.)

Back

is "this" a variable? can its value be changed?

Front

Note that this is not a variable. It is a keyword. You cannot change the value of this.

Back

Polynomial functions

Front

These functions consist of one or more terms of variables with whole number exponents. (Whole numbers are positive integers and zero.) All such functions in one variable (usually x) can be written in this type of format: constant, linear, quadratic, cubic, quartic, quintic

Back

Node EventEmitter class

Front

The EventEmitter class is used as a construct to help us build the publish/subscribe pattern of the event model of writing async code. the subscriber: emitter.on(event, listener); the publisher: emitter.emit(event, [args]);

Back

inflection points

Front

In differential calculus, an inflection point, point of inflection, flex, or inflection (inflexion) is a point on a curve at which the curve changes from being concave (concave downward) to convex (concave upward), or vice versa. A point where the curvature vanishes but does not change sign is sometimes called a point of undulation or undulation point.

Back

What does don't block the event loop mean?

Front

Dont put slow blocking code onto the stack. the event loop wont put other functions onto the stack until it is clear!

Back

Reciprocal function graph?

Front

Back

What is private about a nested function?

Front

The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

Back

CommonJS fixes what problem

Front

encapsulation of modules and ability to connect with other modules.

Back

List all the properties of the arguments keyword

Front

arguments.callee, arguments.length, arguments[@@iterator]. (arguments.caller is deprecated due to security vulnerabilities)

Back

AMD define function?

Front

define(moduleId, dependencies, definitionFunc); define(dependencies, definitionFunc); -- preferred anonymous modules typically defaults module to filename // MyApp/MyModule: define( ['pkgA/modA', 'pkgA/modB', 'pkgZ/modC'], function (modA, modB, modC) { var myModule = { doStuff: function() { ... } } return myModule; } );

Back

Method vs function invocation

Front

x.a() vs a(x) (""the method-invocation syntax is an elegant way to express the fact that function is operating on an object");

Back

var account = require('./myModule2.js')(2000);what is this code doing in relation to CommonJS

Front

you can assume that the module being imported or required is a constructor/class, and by invoking the constructor we're creating a class instance

Back

Why would you want to use setTimeout(function cb() { console.log('there'); }, 0); ???

Front

the event loop only pushes tasks onto the stack when the stack is empty. thus, this code waits for the stack to be code. essentially, this defers the execution of the callback until the stack is cleared.

Back

function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); result = fn_inside(5); Value of result?

Front

8

Back

var foo = function bar() { ... } --> what type of function?

Front

NAMED FUNCTION EXPRESSION

Back

What are the three ways a function can refer to itself? (Recursion)

Front

the function's name arguments.callee an in-scope variable that refers to the function

Back

Front

Back

Primitive parameters are passed to to functions by...

Front

Value. the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function. (If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:)

Back

Using RequireJS show how to import a module in AMD

Front

require(['calculator/add'], function (add){ console.log(add(1,6)); });

Back

What is Bower?

Front

Bower is pretty much dead. Don't need two package managers esp. when NPM is so good and continuously getting grouped with JS overall and not just Node. But, Bower WAS a front-end package manager -- remember when I used it, it sucked. such overtooling. From MPJME: (https://www.quora.com/Why-use-Bower-when-there-is-npm) In almost all cases, it's more appropriate to use Browserify and npm over Bower. It is simply a better packaging solution for front-end apps than Bower is. At Spotify, we use npm to package entire web modules (html, css, js) and it works very well. Bower brands itself as the package manager for the web. It would be awesome if this was true - a package manager that made my life better as a front-end developer would be awesome. The problem is that Bower offers no specialized tooling for the purpose. It offers NO tooling that I know of that npm doesn't, and especially none that is specifically useful for front-end developers. There is simply no benefit for a front-end developer to use Bower over npm. With browserify or webpack, it becomes super-easy to concatenate all your modules into big minified files, which is awesome for performance, especially for mobile devices. Not so with Bower, which will require significantly more labor to get the same effect. npm also offers you the ability to use multiple versions of modules simultaneously. If you have not done much application development, this might initially strike you as a bad thing, but once you've gone through a few bouts of Dependency hell you will realize that having the ability to have multiple versions of one module is a pretty darn great feature. Note that npm includes a very handy dedupe tool that automatically makes sure that you only use two versions of a module if you actually have to - if two modules both can use the same version of one module, they will. But if they can't, you have a very handy out.

Back

Gradient descent vs normal equation

Front

Back

Why is Function.prototype.apply() useful?

Front

(There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. )

Back

What is "this" keyword for?

Front

In JavaScript, the thing called this, is the object that "owns" the current code.

Back

var foo = function() { ... }

Front

ANONYMOUS FUNCTION EXPRESSION

Back

What does module.exports do?

Front

You assign variables that are to be exposed to other files as a module to it. one.js: var doIt = function(i, callback){///} var count = 2; module.exports.doIt = doIt; module.exports.foo = 'bar'; two.js: var one = require('./one'); one.doit(23, function (err, result){ // } console.log(one.foo); Notice the multiple assignments to module.exports Notice how you import the FILE as a module due to the 1 to 1 correspondenceness of Node though you can import just single properties

Back

How many ways can js functions be evoked?

Front

in 4 different ways.

Back

Section 10

(38 cards)

when can we say that the function is invoked with a constructor?

Front

If a function invocation is preceded with the new keyword, it is a constructor invocation.

Back

Is the code in a function executed when the function is defined?

Front

The code in a function is not executed when the function is defined. It is executed when the function is invoked.

Back

What are the 2 predefined function methods by which we can invoke a function?

Front

call() and apply() are predefined JavaScript function methods.

Back

What does this return? function myFunction() { return this; } myFunction();

Front

This example returns the window object as the value of this: // Will return the window object [object Window]

Back

What is the only difference between apply() and call() methods?

Front

The only difference is that call() takes the function arguments separately, and apply() takes the function arguments in an array.

Back

Use Math.max with apply to find the maximum value of [1,2,3,4,5]; and do it without it apply as well.

Front

var numbers = [1,2,3,4,5]; var max = Math.max.apply(null, numbers); var max2 = Math.max(1,2,3,4,5);

Back

Explain Function.prototype.apply()

Front

fun.apply(thisArg, [argsArray]) thisArg The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed. argsArray An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.

Back

Three use cases for apply()

Front

1. Using apply to chain constructors You can use apply to chain constructors for an object, similar to Java. In the following example we will create a global Function method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list. 2. Using apply and built-in functions Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array. (// min/max number in an array var numbers = [5, 6, 2, 3, 7]; // using Math.min/Math.max apply var max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...) var min = Math.min.apply(null, numbers); // vs. simple loop based algorithm max = -Infinity, min = +Infinity; for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } }) 3. Using apply in "monkey-patching" Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given some object.foo function, you can modify the function in a somewhat hacky way, like so: (var originalfoo = someobject.foo; someobject.foo = function() { // Do stuff before calling function console.log(arguments); // Call the function as it would have been called normally: originalfoo.apply(this, arguments); // Run stuff after, here. })

Back

What might happen if we use the window object as a variable?

Front

Using the window object as a variable can easily crash your program.

Back

the In "non-strict" mode if the value of the first argument is null or undefined, What is value of the first argument replaced with?

Front

In "non-strict" mode, if the value of the first argument is null or undefined, it is replaced with the global object.

Back

Where do we put the object when using apply() or call() methods?

Front

Both methods takes an owner object as the first argument.

Back

is myFunction() and window.myFunction() different?

Front

myFunction() and window.myFunction() is the same function:

Back

Invoking a Function with an object Constructor

Front

Invoking a Function with an object Constructor

Back

What do objects have in js?

Front

JavaScript functions have properties and methods.

Back

in strict javascript mode which argument becomes the value of this?

Front

In JavaScript strict mode, the first argument becomes the value of this in the invoked function, even if the argument is not an object. "so it creates an object from anying. "

Back

What will be the value of "this" inside the code block of the function if we Invoke the function as the method of an object?

Front

Invoking a function as an object method, causes the value of this to be the object itself.

Back

What do we create with a constructor invocation? step 1

Front

// This is a function constructor: function myFunction(arg1, arg2) { this.firstName = arg1; this.lastName = arg2; } A constructor invocation creates a new object. The new object inherits the properties and methods from its constructor. // This creates a new object var x = new myFunction("John","Doe"); x.firstName; // Will return "John"

Back

Invoking a Function as a Method

Front

Invoking a Function as a Method

Back

What is the owner of the fullName function?

Front

myObject is the owner of the function.

Back

What is the defult global object in HTML?

Front

In HTML the default global object is the HTML page itself, so the function above "belongs" to the HTML page.

Back

What is the gobal object in a webrowser?

Front

In a web browser the global object is the browser window.

Back

What datatype is a function in js?

Front

In JavaScript, functions are objects.

Back

What is the advantage of using call and apply methods?

Front

With call() or apply() you can set the value of this inside the function and invoke the function as a new method of an existing object.

Back

What do both of the methods have to have?

Front

both methods must have the owner object as first parameter.

Back

What if we invoke a function as a global function?

Front

Invoking a function as a global function, causes the value of this to be the global object.

Back

syntax of testing if the value of this belong to the global object

Front

var myObject = { firstName:"John", lastName: "Doe", fullName: function () { return this; } } myObject.fullName(); // Will return [object Object] (the owner object)

Back

What is the page object in a browser?

Front

In a browser the page object is the browser window. The function above automatically becomes a window function.

Back

What is the value of "this" in a function constructor?

Front

The this keyword in the constructor does not have a value. The value of this will be the new object created when the function is invoked.

Back

Invoking a Function with a Function Method

Front

Invoking a Function with a Function Method

Back

example of call()

Front

function myFunction(a, b) { return a * b; } myFunction.call(myObject, 10, 2); // Will return 20

Back

Does a declared function like the previous one belong to any object?

Front

The previous function does not belong to any object. But in JavaScript there is always a default global object.

Back

is it a good practice to invoke a function like this? window.myFunction(10, 2);

Front

This is a common way to invoke a JavaScript function, but not a good practice in computer programming. Global variables, methods, or functions can easily create name conflicts and bugs in the global object.

Back

What is "this" this time?

Front

The thing called this, is the object that "owns" the JavaScript code. In this case the value of this is myObject.

Back

Where does fullName function belong to?

Front

The function belongs to the object.

Back

an example of apply()

Front

function myFunction(a, b) { return a * b; } myArray = [10,2]; myFunction.apply(myObject, myArray); // Will also return 20

Back

What do we make from a function with call and apply?

Front

we make a method for an existing object. we envoke the function which becomes a method of an existing object because among the arguments we define the object to which the funcion will belong

Back

What does this refer to if a function is called without an owner object?

Front

When a function is called without an owner object, the value of this becomes the global object.

Back

what is the difference between the function constructor and the object constructor?

Front

they look the same.

Back