💾 Overview of Javascript fundamentals - part 2

23 June, 2020


map, filter, reduce. What's the difference?

  • The map method creates a new array fom the results of a callback function on every element in the array.
  • The filter method creates a new array with all elements that pass the test in the callback function.
  • The reduce method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

    const strs = ["I", " ", "am", " ", "Iron", " ", "Man"];
    const result = strs.reduce((acc, currentStr) => acc + str, "");

Implement the Array.prototype.map method by hand.

function map(arr, mapCallback) {
  // First, we check if the parameters passed are right.
  if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== 'function') { 
    return [];
  } else {
    let result = [];
    // We're making a results array every time we call this function
    // because we don't want to mutate the original array.
    for (let i = 0, len = arr.length; i < len; i++) {
      result.push(mapCallback(arr[i], i, arr)); 
      // push the result of the mapCallback in the 'result' array
    }
    return result; // return the result array
  }
}

What are High order functions?

Higher-Order Function are functions that can return a function or receive argument or arguments which has a value of a function.

What is the difference between classical inheritance and prototypal inheritance?

Class Inheritance: instances inherit from classes (like a blueprint — a description of the class), and create sub-class relationships: hierarchical class taxonomies. Instances are typically instantiated via constructor functions with the new keyword.
Class inheritance may or may not use the class keyword from ES6.
Prototypal Inheritance: instances inherit directly from other objects. Instances are typically instantiated via factory functions or Object.create(). Instances may be composed from many different objects, allowing for easy selective inheritance.

truthy/falsy

&& is known as the guard operator ||: 1st expression is always outputted. The 2nd expression only gets outputted if the 1st expression is falsy.

&&: 1st expression is outputted if it's FALSY. The 2nd expression only get outputted if the 1st expression is truthy.

example

const truthy = true;
const falsy = false;
const beer = '🍺';

truthy || beer; // true
falsy || beer; // '🍺';

Can you name two common uses for closures?

First whats a closure? A closure is an inner function that has access to the outer function’s variables.

In JavaScript, closures are created every time a function is created, at function creation time. To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function.

When to use function declarations and expressions

  • Functions are values. They can be assigned, copied or declared in any place of the code.
  • If the function is declared as a separate statement in the main code flow, that’s called a “Function Declaration”.
  • If the function is created as a part of an expression, it’s called a “Function Expression”.
  • Function Declarations are processed before the code block is executed. They are visible everywhere in the block.
  • Function Expressions are created when the execution flow reaches them.

Name some benefits of using webpack

Webpack is a tool that will bundle your code and optionally all of its dependencies into a single .js file.

  • Dead asset elimination
  • This is killer, especially for CSS rules. You only build the images and CSS into your dist folder that your application actually needs.
  • Easier code splitting. For example, because you know that your file Homepage.js only requires specific CSS files, Webpack could easily build a homepage.css file to greatly reduce initial file size. You control how assets are processed. If an image is below a certain size, you could base64 encode it directly into your Javascript for fewer HTTP requests. If a JSON file is too big, you can load it from a URL. You can require('./style.less') and it's automaticaly parsed by Less into vanilla CSS.
  • Stable production deploys. You can't accidentally deploy code with images missing, or outdated styles. Webpack will slow you down at the start, but give you great speed benefits when used correctly.
  • You get hot page reloading. True CSS management.
  • CDN cache busting because Webpack automatically changes file names to hashes of the file contents, etc.

whats the adv of using createDocumentFragment instead of appending straight into the DOM?

Appending once means only one render so performance doesn't suffer.

useful string methods

note: Strings are immutable.
.split() will turn a string into an array
.toLowerCase()
.substring()
.startswith()

Convert objects into arrays

Object.entries()

note: Array useful methods .set() is a data structure that cant have duplicate items. const set = new `arr);

// flatten an array [1, [2], 3] use .flat()

loops and when to use each

forEach is an array method that we can use to execute a function on each element in an array. It can only be used on Arrays, Maps, and Sets.

arr.forEach(element => {
     console.log(element);
   });

When using forEach, we simply have to specify a callback function. This callback will be executed on each element in the array.

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

map utilizes return values and actually returns a new Array of the same size.

For…In

The JavaScript for/in statement loops through the properties of an object:

for (variable in object) {  
  // do something
}

for...in is used to iterate over the enumerable properties of objects. Every property in an object will have an Enumerable value — if that value is set to true, then the property is Enumerable.

For…of

The JavaScript for/of statement loops through the values of an iterable objects such as Arrays, Strings, Maps, NodeLists, and more.

const products = ['oranges', 'apples'];

for (const [index, product] of products.entries()) {
  console.log(index, product);
}
// 0, 'oranges'
// 1, 'apples'

difference between expression and declaration

//a function expression and so only defined when that line is reached
var functionOne = function() {
    // Some code
};
//function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).
function functionTwo() {
    // Some code
}

source: https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname?rq=1

whats 'use strict'

The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables.

What is document?

A Document object represents the HTML document that is displayed in the window. The way a document content is accessed and modified is called the Document Object Model. see more here: https://javascript.info/modifying-document