Skip to content

Instantly share code, notes, and snippets.

@rchovatiya88
Last active October 1, 2019 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rchovatiya88/4b0f7918266e53603c407f0249591675 to your computer and use it in GitHub Desktop.
Save rchovatiya88/4b0f7918266e53603c407f0249591675 to your computer and use it in GitHub Desktop.
React Learnings for Testers

Study Javascript

Browser Developer ConsoleAdding Javascript to HTMLUnderstanding Syntax and Code StructureData TypesWorking with StringsIndex,Split, and manipulate StringsConvert Data TypesVariables, scope, hoistingMath and OperatorsUnderstanding ArraysArray Methods: MutatorArray Methods: AccessorArray Methods: IterationUnderstand ObjectsDate and TimeUnderstand DOMUnderstand EventsWorking with JSONConditional StatementsSwitch StatementsWhile Do While LoopsConstruct For LoopsDefine FunctionsUnderstand Prototypes and InheritanceUnderstand ClassesObject Methods

https://fullstackopen.com/en/

————————————————————

Adding javascript to HTML

Alert Example (inside the html)

<!DOCTYPE html>
<html lang=“en-US”>

<head>
    <meta charset=“UTF-8”>
    <meta name=“viewport” content=“width=device-width, initial-scale=1”>
    <title>Today’s Date</title>
    <script>
        let d = new Date();
        alert(“Today’s date is “ + d);
    </script>
</head>

<body>

</body>

</html>

Syntax

// Initialize a class
class ExampleClass {
    constructor() { }
}

Data Types

  • Numbers
  • Strings
  • Booleans
  • Arrays
  • Objects

With dynamically typed languages, a variable of the same name can be used to hold different data types.

For example, the variable t, defined as a variable by the let keyword (note that let keeps a given variable limited in scope), can be assigned to hold different data types, or can be initialized but left undefined:

let t = 16;         // t is a number
let t = “Teresa”;   // t is a string
let t = true;       // t is a Boolean
let t;              // t is undefined

Each of the variables t above can be set to any data type available in JavaScript; they do not need to be explicitly declared with a data type before they are used.

Click Example

<!DOCTYPE HTML>
<html>
<head>
<script>
function helloFunction() {
    alert(“Hello, World!”);
}
</script>
</head>
<body>
<p><button onclick=“helloFunction()”>Click me</button></p>
</body>
</html>

As with other data types, we can store strings in variables:

let hw = “Hello, World!”; And display the string in the alert() by calling the variable:

…
<script>
let hw = “Hello, World!”;
function helloFunction() {
    alert(hw);
}
</script>
…

There are many operations that we can perform on strings within our programs in order to manipulate them to achieve the results we are seeking. Strings are important for communicating information to the user, and for the user to communicate information back to the program.

###Arrays

An array can hold multiple values within a single variable. This means that you can contain a list of values within an array and iterate through them.

Each item or value that is inside of an array is called an element. You can refer to the elements of an array by using an index number.

Just as strings are defined as characters between quotes, arrays are defined by having values between square brackets [ ].

An array of strings, for example, looks like this:

let fish = [“shark”, “cuttlefish”, “clownfish”, “eel”]; If we call the variable fish, we’ll receive the following output:

[“shark”, “cuttlefish”, “clownfish”, “eel”] Arrays are a very flexible data type because they are mutable in that they can have element values added, removed, and changed.

Objects

The JavaScript object data type can contain many values as name:value pairs. These pairs provide a useful way to store and access data. The object literal syntax is made up of name:value pairs separated by colons with curly braces on either side { }.

Typically used to hold data that are related, such as the information contained in an ID, a JavaScript object literal looks like this, with whitespaces between properties:

let sammy = {firstName:”Sammy”, lastName:”Shark”, color:”blue”, location:”ocean”};

Alternatively, and especially for object literals with a high number of name:value pairs, we can write this data type on multiple lines, with a whitespace after each colon:

let sammy = {
    firstName: “Sammy”,
    lastName: “Shark”,
    color: “blue”,
    location: “Ocean”
};

The object variable sammy in each of the examples above has 4 properties: firstName, lastName, color, and location. These are each passed values separated by colons.

Strings

One special feature of the template literal feature is the ability to include expressions and variables within a string. Instead of having to use concatenation, we can use the ${} syntax to insert a variable.

const author = “Pablo Neruda”;

const favePoem = `My favorite poem is ${poem} by ${author}.`;

Output My favorite poem is The Wide Ocean by Pablo Neruda.

alert(“This is a string in an alert.”);

String Primitives and String Objects First, we will clarify the two types of strings. JavaScript differentiates between the string primitive, an immutable datatype, and the String object.

In order to test the difference between the two, we will initialize a string primitive and a string object.

// Initializing a new string primitive
const stringPrimitive = “A new string.”;
// Initializing a new String object
const stringObject = new String(“A new string.”);  

We can use the typeof operator to determine the type of a value. In the first example, we simply assigned a string to a variable.

typeof stringPrimitive;
Output
string

In the second example, we used new String() to create a string object and assign it to a variable.

typeof stringObject;

Output
object

The slice() method, on the other hand, returns the characters between two index numbers. The first parameter will be the starting index number, and the second parameter will be the index number where it should end.

“How are you?”.slice(8, 11);
Output
you

To summarize, charAt() and slice() will help return string values based on index numbers, and indexOf() and lastIndexOf() will do the opposite, returning index numbers based on the provided string characters.

We will use the split() method to separate the array by a whitespace character, represented by “ “.

const originalString = “How are you?”;

// Split string by whitespace character
const splitString = originalString.split(“ “);

console.log(splitString);
Output
[ ‘How’, ‘are’, ‘you?’ ]

Now that we have a new array in the splitString variable, we can access each section with an index number.

splitString[1];
Output
are

Finding and Replacing String Values We can search a string for a value, and replace it with a new value using the replace() method. The first parameter will be the value to be found, and the second parameter will be the value to replace it with.

const originalString = “How are you?”

// Replace the first instance of “How” with “Where” const newString = originalString.replace(“How”, “Where”);

console.log(newString); Output Where are you?

In addition to being able to replace a value with another string value, we can also use Regular Expressions to make replace() more powerful. For instance, replace() only affects the first value, but we can use the g (global) flag to catch all instances of a value, and the i (case insensitive) flag to ignore case.

const originalString = “Javascript is a programming language. I’m learning javascript.”

// Search string for “javascript” and replace with “JavaScript”
const newString = originalString.replace(/javascript/gi, “JavaScript”);

console.log(newString);
Output
JavaScript is a programming language. I’m learning JavaScript.

Difference Between var, let, and const

JavaScript has three different keywords to declare a variable, which adds an extra layer of intricacy to the language. The differences between the three are based on scope, hoisting, and reassignment.

Keyword | Scope| Hoisting | 	Can Be Reassigned | Can Be Redeclared
	var	| Function scope	| Yes	| Yes	| Yes
let	| Block scope |	No	| Yes |  No
const | 	Block scope | 	| No | No

You may be wondering which of the three you should use in your own programs. A commonly accepted practice is to use const as much as possible, and let in the case of loops and reassignment. Generally, var can be avoided outside of working on legacy code.

The new keywords let and const, however, are block-scoped. This means that a new, local scope is created from any kind of block, including function blocks, if statements, and for and while loops.

To illustrate the difference between function- and block-scoped variables, we will assign a new variable in an if block using let.

var fullMoon = true;

// Initialize a global variable let species = “human”;

if (fullMoon) { // Initialize a block-scoped variable let species = “werewolf”; console.log(It is a full moon. Lupin is currently a ${species}.); }

console.log(It is not a full moon. Lupin is currently a ${species}.); Output It is a full moon. Lupin is currently a werewolf. It is not a full moon. Lupin is currently a human. In this example, the species variable has one value globally (human), and another value locally (werewolf). If we were to use var, however, there would be a different result.

Functional vs Block-scoped

The new keywords let and const, however, are block-scoped. This means that a new, local scope is created from any kind of block, including function blocks, if statements, and for and while loops.

To illustrate the difference between function- and block-scoped variables, we will assign a new variable in an if block using let.

var fullMoon = true;

// Initialize a global variable
let species = “human”;

if (fullMoon) {
  // Initialize a block-scoped variable
  let species = “werewolf”;
  console.log( `It is a full moon. Lupin is currently a ${species}.` );
}

console.log( It is not a full moon. Lupin is currently a ${species}. );

Output

It is a full moon. Lupin is currently a werewolf. It is not a full moon. Lupin is currently a human.

In this example, the species variable has one value globally (human), and another value locally (werewolf). If we were to use var, however, there would be a different result.

Hoisting, a behavior of JavaScript in which variable and function declarations are moved to the top of their scope. Since only the actual declaration is hoisted, not the initialization, the value in the first example returns undefined.

To demonstrate this concept more clearly, below is the code we wrote and how JavaScript actually interpreted it.

// The code we wrote
console.log(x);
var x = 100;

// How JavaScript interpreted it
var x;
console.log(x);
x = 100;

Math

Operator Syntax Example Definition Addition + x + y Sum of x and y Subtraction - x - y Difference of x and y Multiplication * x * y Product of x and y Division / x / y Quotient of x and y Modulo % x % y Remainder of x / y Exponentiation ** x ** y x to the y power Increment ++ x++ x plus one Decrement — x— x minus one

Instead of adding the two numbers, JavaScript will convert the entire statement into a string and concatenate them together. It’s important to be careful with JavaScript’s dynamically-typed nature, as it can have undesired outcomes.

A common reason to use addition or subtraction in JavaScript would be to scroll to an id minus the height in pixels of a fixed navigation bar.

function scrollToId() {
    const navHeight = 60;
    window.scrollTo(0, window.pageYOffset - navHeight);
}

window.addEventListener(‘hashchange’, scrollToId); In the above example, clicking on an id will scroll to 60 pixels above the id.

Multiplication might be used to calculate the price of an item after applying sales tax.

const price = 26.5;    // Price of item before tax
const taxRate = 0.082; // 8.2% tax rate

// Calculate total after tax to two decimal places
let totalPrice = price + (price * taxRate);
totalPrice.toFixed(2);

console.log(“Total:”, totalPrice);
Output
Total: 28.67

We can use the modulo operator to determine whether a number is even or odd, as seen with this function:

// Initialize function to test if a number is even
const isEven = x => {
    // If the remainder after dividing by two is 0, return true
    if (x % 2 === 0) {
        return true;
    }
    // If the number is odd, return false
    return false;
}

// Test the number
isEven(12);
Output
true

In the above example, 12 divides evenly into 2, therefore it is an even number.

The increment or decrement operator will be seen most often in a loop. In this for loop example, we will run the operation ten times, starting with 0, and increasing the value by 1 with each iteration.

// Run a loop ten times
for (let i = 0; i < 10; i++) {
  console.log(i);
}
Output
0
1
2
3
4
5
6
7
8
9

The code above shows an iteration through a loop that is achieved through using the increment operator.

We can think of x++ as shorthand for x = x + 1, and x— as shorthand for x = x - 1.

###Array

There are two ways to create an array in JavaScript:

The array literal, which uses square brackets. The array constructor, which uses the new keyword.

sharks.js
// Initialize array of shark species with array literal
let sharks = [
    “Hammerhead”,
    “Great White”,
    “Tiger”,
];
Now here is the same data created with the array constructor, which is initialized with new Array().

sharks.js
// Initialize array of shark species with array constructor
let sharks = new Array(
    “Hammerhead”,
    “Great White”,
    “Tiger”,
);
Both methods will create an array. However, the array literal (square brackets) method is much more common and preferred, as the new Array() constructor method may have inconsistencies and unexpected results. It’s useful to be aware of the array constructor in case you encounter it down the line.

We can print out an entire array, which will display the same as our input.

// Print out the entire sharks array
sharks;
Output
[ ‘Hammerhead’, ‘Great White’, ‘Tiger’ ]

We know 0 will always output the first item in an array. We can also find the last item in an array by performing an operation on the length property and applying that as the new index number.

const lastIndex = seaCreatures.length - 1;

seaCreatures[lastIndex];

Manipulate ARRAYS

  • push() = adds an item to the end of an array.
  • unshift() = add an item to the beginning of an array.
  • splice() = remove an item from an array from a specific spot.
  • pop() = remove the last item in an array.

Looping Through an Array We can loop through the entirety of the array with the for keyword, taking advantage of the length property. In this example, we can create an array of shellfish and print out each index number as well as each value to the console.

// Create an array of shellfish species
let shellfish = [
    “oyster”,
    “shrimp”,
    “clam”,
    “mussel”,
];

// Loop through the length of the array
for (let i = 0; i < shellfish.length; i++) {
  console.log(i, shellfish[i]);
}
Output
0 ‘oyster’
1 ‘shrimp’
2 ‘clam’
3 ‘mussel’

We can also use the for…of loop, a newer feature of JavaScript.

// Create an array of aquatic mammals
let mammals = [
    “dolphin”,
    “whale”,
    “manatee”,
];

// Loop through each mammal
for (let mammal of mammals) {
    console.log(mammal);
}
Output
dolphin
whale
manatee

Array Functions

Var example = function () {

}

example () ;
———————

Var example = () => {

}

Different types of functions

  • forEach() = method calls a function for each element in an array.
Let’s start with the following array assigned to the variable fish:

let fish = [ “piranha”, “barracuda”, “cod”, “eel” ];
We can use forEach() to print each item in the fish array to the console.

// Print out each item in the array
fish.forEach(individualFish => {
    console.log(individualFish);
})
Once we do so, we’ll receive the following output:

Output
piranha
barracuda
cod
eel
Another way to do this is using the for loop keyword and testing it against the length property of the array.

// Loop through the length of the array
for (let i = 0; i < fish.length; i++) {
    console.log(fish[i]);
}
  • map() method creates a new array with the results of a function call on each element in the array.
let pluralFish = fish.map(individualFish => {
    return `${individualFish}s`;
});

pluralFish;
Output
[ ‘piranhas’, ‘barracudas’, ‘cods’, ‘eels’ ]
  • filter() method creates a new array with the elements that pass the result of a given test.
We could use filter() to return a new array containing only the items in a list that start with a specific letter. To do this, we can utilize string indexing to call the first item (or letter) in each string item of the array.

let seaCreatures = [ “shark”, “whale”, “squid”, “starfish”, “narwhal” ];

// Filter all creatures that start with “s” into a new list
let filteredList = seaCreatures.filter(creature => {
  return creature[0] === “s”;
});

filteredList;
Output
[ ‘shark’, ‘squid’, ‘starfish’ ]
  • reduce() method will reduce an array to a single value.

This is seen commonly with numbers, such as finding the sum of all the numbers in an array.

let numbers = [ 42, 23, 16, 15, 4, 8 ];

// Get the sum of all numerical values
let sum = numbers.reduce((a, b) => {
    return a + b;
});

sum;
Output
108
  • find() method returns the first value in an array that passes a given test.

As an example, we will create an array of sea creatures.

letCreatures = [ “whale”, “octopus”, “shark”, “cuttlefish”, “flounder” ];
Then we will use the find() method to test if any of the creatures in the array are cephalopods.

// Check if a given value is a cephalopod
const isCephalopod = cephalopod => {
    return [ “cuttlefish”, “octopus” ].includes(cephalopod);
}

seaCreatures.find(isCephalopod);
Output

octopus was the first entry in the array to satisfy the test in the isCephalopod() function, it is the first value to be returned.

The find() method can help you work with arrays that contain many values.

Objects

There are two ways to construct an object in JavaScript:

  • The object literal, which uses curly brackets: {}
  • The object constructor, which uses the new keyword
// Initialize object constructor with new Object
const objectConstructor = new Object();

// Initialize gimli object
const gimli = {
    name: “Gimli”,
    race: “dwarf”,
    weapon: “axe”,
    greet: function() {
        return `Hi, my name is ${this.name}!`;
    },
};

JavaScript has a built-in type of for loop that is specifically meant for iterating over the properties of an object. This is known as the for…in loop.

Here is a simplified version of our main object example, gimli.

const gimli = {
    name: “Gimli”,
    race: “dwarf”,
    weapon: “battle axe”,
};

We can use for…in to traverse through all the properties of gimli and print them to the console. Using bracket notation, we can retrieve the property value as a variable, in this case key.

// Iterate through properties of gimli
for (let key in gimli) {
  console.log(gimli[key]);
}
Output
Gimli
dwarf
battle axe
We can also retrieve the property name itself using just the first variabe in the for…in loop. We have used a string method to convert the key values to upper case.

// Get keys and values of gimli properties
for (let key in gimli) {
  console.log(key.toUpperCase() + ‘:’, gimli[key]);
}
Output
NAME: Gimli
RACE: dwarf
WEAPON: battle axe

The for…in loop is not to be confused with the for…of loop, which is used exclusively on the Array object type. You can learn more about iterating through arrays in the “Understanding Arrays in JavaScript” tutorial.

Another useful enumeration method is the Object.keys() method, which will return an array of the object’s keys.

// Initialize method on gimli object to return property keys
Object.keys(gimli);
Output
[“name”, “race”, “weapon”]

Events

An event handler is a JavaScript function that runs when an event fires.

An event listener attaches a responsive interface to an element, which allows that particular element to wait and “listen” for the given event to fire.

There are three ways to assign events to elements:

  • Inline event handlers
  • Event handler properties
  • Event listeners

To begin learning about event handlers, we’ll first consider the inline event handler. Let’s start with a very basic example that consists of a button element and a p element. We want the user to click the button to change the text content of the p.

Let’s begin with an HTML page with a button in the body. We’ll be referencing a JavaScript file that we’ll add code to in a bit.

events.html

<title>Events</title>

<!— Add button —> Click me

Try to change me.

<!— Reference JavaScript file —>

<script src=“js/events.js”></script> Directly on the button, we will add an attribute called onclick. The attribute value will be a function we create called changeText().

events.html

<title>Events</title>
<button onclick=“changeText()”>Click me</button>

<p>Try to change me.</p>
<script src=“js/events.js”></script> ``` Let’s create our events.js file, which we placed in the js/ directory here. Within it, we will create the changeText() function, which will modify the textContent of the p element.
js/events.js
// Function to modify the text content of the paragraph
const changeText = () => {
    const p = document.querySelector(‘p’);

    p.textContent = “I changed because of an inline event handler.”;
}

The event handler property is slightly more maintainable than the inline handler, but it still suffers from some of the same hurdles. For example, trying to set multiple, separate onclick properties will cause all but the last one to be overwritten, as demonstrated below.

js/events.js
const p = document.querySelector(‘p’);
const button = document.querySelector(‘button’);

const changeText = () => {
    p.textContent = “Will I change?”;
}

const alertText = () => {
    alert(‘Will I alert?’);
}

// Events can be overwritten
button.onclick = changeText;
button.onclick = alertText;

In the above example, the button click would only display an alert, and not change the p text, since the alert() code was the last one added to the property.

We will still be using the same changeText() function as before. We’ll attach the addEventListener() method to the button.

js/events.js
// Function to modify the text content of the paragraph
const changeText = () => {
    const p = document.querySelector(‘p’);

    p.textContent = “I changed because of an event listener.”;
}

// Listen for click event
const button = document.querySelector(‘button’);
button.addEventListener(‘click’, changeText);

Working JSON

The JSON.stringify() function converts an object to a JSON string.

Strings are useful for transporting data from a client to a server through storing or passing information in a lightweight way. For example, you may gather a user’s settings on the client side and then send them to a server. Later, you can then read the information with the JSON.parse() method and work with the data as needed.

We’ll look at a JSON object that we assign to the variable obj, and then we’ll convert it using JSON.stringify() by passing obj to the function. We can assign this string to the variable s:

var obj = {“first_name” : “Sammy”, “last_name” : “Shark”, “location” : “Ocean”}

var s = JSON.stringify(obj)
Now, if we work with s, we’ll have the JSON available to us as a string rather than an object.

‘{“first_name” : “Sammy”, “last_name” : “Shark”, “location” : “Ocean”}’

The JSON.stringify() function lets us convert objects to strings. To do the opposite, we’ll look at the JSON.parse() function.

JSON.parse() Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side. While you can convert text to an object with the eval() function, it is not very secure, so we’ll use the JSON.parse() function instead.

To convert the example in the JSON.stringify() section above, we would pass the string s to the function, and assign it to a new variable:

var o = JSON.parse(s) Then, we would have the object o to work with, which would be identical to the object obj.

IF ELSE

// Set the current grade of the student
let grade = 87;

// Check if grade is an A, B, C, D, or F
if (grade >= 90) {
  console.log(“A”);
} else if (grade >= 80) {
  console.log(“B”);
} else if (grade >= 70) {
  console.log(“C”);
} else if (grade >= 60) {
  console.log(“D”);
} else {
  console.log(“F”);
}


Output
B

In our example, we first check for the highest score, which will be greater than or equal to 90. After that, the else if statements will check for greater than 80, 70, and 60 until it reaches the default else of a failing grade.

A ternary operator is written with the syntax of a question mark (?) followed by a colon (:), as demonstrated below.

(condition) ? expression on true : expression on false In the above statement, the condition is written first, followed by a ?. The first expression will execute on true, and the second expression will execute on false. It is very similar to an if…else statement, with more compact syntax.

In this example, we will create a program that checks if a user is 21 or older. If they are, it will print “You may enter” to the console. If they are not, it will print “You may not enter.” to the console.

age.js
// Set age of user
let age = 20;

// Place result of ternary operation in a variable
const oldEnough = (age >= 21) ? “You may enter.” : “You may not enter.”;

// Print output
oldEnough;
Output
‘You may not enter.’

Since the age of the user was less than 21, the fail message was output to the console. The if…else equivalent to this would be “You may enter.” in the if statement, and “You may not enter.” in the else statement.

SWITCH ()

Let’s make a working example of a switch statement following the syntax above. In this code block, we will find the current day of the week with the new Date() method, and getDay() to print a number corresponding to the current day. 1 stands for Monday, all the way through 7 which stands for Sunday. We’ll start by setting up our variable.

const day = new Date().getDay();

Using switch, we will send a message to the console each day of the week. The program will run in order from top to bottom looking for a match, and once one is found, the break command will halt the switch block from continuing to evaluate statements.

week.js
// Set the current day of the week to a variable, with 1 being Monday and 7 being Sunday
const day = new Date().getDay();

switch (day) {
    case 1:
        console.log(“Happy Monday!”);
        break;
    case 2:
        console.log(“It’s Tuesday. You got this!”);
        break;
    case 3:
        console.log(“Hump day already!”);
        break;
    case 4:
        console.log(“Just one more day ’til the weekend!”);
        break;
    case 5:
        console.log(“Happy Friday!”);
        break;
    case 6:
        console.log(“Have a wonderful Saturday!”);
        break;
    case 7:
        console.log(“It’s Sunday, time to relax!”);
        break;
    default:
        console.log(“Something went horribly wrong…”);
}

Output
‘Just one more day ’til the weekend!’

This code was tested on a Thursday, which corresponds to 4, therefore the console output was Just one more day ’til the weekend!. Depending on what day of the week you are testing the code, your output will be different. We have included a default block at the end to run in case of an error, which in this case should not happen as there are only 7 days of the week. We also could have, for example, only printed results for Monday to Friday, and the default block could have had the same message for the weekend.

If we had omitted the break keyword in each statement, none of the other case statements would have evaluated too true, but the program would have continued to check until it reached the end. In order to make our programs faster and more efficient, we include the break.

// Get number corresponding to the current month, with 0 being January and 11 being December
const month = new Date().getMonth();

switch (month) {
    // January, February, March
    case 0:
    case 1:
    case 2:
        console.log(“Winter”);
        break;
    // April, May, June
    case 3:
    case 4:
    case 5:
        console.log(“Spring”);
        break;
    // July, August, September
    case 6:
    case 7:
    case 8:
        console.log(“Summer”);
        break;
    // October, November, December
    case 9:
    case 10:
    case 11:
        console.log(“Autumn”);
        break;
    default:
        console.log(“Something went wrong.”);
}
When we run the code, we’ll receive output identifying the current season based on the specifications above.

Output
Summer

To make this easier to understand, we will use a familiar example. In the conditional statements tutorial, we made a simple grading app which would take a number score and convert it to a letter grade, with the following requirements.

  • Grade of 90 and above is an A
  • Grade of 80 to 89 is a B
  • Grade of 70 to 79 is a C
  • Grade of 60 to 69 is a D
  • Grade of 59 or below is an F

Now we can write that as a switch statement. Since we’re checking a range, we will perform the operation in each case to check if each expression is evaluating to true then break out of the statement once the requirements for true have been satisfied.

grades.js
// Set the student’s grade
const grade = 87;

switch (true) {
    // If score is 90 or greater
    case grade >= 90:
        console.log(“A”);
        break;
    // If score is 80 or greater
    case grade >= 80:
        console.log(“B”);
        break;
    // If score is 70 or greater
    case grade >= 70:
        console.log(“C”);
        break;
    // If score is 60 or greater
    case grade >= 60:
        console.log(“D”);
        break;
    // Anything 59 or below is failing
    default:
        console.log(“F”);
}
Output
‘B’

While LOOP

// Set a condition to true
const iceCapsAreMelting = true;
let polarBears = 5;

// Initiate infinite loop
while (iceCapsAreMelting) {
  console.log(`There are ${polarBears} polar bears.`);
  polarBears—;
  // Terminate infinite loop when following condition is true
  if (polarBears === 0) {
    console.log(“There are no polar bears left.”);
    break;
  }
}

When we run the code above, the output will be as follows.

Output There are 5 polar bears. There are 4 polar bears. There are 3 polar bears. There are 2 polar bears. There are 1 polar bears. There are no polar bears left.

For Loop

The for statement is a type of loop that will use up to three optional expressions to implement the repeated execution of a code block.

Let’s take a look at an example of what that means.

for (initialization; condition; final expression) { // code to be executed } In the syntax above there are three expressions inside the for statement: the initialization, the condition, and the final expression, also known as incrementation.

Let’s use a basic example to demonstrate what each of these statements does.

forExample.js
// Initialize a for statement with 5 iterations
for (let i = 0; i < 4; i++) {
    // Print each iteration to the console
    console.log(i);
}

Object.create()

The Object.create() method is used to create a new object and link it to the prototype of an existing object.

We can create a job object instance, and extend it to a more specific object.

// Initialize an object with properties and methods
const job = {
    position: ‘cashier’,
    type: ‘hourly’,
    isAvailable: true,
    showDetails() {
        const accepting = this.isAvailable ? ‘is accepting applications’ : “is not currently accepting applications”;

        console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);
    }
};

// Use Object.create to pass properties
const barista = Object.create(job);

barista.position = “barista”;
barista.showDetails();

Output The barista position is hourly and is accepting applications.

Object.keys()

Object.keys() creates an array containing the keys of an object.

We can create an object and print the array of keys.

// Initialize an object
const employees = {
    boss: ‘Michael’,
    secretary: ‘Pam’,
    sales: ‘Jim’,
    accountant: ‘Oscar’
};

// Get the keys of the object
const keys = Object.keys(employees);

console.log(keys);

Output [“boss”, “secretary”, “sales”, “accountant”]

Object.keys can be used to iterate through the keys and values of an object.

// Iterate through the keys
Object.keys(employees).forEach(key => {
    let value = employees[key];

     console.log(`${key}: ${value}`);
});

Output boss: Michael secretary: Pam sales: Jim accountant: Oscar

Object.keys is also useful for checking the length of an object.

// Get the length of the keys
const length = Object.keys(employees).length;

console.log(length);

Output 4

Using the length property, we were able to count the 4 properties of employees.

Object.values()

Object.values() creates an array containing the values of an object.

// Initialize an object
const session = {
    id: 1,
    time: `26-July-2018`,
    device: ‘mobile’,
    browser: ‘Chrome’
};

// Get all values of the object
const values = Object.values(session);

console.log(values);

Output [1, “26-July-2018”, “mobile”, “Chrome”]

Object.keys() and Object.values() allow you to return the data from an object.

Object.entries()

Object.entries() creates a nested array of the key/value pairs of an object.

// Initialize an object
const operatingSystem = {
    name: ‘Ubuntu’,
    version: 18.04,
    license: ‘Open Source’
};

// Get the object key/value pairs
const entries = Object.entries(operatingSystem);

console.log(entries);

Output [ [“name”, “Ubuntu”] [“version”, 18.04] [“license”, “Open Source”] ]

Once we have the key/value pair arrays, we can use the forEach() method to loop through and work with the results.

// Loop through the results
entries.forEach(entry => {
    let key = entry[0];
    let value = entry[1];

    console.log(`${key}: ${value}`);
});

Output name: Ubuntu version: 18.04 license: Open Source

The Object.entries() method will only return the object instance’s own properties, and not any properties that may be inherited through its prototype.

Object.assign()

Object.assign() is used to copy values from one object to another.

We can create two objects, and merge them with Object.assign()

// Initialize an object
const name = {
    firstName: ‘Philip’,
    lastName: ‘Fry’
};

// Initialize another object
const details = {
    job: ‘Delivery Boy’,
    employer: ‘Planet Express’
};

// Merge the objects
const character = Object.assign(name, details);

console.log(character);

Output {firstName: “Philip”, lastName: “Fry”, job: “Delivery Boy”, employer: “Planet Express”}

It is also possible to use the spread operator (…) to accomplish the same task. In the code below, we’ll modify how we declare character through merging the name and details objects.

// Initialize an object
const name = {
    firstName: ‘Philip’,
    lastName: ‘Fry’
};

// Initialize another object
const details = {
    job: ‘Delivery Boy’,
    employer: ‘Planet Express’
};

// Merge the object with the spread operator
const character = {…name, …details}

console.log(character);

Output {firstName: “Philip”, lastName: “Fry”, job: “Delivery Boy”, employer: “Planet Express”} This spread syntax in object literals is also known as shallow-cloning.

Object.freeze()

Object.freeze() prevents modification to properties and values of an object, and prevents properties from being added or removed from an object.

// Initialize an object
const user = {
    username: ‘AzureDiamond’,
    password: ‘hunter2’
};

// Freeze the object
const newUser = Object.freeze(user);

newUser.password = ‘*******’;
newUser.active = true;

console.log(newUser);

Output {username: “AzureDiamond”, password: “hunter2”}

In the example above, we tried to override the password hunter2 with *******, but the password property remained the same. We also tried to add a new property, active, but it was not added.

Object.isFrozen() is available to determine whether an object has been frozen or not, and returns a Boolean.

Object.seal()

Object.seal() prevents new properties from being added to an object, but allows the modification of existing properties. This method is similar to Object.freeze(). Refresh your console before implementing the code below to avoid an error.

// Initialize an object
const user = {
    username: ‘AzureDiamond’,
    password: ‘hunter2’
};

// Seal the object
const newUser = Object.seal(user);

newUser.password = ‘*******’;
newUser.active = true;

console.log(newUser);

Output {username: “AzureDiamond”, password: “*******”} The new active property was not added to the sealed object, but the password property was successfully changed.

Object.getPrototypeOf()

Object.getPrototypeOf() is used to get the internal hidden [[Prototype]] of an object, also accessible through the proto property.

In this example, we can create an array, which has access to the Array prototype.

const employees = [‘Ron’, ‘April’, ‘Andy’, ‘Leslie’];

Object.getPrototypeOf(employees);

Output

[constructor: ƒ, concat: ƒ, find: ƒ, findIndex: ƒ, pop: ƒ, …]

We can see in the output that the prototype of the employees array has access to pop, find, and other Array prototype methods. We can confirm this by testing the employees prototype against Array.prototype.

Object.getPrototypeOf(employees) === Array.prototype; Output true

ES6

Variable: x Object: obj Array: arr Function: func Parameter, method: a, b, c String: str

 Variable declaration let x = 0  Constant declaration const CONST_ID = 0  Arrow function syntax let func = a => {} // parentheses optional with one parameter let func = (a, b, c) => {} // parentheses required with multiple parameters  Template literals let str = Release Date: ${date}  Implicit returns let func = (a, b, c) => a + b + c // curly brackets must be omitted  Key/property shorthand let obj = { a, b, }  Method definition shorthand let obj = { a(c, d) {}, b(e, f) {}, } obj.a() // call method a  Destructuring (object matching) let { a, b, c } = obj  Array iteration (looping) var arr = [‘a’, ‘b’, ‘c’] for (let i of arr) { console.log(i) }  Default parameters let func = (a, b = 2) => { return a + b } func(10) // returns 12 func(10, 5) // returns 15  Spread syntax `let arr1 = [1, 2, 3] let func = (a, b, c) => a + b + c

console.log(func(…arr1)) // 6`

 Classes/constructor functions

ES5
function Func(a, b) {
  this.a = a
  this.b = b
}

Func.prototype.getSum = function() {
  return this.a + this.b
}

var x = new Func(3, 4)
ES6
class Func {
  constructor(a, b) {
    this.a = a
    this.b = b
  }

  getSum() {
    return this.a + this.b
  }
}

let x = new Func(3, 4)
x.getSum() // returns 7

 Inheritance

ES5
function Inheritance(a, b, c) {
  Func.call(this, a, b)

  this.c = c
}

Inheritance.prototype = Object.create(Func.prototype)
Inheritance.prototype.getProduct = function() {
  return this.a * this.b * this.c
}

var y = new Inheritance(3, 4, 5)
ES6
class Inheritance extends Func {
  constructor(a, b, c) {
    super(a, b)

    this.c = c
  }

  getProduct() {
    return this.a * this.b * this.c
  }
}

let y = new Inheritance(3, 4, 5)
y.getProduct() // 60

 Modules - export/import

index.html
<script src=“export.js”></script>
<script type=“module” src=“import.js”></script>
export.js

let func = a => a + a
let obj = {}
let x = 0

export { func, obj, x }
import.js
import { func, obj, x } from ‘./export.js’

console.log(func(3), obj, x)

 Promises/callbacks

ES5 callback
function doSecond() {
  console.log(‘Do second.’)
}

function doFirst(callback) {
  setTimeout(function() {
    console.log(‘Do first.’)

    callback()
  }, 500)
}

doFirst(doSecond)
ES6 Promise
let doSecond = () => {
  console.log(‘Do second.’)
}

let doFirst = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log(‘Do first.’)

    resolve()
  }, 500)
})

doFirst.then(doSecond)
An example below using XMLHttpRequest, for demonstrative purposes only (Fetch API would be the proper modern API to use).

ES5 callback
function makeRequest(method, url, callback) {
  var request = new XMLHttpRequest()

  request.open(method, url)
  request.onload = function() {
    callback(null, request.response)
  }
  request.onerror = function() {
    callback(request.response)
  }
  request.send()
}

makeRequest(‘GET’, ‘https://url.json’, function(err, data) {
  if (err) {
    throw new Error(err)
  } else {
    console.log(data)
  }
})
ES6 Promise
function makeRequest(method, url) {
  return new Promise((resolve, reject) => {
    let request = new XMLHttpRequest()

    request.open(method, url)
    request.onload = resolve
    request.onerror = reject
    request.send()
  })
}

makeRequest(‘GET’, ‘https://url.json’)
  .then(event => {
    console.log(event.target.response)
  })
  .catch(err => {
    throw new Error(err)
  })

API with Javascript

script.js

const app = document.getElementById(‘root’);

const logo = document.createElement(‘img’);
logo.src = ‘logo.png’;

const container = document.createElement(‘div’);
container.setAttribute(‘class’, ‘container’);

app.appendChild(logo);
app.appendChild(container);

var request = new XMLHttpRequest();
request.open(‘GET’, ‘https://ghibliapi.herokuapp.com/films’, true);
request.onload = function () {

  // Begin accessing JSON data here
  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
    data.forEach(movie => {
      const card = document.createElement(‘div’);
      card.setAttribute(‘class’, ‘card’);

      const h1 = document.createElement(‘h1’);
      h1.textContent = movie.title;

      const p = document.createElement(‘p’);
      movie.description = movie.description.substring(0, 300);
      p.textContent = ${movie.description}…;

      container.appendChild(card);
      card.appendChild(h1);
      card.appendChild(p);
    });
  } else {
    const errorMessage = document.createElement(‘marquee’);
    errorMessage.textContent = Gah, it’s not working!;
    app.appendChild(errorMessage);
  }
}

request.send();

Local Storage

setItem()- Add key and value to local storage getItem()- Retrieve a value by the key removeItem()- Remove an item by key clear() - Clear all storage

React Learning

Component Nesting

Diagram

Props (properties)

- System for passing data from a *parent* component to a *child* component
- Goal is to customize or configure a child component. 

Functional Components

- Good for simple Content

Class Base Components

- For more complex
- Easier code organization
- Can use ‘state’ (another React System)
	- Easier to handle user input
- Understands lifecycle events 
	- Easier to do things when the app first starts 

Steps set up basic React App

  • create-react-app appName
  • Add semantic ui Styling https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css to index.html in the head tag <link rel=“stylesheet” href=“https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css”>
  • Delete all the files from the src folder and then make a new file index.js
  • Basic App code in index.js
import React from ‘react’;
import ReactDOM from ‘react-dom’;


const App = () => {
    return <div> Hi there! </div>;
};

ReactDOM.render(
<App />,
 document.querySelector(‘#root’)
);
  • Adding Basic component code i.e ComponentName.js
import React from ‘react’;

const ComponentDisplay = () => {
    return <div>Component Display!</div>;
};
export default ComponentDisplay; 

Rules of Class Components

 - Must be a Javascript Class
 - Must extend (subclass) React.Component
 - Must define a ‘render’ method that returns some amount of JSX

Rules of State

- Only usable with class components 
- you will confuse props with state 
- ‘State’ is a JS object that contains data relevant to a component
- Updating ‘state’ on a component causes the component to (almost) instantly re-render.
- State must be initialized when a component is created. 
- State can *only* be updated using the function ‘SetState’

Component Lifecycle

- constructor
- render
- componentDidMount
- componentDidUpdate
- componentWillUnmount

Example JSX component

class FirstComponent extends React.Component {
  constructor(props) {
    super(props)
  }
  render() {
    return (
      <div>
        <h1>My First React Component!</h1>
      </div>
    );
  }
};
ReactDOM.render(<FirstComponent />,document.querySelector('#challenge-node'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment