DEV Community

Cover image for All Of My Articles Combined
Bryan C Guner
Bryan C Guner

Posted on

All Of My Articles Combined

Absolutely Everything You Could Need To Know About How JavaScript Works.

Seriously… this list is utterly exhaustive it covers more core concepts than I can hold the names of in working memory on a very good day.


Absolutely Everything You Could Need To Know About How JavaScript Works.

Seriously… this list is utterly exhaustive it covers more core concepts than I can hold the names of in working memory on a very good day.

But first a little bit of mildly shameful self promotion:

(self promotion ends after the line denoted by a bunch of pictures of my dog🐕 )

(Followed by a brief introduction to JavaScript for beginners)

(Finally the main content / resources / imbedded YouTube links)

### My Blog:

Discover More:

Web-Dev-Hub

Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app

This is a work in progress and may be broken or hosted elsewhere at some time in the future.

Related posts:

JS Modules

A module is a reusable piece of code that encapsulates implementation details and exposes a public API so it can be…dev.to

Closures In JavaScript

Answer A closure is a function defined inside another function and has access to its lexical scope even when it is…dev.to

A list of all of my articles to link to future posts

bryanguner.medium.com

The Complete JavaScript Reference Guide

You will want to bookmark thisjavascript.plainenglish.io

The Beginner’s Guide To JavaScript

This is a quick intro for complete beginners … skip below for more advanced content and resources! (below the next photo montage of my dog)

Skip The Following To Get To Main Content!!

If you wanna skip this section you’ll find the main content about 10% of the way down the page… it will look like this:

### The Number Data Type

The number data type in JS is used to represent any numerical

values, including integers and decimal numbers. Basic Arithmetic Operators are the symbols that perform particular operations.

  • + (addition)
  • - (subtraction)
  • asterisk (multiplication)
  • / (division)
  • % (modulo)

JS evaluates more complex expressions using the general math order of

operations aka PEMDAS.

  • PEMDAS : Parentheses, Exponents, Multiplication, Division, Modulo, Addition, Subtraction.
  • To force a specific order of operation, use the group operator ( ) around a part of the expression.

Modulo : Very useful operation to check divisibility of numbers,

check for even & odd, whether a number is prime, and much more!

(Discrete Math concept, circular problems can be solved with modulo)

  • Whenever you have a smaller number % a larger number, the answer will just be the initial small number.
  • console.log(7 % 10); // => 7;

The String Data Type

The string data type is a primitive data type that used to represent

textual data.

  • can be wrapped by either single or double quotation marks, best to choose one and stick with it for consistency.
  • If your string contains quotation marks inside, can layer single or double quotation marks to allow it to work.

    "That's a great string"; (valid)
    'Shakespeare wrote, "To be or not to be"'; (valid)
    'That's a bad string'; (invalid)

  • Alt. way to add other quotes within strings is to use template literals.

This is a template literal

${function} // use ${} to invoke functions within.

> .length : property that can be appended to data to return the length.

> empty strings have a length of zero.

> indices : indexes of data that begin at 0, can call upon index by using the bracket notation [ ].

console.log("bootcamp"[0]); // => "b"
console.log("bootcamp"[10]); // => "undefined"
console.log("boots"[1 * 2]); // => "o"
console.log("boots"["boot".length - 1]); // => "t"
Enter fullscreen mode Exit fullscreen mode
  • we can pass expressions through the brackets as well since JS always evaluates expressions first.
  • The index of the last character of a string is always one less than it’s length.
  • indexOf() : method used to find the first index of a given character within a string.
  • console.log("bagel".indexOf("b")); // => 0 console.log("bagel".indexOf("z")); // => -1
  • if the character inside the indexOf() search does not exist in the string, the output will be -1.
  • the indexOf() search will return the first instanced index of the the char in the string.
  • concatenate : word to describe joining strings together into a single string.

The Boolean Data Type

The Boolean data type is the simplest data type since there are only

two values: true and false.

  • Logical Operators (Boolean Operators) are used to establish logic in our code.
  • ! (not) : reverses a Boolean value.

console.log(!true); // => false console.log(!!false); // => false

  • && (and) Truth Table

- Logical Order of Operations : JS will evaluate !, then &&, then ||.

  • De Morgan’s Law : Common mistake in Boolean logic is incorrectly distributing ! across parentheses.
  • !(A || B) === !A && !B; !(A && B) === !A || !B;
  • In summary, to correctly distribute ! across parentheses we must also flip the operation within.

Comparison Operators

All comparison operators will result in a Boolean output.

The relative comparators

  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
  • === (equal to)
  • !== (not equal to)

> Fun Fact: “a” < “b” is considered valid JS Code because string

> comparisons are compared lexicographically (meaning dictionary order),

> so “a” is less than “b” because it appears earlier!

> If there is ever a standstill comparison of two string

> lexicographically (i.e. app vs apple) the comparison will deem the

> shorter string lesser.

Difference between == and ===

  • === : Strict Equality, will only return true if the two comparisons are entirely the same.
  • == : Loose Equality, will return true even if the values are of a different type, due to coercion. (Avoid using this)

Variables

Variables are used to store information to be referenced and manipulated

in a program.

  • We initialize a variable by using the let keyword and a = single equals sign (assignment operator).
  • let bootcamp = "Lambda"; console.log(bootcamp); // "Lambda"
  • JS variable names can contain any alphanumeric characters,
    underscores, or dollar signs (cannot being with a number).
  • If you do not declare a value for a variable, undefined is
    automatically set.
  • let bootcamp; console.log(bootcamp); // undefined
  • We can change the value of a previously declared variable (let, not
    const) by re-assigning it another value.
  • let is the updated version of var; there are some
    differences in terms of hoisting and global/block scope — will be
    covered later in the course (common interview question!)

Assignment Shorthand

let num = 0;num += 10; // same as num = num + 10num -= 2; // same as num = num - 2num /= 4; // same as num = num / 4num *= 7; // same as num = num * 7
Enter fullscreen mode Exit fullscreen mode
  • In general, any nonsensical arithmetic will result in NaN ; usually operations that include undefined.
  • declaration : process of simply introducing a variable name.
  • initialization : process of both declaring and assigning a variable on the same line.

Functions

A function is a procedure of code that will run when called. Functions

are used so that we do not have to rewrite code to do the same thing

over and over. (Think of them as ‘subprograms’)

  • Function Declaration : Process when we first initially write our function.
  • Includes three things:
  • Name of the function.
  • A list of parameters ()
  • The code to execute {}
  • Function Calls : We can call upon our function whenever and wherever* we want. (*wherever is only after the initial declaration)
  • JS evaluates code top down, left to right.
  • When we execute a declared function later on in our program we refer to this as invoking our function.
  • Every function in JS returns undefined unless otherwise specified.
  • When we hit a return statement in a function we immediately exit the function and return to where we called the function.
  • When naming functions in JS always use camelCase and name it something appropriate. > Great code reads like English and almost explains itself. Think: Elegant, readable, and maintainable!

Parameters and Arguments

  • Parameters : Comma separated variables specified as part of a function’s declaration.
  • Arguments : Values passed to the function when it is invoked.
  • If the number of arguments passed during a function invocation is different than the number of parameters listed, it will still work.
  • However, is there are not enough arguments provided for parameters our function will likely yield Nan.

END OF INTRO FOR BEGINNERS (MAIN ARTICLE BELOW)

↓↓Absolutely Everything You Could Need To Know About JavaScript↓↓

leonardomso/33-js-concepts

This repository was created with the intention of helping developers master their concepts in JavaScript. It is not a…github.com

Call stack - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its…developer.mozilla.org

Understanding Javascript Function Executions — Call Stack, Event Loop , Tasks & more

Web developers or Front end engineers, as that’s what we like to be called, nowadays do everything right from acting as…medium.com

Understanding the JavaScript call stack

The JavaScript engine (which is found in a hosting environment like the browser), is a single-threaded interpreter…medium.freecodecamp.org

Javascript: What Is The Execution Context? What Is The Call Stack?

What is the Execution Context in Javascript? I bet you don't know the answer. What are the most basic components of a…web.archive.org

Understanding Execution Context and Execution Stack in Javascript

Understanding execution context and stack to become a better Javascript developer.blog.bitsrc.io

How JavaScript works: an overview of the engine, the runtime, and the call stack

As JavaScript is getting more and more popular, teams are leveraging its support on many levels in their stack …blog.sessionstack.com

Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms.

“JavaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with…medium.com

The Ultimate Guide to Hoisting, Scopes, and Closures in JavaScript - ui.dev

It may seem surprising, but in my opinion the most important and fundamental concept to understanding the JavaScript…tylermcginnis.com

How JavaScript Works: An Overview of JavaScript Engine, Heap, and Call Stack

Hello everyone 👋, I hope you are doing great. So, today you are going to learn An Overview of JavaScript Engine, Heap…dev.to

Fundamental Data Structures In JavaScript

Data structures in JavaScriptmedium.com

Here’s a live code editor where you can mess with any of the examples…

Here’s a live code editor where you can mess with any of the examples…

Coding practice

Dependent on data

> Something that data structure and algorithms have in common when talking about time complexity is that they are both dealing with data. When you deal with data you become dependent on them and as a result the time complexity is also dependent of the data that you received. To solve this problem we talk about 3 different time complexity.

  • The best-case complexity: when the data looks the best
  • The worst-case complexity: when the data looks the worst
  • The average-case complexity: when the data looks average

Big O notation

The complexity is usually expressed with the Big O notation. The wikipedia page about this subject is pretty complex but you can find here a good summary of the different complexity for the most famous data structures and sorting algorithms.

The Array data structure

### Definition

An Array data structure, or simply an Array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. The simplest type of data structure is a linear array, also called one-dimensional array. From Wikipedia

Arrays are among the oldest and most important data structures and are used by every program. They are also used to implement many other data structures.

JavaScript data types and data structures - JavaScript | MDN

Programming languages all have built-in data structures, but these often differ from one language to another. This…developer.mozilla.org

How numbers are encoded in JavaScript

Edit description2ality.com

Here is what you need to know about JavaScript’s Number type

Why 0.1+0.2 IS NOT equal to 0.3 and 9007199254740992 IS equal to 9007199254740993medium.com

What Every JavaScript Developer Should Know About Floating Point Numbers

After I gave my talk on JavaScript (really, I was there trying to shamelessly plug my book - Underhanded JavaScript and…blog.chewxy.com

The Secret Life of JavaScript Primitives

You may not know it but, in JavaScript, whenever you interact with string, number or boolean primitives you enter a…javascriptweblog.wordpress.com

A primitive as an object

Here’s the paradox faced by the creator of JavaScript:

  • There are many things one would want to do with a primitive like a string or a number. It would be great to access them using methods.
  • Primitives must be as fast and lightweight as possible.

The solution looks a little bit awkward, but here it is:

  1. Primitives are still primitive. A single value, as desired.
  2. The language allows access to methods and properties of strings, numbers, booleans and symbols.
  3. In order for that to work, a special “object wrapper” that provides the extra functionality is created, and then is destroyed.

The “object wrappers” are different for each primitive type and are called: String, Number, Boolean and Symbol. Thus, they provide different sets of methods.

For instance, there exists a string method str.toUpperCase() that returns a capitalized str.

Here’s how it works:

let str = "Hello";

alert( str.toUpperCase() ); // HELLO
Enter fullscreen mode Exit fullscreen mode

Simple, right? Here’s what actually happens in str.toUpperCase():

  1. The string str is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like toUpperCase().
  2. That method runs and returns a new string (shown by alert).
  3. The special object is destroyed, leaving the primitive str alone.

So primitives can provide methods, but they still remain lightweight.

The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one.

Primitive Types | Flow

JavaScript has a number of different primitive types ( MDN): The primitive types appear in the language as either…flow.org

(Not) Everything in JavaScript is an Object

This was originally published on The Brewing Press For those who just wants the answers, feel free to jump to the…dev.to

Objects In JavaScript

The object is a data structure that stores other data, similar to how an array stores elements.medium.com

Diving Deeper in JavaScripts Objects

A Closer Look at JavaScript Object Descriptorsblog.bitsrc.io

The differences between Object.freeze() vs Const in JavaScript

ES6 has brought several new features and methods into JavaScript since its release. These features have better improved…medium.com

Explaining Value vs. Reference in Javascript

A simple look at computer memory explains what’s happeningcodeburst.io

DOES IT MUTATE:

LINK….

.concat

no mutation

Description

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Array.prototype.concat ( [ item1 [ , item2 [ , … ] ] ] )
Enter fullscreen mode Exit fullscreen mode

Array.prototype.concat() - JavaScript | MDN

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead…developer.mozilla.org

Example

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Enter fullscreen mode Exit fullscreen mode

.copyWithin()

mutates

Description

The copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

arr.copyWithin(target)
arr.copyWithin(target, start)
arr.copyWithin(target, start, end)
Enter fullscreen mode Exit fullscreen mode

Array.prototype.copyWithin() - JavaScript | MDN

The copyWithin() method shallow copies part of an array to another location in the same array and returns it without…developer.mozilla.org

Example

var array1 = ['a', 'b', 'c', 'd', 'e'];

// copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// expected output: Array ["d", "b", "c", "d", "e"]

// copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// expected output: Array ["d", "d", "e", "d", "e"]
Enter fullscreen mode Exit fullscreen mode

.entries()

no mutation

Description

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.

a.entries()
Enter fullscreen mode Exit fullscreen mode

Array.prototype.entries() - JavaScript | MDN

The entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.developer.mozilla.org

Example

var array1 = ['a', 'b', 'c'];

var iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]
Enter fullscreen mode Exit fullscreen mode

.every

no mutation

Description

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Array.prototype.every ( callbackfn [ , thisArg ] )
Enter fullscreen mode Exit fullscreen mode

Array.prototype.every() - JavaScript | MDN

The every() method tests whether all elements in the array pass the test implemented by the provided function. It…developer.mozilla.org

Example

function isBelowThreshold(currentValue) {
  return currentValue &lt; 40;
}

var array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true
Enter fullscreen mode Exit fullscreen mode

.fill()

mutates

Description

The fill() method fills all the elements of an array from a start index to an end index with a static value.

arr.fill(value)
arr.fill(value, start)
arr.fill(value, start, end)
Enter fullscreen mode Exit fullscreen mode

Array.prototype.fill() - JavaScript | MDN

The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index…developer.mozilla.org

Example :

var array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Enter fullscreen mode Exit fullscreen mode

.filter

no mutation

Description

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.filter ( callbackfn [ , thisArg ] )
Enter fullscreen mode Exit fullscreen mode

Array.prototype.filter() - JavaScript | MDN

The method creates a new array with all elements that pass the test implemented by the provided function. Function is a…developer.mozilla.org

Example

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word =&gt; word.length &gt; 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Enter fullscreen mode Exit fullscreen mode

.find()

no mutation

Description

The find() method returns a value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

arr.find(callback[, thisArg])
Enter fullscreen mode Exit fullscreen mode

Array.prototype.find() - JavaScript | MDN

The find() method returns the value of the first element in the provided array that satisfies the provided testing…developer.mozilla.org

Example

var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
  return element &gt; 10;
});

console.log(found);
// expected output: 12
Enter fullscreen mode Exit fullscreen mode

Value types, reference types and scope in JavaScript

There are only two things fundamental to JavaScript: objects and functions.medium.com

Back to roots: JavaScript Value vs Reference

Let’s look at the concept of Value vs Reference. Every JavaScript developer should know this topic as it’s often the…medium.com

Grasp “By Value” and “By Reference” in JavaScript

And learn why it’s crucial to know the differencehackernoon.com

JavaScript Reference and Copy Variables | Hacker Noon

Each programming language has its own peculiarities (and JavaScript has a lot), and today I'm going to talk about…hackernoon.com

JavaScript Primitive vs. Reference Values

Summary: in this tutorial, you will learn the differences between primitive and reference values. In JavaScript, a…
www.javascripttutorial.net

JavaScript by reference vs. by value

I'm looking for some good comprehensive reading material on when JavaScript passes something by value and when by…stackoverflow.com

JavaScript Interview Prep: Primitive vs. Reference Types

original article In a JavaScript interview, they might ask if you understand the difference between primitive and…dev.to

What you need to know about Javascript's Implicit Coercion

Javascript's implicit coercion simply refers to Javascript attempting to coerce an unexpected value type to the…dev.to

JavaScript type coercion explained

Know your enginesmedium.freecodecamp.org

Javascript Coercion Explained

Along with some practical exampleshackernoon.com

What exactly is Type Coercion in Javascript?

Let's start with a short intro to type systems which I think will help you understand the general idea of type…stackoverflow.com

https://thedevs.network/

Weak dynamic typing is arguably one of those things everybody likes to pick at about JavaScript. For an elegant dynamic…thedevs.network

getify/You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter. Contribute to getify/You-Dont-Know-JS development by creating an…github.com

JavaScript — Double Equals vs. Triple Equals

Learn equality in JavaScript in 3 minutescodeburst.io

Should I use === or == equality comparison operator in JavaScript?

You know there are two different equality comparison operators in JavaScript: the === and == operators, or the triple…bytearcher.com

== vs === JavaScript: Double Equals and Coercion | Codementor

The == (double equals or loose equality) operator is an interesting operator. Many avoid it because they don't know how…
www.codementor.io

Why Use the Triple-Equals Operator in JavaScript? - Impressive Webs

"Determining whether two variables are equivalent is one of the most important operations in programming." That's…
www.impressivewebs.com

What is the difference between == and === in JavaScript?

On the surface == and === appear to be functionally the same, so why bother typing an extra character? In this video…
www.oreilly.com

Why javascript's typeof always return "object"?

To add in with the others, typeof returns both objects and primitives. There are 5 primitive types in javascript…stackoverflow.com

Checking Types in Javascript

Have you ever wondered: what is the correct way to check if a Javascript variable is an Array? Do a Google search and…tobyho.com

How to better check data types in javascript - Webbjocke

To check what data type something has in javascript is not always the easiest. The language itself provides an operator…webbjocke.com

Tomer Aberbach | Checking for the Absence of a Value in JavaScript

When I first started learning JavaScript I was confused by the seemingly endless ways developers check for the absence…tomeraberba.ch

getify/You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter. Contribute to getify/You-Dont-Know-JS development by creating an…github.com

JavaScript Functions — Understanding The Basics

Explore Functions in JavaScript — declaration, expressions, invocation, and more.codeburst.io

ES6: var, let and const - The battle between function scope and block scope

In the pre-ES6 era, there was only one way of declaring variables in JavaScript - being the usage of var. var has…
www.deadcoderising.com

Emulating Block Scope in JavaScript

While there are many issues that trip up developers coming from other languages, variable scoping may be number one…adripofjavascript.com

The Difference Between Function and Block Scope in JavaScript

Back to the basics with the var, let and const variablesjosephcardillo.medium.com

Function scopes and block scopes in JavaScript

Is the following line a valid line of JavaScript code?edgecoders.com

Understanding Scope and Context in JavaScript

Understanding Scope and Context in JavaScript August 16, 2013 JavaScript JavaScript's implementation of scope and…ryanmorr.com

JavaScript Scope and Closures

Scopes and closures are important in JavaScript. But, they were confusing for me when I first started. Here's an…css-tricks.com

Understanding Scope in JavaScript - Telerik Blogs

Scope is an important, yet ambiguous concept in JavaScript. Used correctly, it allows you to leverage good design…developer.telerik.com

Chapter 16. Variables: Scopes, Environments, and Closures

Chapter 16. Variables: Scopes, Environments, and Closures This chapter first explains how to use variables and then…speakingjs.com

Understanding Scope in JavaScript

JavaScript has a feature called Scope. Though the concept of scope is not that easy to understand for many new…scotch.io

When to use a function declaration vs. a function expression

The differences between them and when to use one or the other.medium.freecodecamp.org

A JavaScript Fundamentals Cheat Sheet: Scope, Context, and "this"

Scope Scope refers to where a variable can be accessed within a program. Some variables can be accessed from anywhere…dev.to

Quick Tip: Function Expressions vs Function Declarations - SitePoint

This article was peer reviewed by Jeff Mott. Thanks to all of SitePoint's peer reviewers for making SitePoint content…
www.sitepoint.com

JavaScript Function — Declaration vs Expression

Functions are considered as First Class citizen in JavaScript and it is really important to be clear with the concept…medium.com

Function Declarations vs. Function Expressions

What is Function Statement/Declarations in JavaScript?medium.com

Function Declarations vs. Function Expressions

Lets start with a short quiz. What is alerted in each case?: Question 1: Question 2: Question 3: Question 4: If you…javascriptweblog.wordpress.com

Essential JavaScript: Mastering Immediately-invoked Function Expressions

Understanding functions inside out and then learning how to exploit them to write modern, clean JavaScript code is a…vvkchandra.medium.com

Do ES6 Modules make the case of IIFEs obsolete? - Hashnode

IIFE was one of the most used patterns in the ES5 standard, as functions were the only way to declare a scoped block of…hashnode.com

A 10 minute primer to JavaScript modules, module formats, module loaders and module bundlers

Modern JavaScript development can be overwhelming. When working on a project, you may wonder why all the modern…
www.jvandemo.com

16. Modules

Edit descriptionexploringjs.com

ES modules: A cartoon deep-dive - Mozilla Hacks - the Web developer blog

ES modules bring an official, standardized module system to JavaScript. With the release of Firefox 60 in May, all…hacks.mozilla.org

Understanding ES6 Modules - SitePoint

Almost every language has a concept of modules - a way to include functionality declared in one file within another…
www.sitepoint.com

An overview of ES6 Modules in JavaScript

Introduction Until recently if you wanted to take full advantage of modules in JavaScript you needed to make use of…blog.cloud66.com

ES6 Modules in Depth

Welcome back to ES6 - "Oh, good. It's not another article about Unicode" - in Depth series. If you've never been around…ponyfoo.com

ES6 modules, Node.js and the Michael Jackson Solution

JavaScript’s never had a standard way to import and export functionality from a source file to another. Well, it has…medium.com

JavaScript Modules: A Beginner’s Guide

If you’re a newcomer to JavaScript, jargon like “module bundlers vs. module loaders,” “Webpack vs. Browserify” and “AMD…medium.freecodecamp.org

JavaScript modules

This article explains how to use JavaScript modules, how to deploy them responsibly, and how the Chrome team is working…developers.google.com

IIFE: Immediately Invoked Function Expressions

IIFE is a function that is declared and invoked at the same time. You create them by using anonymous functions and…dev.to

JavaScript Event Loop Explained

“How is JavaScript asynchronous and single-threaded ?” The short answer is that JavaScript language is single-threaded…medium.com

The JavaScript Event Loop: Explained

With JavaScript approaching near-ubiquity as the scripting language of the web browser, it benefits you to have a basic…blog.carbonfive.com

Understanding JS: The Event Loop

Due to the amazing quantity of libraries, tools and all kinds of things that make your development easier, a lot of…hackernoon.com

Understanding the JavaScript event loop

If you are someone who has heard about the terms event loop, callback queue, concurrency model and call stack but…
www.zeolearn.com

Event loop in javascript

If you love javascript you’ve need to learn this. One of the deeper aspects of JavaScript is it’s Event Loop. Its…code.likeagirl.io

The JavaScript Event Loop

The Event Loop is one of the most important aspects to understand about JavaScript. I've programmed for years with…flaviocopes.com

How JavaScript works: Event loop and the rise of Async programming + 5 ways to better coding with…

Welcome to post # 4 of the series dedicated to exploring JavaScript and its building components. In the process of…blog.sessionstack.com

Tasks, microtasks, queues and schedules

Edit descriptionjakearchibald.com

Visualising the JavaScript Event Loop with a Pizza Restaurant analogy

Consider a pizza restaurant. There are two types of orders that we currently have from a single customer - one is an…dev.to

✨♻️ JavaScript Visualized: Event Loop

Oh boi the event loop. It's one of those things that every JavaScript developer has to deal with in one way or another…dev.to

Scheduling: setTimeout and setInterval

Edit descriptionjavascript.info

Why not to use setInterval

Recently, I came across a requirement where I had to call a function repeatedly after specific time interval, like…dev.to

setTimeout VS setInterval

Introdeveloger.com

Using requestAnimationFrame

There used to be just one way to do a timed loop in JavaScript: setInterval(). If you needed to repeat something pretty…css-tricks.com

Understanding JavaScript's requestAnimationFrame() method for smooth animations

Updated: Nov 1st, 2017 The modern web of today is filled with sights to behold on every page, where menus slide in and…
www.javascriptkit.com

Handling time intervals in JavaScript

While working on an Electron app Pomolectron, I needed to handle different time intervals through setInterval()…
www.amitmerchant.com

JavaScript Engines -

By Jen Looper Writing code for the Web sometimes feels a little magical in that developers write a sequence of…
www.softwaremag.com

Understanding How the Chrome V8 Engine Translates JavaScript into Machine Code

Before diving deep into the core of Chrome’s V8, first, let’s get our fundamentals down. All of our systems consist of…medium.freecodecamp.org

Understanding V8’s Bytecode

V8 is Google’s open source JavaScript engine. Chrome, Node.js, and many other applications use V8. This article…medium.com

A Brief History of Google's V8 JavaScript Engine

Javascript has a reputation in developer circles as a terrible language. It's classless, loosely typed, and plagued by…
www.mediacurrent.com

JavaScript essentials: why you should know how the engine works

This article is also available in Spanish.medium.freecodecamp.org

JavaScript engine fundamentals: Shapes and Inline Caches

This article describes some key fundamentals that are common to all JavaScript engines - and not just V8, the engine…mathiasbynens.be

JavaScript engine fundamentals: optimizing prototypes

This article describes some key fundamentals that are common to all JavaScript engines - and not just V8, the engine…mathiasbynens.be

Elements kinds in V8

Note: If you prefer watching a presentation over reading articles, then enjoy the video below! JavaScript objects can…v8.dev

Programming with JS: Bitwise Operations

In this series of articles we take a look at different Computer Science topics from the prism of JavaScript. We’ve…hackernoon.com

Using JavaScript’s Bitwise Operators in Real Life

Let’s pretend we’re machine code programmers!codeburst.io

JavaScript Bitwise Operators - w3resource

Bitwise operators perform an operation on the bitwise (0,1) representation of their arguments, rather than as decimal…
www.w3resource.com

Bitwise Operators in Javascript

So far the two programming languages we have worked with are Ruby and Javascript. There are many differences between…medium.com

A Comprehensive Primer on Binary Computation and Bitwise Operators in Javascript

Bitwise operators, though they take a few minutes to learn, are a fun way to make your code more space and…medium.com

How can I understand Bitwise operation in JavaScript?

Answer: Okay, I was going to just write that bitwise operations in JavaScript are the same as in every other language…
www.quora.com

The Document Object Model :: Eloquent JavaScript

Too bad! Same old story! Once you've finished building your house you notice you've accidentally learned something that…eloquentjavascript.net

How To Understand and Modify the DOM in JavaScript | DigitalOcean

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is…
www.digitalocean.com

What’s the Document Object Model, and why you should know how to use it.

So, you’ve studied HTML, you’ve created your first tags, learned about CSS, made beautiful forms, amazing buttons…medium.freecodecamp.org

JavaScript DOM Tutorial with Example

Details JavaScript can access all the elements in a webpage making use of Document Object Model (DOM). In fact, the web…
www.guru99.com

What is the DOM?

A reader recently wrote in asking me what the DOM was. They said they've heard it mentioned and alluded to, but aren't…css-tricks.com

Traversing the DOM with JavaScript

A good JavaScript developer needs to know how to traverse the DOM-it's the act of selecting an element from another…zellwk.com

DOM tree

The backbone of an HTML document is tags. According to the Document Object Model (DOM), every HTML tag is an object…javascript.info

How to traverse the DOM in JavaScript

Learn how to navigate your way through the DOM tree.javascript.plainenglish.io

Render-tree Construction, Layout, and Paint | Web Fundamentals

The CSSOM and DOM trees are combined into a render tree, which is then used to compute the layout of each visible…developers.google.com

What, exactly, is the DOM?

The Document Object Model, or the "DOM", is an interface to web pages. It is essentially an API to the page, allowing…bitsofco.de

A Vanilla JS Guide On Mastering the DOM

Note: The contents of this post are intended to be introductory and does not include use of any libraries like jQuery…dev.to

How To Use Classes in JavaScript | DigitalOcean

JavaScript is a prototype-based language, and every object in JavaScript has a hidden internal property called…
www.digitalocean.com

Javascript Classes — Under The Hood

Javascript classes are nothing but a syntactic sugar over existing prototype based inheritance and constructor…medium.com

ES6 Classes - JavaScript January

Object-Oriented Programming (OOP) can be a great way to organize your projects. Introduced with ES6, the javascript…
www.javascriptjanuary.com

Better JavaScript with ES6, Pt. II: A Deep Dive into Classes

Out with the Old, In with the new Let's be clear about one thing from the start: Under the hood, ES6 classes are not…scotch.io

Understand the Factory Design Pattern in plain javascript

The simplest way to understand Factory Design Patternmedium.com

Factory Functions in JavaScript | Aten Design Group

As we move from an age of jQuery plugins and script drop-ins to a world of CommonJS and modular architectures it's…atendesigngroup.com

The Factory Pattern in JS ES6

I’m trying to get the most out of all the new things in ES6 (ES2015). And I’m writing a new library where I need a…medium.com

Class vs Factory function: exploring the way forward

ECMAScript 2015 (aka ES6) comes with the class syntax, so now we have two competing patterns for creating objects. In…medium.freecodecamp.org

How ES6 classes really work and how to build your own

The 6th edition of ECMAScript (or ES6 for short) revolutionized the language, adding many new features, including…medium.com

Understanding super in JavaScript

With the adoption of ES6/2015 by nearly all browsers (with one notable exception), developers have access to the new…jordankasper.com

An Easy Guide To Understanding Classes In JavaScript

1. An Introduction To Classes In JavaScript In the previous article in this series we looked at function constructors…dev.to

Function.prototype.call() - JavaScript | MDN

The value to use as this when calling . Note: In certain cases, may not be the actual value seen by the method. If the…developer.mozilla.org

Function.prototype.bind() - JavaScript | MDN

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a…developer.mozilla.org

Function.prototype.apply() - JavaScript | MDN

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like…developer.mozilla.org

Grokking call(), apply() and bind() methods in JavaScript

These are very important for every aspiring JavaScript Developer, these are used in almost every JavaScript Library or…levelup.gitconnected.com

How-to: call() , apply() and bind() in JavaScript | Codementor

In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions…
www.codementor.io

JavaScript's Apply, Call, and Bind Methods are Essential for JavaScript Professionals

Prerequisite: - Understand JavaScript's "this" With Ease, and Master It. - JavaScript Objects - Understand JavaScript…javascriptissexy.com

Understanding the "this" keyword, call, apply, and bind in JavaScript - ui.dev

Before diving into the specifics of the this keyword in JavaScript, it's important to take a step back and first look…tylermcginnis.com

Javascript: call(), apply() and bind()

“this” refreshermedium.com

The difference between call / apply / bind

JavaScript is a dynamic language, and is flexible enough to let you do things like multiple inheritance. That’s when an…medium.com

What the hack is call, apply, bind in JavaScript

Before start looking into call, apply, bind you should understand - how does "this" keyword works in JavaScript. In…dev.to

Mastering 'this' in JavaScript: Callbacks and bind(), apply(), call() - The New Stack

In Part One of our tutorial on mastering the 'this' keyword in JavaScript, we looked at why the concept of 'this' can…thenewstack.io

JavaScript's apply, call, and bind explained by hosting a cookout

If you have ever been in charge of operating the grill at a family event or party, then you can understand apply, call…dev.to

How AND When to use bind, call, and apply in Javascript - Eigen X

In order for you to fully understand bind, call, and apply you have to understand the Javascript concept of this …
www.eigenx.com

JavaScript: bind() vs apply() and call()

var fruit = { name: 'Apple' }; and this function: function showDetails(size, price) { console.log(this.name + ' ' +…
www.hacksparrow.com

Let me explain to you what is this. (Javascript)

Original post:
https://www.ycmjason.com/blog/2018/06/15.html this article assumes 'use strict' in all context this…dev.to

Understanding the “this” Keyword in JavaScript

How the value of “this” is assigned in different scenariosbetterprogramming.pub

How to understand the keyword this and context in JavaScript

As mentioned in one of my earlier articles, mastering JavaScript fully can be a lengthy journey. You may have come…medium.freecodecamp.org

What is "this" in Javascript ?

While learning JavaScript there are many roadblocks like closures, asynchronous programming, this keywords, etc. These…dev.to

This and Bind In Javascript

If you're learning Javascript, you'll no doubt run into the this keyword early on. At first, it appears quite simple…dev.to

3 Techniques for Maintaining Your Sanity Using "This" in JavaScript

Of JavaScript's many confusing aspects, the keyword this can be one of the most complicated -- Here's a joke about the…dev.to

Mastering the JavaScript "this" Keyword

The this keyword is a very important concept in JavaScript, and also a particularly confusing one to both new…dev.to

This binding in JavaScript - 4. New binding

This post ( This binding in JavaScript - 4. New binding) was originally published on Sargalias. In this series we talk…dev.to

A quick intro to 'this' in JavaScript

Probably one of the most confusing aspects of JavaScript is finding out what 'this' means. In this post, I will try to…dev.to

Explaining JavaScript 'this' to my cat

My cat is not very good at JavaScript (also at many other things), so today I will try to explain this keyword to him…dev.to

A conversation with the 'this' keyword in Javascript

'This' is one of the most confusing concepts in Javascript. Here's the sad news. It is just as important to understand…dev.to

What are call(), apply() and bind() in JavaScript - JS Curious

In JavaScript this refers to the owner object. If you want to attach some extra properties to a function, then you can…jscurious.com

Understanding “this” binding in Javascript

In order to understand “this” keyword clearly, we need to go through of how the execution context works at first. Every…medium.com

JavaScript For Beginners: the ‘new’ operator

Prefacecodeburst.io

Let’s demystify JavaScript’s ‘new’ keyword

Over the weekend, I completed Will Sentance’s JavaScript: The Hard Parts. It might not sound like the most glorious way…medium.freecodecamp.org

Constructor, operator "new"

The regular {...} syntax allows to create one object. But often we need to create many similar objects, like multiple…javascript.info

Understanding JavaScript Constructors

The following is a guest post by Faraz Kelhini. Some of this stuff is out of my comfort zone, so I asked Kyle Simpson…css-tricks.com

Beyond typeof and instanceof: simplifying dynamic type checks

This blog post describes a technique for making instanceof applicable to more values (on the right-hand side)…2ality.com

What Is the Instanceof Operator in JavaScript?

Learn more about What Is the Instanceof Operator in JavaScript? from DevelopIntelligence. Your trusted developer…appendto.com

Function and Object, instances of each other

Explaining why Function is an instance of Object, and why Object is an instance of Functionjavascriptrefined.io

Inheritance and the prototype chain - JavaScript | MDN

JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic…developer.mozilla.org

Javascript : Prototype vs Class

Let’s see how classes in JS are not what you think they are.medium.com

https://codeburst.io/javascript-prototype-cb29d82b8809

Prototype in Javascript | Codementor

By default every function has a property name as prototype which is EMPTY ( by default). We can add properties and…
www.codementor.io

Prototypes in JavaScript

In this post, we will discuss what are prototypes in JavaScript, how they help JavaScript in achieving the concepts of…betterprogramming.pub

Prototype in JavaScript: it’s quirky, but here’s how it works

The following four lines are enough to confuse most JavaScript developers:medium.freecodecamp.org

Understanding JavaScript: Prototype and Inheritance

Due to the amazing quantity of libraries, tools and all kinds of things that make your development easier, a lot of…hackernoon.com

Understanding Classes (ES5) and Prototypal Inheritance in JavaScript

In a nutshell the above snippet creates a Person class that can have multiple instances. By convention functional…dev.to

prototype, proto and Prototypal inheritance in JavaScript

This post was originally published on my website If you have spent some time with JavaScript, chances are that you have…dev.to

Prototypal inheritance

In programming, we often want to take something and extend it. For instance, we have a user object with its properties…javascript.info

How To Work with Prototypes and Inheritance in JavaScript | DigitalOcean

JavaScript is a prototype-based language, meaning object properties and methods can be shared through generalized…
www.digitalocean.com

Master JavaScript Prototypes & Inheritance

Inheritancecodeburst.io

JavaScript’s Prototypal Inheritance Explained Using CSS

Prototypal inheritance is arguably the least understood aspect of JavaScript. Well the good news is that if you…medium.freecodecamp.org

Demystifying ES6 Classes And Prototypal Inheritance

In the early history of the JavaScript language, a cloud of animosity formed over the lack of a proper syntax for…scotch.io

Intro To Prototypal Inheritance - JS

In this article I will try to give an introduction to protypal inheritance. As an "optional" pre-requisite, you can…dev.to

Let's Build Prototypal Inheritance in JS

The idea for this post is pretty simple. I want to some extent build and with that, illustrate how prototypes work in…dev.to

Objects, Prototypes and Classes in JavaScript

JavaScript is based on a simple object-oriented programming model with objects being a fundamental part of the…dev.to

The magical world of JavaScript prototypes

How many times have we heard "JavaScript is not an Object-Oriented language, it's Prototype-oriented"? It turns out…dev.to

Understanding Prototypal Inheritance In JavaScript

What Is Object-oriented Programming (OOP) Classical vs Prototypal Inheritance The Prototype Object And The Prototype…dev.to

Object.create() - JavaScript | MDN

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object…developer.mozilla.org

Object.assign() - JavaScript | MDN

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It…developer.mozilla.org

Object.create in JavaScript

The Object.create method is one of the methods to create a new object in JavaScript.medium.com

Javascript Objects | A New Way to Create Objects | HTML Goodies

There are a lot of ways to create Objects in JavaScript, perhaps even more to integrate inheritance into them. Just…
www.htmlgoodies.com

Basic Inheritance with Object.create

A few issues back we looked at how to implement basic inheritance with constructors. In this issue, we'll look at how…adripofjavascript.com

Object.create( ) In JavaScript - GeeksforGeeks

Object and Object Constructors in JavaScript? In the living world of object-oriented programming we already know the…
www.geeksforgeeks.org

Understanding the difference between Object.create() and the new operator.

Why is it important to know the difference?medium.com

JavaScript Object Creation: Patterns and Best Practices - SitePoint

Jeff Mott guides you through a step-by-step approach to JavaScript object creation - from object literals to factory…
www.sitepoint.com

Dealing With Objects in JavaScript With Object.assign, Object.keys and hasOwnProperty |…

This post is a sort of grab bag to help you explore a few very useful methods to help you manage your objects in…alligator.io

Copying Objects in JavaScript | DigitalOcean

Objects are the fundamental blocks of JavaScript. An object is a collection of properties, and a property is an…scotch.io

JavaScript: Object.assign()

Veja nesse artigo como utilizar o Object.assign() do ECMAScript 6codeburst.io

How to deep clone a JavaScript object

Copying objects in JavaScript can be tricky. Some ways perform a shallow copy, which is the default behavior in most of…flaviocopes.com

Object.create(): When and Why to Use

Object.create() is a method available on all JavaScript objects. It takes two arguments: the object you want to copy…dev.to

JavaScript Functional Programming — map, filter and reduce

Even if you don’t know what functional programming is you’ve probably been using map, filter and reduce just because…medium.com

Learn map, filter and reduce in Javascript

The perfect toolset for your venture in Functional Programmingmedium.com

JavaScript's Map, Reduce, and Filter * Dan Martensen

As engineers we build and manipulate arrays holding numbers, strings, booleans and objects almost everyday. We use them…danmartensen.svbtle.com

How to Use Map, Filter, and Reduce in JavaScript

Functional programming has been making quite a splash in the development world these days. And for good reason…code.tutsplus.com

JavaScript — Learn to Chain Map, Filter, and Reduce

Learn how to chain map, filter, and reduce in JavaScriptcodeburst.io

Understanding map, filter and reduce in Javascript

When working on Javascript projects you inevitably come across situations where you have to do some data manipulation…hackernoon.com

Functional Programming in JS: map, filter, reduce (Pt. 5)

Note: This is part of the “Javascript and Functional Programming” series on learning functional programming techniques…hackernoon.com

JavaScript: Map, Filter, Reduce

JavaScript's built-in map, filter, and reduce array methods are invaluable to a modern JavaScript developer. First…wsvincent.com

JavaScript Arrow Functions: Fat and Concise Syntax in ES6

In this article, you'll learn all about JavaScript's arrow function syntax - including some of the gotchas you need to…
www.sitepoint.com

JavaScript: Arrow Functions for Beginners

Last week I published this post on the keyword this for beginners. One of the topics that wasn’t covered in that…codeburst.io

When (and why) you should use ES6 arrow functions — and when you shouldn’t

Arrow functions (also called “fat arrow functions”) are undoubtedly one of the more popular features of ES6. They…medium.freecodecamp.org

JavaScript — Learn & Understand Arrow Functions

A beginners guide to Arrow Functions in JavaScriptcodeburst.io

(JavaScript )=> Arrow functions

This post is meant to summarise some of the things someone new to JavaScript and arrow functions needs to know. I do…medium.com

Javascript.reduce()

The Mutli-Tool of JSandepaulj.medium.com

Why you should replace forEach with map and filter in JavaScript - Gofore

TL;DR Prefer map and filter over forEach when you need to copy an array or part of it to a new one. One of the best…gofore.com

Simplify your JavaScript – Use .map(), .reduce(), and .filter()

If you haven’t heard of .map(), .reduce(), and .filter() in JavaScript, you might want to learn to use it!medium.com

JavaScript's Reduce Method Explained By Going On a Diet

The reduce method in JavaScript gives you a simple way to take an array of values and combine them into one value, or…blog.codeanalogies.com

Difference between map, filter and reduce in JavaScript

I’ve seen a lot of JS beginners struggle when using map, filter or reduce and don’t know the different use cases of…medium.com

Map⇄Filter⇄Reduce↻ | Hacker Noon

Share it on LinkedIn! Due to that reason we were introduced with these three higher order functions, namely 🗺️Map…hackernoon.com

Finding Your Way With .Map()

At the end of the article is a CodePen that demonstrates the concepts presented here.medium.freecodecamp.org

How to write your own map, filter and reduce functions in JavaScript

A sneak peek into functional programming and higher order functions in Javascript.medium.freecodecamp.org

How to Manipulate Arrays in JavaScript

An important part of any programming language. Most times we need to do several operations on arrays, hence this…
www.freecodecamp.org

.map(), .filter(), and .reduce()

Originally posted on my blog For the last several weeks I've been applying for jobs. Sadly, the startup I was working…dev.to

Map, Filter and Reduce – Animated

Map, filter and reduce have been around for a long time. They are often seen as part of Functional Programming style.jstutorial.medium.com

Map, Filter, Reduce and others Arrays Iterators You Must Know to Become an Algorithms Wizard

In this article we are going to take a close look at some arrays iterators like , , or others methods that use…dev.to

How to Use JavaScript’s .map, .filter, and .reduce

How to use these three useful JavaScript functionsbetterprogramming.pub

Javascript performance test - for vs for each vs (map, reduce, filter, find).

We all know that for loop are faster than for each or javascript function since under the hood of javascript functions…towardsdatascience.com

Using .map(), .filter() and .reduce() properly 👩🏽‍💻

Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a…javascript.plainenglish.io

Javascript and Functional Programming — Pt. 3: Pure Functions

Purityhackernoon.com

Master the JavaScript Interview: What is a Pure Function?

Pure functions are essential for a variety of purposes, including functional programming, reliable concurrency, and…medium.com

JavaScript: What Are Pure Functions And Why Use Them?

The first time I heard the term “Pure Function” I was confused. What was wrong with a regular function? Why does it…medium.com

Pure functions in JavaScript

A pure function doesn't depend on and doesn't modify the states of variables out of its scope. Concretely, that means a…
www.nicoespeon.com

Functional Programming: Pure Functions - SitePoint

This is the second part of a two part series on functional programming in Ruby. Before we explored immutable values…
www.sitepoint.com

Pure Functions In Javascript

Pure functions in Javascript are kind of Functions where the return value is determined by its parameter passed at call…appdividend.com

Making your JavaScript Pure

Once your website or application goes past a small number of lines, it will inevitably contain bugs of some sort. This…alistapart.com

Arrays, Objects and Mutations

Here are some thoughts on how to avoid mutations when working with arrays and objects in JavaScript by treating them as…medium.com

The State of Immutability

Immutability is a hot subject in modern JavaScript. The reason why this topic is so popular now is of course the…medium.com

How to deal with dirty side effects in your pure functional JavaScript

If you start learning about functional programming, it won't be long before you come across the idea of pure functions…jrsinclair.com

Preventing Side Effects in JavaScript

JavaScript is very dynamic these days but I still see a lot of legacy code, whether it be for optimal backward…davidwalsh.name

Wielding Pure Functions in JavaScript and Function Composition

Today, I'd like to share some thoughts on two fundamental concepts in functional programming: Pure functions and…scotch.io

JavaScript: Pure Functions

Pure functions are fundamental to functional programming, concurrency, writing testable code, and having deterministic…wsvincent.com

Functional programming paradigms in modern JavaScript: Pure functions

JavaScript is one of the most popular programming languages out there. It runs in the browser, on desktop, on mobile…hackernoon.com

Understanding Javascript Mutation and Pure Functions

Boost your app performance by better understanding Mutation and Pure Functions in JSblog.bitsrc.io

Functional-ish JavaScript

Functional programming is a great discipline to learn and apply when writing JavaScript. Writing stateless, idempotent…bluepnume.medium.com

Introduction to events - Learn web development | MDN

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so…developer.mozilla.org

Bubbling and capturing

Let's start with an example. This handler is assigned to , but also runs if you click any nested tag like or : Isn't it…javascript.info

https://www.youtube.com/watch?v=Jh_Uzqzz_wM

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

https://javascript.info/closure

I never understood JavaScript closures

Until someone explained it to me like this …medium.com

Understand JavaScript Closures With Ease

Closures allow JavaScript programmers to write better code. Creative, expressive, and concise. We frequently use…javascriptissexy.com

Understanding JavaScript Closures

When you’re first learning JavaScript, terms like “closures” may make the language appear mystical and hard to…codeburst.io

https://codeburst.io/understand-closures-in-javascript-d07852fa51e7

A simple guide to help you understand closures in JavaScript

Closures in JavaScript are one of those concepts that many struggle to get their heads around. In the following…medium.freecodecamp.org

Understanding JavaScript Closures: A Practical Approach

Learning a new language involves a series of steps, whereas its mastery is a product of patience, practice, mistakes…scotch.io

Understanding JavaScript: Closures

Why learn JavaScript in depth?hackernoon.com

How to use JavaScript closures with confidence

Using closures will be a piece of (chocolate) cakehackernoon.com

JavaScript Closures by Example

At some point you may have run into a problem when executing functions from within a for loop. The first time it…howchoo.com

JavaScript — Closures and Scope

Looking at JavaScript today, it can be scary as a beginner. People talk about watching out for all the little quirks or…codeburst.io

Discover the power of closures in JavaScript

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority! A closure…medium.freecodecamp.org

Simplified JavaScript: Getting Started with Closures

Eric Elliot, in his Medium article Master the JavaScript Interview: What is a Closure?, explains that when he…code.likeagirl.io

Javascript Closures 101 - Explaining how closures work

So, "closures", right? That's a fun one that tends to cause confusion all around. It's pretty much a given that at some…reallifejs.com

Closure, Currying and IIFE in JavaScript

These are some of the concepts of JavaScript where everyone struggle in beginning. Lets try to simplify them bit by…dev.to

Understanding Closures in JavaScript

Learn How Closures Really Work in JavaScript: hands-on guideblog.bitsrc.io

A basic guide to Closures in JavaScript

The Closure is a collection of all variables in scope at the time of function creation. To use closure create a…medium.freecodecamp.org

Closures: Using Memoization

One of the core tenets of Functional Programming is that a function should return the same value if given the same…dev.to

A Brief Introduction to Closures and Lexical Scoping in JavaScript

“Writing in ECMAScript language without understanding closure is like writing Java without understanding classes”betterprogramming.pub

Demystify Closures

In the previous post we implemented functions, but not about closures. Let's fix this. Without closures following code…dev.to

Scope - JavaScript Concepts

This is part of a series where I try to explain through each of 33 JS Concepts. Originally written on my blog with…dev.to

Understanding Closures in JavaScript

When you declare a function inside another function, a closure is the new environment created by combining the inner…dev.to

What the fuck is a closure? ・ Dan's JavaScript Glossary

Closures are confusing because they are an "invisible" concept. When you use an object, a variable, or a function, you…whatthefuck.is

Closures in JavaScript can...

I gain more understanding of a topic when I get to talk/write about it... much to my wife's horror as she has zero…dev.to

https://www.youtube.com/watch?v=1JsJx1x35c0

Higher-Order Functions :: Eloquent JavaScript

Tzu-li and Tzu-ssu were boasting about the size of their latest programs. 'Two-hundred thousand lines,' said Tzu-li…eloquentjavascript.net

Higher-Order Functions in JavaScript - SitePoint

Continuing his look at functional programming in JavaScript, M. David Green examines higher-order functions and how…
www.sitepoint.com

Higher Order Functions: Using Filter, Map and Reduce for More Maintainable Code

Higher order functions can help you to step up your JavaScript game by making your code more declarative. That is…medium.freecodecamp.org

First-class and Higher Order Functions: Effective Functional JavaScript

Functions: the killer JavaScript feature we never talk about.hackernoon.com

Higher Order Functions in JavaScript

Higher-order functions can be intimidating at first, but they're not that hard to learn. A higher-order function is…
www.lullabot.com

Higher-order Functions - JavaScript Is Sexy

In JavaScript, functions are first-class objects; that is, functions are of the type Object and they can be used in a…javascriptissexy.com

Fun With Higher Order Functions In JavaScript

JavaScript is often referred to as a language with functional programming capabilities because of it's "higher order…derickbailey.com

pedroapfilho/array-methods

Just a reminder on how to use array methods. Contribute to pedroapfilho/array-methods development by creating an…github.com

Understanding Higher-Order Functions in JavaScript

Learn What Higher-Order Functions are and how to use them in JavaScriptblog.bitsrc.io

Higher Order Functions - A pragmatic approach

Its a common saying that functions are the bread and butter of programming, and the basic unit for building reusable…dev.to

Recursion in JavaScript

I’m just gonna get this out of the way right up front, because people get really angry otherwise:medium.freecodecamp.org

Understanding Recursion in JavaScript

One of the many things that JavaScript has going for it is the ability to recursively call functions. This feature is…medium.com

Learn and Understand Recursion in JavaScript

I’ll walk you through two popular JS recursion examples in 10 minutes so you can finally understand how recursion works…codeburst.io

Recursion in Functional JavaScript - SitePoint

M. David Green demonstrates the powerful, but dizzying concept of recursion by refactoring normal for and while loops…
www.sitepoint.com

Programming with JS: Recursion

Understanding data structures, algorithms and basic programming concepts is essential for one to become a better…hackernoon.com

Anonymous Recursion in JavaScript

Yes, there is such thing, and I thought it would be an interesting example to share. It features: closures…dev.to

Recursion, iteration and tail calls in JS

If you've been on the business for some time, you have, most likely, come across the definition of recursion, for which…
www.jstips.co

Intro to Recursion

Recursion can be a difficult concept to wrap your head around, but its definition is rather simple: recursion is when a…medium.com

Accio Recursion!: Your New Favorite JavaScript Spell

The spell “Accio” allows a witch or wizard to summon something to them. Casting Accio is just like accessing a value in…medium.datadriveninvestor.com

Recursion Explained (with Examples)

"To understand recursion, one must first understand recursion" - Unknown Recursion is a method of solving problems…dev.to

Generator - JavaScript | MDN

This object cannot be instantiated directly. Instead, a Generator instance can be returned from a generator function…developer.mozilla.org

ES6 In Depth: Collections - Mozilla Hacks - the Web developer blog

ES6 In Depth is a series on new features being added to the JavaScript programming language in the 6th Edition of the…hacks.mozilla.org

ES6 Collections: Using Map, Set, WeakMap, WeakSet - SitePoint

Most major programming languages have several types of data collections. Python has lists, tuples, and dictionaries…
www.sitepoint.com

Introduction to Maps in JavaScript | DigitalOcean

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited…alligator.io

Map and Set

Till now, we've learned about the following complex data structures: Objects are used for storing keyed collections…javascript.info

Maps in ES6 - A Quick Guide

Maps and Sets often get lumped together in articles. They're both new ES6 collection types with similar interfaces but…dev.to

ES6 — Set vs Array — What and when?

What is Set and what is Array?medium.com

ES6 — Map vs Object — What and when?

You may wonder — why Map vs Object but not Map vs Array, or Object vs Set? Well, you can also compare between any of…medium.com

ES6: Working with Sets in JavaScript

In this post we're continuing to look at features introduced in ES6. Amongst all the cool things happening in ES6, we…
www.deadcoderising.com

Array vs Set vs Map vs Object — Real-time use cases in Javascript (ES6/ES7)

The internet is a great place to find information, but there is one teeny-tiny problem. You are on a boat in the middle…codeburst.io

How to create an array of unique values in JavaScript using Sets

Sorry for the verbose title - sometimes things can be explained better with a code example. Imagine you have a…dev.to

What You Should Know About ES6 Maps

JavaScript ES6 introduces a new data structure, called maps. Maps are designed as an alternative to using Object…hackernoon.com

ES6 Maps in Depth

A very common abuse case of JavaScript objects is hash-maps, where we map string keys to arbitrary values.ponyfoo.com

What are JavaScript Generators and how to use them

In this article, we’re going to take a look at the generators that were introduced in ECMAScript 6. We’ll see what it…codeburst.io

Understanding Generators in ES6 JavaScript with Examples

ES6 introduced a new way of working with functions and iterators in the form of Generators (or generator functions). A…codeburst.io

The Basics Of ES6 Generators

One of the most exciting new features coming in JavaScript ES6 is a new breed of function, called a generator. The name…davidwalsh.name

An Introduction to JavaScript Generators

One of the fundamentals of JavaScript is that it is single-threaded, meaning that two pieces of code cannot run at the…dev.to

Promise - JavaScript | MDN

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting…developer.mozilla.org

Understanding JavaScript Promises | DigitalOcean

Javascript Promises can be challenging to understand. Therefore, I would like to write down the way I understand…scotch.io

Understanding Promises in JavaScript

An in-depth look at creating and handling Promiseshackernoon.com

Master the JavaScript Interview: What is a Promise?

“Master the JavaScript Interview” is a series of posts designed to prepare candidates for common questions they are…medium.com

An Overview of JavaScript Promises - SitePoint

This article explores JavaScript's new Promises API, showing how you can leverage promises in your JavaScript…
www.sitepoint.com

How to use Promises in JavaScript

Promises in JavaScript are a way to handle async calls. Before Promises were introduced in JavaScript ES6, async calls…medium.freecodecamp.org

Implementing Promises In JavaScript

The thing I love most about programming is the aha! moment when you start to fully understand a concept. Even though it…medium.freecodecamp.org

JavaScript: Promises explained with simple real life analogies

Talking about promises in layman termscodeburst.io

25. Promises for asynchronous programming

This chapter is an introduction to asynchronous programming via Promises in general and the ECMAScript 6 Promise API in…exploringjs.com

JavaScript Promises Explained By Gambling At A Casino

We all love the asynchronous capabilities of JavaScript. In fact, we love them so much that sometimes, we overindulge…blog.codeanalogies.com

ES6 Promises: Patterns and Anti-Patterns

When I first got started with NodeJS a few years ago, I was mortified by what is now affectionately known as “callback…medium.com

A Simple Guide to ES6 Promises

The woods are lovely, dark and deep. But I have promises to keep, and miles to go before I sleep. — Robert Frostcodeburst.io

The ES6 Promises

A very helpful feature in ES6codeburst.io

ES6 Promises in Depth

Promises are a very involved paradigm, so we'll take it slow. Here's a table of contents with the topics we'll cover in…ponyfoo.com

Javascript Promises: An In-Depth Approach

“Write down the syntax for promises on this sheet of paper”, is enough to give nightmares to a lot of junior and even…codeburst.io

How to Write a JavaScript Promise

What is a promise?medium.freecodecamp.org

A Coding Writer’s Guide: An Introduction To ES6 Promises

Welcome back to the ‘A Coding Writer’s Guide’ series! If you have been keeping up with this series, you’d know that I…medium.com

Reverse engineering - Understanding Promises in JavaScript

We will reverse engineer Promises in JavaScript together with some 90s nostalgia. Tagged with showdev, tutorial…dev.to

Converting callbacks to promises

It's easier to work with Promises (or Async/await) compared to callbacks. This is especially true when you work in…dev.to

JavaScript Promises: Zero To Hero Plus Cheat Sheet

It’s time, friend. Native JavaScript promises explained how I wish they were explained to me — plus a handy cheat…medium.com

Promises - JavaScript concepts

This is part of a series where I try to explain through each of 33 JS Concepts. This part corresponds to Promises…dev.to

Javascript Promise 101

Knowing how Promise works in javascript will boost your development skill exponentially. Here I will share: I promise…dev.to

Simplify JavaScript Promises

I love promises. Not from people, but from JavaScript. Tweet Quote I love promises. Not from people, but from…dev.to

The Lowdown on Promises

A quick and concise guide on how Promises work in JavaScriptmedium.com

⭐️🎀 JavaScript Visualized: Promises & Async/Await

Ever had to deal with JS code that just... didn't run the way you expected it to? Maybe it seemed like functions got…dev.to

Promises in JavaScript

Callbacks are functions that run after something happens or something completes. If you have to make an asynchronous…dev.to

Best Practices for ES6 Promises

ES6 promises are great! Yet... they are still quite painful to deal with. In this article, I share the best practices I…dev.to

Async/await

There's a special syntax to work with promises in a more comfortable fashion, called "async/await". It's surprisingly…javascript.info

Asynchronous Programming :: Eloquent JavaScript

Who can wait quietly while the mud settles?Who can remain still until the moment of action? Laozi, Tao Te Ching The…eloquentjavascript.net

24. Asynchronous programming (background)

This chapter explains foundations of asynchronous programming in JavaScript. It provides background knowledge for the…exploringjs.com

Understanding async-await in JavaScript

Rules of thumb and examples for when and how to use async and awaithackernoon.com

Exploring Async/Await Functions in JavaScript | DigitalOcean

Promises give us an easier way to deal with asynchrony in our code in a sequential manner. Considering that our brains…alligator.io

Asynchronous Javascript using Async - Await

Async/await is a relatively new way to write asynchronous code in Javascript. Before we used callbacks and promises…scotch.io

Modern Asynchronous JavaScript with Async and Await

JavaScript evolved in a very short time from callbacks to promises (ES2015), and since ES2017 asynchronous JavaScript…flaviocopes.com

Asynchronous JavaScript: From Callback Hell to Async and Await

One of the keys to writing a successful web application is being able to make dozens of AJAX calls per page. This is a…
www.toptal.com

Javascript — ES8 Introducing async/await Functions

To gain some perspective on why folks are so excited about the ES8 async/await functions, you have to be familiar with…medium.com

How to escape async/await hell

async/await freed us from callback hell, but people have started abusing it — leading to the birth of async/await hell.medium.freecodecamp.org

Understanding JavaScript's async await

Let's suppose we had code like the following. Here I'm wrapping an HTTP request in a Promise. The promise fulfills with…ponyfoo.com

JavaScript Async/Await: Serial, Parallel and Complex Flow - TechBrij

If you have experience on ASP.NET MVC then probably you are familiar with async/await keywords in C#. The same thing is…techbrij.com

From JavaScript Promises to Async/Await: why bother?

In this tutorial, we will cover why we need async/await when we could achieve the same fit with JavaScript Promises, to…blog.pusher.com

Flow Control in Modern JS: Callbacks to Promises to Async/Await - SitePoint

JavaScript is regularly claimed to be asynchronous. What does that mean? How does it affect development? How has the…
www.sitepoint.com

JavaScript: Promises and Why Async/Await Wins the Battle - DZone Performance

Calling the validatePassword() function: The code snippet below shows a full end to end check for validating a password…dzone.com

How to Improve Your Asynchronous JavaScript Code With Async and Await

If you’ve had the chance to observe modern JavaScript code, there are high chances that you’ve seen the async and await…medium.freecodecamp.org

Making Fetches Easy With Async Await

Asynchronous requests are the source of many common and frustrating bugs in otherwise clean code. Because most of…medium.com

7 Reasons Why JavaScript Async/Await Is Better Than Plain Promises (Tutorial)

Async/await was introduced in NodeJS 7.6 and is currently supported in all modern browsers. I believe it has been the…dev.to

Asynchronous Operations in JavaScript

JavaScript comes from a legacy of peril with asynchronous operations. It began with callbacks to make Ajax calls for…dev.to

Async/await: A slight design flaw.

My experience with async/await is that it's amazing for simple cases and fulfils expectations. If your use cases are…dev.to

JavaScript: Promises or async-await

A set of rules for when to use whichbetterprogramming.pub

Async / Await: From Zero to Hero

I had absolutely no idea what async / await was and learning it was hard as: There's 27 minutes worth of text to read…dev.to

Data Structures in JavaScript

For Frontend Software Engineersmedium.com

Algorithms and Data Structures in JavaScript

Algorithms and data structures implemented in JavaScript with explanations and links to further readings and YouTube…itnext.io

Data Structures: Objects and Arrays

Ever seen some data in square brackets and curly brackets in JavaScript? These are Arrays and Objects respectively. //…scotch.io

Data structures in JavaScript

The #data-structures series is a collection of posts about reimplemented data structures in JavaScript. If you are not…blog.benoitvallon.com

Playing with data structures in Javascript — Stack

Javascript is evolving each day. With the rapid growth of frameworks and platforms like React, Angular, Vue, NodeJS…blog.cloudboost.io

The Little Guide of Queue in JavaScript

A queue is a simple data structure that allows elements to be inserted from one end, called the rear (also called…hackernoon.com

barretlee/algorithms

Detail & Discusion (讨论和细节) All algorithms writing with JavaScript in book ' Algorithms Fourth Edition'. Run…github.com

humanwhocodes/computer-science-in-javascript

Collection of classic computer science paradigms, algorithms, and approaches written in JavaScript. …github.com

jamiebuilds/itsy-bitsy-data-structures

Welcome to Itsy Bitsy Data Structures! In here are super simplified examples of many of the common data structures…github.com

About DEV - DEV Community

DEV is a community of software developers getting together to help one another out. The software industry relies on…dev.to

Data Structures: Understanding Graphs

What is a graph? Graphs are used to represents relationships and hierarchies and are composed of nodes and edges.javascript.plainenglish.io

Data Structures Two Ways: Linked List (Pt 1)

I work primarily with JavaScript, but the place I work is using Java on the backend. Always being fascinated with…dev.to

Data Structures Two Ways: Linked List (Pt2)

If you are new- well hello! check out part one if you like to start at the beginning or just jump straight in Right on…dev.to

Graph Data Structures Explained in JavaScript

In this post, we are going to explore non-linear data structures like graphs. Also, we'll cover the central concepts…dev.to

Big O Notation in Javascript

Get ready for your tech job interviewmedium.com

Time Complexity/Big O Notation

Scaling Algorithms Instead of Applicationsmedium.com

Big O in JavaScript

Like many new developers before me, Big O went straight over my head the first time I heard about it. It was a topic…medium.com

http://www.bradoncode.com/blog/2012/04/big-o-algorithm-examples-in-javascript.html

Time Complexity Analysis in JavaScript

An algorithm is a self-contained step-by-step set of instructions to solve a problem. It takes time for these steps to…
www.jenniferbland.com

Algorithms in plain English: time complexity and Big-O notation

Every good developer has time on their mind. They want to give their users more of it, so they can do all those things…medium.freecodecamp.org

An Introduction to Big O Notation

Big O notation is a big topic, and its universal importance stems from the fact that it describes the efficiency of…dev.to

Crizstian/data-structure-and-algorithms-with-ES6

Num Type Exercises Description 10.- Graph Data Structure 2 A graph consists of a set of vertices and a set of edges. A…github.com

trekhleb/javascript-algorithms

This repository contains JavaScript based examples of many popular algorithms and data structures. Each algorithm and…github.com

JS: Algorithm

More Questions CSS Interview Questions , HTML Interview Questions if you are little more comfortable or claim to be…
www.thatjsdude.com

Algorithms in JavaScript

40 Problems, Solutions, and Explanationsmedium.com

JavaScript Objects, Square Brackets and Algorithms

One of the most powerful aspects of JavaScript is being able to dynamically refer to properties of objects. In this…medium.freecodecamp.org

felipernb/algorithms.js

Classic algorithms and data structures implemented in JavaScript, you know... FOR SCIENCE.github.com

yangshun/lago

📕 Data Structures and Algorithms library in TypeScript - yangshun/lagogithub.com

idosela/algorithms-in-javascript

Collection of computer science algorithms and data structures written in JavaScript. Run the sort performence test…github.com

Algorithms and Data Structures in JavaScript

Hello Readers! I've recently launched JavaScript Algorithms and Data Structures repository on GitHub with a collection…dev.to

Inheritance in JavaScript - Learn web development | MDN

This article has covered the remainder of the core OOJS theory and syntax that we think you should know now. At this…developer.mozilla.org

Class inheritance

Class inheritance is a way for one class to extend another class. So we can create new functionality on top of the…javascript.info

Inheritance in JavaScript

Detailed walk thorough of inheritance in JavaScriptmedium.com

https://www.sitepoint.com/simple-inheritance-javascript/

JavaScript — Inheritance, delegation patterns and Object linking

Learn about inheritance in JavaScript (prototypal inheritance), behavior/object delegation pattern and objects linked…codeburst.io

Object Oriented JavaScript: Polymorphism with examples

Again this is not the advance topic of JavaScript but it relies under Object Oriented JavaScript & polymorphism is one…blog.knoldus.com

Program Like Proteus — A beginner’s guide to polymorphism in Javascript

medium.com

Object-oriented JavaScript: A Deep Dive into ES6 Classes - SitePoint

Often we need to represent an idea or concept in our programs - maybe a car engine, a computer file, a router, or a…
www.sitepoint.com

Learning JavaScript Design Patterns

An open-source book on JavaScript Design Patternsaddyosmani.com

JavaScript Design Patterns | DigitalOcean

There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the…scotch.io

JavaScript Design Patterns

The ultimate guide to the most useful design patternsbetterprogramming.pub

JavaScript Design Patterns

Constructor Patternmedium.com

Javascript Design Patterns: What They Are & How To Use Them

Developers often encounter coding problems in JavaScript that can be solved by using well-established design patterns…seesparkbox.com

Understanding Design Patterns in JavaScript

Learn About Various Design Patterns in JavaScriptblog.bitsrc.io

fbeline/design-patterns-JS

Here you will find the 23 (GoF) design patterns implemented in JavaScript using both prototype and ES6 classes. You can…github.com

The Power of the Module Pattern in JavaScript

Embellish your app with the module patternbetterprogramming.pub

Design Patterns for Developers using JavaScript - Part One

Most developers using JavaScript strives to write code that is readable, maintainable, and reusable because writing…dev.to

Design Patterns for Developers using JavaScript - Part Two

In the previous article, we had a look at design patterns, its definition, history, and the incorporation into software…dev.to

Design patterns in modern JavaScript development

Thoughts on effective communication in the design of software projectslevelup.gitconnected.com

Understanding Design Patterns: Iterator using Dev.to and Medium social networks!

There are 23 classic design patterns, which are described in the original book, Design Patterns: Elements of Reusable…dev.to

JavaScript Design Patterns - Factory Pattern

Welcome to my new development series where I try my best to explain design patterns by using JavaScript! In software…dev.to

JavaScript Design Pattern — Module Pattern

One of the most common patterns in JavaScriptjavascript.plainenglish.io

Design Patterns: Null Object

Avoid conditional complexity using this patternbetterprogramming.pub

Strategy Pattern

GitHub Link:
https://github.com/FrancescoXX/Design-Patterns-Strategy-Javascript The Strategy pattern, also called…dev.to

Adapter Pattern

Github link:
https://github.com/FrancescoXX/Design-Pattern-Adapter-Javascript The Adapter pattern is used to allow a…dev.to

The Power of Composite Pattern in JavaScript

Find me on medium In this post, we will be going over the Composite Design Pattern in JavaScript. In... Tagged with…dev.to

In Defense of Defensive Programming

NOTE: In this article I reference a validation library that I wrote called allow. It's now in an NPM package that can…dev.to

JavaScript Design Patterns | Udacity Free Courses

Free Course Organizing Code in a Disorganized World Start Free Course About this Course This course covers methods for…
www.udacity.com

getify/Functional-Light-JS

Chapter 2 explored the core nature of JS functions, and laid the foundation for what makes a function an FP function…github.com

Use function composition in JavaScript | Codementor

Prerequisite: I use currying in this post, so if you don't know about that, I encourage you to read my previous post…
www.codementor.io

Currying in JavaScript ES6

Currying can give you a deeper understanding to JavaScript. Let’s see how it can be done with arrow functions!blog.benestudio.co

Writing Middleware —Composition and Currying Elegance in JavaScript

Javascript is an elegant and beautiful language which allows the developers to have the flexibility to move between the…medium.com

Functional JavaScript: Function Composition For Every Day Use.

Function composition has got to be my favorite part of functional programming. I hope to provide you with a good real…medium.com

What I Learned Today 💡 July 2, 2017

Functional Composition: compose() and pipe()medium.com

Why The Hipsters Compose Everything: Functional Composing In JavaScript

Lodash and Underscore are everywhere and still there is this one supper efficient method that actually only those…busypeoples.github.io

A Gentle Introduction to Functional JavaScript: Part 3

This is part three of a four-part series introducing 'functional' programming in JavaScript. In the last article we saw…jrsinclair.com

Curry And Compose (why you should be using something like ramda in your code)

When it comes to functional programming, the main cornerstone is composability, the ability to create new functions…jsleao.wordpress.com

Function Composition in JavaScript with Pipe

December 13, 2016 This post uses ES6 syntax. The same things can be accomplished with ES5, but it would require more…vanslaars.io

Practical Functional Javascript with Ramda - Telerik Blogs

Article co-authored by: Andrew D'Amelio and Yuri Takhteyev At rangle.io we've been fans of the functional programming…developer.telerik.com

The beauty in Partial Application, Currying, and Function Composition.

Story Timehackernoon.com

Curry or Partial Application?

The Difference Between

Partial Application and Curry
medium.com

Partial Application in JavaScript

Unless you've used another functional programming language such as ML or Haskell, concepts such as partial application…benalman.com

Partial Application of Functions

Providing function with fewer arguments than it expects is called Partial Application of functions.hackernoon.com

Javascript- Currying VS Partial Application

A lot of people get confused in between currying and partial application and many of us do not know what, where and…towardsdatascience.com

Partial Application in ECMAScript 2015

Some of this material originally appeared in What's the difference between Currying and Partial Application? Here it is…raganwald.com

Functional Composition in Javascript

Functional composition is when you take two or more functions, and make one a single function out of them. When you…joecortopassi.com

So You Want to be a Functional Programmer (Part 1)

Taking that first step to understanding Functional Programming concepts is the most important and sometimes the most…cscalfani.medium.com

So You Want to be a Functional Programmer (Part 2)

Taking that first step to understanding Functional Programming concepts is the most important and sometimes the most…cscalfani.medium.com

So You Want to be a Functional Programmer (Part 3)

Taking that first step to understanding Functional Programming concepts is the most important and sometimes the most…cscalfani.medium.com

So You Want to be a Functional Programmer (Part 4)

Taking that first step to understanding Functional Programming concepts is the most important and sometimes the most…cscalfani.medium.com

So You Want to be a Functional Programmer (Part 5)

Taking that first step to understanding Functional Programming concepts is the most important and sometimes the most…cscalfani.medium.com

An Introduction to the basic principles of Functional Programming

After a long time learning and working with object-oriented programming, I took a step back to think about system…medium.freecodecamp.org

Concepts of Functional Programming in Javascript

After a long time learning and working with object-oriented programming, I took a step back to think about system…medium.com

An Introduction to Functional Programming Style in JavaScript

In recent years there has been a tectonic shift happening between traditional programming and Functional Programming…medium.freecodecamp.org

A practical guide to writing more functional JavaScript

Functional programming is great. With the introduction of React, more and more JavaScript front-end code is being…medium.freecodecamp.org

A simple explanation of functional pipe in JavaScript

Sometimes I'm asked why we don't have "dot-chaining" in RxJS anymore, or why RxJS made the switch to use pipe. There…dev.to

ryanmcdermott/clean-code-javascript

Software engineering principles, from Robert C. Martin's book , adapted for JavaScript. This is not a style guide. It's…github.com

JavaScript Clean Coding Best Practices | @RisingStack

Writing clean code is what you must know and do in order to call yourself a professional developer. There is no…blog.risingstack.com

Function parameters in JavaScript — Clean Code

In my time as a web developer I have to deal a lot with JavaScript Code. I love JavaScript, no question asked. But…kevin-peters.medium.com

Keeping your code clean

I settled down in my sit, cranking the solution with my team members. “We must win this” I said, burying myself deep…codeburst.io

Best Practices for Using Modern JavaScript Syntax - SitePoint

This article is featured in our book, Modern JavaScript is evolving quickly to meet the changing needs of new…
www.sitepoint.com

cross-js/cross-js

Adopting CrossJS style means your javascript can work in any environment without being dependent on any core…github.com

Writing Clean Code

We can all agree that writing clean code is important. It makes it easier to work in a team, and even if we're a single…dev.to

Writing Clean Code and The Practice of Programming: Actionable advice for beginners

"The purpose of style is to make the code easy to read for yourself and others, and good style is crucial to good…dev.to

Clean code, dirty code, human code

Last week, Dan Abramov posted a very personal and humbling blog post entitled Goodbye, Clean Code. I saw a tweet about…dev.to

Practical Ways to Write Better JavaScript

Solid methods of improving your JS. Tagged with javascript, webdev, beginners, react.dev.to

By Bryan Guner on July 3, 2021.

Canonical link

Exported from Medium on August 24, 2021.

A Collection of my most useful Gist Entries

This list is in no particular order!


A Collection of my most useful Gist Entries

This list is in no particular order!

Web-Dev-Hub

Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app

Ubuntu Setup:

Markdown Notes Template:

Jquery Cheat Sheet:

Useful Bash Commands:

Python Cheat Sheet:

Html Cheat Sheet:

Git Cheat Sheet:

Deploy React App To Heroku:

Bash Aliases:

JS Cheat Sheet:

CSS Cheat Sheet:

If you found this guide helpful feel free to checkout my github/gists where I host similar content:

bgoonz’s gists · GitHub

bgoonz — Overview

Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com

Or Checkout my personal Resource Site:

https://bgoonz-blog.netlify.app/

By Bryan Guner on March 6, 2021.

Canonical link

Exported from Medium on August 24, 2021.

A Comprehensive Deep Dive into React

An in-depth look into the world of React.


React in Depth: A Comprehensive Guide

A deep dive into the world of React.

Photo by Ferenc Almasi on Unsplash
Photo by Ferenc Almasi on Unsplash
ALLOFMYOTHERARTICLES

bryanguner.medium.com

Random Things to Remember

  • Using () implictly returns components.
  • Role of index.js is to render your application.
  • The reference to root comes from a div in the body of your public HTML file.
  • State of a component is simply a regular JS Object.
  • Class Components require render() method to return JSX.
  • Functional Components directly return JSX.
  • Class is className in React.
  • When parsing for an integer just chain Number.parseInt("123")
  • Use ternary operator if you want to make a conditional inside a fragment.

    { x === y ? Naisu : Not Naisu; }

  • Purpose of React.Fragment is to allow you to create groups of children without adding an extra dom element.


Front-End History

  • React makes it easier for you to make front-end elements. A front-end timeline
  • Some noteworthy front end libraries that have been used in the past few years:
  • 2005: Script.aculo.us
  • 2005: Dojo
  • 2006: YUI
  • 2010: Knockout
  • 2011: AngularJS
  • 2012: Elm
  • 2013: React (Considered the standard front-end library)
  • React manages the creation and updating of DOM nodes in your Web page.
  • All it does is dynamically render stuff into your DOM.
  • What it doesn’t do:
  • Ajax
  • Services
  • Local Storage
  • Provide a CSS framework
  • React is unopinionated
  • Just contains a few rules for developers to follow, and it just works.
  • JSX : Javascript Extension is a language invented to help write React Applications (looks like a mixture of JS and HTML)
  • Here is an overview of the difference between rendering out vanilla JS to create elements, and JSX:

    fetch("https://example.com/api/people")
    .then((response) => response.json())
    .then((people) => {
    const html = "

      "; for (let person of data.people) { html += <li>${person.lastName}, ${person.firstName}</li>; } html += "
    "; document.querySelector("#people-list").innerHTML = html; });

    function PeopleList(props) {
    return (

      $ {props.people.map((person) => (
    • {person.lastName}, {person.firstName}
    • ))}
    ); } const peopleListElement = document.querySelector("#people-list"); fetch("https://example.com/api/people") .then((response) => response.json()) .then((people) => { const props = { people }; ReactDOM.render(, peopleListElement); });
  • This may seem like a lot of code but when you end up building many components, it becomes nice to put each of those functions/classes into their own files to organize your code. Using tools with React

  • React DevTools : New tool in your browser to see ow React is working in the browser

  • create-react-app : Extensible command-line tool to help generate standard React applications.

  • Webpack : In between tool for dealing with the extra build step involved.

- HMR : (Hot Module Replacement) When you make changes to your source code the changes are delivered in real-time.

  • React Developers created something called Flux Architecture to moderate how their web page consumes and modifies data received from back-end API's.

- Choosing React

  • Basically, React is super important to learn and master.

React Concepts and Features

There are many benefits to using React over just Vanilla JavaScript.

  • Modularity
  • To avoid the mess of many event listeners and template strings, React gives you the benefit of a lot of modularity.
  • Easy to start
  • No specials tools are needed to use Basic React.
  • You can start working directly with createElement method in React.
  • Declarative Programming
  • React is declarative in nature, utilizing either it’s built-in createElement method or the higher-level language known as JSX.
  • Reusability
  • Create elements that can be re-used over and over. One-flow of data
  • React apps are built as a combination of parent and child components.
  • Parents can have one or more child components, all children have parents.
  • Data is never passed from child to the parent.
  • Virtual DOM : React provides a Virtual DOM that acts as an agent between the real DOM and the developer to help debug, maintain, and provide general use.
  • Due to this usage, React handles web pages much more intelligently; making it one of the speediest Front End Libraries available.

ES6 Refresher

Exporting one item per file

  • Use export default statement in ES6 to export an item. ES6

    export default class Wallet {
    // ...
    }
    // sayHello will not be exported
    function sayHello() {
    console.log("Hello!");
    }

CommonJS (Equivalent)

class Wallet {
  // ...
}
// sayHello will not be exported
function sayHello() {
  console.log("Hello!");
}
module.exports = Wallet;
Enter fullscreen mode Exit fullscreen mode

Exporting multiple items per file

  • Use just thw export keyword (without default) to export multiple items per file. ES6 (Better to export them individually like this, rather than bunching them all into an object)

    export class Wallet {
    // ...
    }
    export function sayHello() {
    console.log("Hello!");
    }
    export const sayHi = () => {
    console.log("Hi!");
    };
    class Wallet {
    // ...
    }
    function sayHello() {
    console.log("Hello!");
    }
    const sayHi = () => {
    console.log("Hi!");
    };
    export { Wallet, sayHello, sayHi };

CommonJS (Equivalent)

class Wallet {
  // ...
}
function sayHello() {
  console.log("Hello!");
}
const sayHi = () =&gt; {
  console.log("Hi!");
};
module.exports = {
  Wallet,
  sayHello,
  sayHi,
};
Enter fullscreen mode Exit fullscreen mode

Importing with ES6 vs CommonJS

- Import statements in ES6 modules must always be at the top of the file, because all imports must occur before the rest of the file’s code runs. ES6

import { Wallet } from "./wallet";
import * as fs from "fs";
const wallet = new Wallet();
Enter fullscreen mode Exit fullscreen mode

CommonJS

let { Wallet } = require("./wallet");
const wallet = new Wallet();
let fs = require("fs");
Enter fullscreen mode Exit fullscreen mode

Unnamed default imports

  • You can name unnamed items exported with export default any name when you import them.

    // exporting
    export default class Wallet {
    // ...
    }
    // importing
    import Money from "wallet.js";
    const wallet = new Money();

  • Just remember if you use export instead of export default then your import is already named and cannot be renamed.

    // exporting
    export class Wallet {
    // ...
    }
    // importing
    import { Wallet } from "wallet.js";
    const wallet = new Wallet();

Aliasing imports

  • Use as asterisk to import an entire module’s contents.
  • Keep in mind you must use an as keyword to refer to it later.

    // export
    export function sayHello() {
    console.log("Hello!");
    }
    export const sayHi = () => {
    console.log("Hi!");
    };
    //import
    import * as Greetings from "greetings.js";
    Greetings.sayHello(); // Hello!
    Greetings.sayHi(); // Hi!

  • You can also name identically named functions or items from different files.

    import { Wallet as W1 } from "./wallet1";
    import { Wallet as W2 } from "./wallet2";
    const w1 = new W1();
    const w2 = new W2();

Browser support for ES6 Modules

  • ES6 Modules can only be used when a JS file is specified as a module. ``
  • You can get browser support for ES6 modules by adding module into your script tag.

Notes

JSX In Depth

  • Remember that JSX is just syntactic sugar for the built in React.createElement(component, props, ...children)
  • React Library must always be in scope from your JSX code.
  • Use Dot Notation for JSX Type
  • User-Defined Components Must Be Capitalized vs
  • Cannot use a general expression as the React element type. (Incorrect)

    function Story(props) {
    // Wrong! JSX type can't be an expression.
    return ;
    };

(Corrected)

function Story(props) {
  // Correct! JSX type can be a capitalized variable.
  const SpecificStory = components[props.storyType];
  return ;
}
Enter fullscreen mode Exit fullscreen mode

Props in JSX

  • Several ways to specify props in JSX.
  • Javascript Expressions as Props

  • String Literals

  • Props Default to “True”

  • Spread Attributes

    function App1() { return ; } function App2() { const props = { firstName: "Ben", lastName: "Hector" }; return ; }

Children in JSX

  • props.children : The content between opening and closing tag. JavaScript Expressions as Children

    function Item(props) {
    return

  • {props.message}
  • ; } function TodoList() { const todos = ["finish doc", "submit pr", "nag dan to review"]; return (
      {todos.map((message) => (
        ))}
      </ul>
      
      Enter fullscreen mode Exit fullscreen mode

      );
      }

    Functions as Children

    • props.children works like any other prop, meaning it can pass any sort of data.

      // Calls the children callback numTimes to produce a repeated component
      function Repeat(props) {
      let items = [];
      for (let i = 0; i < props.numTimes; i++) {
      items.push(props.children(i));
      }
      return {items};
      }
      function ListOfTenThings() {
      return (

        {(index) =&gt; This is item {index} in the list}
      
      Enter fullscreen mode Exit fullscreen mode

      );
      }

    Booleans, Null, and Undefined Are Ignored

    • false, null, undefined, and true are all valid children.
    • They will not render.
    • You can use these to conditionally render items.

      {showHeader && }

    • In this example, the component will only render if showHeader evals to True.

      // Before work-around

      {props.messages.length &&

      }

      // After work-around

      {props.messages.length > 0 &&

      }

    • Note that certain falsy values such as zero will still be rendered by React, you can work around this by ensuring situations like the above eval. into a boolean.

    • In the times you want booleans to be rendered out, simply convert it into a string first.

      My JavaScript variable is {String(myVariable)}.

    Reconciliation

    The Diffing Algorithm

    • Diffing : When the state of a component changes React creates a new virtual DOM tree.
    • Elements of Different Types
    • Every time the root elements have different types, React tears down the old tree and builds the new tree from scratch.
    • DOM Elements Of the Same Type
    • When comparing two DOM elements of the same type, React keeps the same underlying DOM node and only updates the changes attributes.

    • Component Elements Of The Same Type

    • When components update, instances will remain the same, so that state maintains across renders.

    • React will only update the props, to match the new element.

    • Recursing On Children

    • React will iterate both lists of children and generate a mutation whenever there’s a difference.

    • This is why we use keys.

    • Makes it easier for React to match children in the original tree with children in the subsequent tree.

    • Tradeoffs

    • Important to remember that reconciliation algorithm is an implementation detail.

    • Re-rendering only to apply the differences following the rules stated in the previous sections.

    Typechecking With PropTypes

    • As your application grows, you can use React’s typechecking to catch bugs.
    • propTypes is a special property to run typechecking.
    • exports range of built in validators to ensure your received data is valid.
    • propTypes is only checked in development mode.

      import PropTypes from "prop-types";
      class Greeting extends React.Component {
      render() {
      return

      Hello, {this.props.name}

      ; } } Greeting.propTypes = { name: PropTypes.string, };

    Requiring Single Child

    • Use PropTypes.element to specify only a single child can be passed to a component as children.

      import PropTypes from "prop-types";
      class MyComponent extends React.Component {
      render() {
      // This must be exactly one element or it will warn.
      const children = this.props.children;
      return {children};
      }
      }
      MyComponent.propTypes = {
      children: PropTypes.element.isRequired,
      };

    Default Prop Values

    • Use defaultProps to assign default values for props.

      class Greeting extends React.Component {
      render() {
      return

      Hello, {this.props.name}

      ; } } // Specifies the default values for props: Greeting.defaultProps = { name: "Stranger", }; // Renders "Hello, Stranger": ReactDOM.render(, document.getElementById("example"));

      class Greeting extends React.Component {
      static defaultProps = {
      name: 'stranger'
      }
      render() {
      return (
      Hello, {this.props.name}
      )
      }


    Notes

    React Router Introduction

    • React Router is the answer for rendering different components for different pages.
    • A front-end library that allows you to control which components to display using the browser location.
    • Client-side Routing Getting started with routing
    • Install React Router with:
    • npm install — save react-router-dom@⁵.1.2
    • Import Browser Router from package.
    • import { BrowserRouter } from “react-router-dom”;
    • BrowserRouter is the primary component of the router that wraps your route hierarchy.
    • Wrap it around components.
    • Creates a React Context that passes routing information down to all its descendant components.
    • You can also use HashRouter, where it would generate a hash before the endpoint. Creating frontend routes
    • React Router helps your app render specific components based on the URL.
    • The most common component is ``
    • Wrapped around another component, causing the comp. to only render if the a certain URL is matched.
    • Props : path, component, exact, and [render]
    • Browser Router can only have a single child component.
    • The Browser Router wraps all routes within a parent div element.

      const Root = () => {
      const users = {
      1: { name: "Andrew" },
      2: { name: "Raymond" },
      };
      return (

          <h1>Hi, I'm Root!</h1>
      
           <h1>Hello!</h1>} /&gt;
           } /&gt;
      
      Enter fullscreen mode Exit fullscreen mode

      );
      };

    • component

    • Indicates component to render.

    • path

    • Indicates path to render a specific component.

    • exact

    • Tells route to not pattern match and only render a certain route exclusively to it’s associated component.

    • render

    • Optional prop that takes in a function to be called.

    • Causes extra work for React.

    • Preferred for inline rendering of simple functional components.

    • Difference between component and render is that component returns new JSX that be re-mounted, but render returns the JSX that will be mounted only once.

    • // This inline rendering will work, but is unnecessarily slow. <Route path=”/hello” component={() => <h1>Hello!</h1>} /> // This is the preferred way for inline rendering. <Route path=”/hello” render={() => <h1>Hello!</h1>} />

    • Also useful if you need to pass in specific props to a component.

    • // `users` to be passed as a prop: const users = { 1: { name: “Andrew” }, 2: { name: “Raymond” }, }; <Route path=”/users” render={() => <Users users={users} />} />;

    Route path params

    • Your component’s props can hold information about URL’s parameters.
    • Will match segments starting at : to the next /?, #.

      }
      />

    • {...props} spreads out the router's props.

    • props.match.params is used to access the match prop's parameters.

    • Useful keys on the match object:

    • isExact : boolean that tells you whether or not the URL exactly matches the path.

    • url : the currentURL

    • path : Route path it matched against (w/o wildcards)

    • params : Matches for the individual wildcard segments.


    Navigation

    React Router Navigation

    • Link, NavLink, Redirect, history props of React Router are used to help your user navigate routes. Adding links for navigation
    • Issues on-click navigation event to a route defined in app.
    • Usage renders an anchor tag with a correctly set href attribute.

      import { BrowserRouter, Route, Link } from "react-router-dom";

    • Link takes two properties: to and onClick.

    • to : route location that points to an absolute path.

    • onClick : clickHandler.

    • NavLink works just like Link but has a bit of extra functionality.

    • Adds extra styling, when the path it links to matches the current path.

    • As it’s name suggests, it is used to Nav Bars.

    • Takes three props:

    • activeClassName : allows you to set a CSS class name for styling. (default set to 'active')

    • activeStyle : style object that is applied inline when it's to prop. matches the current URL.

    • exact prop is a boolean that defaults to false; you can set it to true to apply requirement of an exact URL match.

    • exact can also be used as a flag instead of a reg. property value.

    • benefit of adding this is so that you don’t trigger other matches. Switching between routes

    • `` : Component allows you to only render one route even if several match the current URL.

    • You may nest as many routes as you wish but only the first match of the current URL will be rendered.

    • Very useful if we want a default component to render if none of our routes match.

    • DefaultComponent will only render if none of the other URLs match up.

    • `` : Helps redirect users.

    • Only takes a single prop: to.

      (this.props.currentUser ? : )}
      />

    History

    • History allows you to update the URL programmatically.
    • Contains two useful methods:
    • push : Adds a new URL to the end of the history stack.
    • replace : Replaces the current URL on the history stack, so the back button won't take you to it.

      // Pushing a new URL (and adding to the end of history stack):
      const handleClick = () => this.props.history.push("/some/url");
      // Replacing the current URL (won't be tracked in history stack):
      const redirect = () => this.props.history.replace("/some/other/url");


    Nested Routes

    Why nested routes?

    • Create routes that tunnel into main components vs getting rendered on the main page as it’s own thing. What are nested routes?

      const Profile = (props) => {
      // Custom call to database to fetch a user by a user ID.
      const user = fetchUser(props.match.params.userId);
      const { name, id } = user;
      return (

        <h1>Welcome to the profile of {name}!</h1>
        {name}'s Posts
        {name}'s Photos
      
      Enter fullscreen mode Exit fullscreen mode

      );
      };

    Alt. version using props.match

    // Destructure `match` prop
    const Profile = ({ match: { url, path, params }) =&gt; {
      // Custom call to database to fetch a user by a user ID.
      const user = fetchUser(params.userId);
      const { name, id } = user;
      return (
    
          <h1>Welcome to the profile of {name}!</h1>
          {name}'s Posts
          {name}'s Photos
    
    
        }
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode
    • As you can see above, our end URL isn’t even defined until we apply those flexible values in.

    React Builds

    • Build : Process of converting code into something that can actually execute or run on the target platform.
    • In regards to React, the minimum a build should do is convert JSX to something that browsers can understand. Reviewing common terminology
    • Linting : Process of using a tool to analyze your code to catch common errors, bugs, inconsistencies etc...
    • Transpilation : Process of converting source code, like JS, from one version to another.
    • Minification : Process of removing all unnecessary characters in your code.
    • Bundling : Process of combining multiple code files into a single file.
    • Tree Shaking : Process of removing unused or dead code from your application before it's bundled. Configuration or code?
    • Configuration allows developers to create build tasks by declaring either JSON, XML, or YAML without explicitly writing every step in the process.
    • Coding or Scripting simply requires code. Babel and webpack (yes, that's intentionally a lowercase 'w')
    • Babel : Code Transpiler that allows you to use all of the latest features and syntax wihtout worrying about what browsers support what.
    • webpack : Allows developers to use JS modules w/o requiring users to use a browser that natively supports ES modules.
    • Create React App uses webpack and Babel under the hood to build applications. The Create React App build process
    • What happens when you run npm start:
    1. .env variables are loaded.
    2. list of browsers to support are checked.
    3. config’d HTTP port checked for availability.
    4. application compiler is configured and created.
    5. webpack-dev-starter is started
    6. webpack-dev-starter compiles app.
    7. index.html is loaded into browser
    8. file watcher is started to watch for changes. Ejecting
    • There is a script in Create React App called eject that allows you to 'eject' your application and expose all the hidden stuff. Preparing to deploy a React application for production
    • Defining Env Variables

      REACT_APP_FOO: some value
      REACT_APP_BAR: another value

      console.log(process.env.REACT_APP_FOO);

      Can be referenced in your index.html like so: %REACT_APP_BAR%

    Configuring the supported browsers

    {
      "browserslist": {
        "production": [
          "&gt;0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode
    • If you specify older browsers it will affect how your code get’s transpiled. Creating a production build
    • Run npm run build to create a production build.
    • Bundles React in production mode and optimizes the build for the best performance.

    Notes

    Introduction to React

    • Simply a nice library that turns data into DOM.
    • Tree Diffing : Fast comparison and patching of data by comparing the current virtual DOM and new virtual DOM - updating only the pieces that change.
    • It's just a tree with some fancy diffing

    Create Element

    From JavaScript To DOM

    • The React.createElement function has the following form:

      React.createElement(type, [props], [...children]);

    • Type : Type of element to create, i.e. a string for an HTML element or a reference to a function or class that is a React component.

    • Props : Object that contains data to render the element.

    • Children : Children of the elemet, as many as you want. Creating elements

    • Our rendering goal:

    • There are five tags to create:

    • One ul

    • Two li

    • Two a

    • There are certain attributes we want to appear in the DOM for these tags as well:

    • Each li has a class (or className in React)

    • Both a ele's have href attributes

    • Also keep in mind the parent child relationships happening between the tags.

    • ul is the parent of both li

    • Each li has an a element as a child

    • Each a has a text content child

    React.createElement(
    "ul",
    null,
    React.createElement(
    "li",
    { className: "selected" },
    React.createElement("a", { href: "/pets" }, "Pets")
    ),
    React.createElement(
    "li",
    null,
    React.createElement("a", { href: "/owners" }, "Owners")
    )
    );

    Converting to virtual DOM

    • After you set up your React.createElement, you use React.render to take the value returned from cE and a DOM node to insert into the conversion of the real DOM.

      // Put the element tree in a variable
      const navList = React.createElement(
      "ul",
      null,
      React.createElement(
      "li",
      { className: "selected" },
      React.createElement("a", { href: "/pets" }, "Pets")
      ),
      React.createElement(
      "li",
      null,
      React.createElement("a", { href: "/owners" }, "Owners")
      )
      );
      // Get a DOM node for React to render to
      const mainElement = document.querySelector("main");
      // Give React the element tree and the target
      ReactDOM.render(navList, mainElement);

    • JS Code => Virtual DOM => Real Dom Updates

    • If you call React.render a second or multiple times it just checks the existing Virtual DOM and it knows which smaller areas to change. Thinking in Components

    • Components are pieces of reusable front-end pieces.

    • Components should be Single Responsibility Principle compliant.


    Create Element

    React.createElement Demo

    • Can import non-local dependencies with import 'package-link'

      const App = () => React.createElement("h1", null, "Hello, Programmers!");
      const target = document.querySelector("main");
      const app = React.createElement(App, null);
      // Give React the element tree and the target
      ReactDOM.render(app, target);

    • Remember when importing modules from other files you have to denote the file type in the import statement. HTML Original

      Clue$ 268530

        2009: I dreamed a Dream
      
        &lt;&gt;
      
        $800
      
      Enter fullscreen mode Exit fullscreen mode

    React Version

    const Clue = () =&gt;
      React.createElement(
        "section",
        { className: "clue" },
        React.createElement("h1", { className: "clue__title" }, "Title"),
        React.createElement("div", { className: "clue__question" }, "?"),
        React.createElement("div", { className: "clue__category" }, "Category"),
        React.createElement("div", { className: "clue__amount" }, "$800")
      );
    
    Enter fullscreen mode Exit fullscreen mode
    • Because class is a reserved keyword in JS, in React we can use className to assign a class to an element.
    • Remember the data that goes into createElement: element type, data to pass into the element, and then children.
    • props : Properties;
    • To handle certain values that are initially undefined, we can use defaultProps.

      Clue.defaultProps = {
      category: {},
      };

    • You can change in the devTools Network tab the internet speed to check for values that may be undefined to hangle with defaultProps.

    • If we fetch multiple pieces of data, we can render many things by using map.

    • You need to assign a unique key to each of the clues.

    • We need to keep track of them individually so that React can easily refer to a specific one if there is an issue. clue =&gt; { key:clue.id, ...clue }

      const App = (props) =>
      React.createElement(
      "h1",
      null,
      props.clues.map((clue) =>
      React.createElement(Clue, { key: clue.id, ...clue })
      )
      );
      export default App;

    • Note: JSX is preferred over React.createElement;


    Notes from Hello Programmer Exercise

    • When you import modules from websites they must have CORs activated.
    • These import statements, import global variables.
    • When we want to move our code into production we need to change the imports into the production minified versions.

      import "https://unpkg.com/react@16/umd/react.production.min.js";
      import "https://unpkg.com/react-dom@16.13.1/umd/react-dom.production.min.js";

    • While we will never actually be creating full apps with just React.createElement => it is the enginer that is running under the hood!

      import "https://unpkg.com/react@16/umd/react.development.js";
      import "https://unpkg.com/react-dom@16/umd/react-dom.development.js";
      const Links = () =>
      React.createElement(
      "ul",
      { id: "nav-links" },
      React.createElement(
      "li",
      { className: "is-selected" },
      React.createElement("a", { href: "http://appacademy.io" }, "App Academy")
      ),
      React.createElement(
      "li",
      null,
      React.createElement("a", { href: "https://aaonline.io" }, "a/A Open")
      )
      );
      // Set up React Element: Type, Imported Data, Child (Child is Text in this Scenario)
      // HelloWorld is a function based component
      const HelloWorld = () => React.createElement("h1", null, "Hello, Programmers");
      const AllTogether = () =>
      React.createElement(
      "div",
      null,
      React.createElement(HelloWorld, null),
      React.createElement(Links, null)
      );
      // Target the Element to append new Ele
      const target = document.querySelector("main");
      // Assign your 'App' to your created Elements
      // We are creating an element from the HelloWorld function.
      const app = React.createElement(AllTogether, null);
      // Render from the Virtual Dom to the Actual Dom
      ReactDOM.render(app, target);


    Introduction to JSX

    • JSX : Javascript Extension, a new language created by React developers to have an easier way of interacting with the React API. How to use JSX
    • We will use babel to convert version of modern JS into an older version of JS. React Create Element

      const ExampleComponent = (props) =>
      React.createElement(
      React.Fragment,
      null,
      React.createElement("h1", null, "Hello!"),
      React.createElement("img", { src: "https://via.placeholder.com/150" }),
      React.createElement("a", { href: props.searchUrl }, props.searchText)
      );

    JSX Version

    const ExampleComponent = (props) =&gt; (
    
        <h1>Hello!</h1>
        <img src="https://via.placeholder.com/150">
        <a href="{props.searchUrl}">{props.searchText}</a>
    
    );
    
    Enter fullscreen mode Exit fullscreen mode
    • Keep in mind that self closing tags in React must have a forward slash to close it.

    - Properties and Data

    <img src="https://via.placeholder.com/150">;
    // becomes..
    React.createElement("img", { src: "https://via.placeholder.com/150" });
    // if we want to pass in data vs just a string literal
    <a href="{props.searchUrl}">{props.searchText}</a>;
    // so it becomes..
    React.createElement("a", { href: props.searchUrl }, props.searchText);
    // if you want the text search uppercase..
    <a href="{props.searchUrl}">{props.searchText.toUpperCase()}</a>;
    
    Enter fullscreen mode Exit fullscreen mode
    • Comments in JSX have the following syntax:

      This is JSX

      {/* This is a comment in JSX */}
    • Property Names:

    • checked : Attribute of input components such as checkbox or radio, use it to set whether the component is checked or not.

    • className : Used to specify a CSS class.

    • dangerouslySetInnerHTML : React's equivalent of innerHTML because it is risky to cross-site scripting attacks.

    • htmlFor : Because for is protected keyword, React elements use this instead.

    • onChange : Event fired whenever a form field is changed.

    • style : Accepts a JS object with camelCase properties rather than a CSS string.

    • value : Supported by Input, Select, and TextArea components; use it to set the value of the component.

    • Note: React uses camel-case!!! The JSX semicolon gotcha

      function App() {
      return (

        <h1>Hello!</h1>
        Welcome to JSX.
      
      Enter fullscreen mode Exit fullscreen mode

      );
      }

    create Element equivalent

    is equivalent to
    function App() {
      return (
        React.createElement(
          'div',
          null,
          React.createElement('h1', null, 'Hello!'),
          React.createElement('div', null, 'Welcome to JSX.'),
        )
      );
    }
    
    Enter fullscreen mode Exit fullscreen mode
    • We wrap what want to return in parenthesis so JS doesn’t auto add semi-colons after every line and run the code incorrectly.
    • Just remember if you decided to use the return keyword in a function to ‘return some JSX’, then make sure you wrap the JSX in parenthesis.

    npx create-react-app my-app

    • Single line used to initiate a React application.
    • React has a great toolchain where you can see changes live as you’re editing your application.
    • React errors will be rendered directly onto the browser window.
    • A downside is that it installs a lot of bloat files.
    • Examples of React create Element and JSX equivalent

      React.createElement(
      "a",
      {
      className: "active",
      href: "https://appacademy.io",
      },
      "App Academy"
      );
      // JSX Version

      App Academy
      ;

      React.createElement(
      OwnerDetails,
      {
      owner: props.data.owner,
      number: props.index + 1,
      },
      props.name
      );
      // JSX Version

      {props.name}
      ;

    More Complex JSX Example

    const BookPanel = (props) =&gt; {
    
        <h1>{props.title}</h1>
        <img src="{props.coverUrl}">
        {props.description}
      ;
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Notes

    Using Custom CRA Templates

    Using a Custom Template npx create-react-app my-app --template @appacademy/simple

    • Keep in mind that using create-react-app automatically initializes a git repository for you!
    • App Academy custom template for creating a react app.
    • If using the default react create project you can delete the following files:
    • favicon.ico
    • robots.txt
    • logo192.png
    • logo512.png
    • manifest.json
    • You can also simplify the html file into:

      React App
      
      Enter fullscreen mode Exit fullscreen mode

    Simplifying the src folder

    • Remove: App.css App.test.js logo.svg serviceWorker.js setupTests.js
    • Update the Following Files:

      // ./src/App.js
      import React from "react";
      function App() {
      return

      Hello world!

      ; } export default App; ``;

      // ./src/index.js
      import React from "react";
      import ReactDOM from "react-dom";
      import "./index.css";
      import App from "./App";
      ReactDOM.render(

      ,
      document.getElementById("root")
      );


    React Class Components

    Class Components

    • You can write React components using ES2015 Classes: Function Component

      // ./src/Message.js
      import React from "react";
      const Message = (props) => {
      return {props.text};
      };
      export default Message;

    ES2015 Version

    // ./src/Message.js
    import React from "react";
    class Message extends React.Component {
      render() {
        return {this.props.text};
      }
    }
    export default Message;
    
    Enter fullscreen mode Exit fullscreen mode
    • We can access props within a class component by using this.props
    • Keep in mind Class Components are used just like function components.

      // ./src/index.js
      import React from "react";
      import ReactDOM from "react-dom";
      import Message from "./Message";
      ReactDOM.render(

      ,
      document.getElementById("root")
      );

    Setting and accessing props

    class Message extends React.Component {
      constructor(props) {
        super(props);
        // TODO Initialize state, etc.
      }
      render() {
        return {this.props.text};
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode
    • If we define a constructor method in our Class Component, we have to define the super method with props passed through it.
    • Side Note: Before React used ES2015 Classes, it used React.createclass function, if you ever need to use this antiquated method make sure you install a module called create-react-class Stateful components
    • One of the major reasons why you would choose to use a Class Component over a Function Component is to add and manage local or internal state to your component.
    • Second of the major reasons is to be able to use a Class Component’s lifecycle methods. What is state?
    • Props are data that are provided by the consumer or caller of the component.
    • Not meant to be changed by a component.
    • State is data that is internal to the component.
    • Intended to be updated or mutated. When to use state
    • Only Use State when it is absolutely necessary
    • If the data never changes, or if it’s needed through an entire application use props instead.
    • State is more often used when creating components that retrieve data from APIs or render forms.
    • The general rule of thumb: If a component doesn’t need to use state or lifecyle methods, it should be prioritized as a function component.
    • Functional:Stateless || Class:Stateful Initializing state
    • Use a class constructor method to initialize this.state object. // Application Entry Point

      // ./src/index.js
      import React from 'react'
      import ReactDOM from 'react-dom';
      import RandomQuote from './RandomQuote';
      ReactDOM.render(

      document.getElementById('root');
      )

    // Class Component: RandomQuote

    import React from "react";
    class RandomQuote extends React.Component {
      constructor() {
        super();
        const quotes = [
          "May the Force be with you.",
          "There's no place like home.",
          "I'm the king of the world!",
          "My mama always said life was like a box of chocolates.",
          "I'll be back.",
        ];
        this.state = {
          quotes,
          currentQuoteIndex: this.getRandomInt(quotes.length);
        }
      }
      getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
      }
      render() {
        return (
    
            <h2>Random Quote</h2>
            <p>{this.state.quotes[this.state.currentQuoteIndex]}</p>
    
        )
      }
    }
    export default RandomQuote;
    
    Enter fullscreen mode Exit fullscreen mode

    Updating State

    • Let’s say we want to update our state with a new quote.
    • We can set up event listeners in React similarly to how we did them before.
    • <button type=”button” onClick={this.changeQuote}> Change Quote </button>
    • onClick is the event listener.
    • {this.changeQuote} is the event handler method.
    • Our Class Component File should now look like this with the new additions:

      import React from "react";
      class RandomQuote extends React.Component {
      constructor() {
      super();
      const quotes = [
      "May the Force be with you.",
      "There's no place like home.",
      "I'm the king of the world!",
      "My mama always said life was like a box of chocolates.",
      "I'll be back.",
      ];
      this.state = {
      quotes,
      currentQuoteIndex: this.getRandomInt(quotes.length);
      }
      }
      changeQuote = () => {
      const newIndex = this.getRandomInt(this.state.quotes.length);
      // Setting the 'new state' of currentQuoteIndex state property
      // to newly generated random index #.
      this.setState({
      currentQuoteIndex: newIndex;
      })
      }
      getRandomInt(max) {
      return Math.floor(Math.random() * Math.floor(max));
      }
      render() {
      return (

          <h2>Random Quote</h2>
          <p>{this.state.quotes[this.state.currentQuoteIndex]}</p>
      
            Change Quote
      
      )
      
      Enter fullscreen mode Exit fullscreen mode

      }
      }
      export default RandomQuote;

    Don’t modify state directly

    • It is important to never modify your state directly!
    • ALWAYS use this.setState method to update state.
    • This is because when you only use this.state to re-assign, no re-rendering will occur => leaving our component out of sync. Properly updating state from the previous state
    • In our current example, the way we have changeQuote set up leaves us with occasionally producing the same index twice in a row.
    • One solution is to design a loop but keep in mind that state updates are handled asynchronously in React (your current value is not guaranteed to be the latest)
    • A safe method is to pass an anonymous method to this.setState (instead of an object literal) Previous

      changeQuote = () => {
      const newIndex = this.getRandomInt(this.state.quotes.length);
      this.setState({
      currentQuoteIndex: newIndex;
      })
      }

    Passing w/ Anon Method

    changeQuote = () =&gt; {
      this.setState((state, props) =&gt; {
        const { quotes, currentQuoteIndex } = state;
        let newIndex = -1;
        do {
          newIndex = this.getRandomInt(quote.length);
        } while (newIndex === currentQuoteIndex);
        return {
          currentQuoteIndex: newIndex,
        };
      });
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Providing default values for props

    • In our current example, we pass in a static array of predefined quotes in our constructor.
    • The way it is set up right now leaves our list of quotes unchanged after initialization.
    • We can make quotes more dynamic by replacing our static array with a props argument passed into super.
    • constructor(props) { super(props); }
    • We can now move our quotes array to our application entry point and pass it in as a prop. // Application Entry Point

      // ./src/index.js
      import React from 'react'
      import ReactDOM from 'react-dom';
      import RandomQuote from './RandomQuote';
      // Re-assign our array here and pass it in as a prop in Render.
      const quotes = [
      "May the Force be with you.",
      "There's no place like home.",
      "I'm the king of the world!",
      "My mama always said life was like a box of chocolates.",
      "I'll be back.",
      "This way I can define more quotes",
      ];
      ReactDOM.render(

      document.getElementById('root');
      )

    • One thing to note about this workaround is that the caller of the component must set the quotes prop or the component will throw an error => so use defaultProps!

      // At the bottom of RandomQuote.js...
      RandomQuote.defaultProps = {
      quotes: [
      "May the Force be with you.",
      "There's no place like home.",
      "I'm the king of the world!",
      "My mama always said life was like a box of chocolates.",
      "I'll be back.",
      "This way I can define more quotes",
      ],
      };

    • A good safety net in case the consumer/caller doesn’t provide a value for the quotes array.

    • We can even remove it from our index.js now and an error will not be thrown.


    Handling Events

    • To add an event listener to an element, just define a method to handle the event and associate that method with the element event you are listening for. Example

      import React from "react";
      class AlertButton extends React.Component {
      showAlert = () => {
      window.alert("Button Clicked!");
      };
      render() {
      return (

          Submit
      
      );
      
      Enter fullscreen mode Exit fullscreen mode

      }
      }

    • Note that when refering the handler method in onClick we’re not invoking showAlert simply just passing a reference. Preventing default behavior

    • HTML Elements in the browser often have a lot of default behavior.

    • I.E. Clicking on an <a> element navigates so a resource denoted by `` property.

    • Here is an example of where using e.preventDefault() could come in handy.

      import React from "react";
      class NoDefaultSubmitForm extends React.Component {
      submitForm = (e) => {
      e.preventDefault();
      window.alert("Handling form submission...");
      };
      render() {
      return (

        Submit
      ;
      )}
      
      Enter fullscreen mode Exit fullscreen mode

      }

    • The button contained within the form will end up refreshing the page before this.submitForm method can be completed.

    • We can stick an e.preventDefault() into the actual method to get around this problem.

    • e : Parameter that references a Synthetic Event object type. Using this in event handlers

      // ./src/AlertButton.js
      import React from "react";
      class AlertButton extends React.Component {
      showAlert = () => {
      window.alert("Button clicked!");
      console.log(this);
      };
      render() {
      return (

          Click Me
      
      );
      
      Enter fullscreen mode Exit fullscreen mode

      }
      }
      export default AlertButton;

    • When we console log this we see the AlertButton object.

    • If we were to write the showAlert method with a regular class method like:

      showAlert() {
      console.log(this);
      }

    • We would get undefined => remember that fat arrow binds to the current context! Reviewing class methods and the this keyword

    • Let’s refresh on binding.

      class Boyfriend {
      constructor() {
      this.name = "Momato Riruru";
      }
      displayName() {
      console.log(this.name);
      }
      }
      const Ming = new Boyfriend();
      Ming.displayName(); // => Momato Riruru
      const displayAgain = Ming.displayName;
      displayAgain(); // => Result in a Type Error: Cannot read property 'name' of undefined.

    • The first time we use our displayMethod call, it is called directly on the instance of the boyfriend class, which is why Momato Riruru was printed out.

    • The second time it was called, the ref of the method is stored as a variable and method is called on that variable instead of the instance; resulting in a type error (it has lost it’s context)

    • Remember we can use the bind method to rebind context!

    • We can refactor to get the second call working like this:

    • const displayAgain = Ming.displayName.bind(Ming); displayAgain(); // => Now Momato Riruru will be printed out.

    • To continue using function declarations vs fat arrow we can assign context in a constructor within a class component.

      import React from "react";
      class AlertButton extends React.Component {
      constructor() {
      super();
      this.showAlert = this.showAlert.bind(this); // binding context
      }
      showAlert() {
      console.log(this);
      }
      render() {
      return (

          Submit
      
      );
      
      Enter fullscreen mode Exit fullscreen mode

      }
      }
      export default AlertButton;

    • Experimental Syntax : Syntax that has been proposed to add to ECMAScript but hasn't officially been added to the language specification yet.

    • It’s good to pick one approach and use it consistently, either:

    1. Class Properties & Arrow Functions
    2. Bind Method & This Keyword The SyntheticEvent object
    • Synthetic Event Objects: Cross Browser wrappeds around the browser’s native event.
    • Includes the use of stopPropagation() and preventDefault();
    • Attributes of the Synthetic Event Object:Attributesboolean bubblesboolean cancelableDOMEventTarget currentTargetboolean defaultPreventednumber eventPhaseboolean isTrustedDOMEvent nativeEventvoid preventDefault()boolean isDefaultPrevented()void stopPropagation()boolean isPropagationStopped()void persist()DOMEventTarget targetnumber timeStampstring type
    • nativeEvent : property defined in a synthetic event object that gives you access to the underlying native browser event (rarely used!)

    Forms in React

    Exercise being done in a separate file Random Notes

    • onChange : detects when a value of an input element changes.
    • Assigning onChange to our input fields makes our component's state update in real time during user input.
    • Dont forget to add preventDefault onto form submissions to deal with the default behavior of the browser refreshing the page!
    • submittedOn: new Date(), Can be added to a form, most likely will persist into a DB.
    • Controlled Components
    • We use the onChange event handlers on form fields to keep our component's state as the "one source of truth"
    • Adding an onChange event handler to every single input can massively bloat your code.
    • Try assiging it to it’s own method to apply everywhere.
    • textarea is handled differently in react: it takes in a value property to handle what the inner text will be.

      // ./src/ContactUs.js
      import React from "react";
      class ContactUs extends React.Component {
      constructor() {
      super();
      this.state = {
      name: "",
      email: "",
      phone: "",
      phoneType: "",
      comments: "",
      validationErrors: [],
      };
      }
      onChange = (e) => {
      const { name, value } = e.target;
      this.setState({ [name]: value });
      };
      // Vanilla JS Function for validating inputs
      validate(name, email) {
      const validationErrors = [];
      if (!name) {
      validationErrors.push("Please provide a Name");
      }
      if (!email) {
      validationErrors.push("Please provide an Email");
      }
      return validationErrors;
      }
      onSubmit = (e) => {
      // Prevent the default form behavior
      // so the page doesn't reload.
      e.preventDefault();
      // Retrieve the contact us information from state.
      const { name, email, phone, phoneType, comments } = this.state;
      // Get Validation Errors - proceeding destructuring values from this.state.
      const validationErrors = this.validate(name, email);
      // If we have errors...
      if (validationErrors.length > 0) {
      this.setState({ validationErrors });
      } else {
      // Proceed normally
      // Create a new object for the contact us information.
      const contactUsInformation = {
      name,
      email,
      phone,
      phoneType,
      comments,
      submittedOn: new Date(),
      };
      console.log(contactUsInformation);
      // Reset the form state.
      this.setState({
      name: "",
      email: "",
      phone: "",
      phoneType: "",
      comments: "",
      validationErrors: [],
      });
      }
      };
      render() {
      const { name, email, phone, phoneType, comments, validationErrors } =
      this.state;
      return (

          <h2>Contact Us</h2>
          {validationErrors.length &gt; 0 &amp;&amp; (
      
              The following errors were found:
              <ul>
                {validationErrors.map((error) =&gt; (
                  <li>{error}</li>
                ))}
              </ul>
      
          )}
      
              Name:
      
              Email:
      
              Phone:
      
                Select a phone type...
                {this.props.phoneTypes.map((phoneType) =&gt; (
                  {phoneType}
                ))}
      
              Comments:
      
              Submit
      
      );
      
      Enter fullscreen mode Exit fullscreen mode

      }
      }
      ContactUs.defaultProps = {
      phoneTypes: ["Home", "Work", "Mobile"],
      };
      export default ContactUs;

    • We can use validation libraries like validate to make our validation functions more complex.

      import isEmail from "validator/es/lib/isEmail";
      validate(name, email) {
      const validationErrors = [];
      if (!name) {
      validationErrors.push("Please provide a Name");
      }
      if (!email) {
      validationErrors.push("Please provide an Email");
      } else if (!isEmail(email)) {
      validationErrors.push("Please provide a valid Email");
      }
      return validationErrors;
      }

    Note About Client-side vs server-side validation

    • Server-side validation is not optional.
    • Tech-savvy users can manipulate client-side validations.
    • Sometimes the ‘best approach’ is to skip implementing validations on the client-side and rely completely on the server-side validation.

    Component Lifecycle

    - Component Lifecycle is simply a way of describing the key moments in the lifetime of a component.

    1. Loading (Mounting)
    2. Updating
    3. Unloading (Unmounting) The lifecycle of a React component
    • Each Class Component has several lifecycle methods that you can add to run code at specific times.
    • componentDidMount : Method called after your component has been added to the component tree.
    • componentDidUpdate : Method called after your component has been updated.
    • componentWillUnmount : Method called just before your component is removed from the component tree.
    • Mounting
    1. constructor method is called
    2. render method is called
    3. React updates the DOM
    4. componentDidMount is called
    • Updating
    • When component receives new props
    1. render method is called
    2. React updates the DOM
    3. componentDidUpdate is called
    • When setState is called
    1. render method is called
    2. React updates the DOM
    3. componentDidUpdate is called
    • Unmounting
    • The moment before a class component is removed from the component tree:
    • componentDidMount will be called. Avoiding the legacy lifecycle methods
    • Occasionally you will encounter some deprecated lifecycle methods:
    • UNSAFE_componentWillMount
    • UNSAFE_componentWillReceiveProps
    • UNSAFE_componentWillUpdate
    • Just know they will be removed soon from React’s API, peace. Using the class component lifecycle methods Exercise done in sep. directory
    • Assorted Notes:
    • Common Use for componentDidMount lifecycle method is for fetching data from an API.

    Notes

    React Context

    • You can use React Context to pass data through a component tree without having to manually thread props.
    • Convenient way to share & update global data. Creating a Context

      // PupContext.js
      import { createContext } from "react";
      const PupContext = createContext();
      export default PupContext;

    • We use React.createContext to create context.

    • Keep in mind if you invoke this method with aruguments, those arguments will be set as default context. Adding a Provider to the App component

    • In order to pass context over to child components we need to wrap them in a provider component.

    • The provider component takes in a value property that points to the information that needs to be passed to the children.

    Setting up a Consumer

      {(value) =&gt; }
    
    Enter fullscreen mode Exit fullscreen mode
    • Keep in mind that Context.Consumer expects a function as a child.
    • The function has a value prop passed in from Context.Provider

    Notes

    Redux Explained

    • JS Framework for managing the frontend state of a web application.
    • Gives us ability to store information in an organized manner in a web app and quickly retrieve that information from anywhere in the app.
    • Redux
    • Client Side Data Management
    • Controls “Frontend State”
    • NOT Your Database
    • NOT Component State
    • Just used for managing Data

    - Visual of how an app without React manages it’s data.

    • A lot of prop threading happening.
    • Data stored in a sep. location — global data. The Anatomy of Redux
    • Store
    • Holds the Frontend State
    • Provides an API for the Frontend State
    • Action
    • POJOs
    • Outline Changes to Frontend State
    • Reducers
    • Functions
    • Make Changes to Frontend State Where did Redux come from?
    • There are three central philosophies of Redux:
    1. A Single Source of Truth : state is stored in a POJO
    2. State is Read Only : State is immutable, modified by dispatching actions.
    3. Changes are Made with Pure Functions : Reducers that receive the actions and return updated state are pure functions of the old state and action. When is it appropriate to use Redux?
    • When doing a project with simpler global state requirements, it may be better to choose React’s Context API over Redux.
    • Redux offers more flexibility and support for middleware along with richer developer tools. Vocabulary
    • State
    • Redux is a State Manager
    • State is all the information stored by that program at a particular point in time.
    • Redux’s main job is to store the state and make it directly available to your entire app.
    • Store
    • Redux stores state in a single store.
    • Redux store is a single JS object with a couple of methods (not a class!)
    • Methods include: getState, dispatch(action), and subscribe(listener)
    • Actions
    • Redux store is updated by dispatching actions
    • Action is just a POJO that includes a mandatory type property.
    • Contain info to update the store.
    • We dispatch actions in response to User actions or AJAX requests.
    • Pure Functions
    • Redux Reducers are Pure Functions
    • Functions are pure when their behavior depends only on it’s arguments as has no side effects.
    • Simply takes in an argument and outputs a value.
    • Reducer
    • Redux handles actions using reducers
    • A function that is called each time an action is dispatched.
    • Takes in an action and current state
    • Required to be pure functions so their behavior is predictable.
    • Middleware
    • Customize response to dispatch actions by using Middleware
    • Middleware is an optional component of Redus that allows custom responses to dispatched actions.
    • Most common use is to dispatch async requests to a server.
    • Time Traveling Dev Tools
    • Redux can time travel wow
    • Time travel refers to Redux’s ability to revert to a previous state because reducers are all pure functions.
    • Thunks
    • Convenient format for taking async actions in Redux
    • General concept in CS referring to a function who’s primary purpose is to call another function.
    • Most commonly used to make async API requests.

    Flux and Redux

    What is Flux?

    • Front-end application architecutre.
    • A pattern in which to structure an application.
    • Unidirectional Data Flow — offers more predictability.
    • Actions : Begins the data flow of data, simple object that contains a type; type indicates the type of change to be performed.
    • Dispatcher : Mechanism for distributing actions to the store.
    • Store : The entire state of the application, responsible for updating the state of your app.
    • View : Unit of code that's responsible for rendering the user interface. Used to re-render the application when actions and changes occur.

    - Redux

    - Library that facilitates the implementation of Flux.

    • Redux Three Principles
    • Single Source of Truth
    • State is Read-Only
    • Only Pure Functions Change State

    Store

    • Simply an object that holds the application state wrapped in an API.
    • Three methods:
    • getState() : Returns the store's current state.
    • dispatch(action) : Passes an action into the store's reducer to tell it what info to update.
    • subscribe(callback) : Registers a callback to be triggered whenever the store updates. Updating the Store

      store.dispatch(action);
      // Add Orange Action
      const addOrange = {
      type: "ADD_FRUIT",
      fruit: "orange",
      };
      // Reducer for Orange Action
      const fruitReducer = (state = [], action) => {
      switch (action.type) {
      case "ADD_FRUIT":
      return [...state, action.fruit];
      default:
      return state;
      }
      };
      // Run the Dispatch
      console.log(store.getState()); // []
      store.dispatch(addOrange);
      console.log(store.getState()); // [ 'orange' ]

    Subscribing to the store

    • Whenever a store process a dispatch(), it triggers all its subscribers.
    • Subscribers : callbacks that can be added to the store via subscribe().

      const display = () => {
      console.log(store.getState());
      };
      const unsubscribeDisplay = store.subscribe(display);
      store.dispatch(addOrange); // [ 'orange', 'orange' ]
      // display will no longer be invoked after store.dispatch()
      unsubscribeDisplay();
      store.dispatch(addOrange); // no output

    Reviewing a simple example

    // app.js
    const { createStore } = require("redux");
    // Define the store's reducer.
    const fruitReducer = (state = [], action) =&gt; {
      switch (action.type) {
        case "ADD_FRUIT":
          return [...state, action.fruit];
        default:
          return state;
      }
    };
    // Create the store.
    const store = createStore(fruitReducer);
    // Define an 'ADD_FRUIT' action for adding an orange to the store.
    const addOrange = {
      type: "ADD_FRUIT",
      fruit: "orange",
    };
    // Log to the console the store's state before and after
    // dispatching the 'ADD_FRUIT' action.
    console.log(store.getState()); // []
    store.dispatch(addOrange);
    console.log(store.getState()); // [ 'orange' ]
    // Define and register a callback to listen for store updates
    // and console log the store's state.
    const display = () =&gt; {
      console.log(store.getState());
    };
    const unsubscribeDisplay = store.subscribe(display);
    // Dispatch the 'ADD_FRUIT' action. This time the `display` callback
    // will be called by the store when its state is updated.
    store.dispatch(addOrange); // [ 'orange', 'orange' ]
    // Unsubscribe the `display` callback to stop listening for store updates.
    unsubscribeDisplay();
    // Dispatch the 'ADD_FRUIT' action one more time
    // to confirm that the `display` method won't be called
    // when the store state is updated.
    store.dispatch(addOrange); // no output
    
    Enter fullscreen mode Exit fullscreen mode

    Reducers

    • Reducer function receives the current state and action, updates the state appropriately based on the action.type and returns the following state.
    • You can bundles different action types and ensuing logic by using a switch/case statement.

      const fruitReducer = (state = [], action) => {
      switch (action.type) {
      case "ADD_FRUIT":
      return [...state, action.fruit];
      case "ADD_FRUITS":
      return [...state, ...action.fruits];
      case "SELL_FRUIT":
      const index = state.indexOf(action.fruit);
      if (index !== -1) {
      // remove first instance of action.fruit
      return [...state.slice(0, index), ...state.slice(index + 1)];
      }
      return state; // if action.fruit is not in state, return previous state
      case "SELL_OUT":
      return [];
      default:
      return state;
      }
      };

    Reviewing how Array#slice works

    const fruits = ["apple", "apple", "orange", "banana", "watermelon"];
    // The index of the 'orange' element is 2.
    const index = fruits.indexOf("orange");
    // `...fruits.slice(0, index)` returns the array ['apple', 'apple']
    // `...fruits.slice(index + 1)` returns the array ['banana', 'watermelon']
    // The spread syntax combines the two array slices into the array
    // ['apple', 'apple', 'banana', 'watermelon']
    const newFruits = [...fruits.slice(0, index), ...fruits.slice(index + 1)];
    
    Enter fullscreen mode Exit fullscreen mode
    • Approach that can be used to remove an element without mutating the original array. Avoiding state mutations
    • Your reducer must always return a new object if the state changes. GOOD

      const goodReducer = (state = { count: 0 }, action) => {
      switch (action.type) {
      case "INCREMENT_COUNTER":
      const nextState = Object.assign({}, state);
      nextState.count++;
      return nextState;
      default:
      return state;
      }
      };

    BAD

    const badReducer = (state = { count: 0 }, action) =&gt; {
      switch (action.type) {
        case "INCREMENT_COUNTER":
          state.count++;
          return state;
        default:
          return state;
      }
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Actions

    • Actions are the only way to trigger changes to the store’s state. Using action creators

      const addOrange = {
      type: "ADD_FRUIT",
      fruit: "orange",
      };
      store.dispatch(addOrange);
      console.log(store.getState()); // [ 'orange' ]

    • fruit is the payload key and orange is the state data

    • Action Creators : Functions created from extrapolating the creation of an action object.

      const addFruit = (fruit) => ({
      type: "ADD_FRUIT",
      fruit,
      });

    • Use parenthesis for implicit return value.

    • We can now add whatever fruit we’d like.

      store.dispatch(addFruit("apple"));
      store.dispatch(addFruit("strawberry"));
      store.dispatch(addFruit("lychee"));
      console.log(store.getState()); // [ 'orange', 'apple', 'strawberry', 'lychee' ]

    Preventing typos in action type string literals

    const ADD_FRUIT = "ADD_FRUIT";
    const ADD_FRUITS = "ADD_FRUITS";
    const SELL_FRUIT = "SELL_FRUIT";
    const SELL_OUT = "SELL_OUT";
    const addFruit = (fruit) =&gt; ({
      type: ADD_FRUIT,
      fruit,
    });
    const addFruits = (fruits) =&gt; ({
      type: ADD_FRUITS,
      fruits,
    });
    const sellFruit = (fruit) =&gt; ({
      type: SELL_FRUIT,
      fruit,
    });
    const sellOut = () =&gt; ({
      type: SELL_OUT,
    });
    
    Enter fullscreen mode Exit fullscreen mode
    • Using constant variables helps reduce simple typos in a reducer’s case clauses.

    Debugging Arrow Functions

    • It is important to learn how to use debugger statements with arrow functions to effectively debug Redux cycle. Understanding the limitations of implicit return values

      const addFruit = (fruit) => {
      return {
      type: "ADD_FRUIT",
      fruit,
      };
      };
      const addFruit = (fruit) => {
      debugger;
      return {
      type: "ADD_FRUIT",
      fruit,
      };
      };

    • You must use explicit return statement arrow function to use a debugger.


    React Router Introduction

    Now that you know how to render components in a React app, how do you handle rendering different components for different website pages? React Router is the answer!

    Think of how you have created server-side routes in Express. Take the following URL and server-side route. Notice how the /users/:userId path corresponds with the http://localhost:3000/users/2 URL to render a specific HTML page.

    // http://localhost:3000/users/2
    app.get('/users/:userId', (req, res) =&gt; {
      res.render('userProfile.pug');
    });
    
    Enter fullscreen mode Exit fullscreen mode

    In the default React setup, you lose the ability to create routes in the same manner as in Express. This is what React Router aims to solve!

    React Router is a frontend routing library that allows you to control which components to display using the browser location. A user can also copy and paste a URL and email it to a friend or link to it from their own website.

    When you finish this article, you should be able to use the following from the react-router-dom library:

    • `to provide your application access to thereact-router-dom` library; and
    • `` to connect specific URL paths to specific components you want rendered; and
    • `to wrap severalRoute` elements, rendering only one even if several match the current URL; and
    • React Router’s match prop to access route path parameters.

    Getting started with routing

    Since you are writing single page apps, you don’t want to refresh the page each time you change the browser location. Instead, you want to update the browser location and your app’s response using JavaScript. This is known as client-side routing. You are using React, so you will use React Router to do this.

    Create a simple react project template:

    npx create-react-app my-app --template @appacademy/simple
    
    Enter fullscreen mode Exit fullscreen mode

    Then install React Router:

    npm install --save react-router-dom@^5.1.2
    
    Enter fullscreen mode Exit fullscreen mode

    Now import BrowserRouter from react-router-dom in your entry file:

    import { BrowserRouter } from 'react-router-dom`;
    
    Enter fullscreen mode Exit fullscreen mode

    BrowserRouter

    BrowserRouter is the primary component of the router that wraps your route hierarchy. It creates a React context that passes routing information down to all its descendent components. For example, if you want to give and all its children components access to React Router, you would wrap like so:

    // ./src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { BrowserRouter } from 'react-router-dom';
    import App from './App';
    
    const Root = () =&gt; {
      return (
    
    
    
      );
    };
    
    ReactDOM.render(
    
    
      ,
      document.getElementById('root'),
    );
    
    Enter fullscreen mode Exit fullscreen mode

    Now you can route the rendering of certain components to certain URLs (i.e https://www.website.com/profile).

    HashRouter

    Alternatively, you could import and use HashRouter from react-router-dom. Links for applications that use `would look likehttps://www.website.com/#/profile` (with an # between the domain and path).

    You’ll focus on using the ``.

    Creating frontend routes

    React Router helps your React application render specific components based on the URL. The React Router component you’ll use most often is ``.

    The component is used to wrap another component, causing that component to only be rendered if a certain URL is matched. The behavior of the component is controlled by the following props: path, component, exact, and render (optional).

    Create a simple Users component that returns <h1>This is the users index!</h1>. Now let's refactor your index.js file so that you can create your routes within the component:

    // ./src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { BrowserRouter, Route } from 'react-router-dom';
    import App from './App';
    import Users from './Users';
    
    const Root = () =&gt; {
      return (
    
    
            {/* TODO: Routes */}
    
    
      );
    };
    
    ReactDOM.render(
    
    
      ,
      document.getElementById('root'),
    );
    
    Enter fullscreen mode Exit fullscreen mode

    Note that BrowserRouter can only have a single child component, so the snippet above wraps all routes within parent a `` element. Now let's create some routes!

    component

    Begin with the component prop. This prop takes a reference to the component to be rendered. Let's render your App component:

    const Root = () =&gt; {
      return (
    
    
    
    
    
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Now you’ll need to connect a path to the component!

    path

    The wrapped component will only be rendered when the path is matched. The path matches the URL when it matches some initial portion of the URL. For example, a path of / would match both of the following URLs: / and /users. (Because /users begins with a / it matches the path /)

    Take a moment to navigate to http://localhost:3000/users to see how both the App component and Users component are rendering.

    exact

    If this exact flag is set, the path will only match when it exactly matches the URL. Then browsing to the /users path would no longer match / and only the Users component will be rendered (instead of both the App component and Users component).

    render

    This is an optional prop that takes in a function to be called. The function will be called when the path matches. The function’s return value is rendered. You could also define a functional component inside the component prop, but this results in extra, unnecessary work for React. The render prop is preferred for inline rendering of simple functional components.

    The difference between using component and render is that component returns new JSX to be re-mounted every time the route renders, while render simply returns to JSX what will be mounted once and re-rendered. For any given route, you should only use either the component prop, or the render prop. If both are supplied, only the component prop will be used.

    // This inline rendering will work, but is unnecessarily slow.
     <h1>Hello!</h1>} /&gt;
    
    // This is the preferred way for inline rendering.
     <h1>Hello!</h1>} /&gt;
    
    Enter fullscreen mode Exit fullscreen mode

    It can be helpful to use render instead of component in your `when you need to pass props into the rendered component. For example, imagine that you needed to pass theusersobject as a prop to yourUserscomponent. Then you could pass in props fromRoottoUsersby returning theUsers` component like so:

    // `users` to be passed as a prop:
    const users = {
      1: { name: 'Andrew' },
      2: { name: 'Raymond' }
    };
    
     } /&gt;
    
    Enter fullscreen mode Exit fullscreen mode

    As a reminder, BrowserRouter can only have a single child component. That's why you have wrapped all your routes within parent a `` element.

    const Root = () =&gt; {
      const users = {
        1: { name: 'Andrew' },
        2: { name: 'Raymond' }
      };
    
      return (
    
    
            <h1>Hi, I'm Root!</h1>
    
             <h1>Hello!</h1>} /&gt;
             } /&gt;
    
    
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    With this Root component, you will always render the <h1>Hi, I'm Root!</h1>, regardless of the path. Because of the first , you will only render the `App` component if the path exactly matches `/`. Because of the second, you will only render the Users component if the path matches /users.

    Route path params

    A component’s props can also hold information about a URL’s parameters. The router will match route segments starting at : up to the next /?, or #. Those matched values are then passed to components via their props. Such segments are wildcard values that make up your route parameters.

    For example, take the route below:

     } /&gt;
    
    Enter fullscreen mode Exit fullscreen mode

    The router would break down the full /users/:userId/photos path to two parts: /users:userId.

    The Profile component's props would have access to the :userId part of the http://localhost:3000/users/:userId/photos URL through the props with router parameter information. You would access the the match prop's parameters (props.match.params). If you are using the render prop of the Route component, make sure to spread the props back into the component if you want it to know about the "match" parameters.

    // Route's `render` prop allows you to pass the `users`
    // prop and spread the router `props`.
    render={(props) =&gt; }
    
    Enter fullscreen mode Exit fullscreen mode

    The params object would then have a property of userId which would hold the value of the :userId wildcard value. Let's render the userId parameter in a user profile component. Take a moment to create a Profile.js file with the following code:

    // ./src/Profile.js
    import React from "react";
    
    const Profile = (props) =&gt; (
    
        The user's id is {props.match.params.userId}.
    
    );
    
    export default Profile;
    
    Enter fullscreen mode Exit fullscreen mode

    Notice how it uses the match prop to access the :userId parameter from the URL. You can use this wildcard to make and AJAX call to fetch the user information from the database and render the return data in the Profile component. Recall that your Profile component was rendered at the path /users/:userId. Thus you can use your userId parameters from match.params to fetch a specific user:

    // ./src/Profile.js
    import React from "react";
    
    const Profile = ({ users, match: { params } }) =&gt; {
    
      // In a real-world scenario, you'd make a call to an API to fetch the user,
      // instead of passing down and keying into a `users` prop.
      const user = users[params.userId];
    
      return (
    
          The user's id is {params.userId} and the user's name is {user.name}.
    
      );
    };
    
    export default Profile;
    
    Enter fullscreen mode Exit fullscreen mode

    Match

    Now that you’ve seen your React Router’s match prop in action, let's go over more about route props! React Router passes information to the components as route props, accessible to all components with access to the React Router. The three props it makes available are location, match and history. You've learned about props.match.params, but now let's review the other properties of the match prop!

    This is an object that contains important information about how the current URL matches the route path. Here are some of the more useful keys on the match object:

    • isExact: a boolean that tells you whether or not the URL exactly matches the path
    • url: the current URL
    • path: the route path it matched against (without wildcards filled in)
    • params: the matches for the individual wildcard segments, nested under their names

    When you use React Router, the browser location and history are a part of the state of your app. You can store information about which component should be displayed, which user profile you are currently viewing, or any other piece of state, in the browser location. You can then access that information from anywhere your Router props are passed to in your app.

    Now that you’ve learned about parameters and route props, let’s revisit your Root component to add an exact flag to your /users route so that it does not render with your /users/:userId route. Your component should look something like this:

    const Root = () =&gt; {
      const users = {
        1: { name: 'Andrew' },
        2: { name: 'Raymond' }
      };
    
      return (
    
          <h1>Hi, I'm Root!</h1>
    
    
             <h1>Hello!</h1>} /&gt;
    
            {/* Render the `Users` page if no ID is included. */}
             } /&gt;
    
            {/* Otherwise, render the profile page for that userId. */}
             } /&gt;
    
    
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    What you learned

    In this article, you learned how to:

    • Use components from the React Router library; and
    • Create routes to render specific components; and
    • Manage the order of rendered routes; and
    • Use the exact flag to ensure that a specific path renders a specific component; and
    • Use the React Router match prop to access Router params.

    React Router Navigation

    Now that you know how to create front-end routes with React Router, you’ll need to implement a way for your users to navigate the routes! This is what using React Router’s Link, NavLink, Redirect, and history prop can help you do.

    In this article, you’ll be working off of the demo project you built in the React Router Intro reading. When you finish this article, you should be able to use the following components from the react-router-dom library:

    • or to create links with absolute paths to routes in your application (like "/users/1"); and,
    • `` to redirect a user to another path (i.e. a login page when the user is not logged in); and
    • React Router’s history prop to update a browser's URL programmatically.

    Adding links for navigation

    React Router’s is one way to simplify navigation around your app. It issues an on-click navigation event to a route defined in your app's router. Using renders an anchor tag with a correctly set href attribute.

    Link

    To use it, update your imports from the react-router-dom package to include Link:

    import { BrowserRouter, Route, Link } from 'react-router-dom';
    
    Enter fullscreen mode Exit fullscreen mode

    Note that `can take two props:toandonClick`.

    The to prop is a route location description that points to an absolute path, (i.e. /users). Add the following Link components in your index.js file above your routes:

    App
    Users
    Andrew's Profile
    
    Enter fullscreen mode Exit fullscreen mode

    The onClick prop is just like any other JSX click handler. You can write a function that takes in an event and handles it. Add the following Link before your routes and the following click handler function within your Root component:

    // Link with onClick prop
    App with click handler
    
    // Click handler function
    const handleClick = () =&gt; {
      console.log('Thanks for clicking!')
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Now, test your routes and links! If you inspect the page, you’ll see that your links are now rendered as <a> elements. Notice that clicking the App with click handler link logs a message in your console while directing your browser to render the App component.

    NavLink

    The works just like a, but with a little extra functionality. It has the ability to add extra styling when the path it links to matches the current path. This makes it an ideal choice for a navigation bar, hence the name. This styling can be controlled by three extra props: activeClassName, activeStyle, and exact. To begin using NavLink, update your imports from the react-router-dom package:

    import { BrowserRouter, Route, NavLink } from 'react-router-dom';
    
    Enter fullscreen mode Exit fullscreen mode

    The activeClassName prop of the NavLink component allows you to set a CSS class name for styling the NavLink when its route is active. By default, the activeClassName is already set to active. This means that you simply need to add an .active class to your CSS file to add active styling to your link. A NavLink will be active if its to prop path matches the current URL.

    Let’s change your “Users”, “Hello”, and “Andrew’s Profile” links to be different colors and have a larger font size when active.

    App
    Users
    Hello
    Andrew's Profile
    App with click handler
    
    Enter fullscreen mode Exit fullscreen mode

    For example, this is what the rendered HTML <a> tag would look like when when the browser is navigated to the / path or the /users path:

    </a><a href="/">App</a>
    
    
    <a href="/">App</a>
    
    
    <a href="/users">Users</a>
    
    
    <a href="/users">Users</a>
    
    Enter fullscreen mode Exit fullscreen mode

    Import NavLink into your index.js file and take a moment to update all your Link elements to NavLink elements. Set an activeClassName prop to an active class. Add the following .active class to your index.css file:

    .active {
      font-weight: bold;
    }
    
    .red {
      color: red;
      font-size: 30px;
    }
    
    .blue {
      color: blue;
      font-size: 30px;
    }
    
    .green {
      color: green;
      font-size: 30px;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Test your styled links! Notice how the App and App with click handler links are always bolded. This is because all of your links include the / path, meaning that the link to / will be active when browsing to /users and /users/1 because of how users and users/1 are both prefaced by a /.

    The activeStyle prop is a style object that will be applied inline to the NavLink when its to prop matches the current URL. Add the following activeStyle to your App link and comment out the .active class in your CSS file.

    App
    
    Enter fullscreen mode Exit fullscreen mode

    The following html is rendered when at the / path:

    <a href="/">App</a>
    
    Enter fullscreen mode Exit fullscreen mode

    Notice how your App with click handler is not bolded anymore. This is because the default active class being applied does not have any CSS stylings set to the class. Uncomment your .active class in your CSS file to bring back bolding to this NavLink.

    The exact prop is a boolean that defaults to false. If set to true, then the activeStyle and activeClassName props will only be applied when the current URL exactly matches the to prop. Update your App and App with click handler links with an exact prop set. Just like in your routes, you can use the exact flag instead of exact={true}.

    App
    App with click handler
    
    Enter fullscreen mode Exit fullscreen mode

    Now your App and App with click handler links will only be bolded when you have navigated precisely to the / path.

    Switching between routes

    You came across styling issues when the /users and /users/1 paths matched the / path. Routing can have this issue as well. This is why you need to control the switching between routes.

    React Router’s component allows you to only render one even if several match the current URL. You can nest as many Routes as you wish between the opening and closing Switch tags, but only the first one that matches the current URL will be rendered.

    This is particularly useful if you want a default component that will only render if none of our other routes match. View the example below. Without the Switch, DefaultComponent would always render. Since there isn't set a path in the DefaultComponent route, it will simply use the default path of /. Now the DefaultComponent will only render when neither of the preceding routes match.

    Import Switch from react-router-dom and add `tags around your routes to take care of ordering and switching between your routes! Begin by adding the following route to the bottom of your routes to render that a404: Page not found` message:

     <h1>404: Page not found</h1>} /&gt;
    
    Enter fullscreen mode Exit fullscreen mode

    This is what your Root component should look like at this point:

    const Root = () =&gt; {
      const users = [
        { name: 'andrew' },
        { name: 'raymond' }
      ];
    
      const handleClick = () =&gt; {
        console.log('Thanks for clicking!')
      };
    
      return (
    
          <h1>Hi, I'm Root!</h1>
    
    
            App
            Users
            Hello
            Andrew's Profile
            App with click handler
    
    
               } /&gt;
               } /&gt;
               <h1>Hello!</h1>} /&gt;
    
               <h1>404: Page not found</h1>} /&gt;
    
    
    
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Now you have control over the precedence of rendered components! Try navigating to http://localhost:3000/asdf or any other route you have not defined. The <h1>404: Page not found</h1> JSX of the last `` will be rendered whenever the browser attempts to visit an undefined route.

    Redirecting users

    But what if you want to redirect users to a login page when they aren’t logged in? The `` component from React Router helps you redirect users!

    The component takes only one prop: to. When it renders, it replaces the current URL with the value of its to prop. Typically you conditionally render to redirect the user away from some page you don't want them to visit. The example below checks whether there is a defined `currentUser` prop. If so, the will render the Home component. Otherwise, it will redirect the user to the /login path.

     (this.props.currentUser ?  : )}
    /&gt;
    
    Enter fullscreen mode Exit fullscreen mode

    Note: you will learn how to use a more flexible auth pattern — don’t directly imitate this example.

    History

    You know how to redirect users with a `component, but what if you need to redirect users programmatically? You've learned about the React Router'smatchprop, but now let's go over another one of the <a href="https://reacttraining.com/react-router/web/api/Route/route-props">route props</a>:history`!

    // Pushing a new URL (and adding to the end of history stack):
    const handleClick = () =&gt; this.props.history.push('/some/url');
    
    // Replacing the current URL (won't be tracked in history stack):
    const redirect = () =&gt; this.props.history.replace('/some/other/url');
    
    Enter fullscreen mode Exit fullscreen mode

    This prop lets you update the URL programmatically. For example, suppose you want to push a new URL when the user clicks a button. It has two useful methods:

    • push - This adds a new URL to the end of the history stack. That means that clicking the back button will take the browser to the previous URL. Note that pushing the same URL multiple times in a row will have no effect; the URL will still only show up on the stack once. In development mode, pushing the same URL twice in a row will generate a console warning. This warning is disabled in production mode.
    • replace - This replaces the current URL on the history stack, so the back button won't take you to it. For example:

    What you learned

    In this article, you learned how to:

    • Create navigation links for your route paths; and
    • Redirect users through using the `` component; and
    • Update a browser’s URL programmatically by using React Router’s history prop.

    React Router Nested Routes

    Now you know how to create front-end routes and add navigation with React Router. When initializing Express projects, you declare static routes. Static routes are routes that are declared when an application is initialized. When using React Router in your application’s initialization, you can declare dynamic routes. React Router introduces dynamic routing, where your routes are created as your application is rendering. This allows you to create nested routes within components!

    In this article, let’s dive into nested routes! When you finish the article, you should:

    • Describe what nested routes are; and
    • Be able to use React Router to create and navigate nested routes; and
    • Know how to use the React Router match prop to generate links and routes.

    Why nested routes?

    Let’s begin with why you might need nested routes. As you remember, you are using React to create a single-page application. This means that you’ll be organizing your application into different components and sub-components.

    For example, imagine creating a simple front-end application with three main pages: a home welcome page (path of /), a users index page (path of /users), and user profile pages (path of /users/:userId). Now imagine if every user had links to separate posts and photos pages.

    You can create those routes and links within the user profile component, instead of creating the routes and links where the main routes are defined.

    What are nested routes?

    Now let’s dive into a user profile component to understand what are nested routes! Imagine you have a route in your application’s entry file to each user’s profile like so:

    This means that upon navigating to http://localhost:3000/users/1, you would render the following Profile component and the userId parameter within props.match.params would have the value of "1".

    const Profile = (props) =&gt; {
      // Custom call to database to fetch a user by a user ID.
      const user = fetchUser(props.match.params.userId);
      const { name, id } = user;
    
      return (
    
          <h1>Welcome to the profile of {name}!</h1>
    
          {/* Links to a specific user's posts and photos */}
          {name}'s Posts
          {name}'s Photos
    
          {/* Routes to a specific user's posts and photos */}
    
    
    
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    Since this route is not created until the Profile component is rendered, you are dynamically creating your nested /users/:userId/posts and /users/:userId/photos routes. Remember that your match prop also has other helpful properties. You can use match.url instead of /users/${id} in your profile links. You can also use match.path instead of /users/:userId in your profile routes. Remember that you can destructure url, path, and params from your match prop!

    // Destructure `match` prop
    const Profile = ({ match: { url, path, params }) =&gt; {
    
      // Custom call to database to fetch a user by a user ID.
      const user = fetchUser(params.userId);
      const { name, id } = user;
    
      return (
    
          <h1>Welcome to the profile of {name}!</h1>
    
          {/* Replaced `/users/${id}` URL with `props.match.url` */}
          {name}'s Posts
          {name}'s Photos
    
          {/* Replaced `/users/:userId` path with `props.match.path` */}
    
    
        }
      );
    };
    
    Enter fullscreen mode Exit fullscreen mode

    In tomorrow’s project, you’ll build a rainbow of routes as well as define nested routes. In the future, you may choose to implement nested routes to keep your application’s routes organized within related components.

    What you learned

    In this article, you learned:

    • What nested routes are; and
    • About creating and navigating nested routes with React Router; and
    • How to use the React Router props to generate nested links and routes.

    React Builds

    A “build” is the process of converting code into something that can actually execute or run on the target platform. A “front-end build” is a process of preparing a front-end or client-side application for the browser.

    With React applications, that means (at a minimum) converting JSX to something that browsers can actually understand. When using Create React App, the build process is automatically configured to do that and a lot more.

    When you finish this article, you should be able to:

    • Describe what front-end builds are and why they’re needed;
    • Describe at a high level what happens in a Create React App when you run npm start; and
    • Prepare to deploy a React application into a production environment.

    Understanding front-end builds

    The need for front-end builds predates React. Over the years, developers have found it helpful to extend the lowest common denominator version of JavaScript and CSS that they could use.

    Sometimes developers extend JavaScript and CSS with something like TypeScript or Sass. Using these non-standard languages and syntaxes require you to use a build process to convert your code into standard JavaScript and CSS that can actually run in the browser.

    Browser-based applications also require a fair amount of optimization to deliver the best, or at least acceptable, experience to end users. Front-end build processes could be configured to lint code, run unit tests, optimize images, minify and bundle code, and more — all automatically at the press of a button (i.e. running a command at the terminal).

    JavaScript versions and the growth of front-end builds

    Developers are generally an impatient lot. When new features are added to JavaScript, we don’t like to wait for browsers to widely support those features before we start to use them in our code. And we really don’t like when we have to support older, legacy versions of browsers.

    In recent years, JavaScript has been updated on a yearly basis and browser vendors do a decent job of updating their browsers to support the new features as they’re added to the language. Years ago though, there was an infamous delay between versions 5 and 6 of JavaScript. It took years before ES6 (or ES2015 as it eventually was renamed to) to officially be completed and even longer before browsers supported all of its features.

    In the period of time before ES2015 was broadly supported by browsers, developers used front-end builds to convert or transpile ES2015 features and syntax to an older version of the language that was more broadly supported by browsers (typically ES5). The transpilation from ES2015/ES6 down to ES5 was one of the major drivers for developers to add front-end builds to their client-side projects.

    Reviewing common terminology

    When learning about front-end or React builds, you’ll encounter a lot of terminology that you may or may not be familiar with. Here’s some of the terminology that you’ll likely encounter:

    Linting is process of using a tool to analyze your code to catch common programming errors, bugs, stylistic inconsistencies, and suspicious coding patterns. ESLint is a popular JavaScript linting tool.

    Transpilation is the process of converting source code, like JavaScript, from one version to another version. Usually this means converting newer versions of JavaScript, ES2019 or ES2021, to a version that’s more widely supported by browsers, like ES2015, or even ES5 or ES3 (if you need to support the browser that your parents or grandparents use).

    Minification is the process of removing all unnecessary characters in your code (e.g. white space characters, new line characters, comments) to produce an overall smaller file. Minification tools will often also rename identifers in your code (i.e. parameter and variable names) in the quest for smaller and smaller file sizes. Source maps can also be generated to allow debugging tools to cross reference between minified code and the original source code.

    Bundling is the process of combining multiple code files into a single file. Creating a bundle (or a handful of bundles) reduces the number of requests that a client needs to make to the server.

    Tree shaking is the process of removing unused (or dead) code from your application before it’s bundled. Tree shaking external dependencies can sometimes have a dramatic positive impact on overall bundled file sizes.

    Configuration or code?

    Front-end build tools have come and gone over the years; sometimes very quickly, which helped bring about the phenomenon known as JavaScript fatigue.

    Configuration based tools allow you to create your build tasks by declaring (usually using JSON, XML, or YAML) what you want to be done, without explicitly writing every step in the process. In contrast, coding or scripting based tools allow you to, well, write code to create your build tasks. Configuration based tools can sometimes feel simpler to use while giving up some control (at least initially) while coding based tools can feel more familiar and predictable (since you’re describing tasks procedurally). Every generalization is false though (including this one), so there are plenty of exceptions.

    Grunt is a JSON configuration based task runner that can be used to orchestrate the various tasks that make up your front-end build. Grunt was very quickly supplanted by Gulp, which allowed developers to write JavaScript to define front-end build tasks. After Gulp, the front-end tooling landscape became a bit more muddled. Some developers preferred the simplicity of using npm scripts to define build tasks while others preferred the power of configuration based bundlers like webpack.

    Babel and webpack (yes, that’s intentionally a lowercase ‘w’)

    As front-end or client-side applications grew in complexity, developers found themselves wanting to leverage more advanced JavaScript features and newer syntax like classes, arrow functions, destructuring, async/await, etc. Using a code transpiler, like Babel, allows you to use all of the latest and greatest features and syntax without worrying about what browsers support what.

    Module loaders and bundlers, like webpack, also allowed developers to use JavaScript modules without requiring users to use a browser that natively supports ES modules. Also, module bundling (along with minification and tree-shaking) helps to reduce the bandwidth that’s required to deliver the assets for your application to the client.

    [Create React App][cra] uses webpack (along with Babel) under the covers to build your React applications. Even if you’re not using Create React App, webpack and Babel are still very popular choices for building React applications.

    Pulling back the covers (a bit) on the Create React App build process

    Running an application created by Create React App using npm start can feel magical. Some stuff happens in the terminal and your application opens into your default browser. Even better, when you make changes to your application, your changes will (usually) automatically appear in the browser!

    The Create React App build process

    At a high level, here’s what happens when you run npm start:

    • Environment variables are loaded (more about this in a bit);
    • The list of browsers to support are checked (more about this too in a bit);
    • The configured HTTP port is checked to ensure that it’s available;
    • The application compiler is configured and created;
    • webpack-dev-server is started;
    • webpack-dev-server compiles your application;
    • The index.html file is loaded into the browser; and
    • A file watcher is started to watch your files, waiting for changes.

    Ejecting

    Create React App provides a script that you can run to “eject” your application from the Create React App tooling. When you eject your application, all of the hidden stuff is exposed so that you can review and customize it.

    > The need to customize Create React App rarely happens. Also, don’t eject an actual project as it’s a one-way trip! Once a Create React App project has been ejected, there’s no going back (though you could always undo the ejection process by reverting to an earlier commit if you’re using source control).

    To eject your application from Create React App, run the command npm run eject. You'll be prompted if you want to continue; type "y" to continue with the ejection process. Once the ejection process has completed, you can review the files that were previously hidden from you.

    In the package.json file, you'll see the following npm scripts:

    {
      "scripts": {
        "start": "node scripts/start.js",
        "build": "node scripts/build.js",
        "test": "node scripts/test.js"
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode

    You can open the ./scripts/start.js file to see the code that's executed when you run npm start.

    If you’re curious about the webpack configuration, you can open and review the ./config/webpack.config.js.

    Preparing to deploy a React application for production

    Before you deploy your application to production, you’ll want to make sure that you’ve replaced static values in your code with environment variables and considered what browsers you need to support.

    Defining environment variables

    Create React App supports defining environment variables in an .env file. To define an environment variable, add an .env file to your project and define one or more variables that start with the prefix REACT_APP_:

    REACT_APP_FOO: some value
    REACT_APP_BAR: another value
    
    Enter fullscreen mode Exit fullscreen mode

    Environment variables can be used in code like this:

    console.log(process.env.REACT_APP_FOO);
    
    Enter fullscreen mode Exit fullscreen mode

    You can also reference environment variables in your index.html like this:

    %REACT_APP_BAR%
    
    Enter fullscreen mode Exit fullscreen mode

    > Important: Environment variables are embedded into your HTML, CSS, and JavaScript bundles during the build process. Because of this, it’s very important to not store any secrets, like API keys, in your environment variables as anyone can view your bundled code in the browser by inspecting your files.

    Configuring the supported browsers

    In your project’s package.json file, you can see the list of targeted browsers:

    {
      "browserslist": {
        "production": [
          "&gt;0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Adjusting these targets affect how your code will be transpiled. Specifying older browser versions will result in your code being transpiled to older versions of JavaScript in order to be compatible with the specified browser versions. The production list specifies the browsers to target when creating a production build and the development list specifics the browsers to target when running the application using npm start.

    The browserl.ist website can be used to see the browsers supported by your configured browserslist.

    Creating a production build

    To create a production build, run the command npm run build. The production build process bundles React in production mode and optimizes the build for the best performance. When the command completes, you'll find your production ready files in the build folder.

    Now your application is ready to be deployed!

    > For more information about how to deploy a Create React App project into production, see this page in the official documentation.

    What you learned

    In this article, you learned how to:

    • Describe what front-end builds are and why they’re needed;
    • Describe at a high level what happens in a Create React App when you run npm start; and
    • Prepare to deploy a React application into a production environment.

    React Router Documentation

    Now that you’ve had an introduction to React Router, feel free to explore the official documentation to learn more! As you become a full-fledged software engineer, remember that documentation is your friend. You can take a brief overview for now, as the documentation might include a lot of information at first. The more you learn about React, the more you should revisit the official documentation and learn!

    Setting up React Router

    Routes and Links

    Switch and Redirect

    React Router Params (ownProps)


    Rainbow Routes Project

    Today you’re going to get our first experience using React Router. The goal is to create a basic app that displays the colors of the rainbow. This rainbow, however, has something special about it — some of the colors are nested within others.

    Phase 0: Setup

    Begin by creating a new React project:

    npx create-react-app rainbow-routes --template @appacademy/simple
    
    Enter fullscreen mode Exit fullscreen mode

    Now you’ll remove all the contents of your src and all the contents from your public directory to build the application architecture from scratch! After you have deleted all your files within the directories, create a new index.html file in your public folder. Use the html:5 emmet shortcut to generate an HTML template. Title your page "Rainbow Routes" and create a div with an id of root in your DOM's `element. Create anindex.cssfile in yoursrc` directory with the following code. Now let's create your entry file!

    h4 {
      color: darkblue;
      cursor: pointer;
    }
    
    h4:hover {
      text-decoration: underline;
    }
    
    #rainbow {
      position: absolute;
      top: 0;
      left: 300px;
    }
    
    h3 {
      position: absolute;
      top: 1px;
    }
    
    .red {
      background-color: red;
      width: 100px;
      height: 100px;
    }
    
    .orange {
      background-color: orange;
      width: 100px;
      height: 50px;
    }
    
    .yellow {
      background-color: yellow;
      width: 100px;
      height: 50px;
    }
    
    .green {
      background-color: green;
      width: 100px;
      height: 100px;
    }
    
    .blue {
      background-color: blue;
      width: 100px;
      height: 100px;
    }
    
    .indigo {
      background-color: mediumslateblue;
      width: 100px;
      height: 50px;
    }
    
    .violet {
      background-color: darkviolet;
      width: 100px;
      height: 100px;
    }
    
    a {
      display: block;
      margin-bottom: 10px;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Create an index.js entry file in the src directory. At the top of the file, make sure to import React from the react package and ReactDOM from the react-dom package. Make sure to also import your the index.css file you just created! This will take care of styling your rainbow routes.

    Now you can use the ReactDOM.render() method to render a `component instead of the DOM element with anidofroot. Lastly, wrap your render function with aDOMContentLoaded` event listener, like so:

    document.addEventListener('DOMContentLoaded', () =&gt; {
      ReactDOM.render(
        ,
        document.getElementById('root'),
      );
    });
    
    Enter fullscreen mode Exit fullscreen mode

    Let’s create your Root component right in your entry file! Your Root component will take care of applying your BrowserRouter to the application. Applying the BrowserRouter to your Root component allows all the child components rendering within `tags to use and access theRoute,Link, andNavLinkcomponents within thereact-router-dom` package.

    const Root = () =&gt; (
      // TODO: Apply BrowserRouter
      // TODO: Render rainbow
    );
    
    Enter fullscreen mode Exit fullscreen mode

    Install the react-router-dom package:

    npm install react-router-dom@^5.0.0
    
    Enter fullscreen mode Exit fullscreen mode

    Now import BrowserRouter from the react-router-dom package, like so:

    import { BrowserRouter } from 'react-router-dom';
    
    Enter fullscreen mode Exit fullscreen mode

    You’re going to be rendering a lot of components, so let’s keep your src directory organized by creating a components directory within. Within your new ./src/components directory, create a Rainbow.js file for your Rainbow component with the following code:

    // ./src/components/Rainbow.js
    import React from 'react';
    import { Route, Link, NavLink } from 'react-router-dom';
    
    const Rainbow = () =&gt; (
    
        <h1>Rainbow Router!</h1>
        {/* Your links should go here */}
    
    
          {/* Your routes should go here */}
    
    
    );
    
    export default Rainbow;
    
    Enter fullscreen mode Exit fullscreen mode

    Your Rainbow component will act as the home page or default path (/) of your application. Import the Rainbow component into your entry file and have your Root component render wrapped within tags, like so:

    const Root = () =&gt; (
    
    
    
    );
    
    Enter fullscreen mode Exit fullscreen mode

    Within your Rainbow component, you'll be rendering and components to add different navigation paths to different components. Let's create all the components you will render!

    Create files for the following components in your ./src/components directory:

    • Red
    • Blue
    • Green
    • Indigo
    • Orange
    • Violet
    • Yellow

    Your Red and Blue components will look something like this:

    import React from 'react';
    import { Route, Link, NavLink } from 'react-router-dom';
    
    const Color = () =&gt; (
    
        <h2>Color</h2>
        {/* Links here */}
    
        {/* Routes here */}
    
    );
    
    export default Color;
    
    Enter fullscreen mode Exit fullscreen mode

    Your Green, Indigo, Orange, Violet, and Yellow components will look something like this:

    import React from 'react';
    
    const Color = () =&gt; (
    
        <h3>Color</h3>
    
    );
    
    export default Color;
    
    Enter fullscreen mode Exit fullscreen mode

    Now start your server and verify you can see the “Rainbow Router!” header from your Rainbow component. Currently there is no functionality. Let's fix that!

    Phase 1: Routes

    As a reminder, wrapping the Rainbow component in `tags makes the router available to all descendent React Router components. Now open theRainbow.js` file. You're going to render some of your color components from here. Ultimately you want your routes to look like this.

    URLComponents/Rainbow/redRainbow -&gt; Red/red/orangeRainbow -&gt; Red -&gt; Orange/red/yellowRainbow -&gt; Red -&gt; Yellow/greenRainbow -&gt; Green/blueRainbow -&gt; Blue/blue/indigoRainbow -&gt; Blue -&gt; Indigo/violetRainbow -&gt; Violet

    This means that the Red, Green, Blue, and Violet components need to render in the Rainbow component, but only when you are at the corresponding URL. You'll do this with Route components. Begin by importing the Red, Green, Blue, and Violet components into your Rainbow.js file. Then add the necessary Route components inside the div with id="rainbow" in the Rainbow component. For example to render the Red component with the /red path, you would use the following Route component:

    Test that your code works! Manually type in each URL you just created, and you should see the color component pop up. Remember, these are React Routes, so the paths you created will come after the /. For example, your default rainbow route will look like http://localhost:3000/ while your red route will look like http://localhost:3000/red.

    You want to nest the Orange and Yellow components inside the Red component, and the Indigo component inside the Blue component. Remember to import your components to use them in a Route tag. You'll have to go add the corresponding Route tags to the Red.js and Blue.js files. Make sure to use the correct nested paths, such as "/red/orange" for the orange Route.

    Phase 2: Links

    Manually navigating to our newly created routes is tiresome, so let’s add functionality to take care of this process for us. React Router provides the Link and NavLink components for this purpose.

    Add Links to the paths /red, /green, /blue, and /violet in the Rainbow component. For example, your red link should look like

    Red
    
    Enter fullscreen mode Exit fullscreen mode

    When you are at blue you want to be able to get to /blue/indigo, and then back to /blue. Add the corresponding Links to the Blue component like this:

    Blue only
    Add indigo
    
    Enter fullscreen mode Exit fullscreen mode

    Similarly, add Links to /red, /red/orange and /red/yellow to the Red component. Test all your links. Navigation is so much easier now!

    Phase 3: NavLinks

    It would be nice if our links gave us some indication of which route you were at. Fortunately, React Router has a special component for that very purpose: NavLink. NavLinks get an extra CSS class when their to prop matches the current URL. By default this class is called active.

    Go ahead and switch all your Links to NavLinks. If you open the app you won't see any change yet. That's because you haven't added any special styling to the active class. Go ahead and open the index.css file. Create an .active class and add the line font-weight: 700. Now your active links will be bold. Isn't that nice!

    The only problem is that now the Blue only link is active even when the path is /blue/indigo. That doesn't make a lot of sense. Let's add the exact flag to that link so it will only be active when its to exactly matches the current path. Now it should look like:

      Blue only
    
    Enter fullscreen mode Exit fullscreen mode

    Do the same for the Red only link. Everything should be working now.

    Phase 4 — Changing NavLink’s Active Class

    You’ve already set up NavLink to bold the link text using the .active class in src/index.css. But what if you wanted this class to be something else? For instance, what if you want your main color links (Red, Green, Blue, Violet) to be styled differently when active than your sub-route links (Red Only, Add Orange, Add Yellow, etc.).

    You can set the class that React Router sets to an active NavLink by adding the activeClassName prop.

    For instance, when we are at a route matching the below NavLink's to prop, the component will have a class of .parent-active applied:

      Blue
    
    Enter fullscreen mode Exit fullscreen mode

    This allows much more flexibility to style an active NavLink!

    Using the example above, add an activeClassName prop to each of your NavLinks in src/components/Rainbow.js. Now, add some CSS styling for that class in your src/index.css to distinguish your main and your sub-route links.

    Compare your work to the solution and make sure the behavior is the same. Time to celebrate! ✨ 🌈 ✨

    You can also learn more about using the React Router at reacttraining.com!


    Exploring React Builds Project

    In this project, you’ll use Create React App to create a simple React application. You’ll experiment with some of the features that Create React App provides and deploy a production build of your application to a standalone Express application.

    Phase 0: Setup

    Begin by using the create-react-app package to create a React application:

    npx create-react-app exploring-react-builds --template @appacademy/simple
    
    Enter fullscreen mode Exit fullscreen mode

    > Remember that using the create-react-app command initializes your project as a Git repository. If you use the ls -a to view the hidden files in your project, you'll see the .git file.

    Update the App component:

    • Wrap the <h1> element with a `` element; and
    • Change the <h1> element content to something like "Exploring React Builds".

      // ./src/App.js

      import React from 'react';

      function App() {
      return (

        <h1>Exploring React Builds</h1>
      
      Enter fullscreen mode Exit fullscreen mode

      );
      }

      export default App;

    Phase 1: Using CSS modules

    You’ve already seen an example of using the import keyword to import a stylesheet into a module so that it'll be included in your application build. That's the technique being used to include the global index.css stylesheet:

    // ./src/index.js
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    
    ReactDOM.render(
    
    
      ,
      document.getElementById('root')
    );
    
    Enter fullscreen mode Exit fullscreen mode

    You can also leverage CSS modules in your Create React App projects. CSS Modules scope stylesheet class names so that they are unique to a specific React component. This allows you to create class names without having to worry if they might collide with class names used in another component.

    Add a new css-modules folder to the src folder. Within that folder, add the following files:

    • HeadingA.js
    • HeadingA.module.css
    • HeadingB.js
    • HeadingB.module.css

    Then update the contents of each file to the following:

    // ./src/css-modules/HeadingA.js
    
    import React from 'react';
    import styles from './HeadingA.module.css';
    
    function HeadingA() {
      return (
        <h1>Heading A</h1>
      );
    }
    
    export default HeadingA;
    
    /* ./src/css-modules/HeadingA.module.css */
    
    .heading {
      color: green;
    }
    
    // ./src/css-modules/HeadingB.js
    
    import React from 'react';
    import styles from './HeadingB.module.css';
    
    function HeadingB() {
      return (
        <h1>Heading B</h1>
      );
    }
    
    export default HeadingB;
    
    /* ./src/css-modules/HeadingB.module.css */
    
    .heading {
      color: red;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Notice how the .heading CSS class name is being used within each component to set the color of the <h1> element. For the HeadingA component, the color is green, and for the HeadingB component, the color is red. Using the file naming convention [name].module.css let's Create React App know that we want these stylesheets to be processed as CSS Modules. Using CSS Modules allows the .heading class name to be reused across components without any issue.

    To see this feature in action, update your App component to render both of your new components:

    import React from 'react';
    import HeadingA from './css-modules/HeadingA';
    import HeadingB from './css-modules/HeadingB';
    
    function App() {
      return (
    
          <h1>Exploring React Builds</h1>
    
    
    
      );
    }
    
    export default App;
    
    Enter fullscreen mode Exit fullscreen mode

    Then run your application (npm start) to see "Heading A" and "Heading B" displayed respectively in green and red. If you use the browser's developer tools to inspect "Heading A", you'll see that the .heading class name has been modified so that it's unique to the HeadingA component:

    CSS Modules is an example of how a front-end build process can be used to modify code to enable a feature that’s not natively supported by browsers.

    Phase 2: Using an image in a component

    Create React App configures webpack with support for loading images (as well as CSS, fonts, and other file types). What this means, for you as the developer, is that you can add an image file to your project, import it directly into a module, and render it in a React component.

    Download any image of off the Web or click here to download the below image.

    Then within the src folder add a new folder named image. Within that folder add a new component file named Image.js. Also add your downloaded image file to the image folder (so it's a sibling to the Image.js file).

    Update the contents of the Image.js file to this:

    // ./src/image/Image.js
    
    import React from 'react';
    import cat from './react-builds-cat.png';
    
    console.log(cat); // /static/media/react-builds-cat.45f7f4d2.png
    
    function Image() {
      // Import result is the URL of your image.
      return <img src="{cat}" alt="images/images/Cat">;
    }
    
    export default Image;
    
    Enter fullscreen mode Exit fullscreen mode

    You can import an image into a component using the import keyword. This tells webpack to include the image in the build. Notice that when you import an image into a module, you'll get a path to the image's location within the build. You can use this path to set the src attribute on an <img> element.

    > Be sure to update the image import statement to the correct file name if you're using your own image!

    Now update the App component to import and render the Image component:

    // ./src/App.js
    
    import React from 'react';
    import HeadingA from './css-modules/HeadingA';
    import HeadingB from './css-modules/HeadingB';
    import Image from './image/Image';
    
    function App() {
      return (
    
          <h1>Exploring React Builds</h1>
    
    
    
    
      );
    }
    
    export default App;
    
    Enter fullscreen mode Exit fullscreen mode

    If you run your application (npm start) you'll see your image displayed on the page! You can also open your browser's developer tools and view the "Sources" for the current page. If you can expand the localhost:3000 > static > media node on the left, you can see the image file that webpack copied to your build.

    Images in stylesheets

    You can also reference images in your CSS files too. Add a CSS file named Image.css to the ./src/image folder and update its contents to this:

    /* ./src/image/Image.css */
    
    .cat {
      background-image: url(./react-builds-cat.png);
      width: 400px;
      height: 400px;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Then update the Image component to this:

    // ./src/image/Image.js
    
    import React from 'react';
    import './Image.css';
    import cat from './react-builds-cat.png';
    
    console.log(cat); // /static/media/react-builds-cat.45f7f4d2.png
    
    function Image() {
      return (
    
          {/* Import result is the URL of your image. */}
          <img src="{cat}" alt="Cat">
    
    
      );
    }
    
    export default Image;
    
    Enter fullscreen mode Exit fullscreen mode

    Now you’ll see the image displayed twice on the page!

    Phase 3: Updating the supported browsers (and its affect on code transpilation)

    Earlier you learned about the browerslist setting in the package.json file and now adjusting these targets affect how your code will be transpiled:

    {
      "browserslist": {
        "production": [
          "&gt;0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode

    The production list specifies the browsers to target when creating a production build and the development list specifics the browsers to target when running the application using npm start. Currently, you're targeting relatively recent versions of the major browsers when creating a development build. Targeting older browser versions results in your code being transpiled to an older version of JavaScript.

    To experiment with this configuration option, let’s add a class component to the project. Add a new folder named class-component to the src folder. Within that folder, add a file named ClassComponent.js containing the following code:

    // ./src/class-component/ClassComponent.js
    
    import React from 'react';
    
    class ClassComponent extends React.Component {
      render() {
        return (
          <h1>Class Component</h1>
        );
      }
    }
    
    export default ClassComponent;
    
    Enter fullscreen mode Exit fullscreen mode

    Don’t forget to update your App component to render the new component:

    // ./src/App.js
    
    import React from 'react';
    import HeadingA from './css-modules/HeadingA';
    import HeadingB from './css-modules/HeadingB';
    import Image from './image/Image';
    import ClassComponent from './class-component/ClassComponent';
    
    function App() {
      return (
    
          <h1>Exploring React Builds</h1>
    
    
    
    
    
      );
    }
    
    export default App;
    
    Enter fullscreen mode Exit fullscreen mode

    Now run your application using npm start. Open your browser's developer tools and view the "Sources" for the current page. Expand the localhost:3000 > static > js node on the left and select the main.chunk.js file. Press CMD+F on macOS or CTRL+F on Windows to search the file for "Class Component". Here's what the transpiled code looks like for the ClassComponent class:

    class ClassComponent extends react__WEBPACK_IMPORTED_MODULE_0___default.a.Component {
      render() {
        return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
          __self: this,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 7,
            columnNumber: 7
          }
        }, "Class Component");
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode

    > Have you wondered yet why you need to use the developer tools to view the bundles generated by Create React App? Remember that when you run npm start, Create React App builds your application using webpack-dev-server. To keep things as performant as possible, the bundles generated by webpack-dev-server are stored in memory instead of writing them to the file system.

    The JSX in the component’s render method has been converted to JavaScript but the ClassComponent ES2015 class is left alone. This makes sense though as JSX isn't natively supported by any browser while ES2015 classes have been natively supported by browsers for awhile now.

    But what if you need to target a version of a browser that doesn’t support ES2015 classes? You can use the “Can I use…” website to see when browsers started supporting ES2105 (or ES6) classes. Starting with version 49, Chrome natively supported classes. But imagine that you need to support Chrome going back to version 30, a version of Chrome that doesn’t support classes.

    Change the browserslist.development property in the package.json file to this:

    {
      "browserslist": {
        "production": [
          "&gt;0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "chrome &gt;= 30",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
    
    Enter fullscreen mode Exit fullscreen mode

    The query chrome &gt;= 30 specifies that you want to target Chrome version 30 or newer.

    > The browserl.ist website can be used to see the browsers supported by your configured browserslist.

    Stop your application if it’s currently running. Delete the ./node_modules/.cache folder and run npm start again. Then view the main.chunk.js bundle again in the developer tools:

    Now your ES2015 class component is being converted to a constructor function! Here’s the transpiled code for reference:

    var ClassComponent = /*#__PURE__*/function (_React$Component) {
      Object(_Users_jameschurchill_Documents_GitHub_Modular_Curriculum_content_react_redux_topics_react_builds_projects_exploring_react_builds_solution_node_modules_babel_preset_react_app_node_modules_babel_runtime_helpers_esm_inherits__WEBPACK_IMPORTED_MODULE_2__["default"])(ClassComponent, _React$Component);
    
      var _super = Object(_Users_jameschurchill_Documents_GitHub_Modular_Curriculum_content_react_redux_topics_react_builds_projects_exploring_react_builds_solution_node_modules_babel_preset_react_app_node_modules_babel_runtime_helpers_esm_createSuper__WEBPACK_IMPORTED_MODULE_3__["default"])(ClassComponent);
    
      function ClassComponent() {
        Object(_Users_jameschurchill_Documents_GitHub_Modular_Curriculum_content_react_redux_topics_react_builds_projects_exploring_react_builds_solution_node_modules_babel_preset_react_app_node_modules_babel_runtime_helpers_esm_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, ClassComponent);
    
        return _super.apply(this, arguments);
      }
    
      Object(_Users_jameschurchill_Documents_GitHub_Modular_Curriculum_content_react_redux_topics_react_builds_projects_exploring_react_builds_solution_node_modules_babel_preset_react_app_node_modules_babel_runtime_helpers_esm_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(ClassComponent, [{
        key: "render",
        value: function render() {
          return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_4___default.a.createElement("h1", {
            __self: this,
            __source: {
              fileName: _jsxFileName,
              lineNumber: 7,
              columnNumber: 7
            }
          }, "Class Component");
        }
      }]);
    
      return ClassComponent;
    }(react__WEBPACK_IMPORTED_MODULE_4___default.a.Component);
    
    Enter fullscreen mode Exit fullscreen mode

    Luckily it’s very rare that you’ll need to read the code in your generated bundles. webpack, by default, is configured to generate sourcemaps. Sourcemaps are a mapping of the code in a generated file, like a bundle file, to the original source code. This gives you access to your original source code in the browser’s developer tools:

    You can even set a breakpoint in your source within the developer tools to stop execution on a specific line of code!

    Phase 4: Adding environment variables

    Earlier you learned that Create React App supports defining environment variables in an .env file. This gives you a convenient way to avoid hard coding values that vary across environments.

    Let’s experiment with this feature so that you can see how the Create React App build process embeds environment variables into your HTML, CSS, and JavaScript bundles.

    Add an .env file to the root of your Create React App project. Define an environment variable named REACT_APP_TITLE:

    REACT_APP_TITLE=Exploring React Builds
    
    Enter fullscreen mode Exit fullscreen mode

    Remember that environment variables need to be prefixed with REACT_APP_ for Create React App to process them. After defining your environment variable, you can refer to it within JSX using an expression and process.env:

    // ./src/App.js
    
    import React from 'react';
    import HeadingA from './css-modules/HeadingA';
    import HeadingB from './css-modules/HeadingB';
    import Image from './image/Image';
    import ClassComponent from './class-component/ClassComponent';
    
    function App() {
      return (
    
          <h1>{process.env.REACT_APP_TITLE}</h1>
    
    
    
    
    
      );
    }
    
    export default App;
    
    Enter fullscreen mode Exit fullscreen mode

    Environment variables can also be referred to in regular JavaScript code:

    console.log(process.env.REACT_APP_TITLE);
    
    Enter fullscreen mode Exit fullscreen mode

    You can also reference environment variables in your ./public/index.html file like this:

        %REACT_APP_TITLE%
    
    Enter fullscreen mode Exit fullscreen mode

    Run your application again using npm start. Open your browser's developer tools and view the "Sources" for the current page. Expand the localhost:3000 node on the left and select (index). Notice that the text %REACT_APP_TITLE% within the `element has been converted to the text literalExploring React Builds`:

    If you expand the localhost:3000 > static > js node on the left and select the main.chunk.js file, you can see how the App component's JSX has been converted to JavaScript:

    Here’s a closer look at the relevant React.createElement method call:

    /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("h1", {
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 10,
          columnNumber: 7
        }
      }, "Exploring React Builds")
    
    Enter fullscreen mode Exit fullscreen mode

    Again, notice how the environment variable has been replaced with a text literal. This has important security implications for you to consider. Because environment variables are embedded into your HTML, CSS, and JavaScript bundles during the build process, it’s very important to not store any secrets, like API keys, in your environment variables. Remember, anyone can view your bundled code in the browser by inspecting your files!

    Phase 5: Deploying a production build

    In the last phase of this project, let’s add routing to the React application, create a production build, and deploy the build to an Express application!

    Adding routing

    To add React Router to the application, start by installing the react-router-dom npm package:

    npm install react-router-dom@^5.0.0
    
    Enter fullscreen mode Exit fullscreen mode

    Then update the App component to this code:

    // ./src/App.js
    
    import React from 'react';
    import {
      BrowserRouter,
      Switch,
      Route,
      Link
    } from 'react-router-dom';
    import HeadingA from './css-modules/HeadingA';
    import HeadingB from './css-modules/HeadingB';
    import Image from './image/Image';
    import ClassComponent from './class-component/ClassComponent';
    
    function App() {
      return (
    
    
            <h1>{process.env.REACT_APP_TITLE}</h1>
    
              <ul>
                <li>
                  Home
                </li>
                <li>
                  Image
                </li>
                <li>
                  Class Component
                </li>
              </ul>
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
      );
    }
    
    export default App;
    
    Enter fullscreen mode Exit fullscreen mode

    Be sure to run and test your application to ensure that the defined routes work as expected:

    • / - Should display the HeadingA and HeadingB components;
    • /image - Should display the Image component; and
    • /class-component - Should display the ClassComponent component.

    Creating a production build

    To create a production build, run the command npm run build from the root of your project. The output in the terminal should look something like this:

    &gt; solution@0.1.0 build [absolute path to your project]
    &gt; react-scripts build
    
    Creating an optimized production build...
    Compiled successfully.
    
    File sizes after gzip:
    
      47.83 KB  build/static/js/2.722c16c4.chunk.js
      773 B     build/static/js/runtime-main.b7d1e5ee.js
      745 B     build/static/js/main.12299197.chunk.js
      197 B     build/static/css/main.e9a0d1f8.chunk.css
    
    The project was built assuming it is hosted at /.
    You can control this with the homepage field in your package.json.
    
    The build folder is ready to be deployed.
    You may serve it with a static server:
    
      npm install -g serve
      serve -s build
    
    Find out more about deployment here:
    
      bit.ly/CRA-deploy
    
    Enter fullscreen mode Exit fullscreen mode

    Ignore the comments about using serve to deploy your application (i.e. npm install -g serve and serve -s build). In the next step, you'll create a simple Express application to server your React application.

    Serving a React application using Express

    Create a new folder for your Express application outside of the Create React App project folder.

    > For example, from the root of your project, use cd .. to go up a level and then create a new folder named express-server by running the command mkdir express-server. This makes the express-server folder a sibling to your Create React App project folder.

    Browse into the express-server folder and initialize it to use npm (i.e. npm init -y). Then install Express by running the command npm install express@^4.0.0.

    App a file named app.js with the following contents:

    // ./app.js
    
    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'public', 'index.html'));
    });
    
    const port = 9000;
    
    app.listen(port, () =&gt; console.log(`Listening on port ${port}...`));
    
    Enter fullscreen mode Exit fullscreen mode

    This simple Express application will:

    • Attempt to match incoming requests to static files located in the public folder; and
    • If a matching static file isn’t found, then the ./public/index.html file will be served for all other requests.

    Now add a folder named public to the root of your Express project. Copy the files from the build folder in your Create React App project to the public folder in the Express application project. Then run your application using the command node app.js.

    Open a browser and browse to the URL http://localhost:9000/. You should see your React application served from your Express application! Be sure to click the navigation links to verify that all of your configured routes work as expected.

    Also, because you configured Express to serve the ./public/index.html file for any request that doesn't match a static file, you can "deep link" to any of your React application's routes:

    More content at plainenglish.io

    By Bryan Guner on July 15, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    Adding CSS To Your HTML

    For beginners … very picture heavy since CSS is such a visual discipline!


    Adding CSS To Your HTML

    For beginners … very picture heavy since CSS is such a visual discipline!

    ### Getting CSS Into Your HTML

    • To connect your CSS sheet to your HTML page, use the link tag like so.
    • Many developers use External pre-written CSS stylesheets for consistent design.
    • You can connect multiple stylesheets.

    CSS Selectors

    • CSS Selector : Applies styles to a specific DOM element(s), there are various types:
    • Type Selectors : Matches by node name.

    - Class Selectors : Matches by class name.

    - ID Selectors : Matches by ID name.

    - Universal Selectors : Selects all HTML elements on a page.

    - Attribute Selectors : Matches elements based on the prescence or value of a given attribute. (i.e. a[title] will match all a elements with a title attribute)

    /* Type selector */
    div {
      background-color: #000000;
    }
    
    /* Class selector */
    .active {
      color: #ffffff;
    }
    
    /* ID selector */
    #list-1 {
      border: 1px solid gray;
    }
    
    /* Universal selector */
    * {
      padding: 10px;
    }
    
    /* Attribute selector */
    a[title] {
      font-size: 2em;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Class Selectors

    • Used to select all elements of a certain class denoted with a .[class name]
    • You can assign multiple classes to a DOM element by separating them with a space.

    Compound Class Selectors

    - To get around accidentally selecting elements with multiple classes beyond what we want to grab we can chain dots.

    • TO use a compound class selector just append the classes together when referencing them in the CSS.

    • i.e. .box.yellow will select only the first element.

    • KEEP IN MIND that if you do include a space it will make the selector into a descendant selector.

      h1#heading,
      h2.subheading {
      font-style: italic;
      }

    • When we want to target all h1 tags with the id of heading.

    CSS Combinators

    • CSS Combinators are used to combine other selectors into more complex or targeted selectors — they are very powerful!
    • Be careful not to use too many of them as they will make your CSS far too complex.

    Descendant Selectors

    - Separated by a space.

    • Selects all descendants of a parent container.

    Direct Child Selectors

    - Indicated with a &gt;.

    • Different from descendants because it only affects the direct children of an element.

    CSS:

    .menu &gt; .is-active { background-color: #ffe0b2; }
    
    Enter fullscreen mode Exit fullscreen mode

    HTML:

      Belka  Strelka     Laika  
    
    Enter fullscreen mode Exit fullscreen mode
    • Belka would be the only element selected.

    Adjacent Sibling Selectors

    - Uses the + symbol.

    • Used for elements that directly follow one another and who both have the same parent.

      h1 + h2 { font-style: italic; }

      //HTML:

      Big header

      This one is styled because it is directly adjacent to the H1

      This one is NOT styled because there is no H1 right before it

      h1 + h2 { font-style: italic; }

      Big header

      This one is styled because it is directly adjacent to the H1

      This one is NOT styled because there is no H1 right before it

    Pseudo-Classes

    courtesy of Pseudo-classes — CSS: Cascading Style Sheets | MDN (mozilla.org)
    courtesy of Pseudo-classes — CSS: Cascading Style Sheets | MDN (mozilla.org)
    - Pseudo-Class : Specifies a special state of the seleted element(s) and does not refer to any elements or attributes contained in the DOM.

    • Format is a Selector:Pseudo-Class Name or A:B

      a:hover {
      font-family: "Roboto Condensed", sans-serif;
      color: #4fc3f7;
      text-decoration: none;
      border-bottom: 2px solid #4fc3f7;
      }

    > Some common pseudo-classes that are frequently used are:

    • active : 'push down', when elements are activated.
    • checked : applies to things like radio buttons or checkbox inputs.

    - disabled : any disabled element.

    - first-child : first element in a group of children/siblings.

    • focus : elements that have current focus.
    • hover : elements that have cursor hovering over it.

    - invalid : any form elements in an invalid state from client-side form validation.

    • last-child : last element in a group of children/siblings.
    • not(selector) : elements that do not match the provided selector.
    • required : form elements that are required.

    - valid : form elements in a valid state.

    • visited : anchor tags of which the user has already visited the URL that the href points to.

    Pseudo-Selectors

    • Used to create pseudo-elements as children of the elements to which the property applies.
    • ::after
    • ::before

      p::before {
      background-color: lightblue;
      border-right: 4px solid violet;
      content: ":-) ";
      margin-right: 4px;
      padding-left: 4px;
      }

      This is the first paragraph

      This is the second paragraph

      This is the third paragraph

    • Will add some blue smiley faces before the p tag elements.

    CSS Rules

    • CSS Rule : Collection of single or compound selectors, a curly brace, zero or more properties
    • CSS Rule Specificity : Sometimes CSS rules will contain multiple elements and may have overlapping properties rules for those same elements - there is an algorithm in CSS that calculates which rule takes precedence.
    • The Four Number Calculation : listed in increasing order of importance.
    1. Who has the most IDs? If no one, continue.
    2. Who has the most classes? If no one, continue.
    3. Who has the most tags? If no one, continue.
    4. Last Read in the browser wins.


    .box {
    width: 50px;
    height: 50px;
    border: 1px solid black;
    }
    .orange {
    background-color: orange;
    }
    .yellow {
    background-color: yellow;
    border: 1px solid purple;
    }

    • Coming back to our example where all the CSS Rules have tied, the last step 4 wins out so our element will have a purple border.

    CSS: Type, Properties, and Imports

    Typography

    • font-family : change the font.

    - Remember that not all computers have the same fonts on them.

    • You can import web fonts via an api by using
    • @import url('https://fonts.googleapis.com/css2?family=Liu+Jian+Mao+Cao&amp;display=swap'); and pasting it st the top of your CSS file.
    • And then reference it in your font-family.
    • font-size : Changes the size of your font.
    • Keep in mind the two kind of units CSS uses:
    • Absolute : Pixels, Points, Inches, Centimeters.
    • Relative : Em, Rem.
    • Em: Calculating the size relative to the previous div (bubbles down)
    • Rem: Calculates relative to the parent element always.
    • font-style : Used to set a font to italics.
    • font-weight : Used to make a font bold.
    • text-align : Used to align your text to the left, center, or right.
    • text-decoration : Use to put lines above, through, or under text. Lines can be solid, dashed, or wavy!
    • text-transform : Used to set text to all lowercase, uppercase, or capitalize all words.

    Background-Images

    • You can use the background-image property to set a background image for an element.

    CSS: Colors, Borders, and Shadows

    Colors

    • You can set colors in CSS in three popular ways: by name, by hexadecimal RGB value, and by their decimal RGB value.
    • rgba() is used to make an rbg value more transparent, the a is used to specify the alpha channel.
    • Color : Property used to change the color of text.
    • Background-Color : Property to change the backgrounf color of an element.

    Borders

    • Borders take three values: The width of the border, the style (i.e. solid, dotted, dashed), color of the border.

    Shadows

    • There are two kinds of shadows in CSS: box shadows and text shadows.
    • Box refers to HTML elements.
    • Text refers to text.
    • Shadows take values such as, the horizontal & vertical offsets of the shadow, the blur radius of the shadow, the spread radius, and of course the colors.

    My Blog:

    Web-Dev-Hub

    my resource sharing and blog site ... centered mostly on web development and just a bit of audio production / generally…bgoonz-blog.netlify.app

    By Bryan Guner on August 22, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    A list of all of my articles to link to future posts

    You should probably skip this one… seriously it’s just for internal use!


    All Of My Medium Stories


    This is another backup of all of them!

    All OF MEDIUM ARTICLES

    2021-02-27_A-Quick-Guide-to-Big-O-Notation--Memoization--Tabulation--and-Sorting-Algorithms-by-Example-803ff193c522…golden-lobe-519.notion.site


    The ExpressJS Way To Write APIs

    This article will cover the basics of express from the perspective of a beginner without concerning it’s self with the…bryanguner.medium.com

    Heroku Deploy Guides & Cheatsheet Compilation

    Heroku lets you deploy, run and manage applications written in Ruby, Node.js, Java, Python, Clojure, Scala, Go and PHP…bryanguner.medium.com

    A Comprehensive Deep Dive into React

    An in-depth look into the world of React.javascript.plainenglish.io

    Web Development Resource List #4

    Update:bryanguner.medium.com

    BASH CHEAT SHEET

    My Bash Cheatsheet Index:bryanguner.medium.com

    Heroku Cheat Sheet

    a cheatsheet for using heroku-clibryanguner.medium.com

    Web Developer’s Technical Glossary

    This will be a running list as I make updates!bryanguner.medium.com

    PostgreSQL In 43 Commands Or Less

    In database jargon, PostgreSQL uses a client/server model. A PostgreSQL session consists of the following cooperating…medium.com

    Why Jamstack Rocks🤘😎🤙

    JAMstack websites don’t use the microservices architecture, but they go for the micro frontends architecture. Each…medium.com

    What Are Bash Aliases And Why Should You Be Using Them!

    A Bash alias is a method of supplementing or overriding Bash commands with new ones. Bash aliases make it easy for…bryanguner.medium.com

    Life Saving Bash Scripts Part 2

    I am not saying they’re in any way special compared with other bash scripts… but when I consider that you can never…medium.com

    Job Boards and The Hunt

    I can’t imagine the kind of masochism it would take to enjoy the act of posting and daily maintenance on a job…medium.com

    Absolutely Everything You Could Need To Know About How JavaScript Works.

    Seriously… this list is utterly exhaustive it covers more core concepts than I can hold the names of in working memory…bryanguner.medium.com

    Basic React Tutorial

    Random Things to Rememberbryanguner.medium.com

    Fundamental Concepts In React That Will Probably Come Up On An Interview

    Incomplete Articlebryanguner.medium.com

    The Penultimate Web Developer’s Cheat Sheet

    I am literally just going to combine a fair number of my Cheat Sheets in no particular order.medium.com

    Bash Commands That Save Me Time and Frustration

    Here’s a list of bash commands that stand between me and insanity.medium.com

    Quick Web Developers Website Checklist & A List Of Tools For Improvement

    A set of questions you should use before handing off your application to the client.bryanguner.medium.com

    10 Essential React Interview Questions For Aspiring Frontend Developers

    Comprehensive React Cheatsheet included at the bottom of this article!javascript.plainenglish.io

    Long List Of Invaluable NodeJS Resources

    Disclaimer: I know that I did not create this list all on my own… I can’t recall or track down the original list if you…levelup.gitconnected.com

    Open Ended Frontend Interview Questions You Should Answer Before Your Next Interview

    Explain event delegation.bryanguner.medium.com

    Data Structures… Under The Hood

    Data Structures Referencebryanguner.medium.com

    Web Development Interview Resource List

    Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it…medium.com

    Beginners Guide To Python

    My favorite language for maintainability is Python. It has simple, clean syntax, object encapsulation, good library…medium.com

    Data Structures & Algorithms Resource List Part 1

    Guess the author of the following quotes:bryanguner.medium.com

    What is Memoization?

    And why this programming paradigm shouldn’t make you cringe.javascript.plainenglish.io

    CSS Interview Prep Quiz

    Plus Css Cheat Sheet (82 questions total)bryanguner.medium.com

    Graph Data Structure Interview Questions At A Glance

    Because they’re just about the most important data structure there is.medium.com

    Object Methods

    Iterating Through Objectsmedium.com

    Github Repositories That Will Teach You How To Code For Free!

    30-seconds/30-seconds-of-codelevelup.gitconnected.com

    Resources By Programming Language

    Here’s a list of programming resources sorted by programming language.bryanguner.medium.com

    Breaking Down Scope, Context, And Closure In JavaScript In Simple Terms.

    “JavaScript’s global scope is like a public toilet. You can’t avoid going in there, but try to limit your contact with…medium.com

    These Are A Few Of My Favorite Things

    A web development student’s declassified school survival guide.medium.com

    Objects In JavaScript

    The object is a data structure that stores other data, similar to how an array stores elements.medium.com

    Fundamental Javascript Concepts You Should Understand

    Plain Old JS Object Lesson Conceptsbryanguner.medium.com

    Mutability And Reference VS Privative Types in JavaScript

    Mutability && Primitive && Reference Examplesbryanguner.medium.com

    Array Callback Methods Implemented With For Loops

    How to implement array callback methods in JavaScriptjavascript.plainenglish.io

    Beginner’s Guide To React Part 2

    As I learn to build web applications in React I will blog about it in this series in an attempt to capture the…bryanguner.medium.com

    A Very Quick Guide To Calculating Big O Computational Complexity

    Big O: big picture, broad strokes, not detailsbryanguner.medium.com

    Introduction to React for Complete Beginners

    All of the code examples below will be included a second time at the bottom of this article as an embedded gist.javascript.plainenglish.io

    Scheduling: setTimeout and setInterval

    We may decide to execute a function not right now, but at a later time. That’s called “scheduling a call”.javascript.plainenglish.io

    LocalStorage VS SessionStorage

    Web storage objects localStorage and sessionStorage allow to save key/value pairs in the browser.bryanguner.medium.com

    These Are The Bash Shell Commands That Stand Between Me And Insanity

    I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack…levelup.gitconnected.com

    How To Implement Native(ES6) Data Structures Using Arrays & Objects

    Smart data structures and dumb code works better than the other way around -“Eric S. Raymond”bryanguner.medium.com

    Objects in Javascript

    Codepen with examples for you to practice with below!medium.com

    The Beginner’s Guide To JavaScript

    Part 1javascript.plainenglish.io

    Web Developer Resource List Part 4

    A all encompassing list of tools and resources for web developersmedium.com

    VSCode Extensions Specifically for JavaScript Development

    VSCode Extensions that are indispensable in JavaScript developmentmedium.com

    A list of all of my articles to link to future posts

    You should probably skip this one… seriously it’s just for internal use!bryanguner.medium.com

    Fundamental Data Structures in JavaScript

    A simple to follow guide to Lists Stacks and Queues, with animated gifs, diagrams, and code examples!javascript.plainenglish.io

    Web Development Resources Part 3

    I’m the psychological equivalent of a physical hoarder only instead of empty soda cans and dead racoons it’s lists of…bryanguner.medium.com

    Web Development Interview Part 3💻

    This installment is going to be the least technically demanding thus far however these questions are a more realistic…medium.com

    The Best Cloud-Based Code Playgrounds of 2021 (Part 1)

    A plethora of front-end code playgrounds have appeared over the years. They offer a convenient way to experiment with…bryanguner.medium.com

    Front End Interview Questions Part 2

    These will focus more on vocabulary and concepts than the application driven approach in my last post!medium.com

    Web Developer Resource List Part 2

    Because I compile these things compulsively anyway…medium.com

    HTTP Basics

    “If you want to build a ship, don’t drum up the men and women to gather wood, divide the work, and give orders…levelup.gitconnected.com

    JavaScript Frameworks & Libraries

    My Awesome JavaScript List Part 2javascript.plainenglish.io

    My ‘awesome’ list of JavaScript resources

    Everyone’s seen the ‘Awesome’ lists on GitHub… and they are indeed awesome… so today I am going to attempt to curate my…javascript.plainenglish.io

    Everything You Need to Get Started With VSCode + Extensions & Resources

    Commands:levelup.gitconnected.com

    My Favorite VSCode Themes

    Themeslevelup.gitconnected.com

    Object Oriented Programming in JavaScript

    Object-Oriented Programminglevelup.gitconnected.com

    JavaScript Rotate (Array) ProblemWalkthrough

    Explanation for Rotate Rightmedium.com

    Super Simple Intro To HTML

    What is HTML, CSS & JS and why do we need all three?levelup.gitconnected.com

    Everything You Need To Know About Relational Databases, SQL, PostgreSQL and Sequelize To Build…

    For Front end developers who like myself struggle with making the jump to fullstack.medium.com

    Understanding Git (A Beginners Guide Containing Cheat Sheets & Resources)

    Basic Git Work Flow.levelup.gitconnected.com

    The Complete JavaScript Reference Guide

    You will want to bookmark thisjavascript.plainenglish.io

    Modules in Javascript

    Differences between Node.js and browsersmedium.com

    An Introduction to Markdown (Bonus Markdown Templates Included)

    Basic Syntax Guidelevelup.gitconnected.com

    Web Dev Resources

    Web Developmentlevelup.gitconnected.com

    Regular Expressions

    description:medium.com

    Writing Files Using Python

    Basics of Writing Files in Python

    The common methods to operate with files are open() to open a file,
    medium.com

    A Collection of my most useful Gist Entries

    This list is in no particular order!bryanguner.medium.com

    Learn CSS So That Your Site Doesn’t Look Like Garbage

    CSS Selectorsjavascript.plainenglish.io

    PostgreSQL Setup For Windows & WSL/Ubuntu

    If you follow this guide to a tee… you will install PostgreSQL itself on your Windows installation. Then, you will…bryanguner.medium.com

    Emmet Cheat Sheet

    EMMETbryanguner.medium.com

    Git-Tricks

    Refsbryanguner.medium.com

    Python Study Guide for a JavaScript Programmer

    A guide to commands in Python from what you know in JavaScriptlevelup.gitconnected.com

    Fetch Quick Sheet

    Fetchbryanguner.medium.com

    Express Quick Sheet

    Settingsbryanguner.medium.com

    Fundamental Data Structures In JavaScript

    Data structures in JavaScriptmedium.com

    Deploy React App To Heroku Using Postgres & Express

    Heroku is an web application that makes deploying applications easy for a beginner.bryanguner.medium.com

    Postgresql Cheat Sheet

    PostgreSQL commandsmedium.com

    A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example

    Curating Complexity: A Guide to Big-O Notationmedium.com

    Basic Web Development Environment Setup

    Windows Subsystem for Linux (WSL) and Ubuntulevelup.gitconnected.com

    By Bryan Guner on March 22, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    https://medium.com/codexwebdevhub/notes-i-wish-i-had-when-i-started-learning-python-16ce4244be12
    https://medium.com/codexwebdevhub/notes-i-wish-i-had-when-i-started-learning-python-16ce4244be12
    https://bryanguner.medium.com/awesome-list-of-github-repositories-f1c433e32b17
    https://bryanguner.medium.com/my-personal-arsenal-of-convenience-scripts-3c7869fdae53
    https://bryanguner.medium.com/my-personal-arsenal-of-convenience-scripts-3c7869fdae53
    https://bryanguner.medium.com/adding-css-to-your-html-3a17ba25ba82
    https://bryanguner.medium.com/adding-css-to-your-html-3a17ba25ba82
    https://bryanguner.medium.com/most-common-javascript-errors-311ea1356a3d
    https://bryanguner.medium.com/most-common-javascript-errors-311ea1356a3d
    https://bryanguner.medium.com/super-simple-intro-to-react-5c78e4207b7f
    https://bryanguner.medium.com/super-simple-intro-to-react-5c78e4207b7f
    https://medium.com/codexcodex/react-state-d8e0fc340714
    https://bryanguner.medium.com/awesome-web-development-youtube-video-archive-792a25839143
    https://bryanguner.medium.com/awesome-web-development-youtube-video-archive-792a25839143
    https://levelup.gitconnected.com/beginner-python-problems-solutions-dd631e9c3a9f
    https://levelup.gitconnected.com/beginner-python-problems-solutions-dd631e9c3a9f
    https://medium.com/codexcodex/fundamental-concepts-in-javascript-8e093a665b04
    https://medium.com/codexcodex/fundamental-concepts-in-javascript-8e093a665b04
    https://bryanguner.medium.com/bash-proficiency-in-under-15-minutes-3ec9d4e2e65
    https://bryanguner.medium.com/bash-proficiency-in-under-15-minutes-3ec9d4e2e65
    https://medium.com/codexanalytics-vidhya/mini-review-of-sql-for-postgresql-w-node-express-f34676f3802b
    https://medium.com/codexanalytics-vidhya/mini-review-of-sql-for-postgresql-w-node-express-f34676f3802b
    https://bryanguner.medium.com/all-the-things-you-can-embed-in-a-medium-article-b03a85c65d86

    All The Things You Can Embed In A Medium Article
    I have this innate desire to make everything available all in one place and it's usually an unnecessary waste of time……bryanguner.medium.com

    https://bryanguner.medium.com/front-end-behavioral-interview-bf5c079f7461

    https://bryanguner.medium.com/front-end-behavioral-interview-bf5c079f7461

    https://medium.com/codexcodex/prerequisites-to-writing-express-apis-75e3267b284a

    https://medium.com/codexcodex/prerequisites-to-writing-express-apis-75e3267b284a

    https://medium.com/codexanalytics-vidhya/heroku-deploy-guides-cheatsheet-compilation-b2897b69ce02

    https://medium.com/codexanalytics-vidhya/heroku-deploy-guides-cheatsheet-compilation-b2897b69ce02

    https://javascript.plainenglish.io/react-in-depth-1965dcde8d4f

    https://javascript.plainenglish.io/react-in-depth-1965dcde8d4f

    https://bryanguner.medium.com/take-a-look-at-the-big-picture-b69e0999a380

    https://bryanguner.medium.com/take-a-look-at-the-big-picture-b69e0999a380

    https://bryanguner.medium.com/bash-d3077114aea7

    https://bryanguner.medium.com/bash-d3077114aea7

    https://bryanguner.medium.com/heroku-cheat-sheet-6107ce6ba52b

    https://bryanguner.medium.com/heroku-cheat-sheet-6107ce6ba52b

    All The Things You Can Embed In A Medium Article

    I have this innate desire to make everything available all in one place and it’s usually an unnecessary waste of time… but here I will…


    All The Things You Can Embed In A Medium Article

    I have this innate desire to make everything available all in one place and it’s usually an unnecessary waste of time… but here I will conduct and ‘experiment’ where I intentionally indulge that tendency.

    Here you can see in just the first frame of my blog site 5 different embedded widgets that I inject onto nearly every page of the site using javascript to append my widgets to various anchor points in the html.

    Update :

    Table with Airtable:

    ### Math With https://math.embed.fun/

    ### 1.) CodePen:

    For this next inclusion I will kill two birds with one stone… I will embed a CodePen…who’s contents are an embedded version of my twitter feed…

    If you wanna get really meta about it you can also embed your medium articles within a medium article…

    ### 2.) Upscribe Form:

    ### 3.) Play.ht Medium Article To Voice-Audio Transcription:

    Play.ht offers the following services:

    ### 4.) : Repl.it:

    ### 5.) :You can also embed a JSFiddle like a code-sandbox.

    bigO (forked) — CodeSandbox

    #### 6.) :GIF :

    ### 7.) Dribble:

    Mihir Beg Muisc

    Mihir Beg Muisc designed by Bryan Guner. Connect with them on Dribbble; the global community for designers and creative…dribbble.com

    ### 8.) SlideShare:

    ### 9.)Google Forms/Quizzes :

    ### 10.) YouTube Videos:

    ### 11.) 360 Degree Photos from Kuula.com:

    ### 13.) A tweet:

    >

    14.) A Spotify Playlist.

    And for good measure a SoundCloud track:

    15.) Infographics:

    TBC…..

    By Bryan Guner on August 6, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    An Introduction to Markdown (Bonus Markdown Templates Included)

    Basic Syntax Guide


    An Introduction to Markdown (Bonus Markdown Templates Included)

    bgoonz/Markdown-Templates

    One Paragraph of project description goes here These instructions will get you a copy of the project up and running on…github.com

    Basic Syntax Guide

    This topic is meant to give you a very basic overview of how Markdown works, showing only some of the most common operations you use most frequently. Keep in mind that you can also use the Edit menus to inject markdown using the toolbar, which serves as a great way to see how Markdown works. However, Markdown’s greatest strength lies in its simplicity and keyboard friendly approach that lets you focus on writing your text and staying on the keyboard.

    What is Markdown

    Markdown is very easy to learn and get comfortable with due it’s relatively small set of markup ‘commands’. It uses already familiar syntax to represent common formatting operations. Markdown understands basic line breaks so you can generally just type text.

    Markdown also allows for raw HTML inside of a markdown document, so if you want to embed something more fancy than what Markdowns syntax can do you can always fall back to HTML. However to keep documents readable that’s generally not recommended.

    Basic Markdown Syntax

    The following are a few examples of the most common things you are likely to do with Markdown while building typical documentation.

    Bold and Italic

    markdown
    
    This text **is bold**.
    This text *is italic*.
    
    Enter fullscreen mode Exit fullscreen mode

    This text is bold.

    This text is italic.

    Header Text

    markdown
    
    # Header 1
    ## Header 2
    ### Header 3
    #### Header 4
    ##### Header 5
    ###### Header 6
    
    Enter fullscreen mode Exit fullscreen mode

    Header 1

    Header 2

    Header 3

    Header 4

    Header 5Header 6

    Line Continuation

    By default Markdown adds paragraphs at double line breaks. Single line breaks by themselves are simply wrapped together into a single line. If you want to have soft returns that break a single line, add two spaces at the end of the line.

    markdown
    
    This line has a paragraph break at the end (empty line after).
    
    Theses two lines should display as a single
    line because there's no double space at the end.
    
    The following line has a soft break at the end (two spaces at end)
    This line should be following on the very next line.
    
    Enter fullscreen mode Exit fullscreen mode

    This line has a paragraph break at the end (empty line after).

    Theses two lines should display as a single line because there’s no double space at the end.

    The following line has a soft break at the end (two spaces at end)

    This line should be following on the very next line.

    Links

    markdown
    
    [Help Builder Web Site](http://helpbuilder.west-wind.com/)
    
    Enter fullscreen mode Exit fullscreen mode

    Help Builder Web Site

    If you need additional image tags like targets or title attributes you can also embed HTML directly:

    markdown
    
    Go the Help Builder sitest Wind site: <a href="http://west-wind.com/">Help Builder Site</a>.
    
    Enter fullscreen mode Exit fullscreen mode

    Images

    markdown
    
    ![Help Builder Web Site](https://helpbuilder.west-wind.com/images/HelpBuilder_600.png)
    
    Enter fullscreen mode Exit fullscreen mode

    ### Block Quotes

    Block quotes are callouts that are great for adding notes or warnings into documentation.

    markdown
    
    &gt; ###  Headers break on their own
    &gt; Note that headers don't need line continuation characters
    as they are block elements and automatically break. Only text
    lines require the double spaces for single line breaks.
    
    Enter fullscreen mode Exit fullscreen mode

    > Headers break on their own

    > Note that headers don’t need line continuation characters as they are block elements and automatically break. Only text lines require the double spaces for single line breaks.

    Fontawesome Icons

    Help Builder includes a custom syntax for FontAwesome icons in its templates. You can embed a @ icon- followed by a font-awesome icon name to automatically embed that icon without full HTML syntax.

    markdown
    
    Gear:  Configuration
    
    Enter fullscreen mode Exit fullscreen mode

    Configuration

    HTML Markup

    You can also embed plain HTML markup into the page if you like. For example, if you want full control over fontawesome icons you can use this:

    markdown
    
    This text can be **embedded** into Markdown:
     Refresh Page
    
    Enter fullscreen mode Exit fullscreen mode

    This text can be embedded into Markdown:

     Refresh Page

    Unordered Lists

    markdown
    
    * Item 1
    * Item 2
    * Item 3
    This text is part of the third item. Use two spaces at end of the the list item to break the line.
    
    A double line break, breaks out of the list.
    
    Enter fullscreen mode Exit fullscreen mode
    • Item 1
    • Item 2
    • Item 3
      This text is part of the third item. Use two spaces at end of the the list item to break the line.

    A double line break, breaks out of the list.

    Ordered Lists

    markdown
    
    1. **Item 1**
    Item 1 is really something
    2. **Item 2**
    Item two is really something else
    
    If you want lines to break using soft returns use two spaces at the end of a line.
    
    Enter fullscreen mode Exit fullscreen mode
    1. Item 1 Item 1 is really something
    2. Item 2
      Item two is really something else

    If you want to lines to break using soft returns use to spaces at the end of a line.

    Inline Code

    If you want to embed code in the middle of a paragraph of text to highlight a coding syntax or class/member name you can use inline code syntax:

    markdown
    
    Structured statements like `for x =1 to 10` loop structures
    can be codified using single back ticks.
    
    Enter fullscreen mode Exit fullscreen mode

    Structured statements like for x =1 to 10 loop structures can be codified using single back ticks.

    Code Blocks with Syntax Highlighting

    Markdown supports code blocks syntax in a variety of ways:

    markdown
    
    The following code demonstrates:
    
        // This is code by way of four leading spaces
        // or a leading tab
    
    More text here
    
    Enter fullscreen mode Exit fullscreen mode

    The following code demonstrates:

    pgsql
    
    // This is code by way of four leading spaces
    // or a leading tab
    
    Enter fullscreen mode Exit fullscreen mode

    More text here

    Code Blocks

    You can also use triple back ticks plus an optional coding language to support for syntax highlighting (space injected before last ` to avoid markdown parsing):

    markdown
    
    `` `csharp
    // this code will be syntax highlighted
    for(var i=0; i++; i &lt; 10)
    {
        Console.WriteLine(i);
    }
    `` `
    
    csharp
    
    // this code will be syntax highlighted
    for(var i=0; i++; i &lt; 10)
    {
        Console.WriteLine(i);
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Many languages are supported: html, xml, javascript, css, csharp, foxpro, vbnet, sql, python, ruby, php and many more. Use the Code drop down list to get a list of available languages.

    You can also leave out the language to get no syntax coloring but the code box:

    markdown
    
    `` `dos
    robocopy c:\temp\test d:\temp\test
    `` `
    
    dos
    
    robocopy c:\temp\test d:\temp\test
    
    Enter fullscreen mode Exit fullscreen mode

    To create a formatted block but without formatting use the txt format:

    markdown
    
    `` `txt
    This is some text that will not be syntax highlighted
    but shows up in a code box.
    `` `
    
    Enter fullscreen mode Exit fullscreen mode

    which gives you:

    text
    
    This is some text that will not be syntax highlighted
    but shows up in a code box.
    
    Enter fullscreen mode Exit fullscreen mode

    If you found this guide helpful feel free to checkout my github/gists where I host similar content:

    bgoonz’s gists · GitHub

    bgoonz — Overview

    Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com

    Or Checkout my personal Resource Site:

    a/A-Student-Resources

    Edit descriptiongoofy-euclid-1cd736.netlify.app

    By Bryan Guner on March 8, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example

    Curating Complexity: A Guide to Big-O Notation


    A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example

    Curating Complexity: A Guide to Big-O Notation

    Medium-article-comp-complex

    A Node.js repl by bgoonzreplit.com

    • Why is looking at runtime not a reliable method of calculating time complexity?
    • Not all computers are made equal( some may be stronger and therefore boost our runtime speed )
    • How many background processes ran concurrently with our program that was being tested?
    • We also need to ask if our code remains performant if we increase the size of the input.
    • The real question we need to answering is: How does our performance scale?.

    big ‘O’ notation

    • Big O Notation is a tool for describing the efficiency of algorithms with respect to the size of the input arguments.
    • Since we use mathematical functions in Big-O, there are a few big picture ideas that we’ll want to keep in mind:
    • The function should be defined by the size of the input.
    • Smaller Big O is better (lower time complexity)
    • Big O is used to describe the worst case scenario.
    • Big O is simplified to show only its most dominant mathematical term.

    Simplifying Math Terms

    • We can use the following rules to simplify the our Big O functions:
    • Simplify Products : If the function is a product of many terms, we drop the terms that don't depend on n.
    • Simplify Sums : If the function is a sum of many terms, we drop the non-dominant terms.
    • n : size of the input
    • T(f) : unsimplified math function
    • O(f) : simplified math function.

    Putting it all together

    - First we apply the product rule to drop all constants.

    • Then we apply the sum rule to select the single most dominant term.

    Complexity Classes

    Common Complexity Classes

    There are 7 major classes in Time Complexity

    #### O(1) Constant

    > The algorithm takes roughly the same number of steps for any input size.

    O(log(n)) Logarithmic

    > In most cases our hidden base of Logarithmic time is 2, log complexity algorithm’s will typically display ‘halving’ the size of the input (like binary search!)

    O(n) Linear

    > Linear algorithm’s will access each item of the input “once”.

    O(nlog(n)) Log Linear Time

    > Combination of linear and logarithmic behavior, we will see features from both classes.

    > Algorithm’s that are log-linear will use both recursion AND iteration.

    O(nc) Polynomial

    > C is a fixed constant.

    O(c^n) Exponential

    > C is now the number of recursive calls made in each stack frame.

    > Algorithm’s with exponential time are VERY SLOW.


    Memoization

    • Memoization : a design pattern used to reduce the overall number of calculations that can occur in algorithms that use recursive strategies to solve.
    • MZ stores the results of the sub-problems in some other data structure, so that we can avoid duplicate calculations and only ‘solve’ each problem once.
    • Two features that comprise memoization:
    1. FUNCTION MUST BE RECURSIVE.
    2. Our additional Data Structure is usually an object (we refer to it as our memo… or sometimes cache!)

    ### Memoizing Factorial

    Our memo object is mapping out our arguments of factorial to it’s return value.

    • Keep in mind we didn’t improve the speed of our algorithm.

    Memoizing Fibonacci

    - Our time complexity for Fibonacci goes from O(2^n) to O(n) after applying memoization.

    The Memoization Formula

    > Rules:

    1. Write the unoptimized brute force recursion (make sure it works);
    2. Add memo object as an additional argument .
    3. Add a base case condition that returns the stored value if the function’s argument is in the memo.
    4. Before returning the result of the recursive case, store it in the memo as a value and make the function’s argument it’s key.

    Things to remember

    1. When solving DP problems with Memoization, it is helpful to draw out the visual tree first.
    2. When you notice duplicate sub-tree’s that means we can memoize.

    Tabulation

    Tabulation Strategy

    > Use When:

    • The function is iterative and not recursive.
    • The accompanying DS is usually an array.

    Steps for tabulation

    • Create a table array based off the size of the input.
    • Initialize some values in the table to ‘answer’ the trivially small subproblem.
    • Iterate through the array and fill in the remaining entries.
    • Your final answer is usually the last entry in the table.

    Memo and Tab Demo with Fibonacci

    > Normal Recursive Fibonacci

    function fibonacci(n) {
      if (n &lt;= 2) return 1;
      return fibonacci(n - 1) + fibonacci(n - 2);
    }
    
    Enter fullscreen mode Exit fullscreen mode

    > Memoization Fibonacci 1

    > Memoization Fibonacci 2

    > Tabulated Fibonacci

    Example of Linear Search

    • Worst Case Scenario: The term does not even exist in the array.
    • Meaning: If it doesn’t exist then our for loop would run until the end therefore making our time complexity O(n).

    Sorting Algorithms

    Bubble Sort

    Time Complexity: Quadratic O(n^2)

    • The inner for-loop contributes to O(n), however in a worst case scenario the while loop will need to run n times before bringing all n elements to their final resting spot.

    Space Complexity: O(1)

    • Bubble Sort will always use the same amount of memory regardless of n.

    - The first major sorting algorithm one learns in introductory programming courses.

    • Gives an intro on how to convert unsorted data into sorted data.

    > It’s almost never used in production code because:

    • It’s not efficient
    • It’s not commonly used
    • There is stigma attached to it
    • Bubbling Up : Term that infers that an item is in motion, moving in some direction, and has some final resting destination.
    • Bubble sort, sorts an array of integers by bubbling the largest integer to the top.

    • Worst Case & Best Case are always the same because it makes nested loops.

    • Double for loops are polynomial time complexity or more specifically in this case Quadratic (Big O) of: O(n²)

    Selection Sort

    Time Complexity: Quadratic O(n^2)

    • Our outer loop will contribute O(n) while the inner loop will contribute O(n / 2) on average. Because our loops are nested we will get O(n²);

    Space Complexity: O(1)

    • Selection Sort will always use the same amount of memory regardless of n.

    - Selection sort organizes the smallest elements to the start of the array.

    Summary of how Selection Sort should work:

    1. Set MIN to location 0
    2. Search the minimum element in the list.
    3. Swap with value at location Min
    4. Increment Min to point to next element.
    5. Repeat until list is sorted.

    Insertion Sort

    Time Complexity: Quadratic O(n^2)

    • Our outer loop will contribute O(n) while the inner loop will contribute O(n / 2) on average. Because our loops are nested we will get O(n²);

    Space Complexity: O(n)

    • Because we are creating a subArray for each element in the original input, our Space Comlexity becomes linear.

    ### Merge Sort

    Time Complexity: Log Linear O(nlog(n))

    • Since our array gets split in half every single time we contribute O(log(n)). The while loop contained in our helper merge function contributes O(n) therefore our time complexity is O(nlog(n)); Space Complexity: O(n)
    • We are linear O(n) time because we are creating subArrays.

    ### Example of Merge Sort

    - Merge sort is O(nlog(n)) time.

    • We need a function for merging and a function for sorting.

    > Steps:

    1. If there is only one element in the list, it is already sorted; return the array.
    2. Otherwise, divide the list recursively into two halves until it can no longer be divided.
    3. Merge the smallest lists into new list in a sorted order.

    Quick Sort

    Time Complexity: Quadratic O(n^2)

    • Even though the average time complexity O(nLog(n)), the worst case scenario is always quadratic.

    Space Complexity: O(n)

    • Our space complexity is linear O(n) because of the partition arrays we create.
    • QS is another Divide and Conquer strategy.
    • Some key ideas to keep in mind:
    • It is easy to sort elements of an array relative to a particular target value.
    • An array of 0 or 1 elements is already trivially sorted.

    ### Binary Search

    Time Complexity: Log Time O(log(n))

    Space Complexity: O(1)

    Recursive Solution

    > Min Max Solution

    • Must be conducted on a sorted array.
    • Binary search is logarithmic time, not exponential b/c n is cut down by two, not growing.
    • Binary Search is part of Divide and Conquer.

    Insertion Sort

    • Works by building a larger and larger sorted region at the left-most end of the array.

    > Steps:

    1. If it is the first element, and it is already sorted; return 1.
    2. Pick next element.
    3. Compare with all elements in the sorted sub list
    4. Shift all the elements in the sorted sub list that is greater than the value to be sorted.
    5. Insert the value
    6. Repeat until list is sorted.

    If you found this guide helpful feel free to checkout my GitHub/gists where I host similar content:

    bgoonz’s gists

    Instantly share code, notes, and snippets. Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python |…gist.github.com

    bgoonz — Overview

    Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap | Python | React | Node.js | Express | Sequelize…github.com

    Or Checkout my personal Resource Site:

    Web-Dev-Hub

    Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app

    ### Discover More:

    Web-Dev-Hub

    Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app

    By Bryan Guner on February 27, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    Array Callback Methods Implemented With For Loops

    How to implement array callback methods in JavaScript


    Array Callback Methods Implemented With For Loops

    How to implement array callback methods in JavaScript

    #### Functions are called “First Class Objects” in JavaScript because:

    • A function is an instance of the Object type
    • A function can have properties and has a link back to its constructor method
    • You can store the function in a variable
    • You can pass the function as a parameter to another function
    • You can return the function from a function

    What do you think will be printed in the following:

    Anonymous callback, a named callback

    function foo(callback) {
        console.log('grape');
        callback();
    }
    
    function bar() {
        console.log('banana');
    }
    
    const fruitBasket = function() {
        console.log('apple');
        bar();
        foo(bar);
        foo(function() {
            console.log('orange');
        });
        console.log('pear');
    };
    
    fruitBasket();
    
    Enter fullscreen mode Exit fullscreen mode

    Function that takes in a value and two callbacks. The function should return the result of the callback who’s invocation results in a larger value.

    function greaterValue(value, cb1, cb2) {
        // compare cb1 invoked with value to cb2 invoked with value
        // return the greater result
    
        let res1 = cb1(value);
        let res2 = cb2(value);
        if (res1 &gt; res2) {
            // if this is false, we move out of if statement
            return res1;
        }
        return res2;
    }
    
    let negate = function(num) {
        return num * -1;
    };
    
    let addOne = function(num) {
        return num + 1;
    };
    
    console.log(greaterValue(3, negate, addOne));
    console.log(greaterValue(-2, negate, addOne));
    
    Enter fullscreen mode Exit fullscreen mode

    Note: we do not invoke negate or addOne (by using () to call them), we are passing the function itself.

    Write a function, myMap, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.map.

    function myMap(arr, callback) {
        // iterate through the array, perform the cb on each element
        // return a new array with those new values
        let mapped = [];
    
        for (let i = 0; i &lt; arr.length; i++) {
            // remember that map passes three args with each element.
            let val = callback(arr[i], i, arr);
            mapped.push(val);
        }
    
        return mapped;
    }
    
    let double = function(num) {
        return num * 2;
    };
    console.log(myMap([1, 2, 3], double));
    
    Enter fullscreen mode Exit fullscreen mode

    Write a function, myFilter, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.filter.

    function myFilter(arr, callback) {
        let filtered = [];
    
        for (let i = 0; i &lt; arr.length; i++) {
            let element = arr[i];
    
            if (callback(element, i, arr)) {
                filtered.push(element);
            }
        }
    
        return filtered;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Write a function, myEvery, that takes in an array and a callback as arguments. The function should mimic the behavior of Array.prototype.every.

    function myEvery(arr, callback) {
        for (let i = 0; i &lt; arr.length; i++) {
            let element = arr[i];
    
            if (callback(element, i, arr) === false) {
                return false;
            }
        }
        return true;
    }
    
    Enter fullscreen mode Exit fullscreen mode

    Further Examples of the above concepts

    const createMeowValue = () =&gt; {
      console.log(this.name);
      let meow = function () {
        console.log(this);
        console.log(this.name + ' meows');
      }
      meow = meow.bind(this);
      return meow;
    };
    
    const name = 'Fluffy';
    
    const cat = {
      name: name,
      age: 12,
      createMeow: function () {
        console.log(this.name);
        let meow = () =&gt; {
          const hello = 'hello';
          console.log(this.name + ' meows');
        };
        let world = '';
        if (true) {
          world = 'world';
        }
        console.log(world);
        // meow = meow.bind(this);
        return meow;
      }
    };
    
    cat.newKey = function () {
      const outermostContext = this;
      const innerFunc = () =&gt; {
        secondContext = this;
        console.log(secondContext === outermostContext)
        return function () {
          innermostContext = this;
        }
      };
      return innerFunc.bind(outermostContext);
    };
    
    const meow = cat.createMeow(); // method-style invocation
    meow(); // function-style invocation
    
    console.log('-------')
    
    const createMeow = cat.createMeow;
    const globalMeow = createMeow(); // function-style
    globalMeow(); // function-style
    
    function createSmoothie(ingredient) {
      const ingredients = [ingredient];
      return ingredients;
    }
    
    // console.log(createSmoothie('banana'));
    // console.log(createSmoothie('apple'));
    
    // one parameter only
    // first argument is a string
    // return an array
    // DO NOT USE forEach
    
    Enter fullscreen mode Exit fullscreen mode

    References:

    App Academy Open

    App Academy Open is the first free, online web development course that's meant to get you hired as a developer. Get…open.appacademy.io

    MDN Web Docs

    Read more at hacks.mozilla.org Roughly a year ago at Mozilla we started an effort to improve Firefox stability on…developer.mozilla.org

    Introduction: callbacks

    To demonstrate the use of callbacks, promises and other abstract concepts, we'll be using some browser methods…javascript.info

    More content at plainenglish.io

    By Bryan Guner on May 27, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

    A Very Quick Guide To Calculating Big O Computational Complexity

    Big O: big picture, broad strokes, not details


    A Very Quick Guide To Calculating Big O Computational Complexity

    Big O: big picture, broad strokes, not details

    For a more complete guide… checkout :

    A Quick Guide to Big-O Notation, Memoization, Tabulation, and Sorting Algorithms by Example

    Curating Complexity: A Guide to Big-O Notationmedium.com

    - way we analyze how efficient algorithms are without getting too mired in details

    • can model how much time any function will take given n inputs
    • interested in order of magnitude of number of the exact figure
    • O absorbs all fluff and n = biggest term
    • Big O of 3x^2 +x + 1 = O(n^2)

    Time Complexity

    no loops or exit & return = O(1)

    0 nested loops = O(n)

    1 nested loops = O(n^2)

    2 nested loops = O(n^3)

    3 nested loops = O(n^4)

    recursive: as you add more terms, increase in time as you add input diminishes

    recursion: when you define something in terms of itself, a function that calls itself

    • used because of ability to maintain state at diffferent levels of recursion
    • inherently carries large footprint
    • every time function called, you add call to stack

    iterative: use loops instead of recursion (preferred)

    • favor readability over performance

    O(n log(n)) & O(log(n)): dividing/halving

    • if code employs recursion/divide-and-conquer strategy
    • what power do i need to power my base to get n

    Time Definitions

    • constant: does not scale with input, will take same amount of time
    • for any input size n, constant time performs same number of operations every time
    • logarithmic: increases number of operations it performs as logarithmic function of input size n
    • function log n grows very slowly, so as n gets longer, number of operations the algorithm needs to perform doesn’t increase very much
    • halving
    • linear: increases number of operations it performs as linear function of input size n
    • number of additional operations needed to perform grows in direct proportion to increase in input size n
    • log-linear: increases number of operations it performs as log-linear function of input size n
    • looking over every element and doing work on each one
    • quadratic: increases number of operations it performs as quadratic function of input size n
    • exponential: increases number of operations it performs as exponential function of input size n
    • number of nested loops increases as function of n
    • polynomial: as size of input increases, runtime/space used will grow at a faster rate
    • factorial: as size of input increases, runtime/space used will grow astronomically even with relatively small inputs
    • rate of growth: how fast a function grows with input size

    ### Space Complexity

    • How does the space usage scale/change as input gets very large?
    • What auxiliary space does your algorithm use or is it in place (constant)?
    • Runtime stack space counts as part of space complexity unless told otherwise.

    Sorting Algorithms

    ### Data Structures

    For similar content check out my GitHub:

    bgoonz - Overview

    Web Developer, Electrical Engineer
    https://bryanguner.medium.com/ https://portfolio42.netlify.app/…github.com

    By Bryan Guner on May 19, 2021.

    Canonical link

    Exported from Medium on August 24, 2021.

Top comments (1)

Collapse
 
aatmaj profile image
Aatmaj

290 min read! That's super cool