React Curriculum
On this page
- Introduction to React
- JavaScript Refresher
- 0. Adding JavaScript to a Web Page
- Inline Script
- Internal Script
- External Script
- Multiple External Scripts
- 1. Variables
- 2. Data types
- 3. Arrays
- How to create an empty array
- How to create an array with values
- Creating an array using split
- Accessing array items using index
- Modifying array element
- Methods to manipulate array
- Array of arrays
- š» Exercise
- 4. Conditionals
- If
- If Else
- If Else if Else
- Switch
- Ternary Operators
- š» Exercises
- 5. Loops
- Types of Loops
- Interrupting a loop and skipping an item
- Conclusions
- 6. Scope
- Window Scope
- Global scope
- Local scope
- 7. Object
- Creating an empty object
- Creating an objecting with values
- Getting values from an object
- Creating object methods
- Setting new key for an object
- Object Methods
- š» Exercises
- 8. Functions
- Function Declaration
- Function without a parameter and return
- Function returning value
- Function with a parameter
- Function with two parameters
- Function with many parameters
- Function with unlimited number of parameters
- Anonymous Function
- Expression Function
- Self Invoking Functions
- Arrow Function
- Function with default parameters
- Function declaration versus Arrow function
- š» Exercises
- 9. Higher Order Function
- Callback
- Returning function
- setting time
- 10. Destructuring and Spreading
- What is Destructuring?
- What can we destructure?
- Exercises
- Spread or Rest Operator
- 11. Functional Programming
- 1. forEach
- 2. map
- 3. filter
- 4. reduce
- 5. find
- 6. findIndex
- 7. some
- 8. every
- Exercises
- 12. Classes
- Defining a classes
- Class Instantiation
- Class Constructor
- Default values with constructor
- Class methods
- Properties with initial value
- getter
- setter
- Static method
- Inheritance
- Overriding methods
- Exercises
- 13 Document Object Model(DOM)
Curriculum sourced from React by Asabeneh Yetayeh.
Introduction to React
- JavaScript Refresher
- 0. Adding JavaScript to a Web Page
- 1. Variables
- 2. Data types
- 3. Arrays
- How to create an empty array
- How to create an array with values
- Creating an array using split
- Accessing array items using index
- Modifying array element
- Methods to manipulate array
- Array Constructor
- Creating static values with fill
- Concatenating array using concat
- Getting array length
- Getting index of an element in an array
- Getting last index of an element in array
- Checking array
- Converting array to string
- Joining array elements
- Slice array elements
- Splice method in array
- Adding item to an array using push
- Removing the end element using pop
- Removing an element from the beginning
- Add an element from the beginning
- Reversing array order
- Sorting elements in array
- Array of arrays
- š» Exercise
- 4. Conditionals
- š» Exercises
- 5. Loops
- 6. Scope
- 7. Object
- š» Exercises
- 8. Functions
- Function Declaration
- Function without a parameter and return
- Function returning value
- Function with a parameter
- Function with two parameters
- Function with many parameters
- Function with unlimited number of parameters
- Anonymous Function
- Expression Function
- Self Invoking Functions
- Arrow Function
- Function with default parameters
- Function declaration versus Arrow function
- š» Exercises
- 9. Higher Order Function
- 10. Destructuring and Spreading
- 11. Functional Programming
- 12. Classes
- 13 Document Object Model(DOM)
JavaScript Refresher
0. Adding JavaScript to a Web Page
JavaScript can be added to a web page in three different ways:
- Inline script
- Internal script
- External script
- Multiple External scripts
The following sections show different ways of adding JavaScript code to your web page.
Inline Script
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an index.html file in the project folder. Then paste the following code and open it in a browser, for example Chrome.
Now, you just wrote your first inline script. We can create a pop up alert message using the alert() built-in function.
Internal Script
The internal script can be written in the head or the body, but it is preferred to put it on the body of the HTML document. First, let us write on the head part of the page.
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the console.log()
Open the browser console to see the output from the console.log()
External Script
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. First, we should create an external JavaScript file with .js extension. All files ending with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body.
External scripts in the head:
External scripts in the body:
Open the browser console to see the output of the console.log()
Multiple External Scripts
We can also link multiple external JavaScript files to a web page. Create a helloworld.js file inside the 30DaysOfJS folder and write the following code.
Your main.js file should be below all other scripts. It is very important to remember this.
1. Variables
We use var, let and const to declare a variable. The var is functions scope, however let and const are block scope. In this challenge we use ES6 and above features of JavaScript. Avoid using var.
2. Data types
If you do not feel comfortable with data types check the following link
3. Arrays
In contrast to variables, an array can store multiple values. Each value in an array has an index, and each index has a reference in a memory address. Each value can be accessed by using their indexes. The index of an array starts from zero, and the index of the last element is less by one from the length of the array.
An array is a collection of different data types which are ordered and changeable(modifiable). An array allows storing duplicate elements and different data types. An array can be empty, or it may have different data type values.
How to create an empty array
In JavaScript, we can create an array in different ways. Let us see different ways to create an array. It is very common to use const instead of let to declare an array variable. If you are using const it means you do not use that variable name again.
- Using Array constructor
- Using square brackets([])
How to create an array with values
Array with initial values. We use length property to find the length of an array.
- Array can have items of different data types
Creating an array using split
As we have seen in the earlier section, we can split a string at different positions, and we can change to an array. Let us see the examples below.
Accessing array items using index
We access each element in an array using their index. An array index starts from 0. The picture below clearly shows the index of each element in the array.
Modifying array element
An array is mutable(modifiable). Once an array is created, we can modify the contents of the array elements.
Methods to manipulate array
There are different methods to manipulate an array. These are some of the available methods to deal with arrays:Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift
Array Constructor
Array:To create an array.
Creating static values with fill
fill: Fill all the array elements with a static value
Concatenating array using concat
concat:To concatenate two arrays.
Getting array length
Length:To know the size of the array
Getting index of an element in an array
indexOf:To check if an item exist in an array. If it exists it returns the index else it returns -1.
Check an element if it exist in an array.
- Check items in a list
Getting last index of an element in array
lastIndexOf: It gives the position of the last item in the array. If it exist, it returns the index else it returns -1.
includes:To check if an item exist in an array. If it exist it returns the true else it returns false.
Checking array
Array.isArray:To check if the data type is an array
Converting array to string
toString:Converts array to string
Joining array elements
join: It is used to join the elements of the array, the argument we passed in the join method will be joined in the array and return as a string. By default, it joins with a comma, but we can pass different string parameter which can be joined between the items.
Slice array elements
Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position.
Splice method in array
Splice: It takes three parameters:Starting position, number of times to be removed and number of items to be added.
Adding item to an array using push
Push: adding item in the end. To add item to the end of an existing array we use the push method.
Removing the end element using pop
pop: Removing item in the end.
Removing an element from the beginning
shift: Removing one array element in the beginning of the array.
Add an element from the beginning
unshift: Adding array element in the beginning of the array.
Reversing array order
reverse: reverse the order of an array.
Sorting elements in array
sort: arrange array elements in ascending order. Sort takes a call back function, we will see how we use sort with a call back function in the coming sections.
Array of arrays
Array can store different data types including an array itself. Let us create an array of arrays
š» Exercise
Exercise: Level 1
- Declare an empty array;
- Declare an array with more than 5 number of elements
- Find the length of your array
- Get the first item, the middle item and the last item of the array
- Declare an array called mixedDataTypes, put different data types in the array and find the length of the array. The array size should be greater than 5
- Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon
- Print the array using console.log()
- Print the number of companies in the array
- Print the first company, middle and last company
- Print out each company
- Change each company name to uppercase one by one and print them out
- Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
- Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is not found
- Filter out companies which have more than one 'o' without the filter method
- Sort the array using sort() method
- Reverse the array using reverse() method
- Slice out the first 3 companies from the array
- Slice out the last 3 companies from the array
- Slice out the middle IT company or companies from the array
- Remove the first IT company from the array
- Remove the middle IT company or companies from the array
- Remove the last IT company from the array
- Remove all IT companies
Exercise: Level 2
-
Create a separate countries.js file and store the countries array into this file, create a separate file web_techs.js and store the webTechs array into this file. Access both file in main.js file
-
First remove all the punctuations and change the string to array and count the number of words in the array
-
In the following shopping cart add, remove, edit items
- add 'Meat' in the beginning of your shopping cart if it has not been already added
- add Sugar at the end of you shopping cart if it has not been already added
- remove 'Honey' if you are allergic to honey
- modify Tea to 'Green Tea'
-
In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list.
-
In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array.
-
Concatenate the following two variables and store it in a fullStack variable.
Exercise: Level 3
-
The following is an array of 10 students ages:
js const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]- Sort the array and find the min and max age - Find the median age(one middle item or two middle items divided by two) - Find the average age(all items divided by number of items) - Find the range of the ages(max minus min) - Compare the value of (min - average) and (max - average), use abs() method1.Slice the first ten countries from the countries array
-
Find the middle country(ies) in the countries array
-
Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half.
4. Conditionals
Conditional statements are used for make decisions based on different conditions. By default , statements in JavaScript script executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two ways:
- Conditional execution: a block of one or more statements will be executed if a certain expression is true
- Repetitive execution: a block of one or more statements will be repetitively executed as long as a certain expression is true. In this section, we will cover if, else , else if statements. The comparison and logical operators we learned in the previous sections will be useful in here.
Conditions can be implementing using the following ways:
- if
- if else
- if else if else
- switch
- ternary operator
If
In JavaScript and other programming languages the key word if is to used check if a condition is true and to execute the block code. To create an if condition, we need if keyword, condition inside a parenthesis and block of code inside a curly bracket({}).
Example:
As you can see in the condition example above, 3 is greater than 0, so it is a positive number. The condition was true and the block of code was executed. However, if the condition is false, we won't see any results.
The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see any output. In order to see the result of a falsy condition, we should have another block, which is going to be else.
If Else
If condition is true the first block will be executed, if not the else condition will be executed.
The last condition is false, therefore the else block was executed. What if we have more than two conditions? In that case, we would use else if conditions.
If Else if Else
On our daily life, we make decisions on daily basis. We make decisions not by checking one or two conditions instead we make decisions based on multiple conditions. As similar to our daily life, programming is also full of conditions. We use else if when we have multiple conditions.
Example:
Switch
Switch is an alternative for if else if else else. The switch statement starts with a switch keyword followed by a parenthesis and code block. Inside the code block we will have different cases. Case block runs if the value in the switch statement parenthesis matches with the case value. The break statement is to terminate execution so the code execution does not go down after the condition is satisfied. The default block runs if all the cases don't satisfy the condition.
// Examples to use conditions in the cases
Ternary Operators
Ternary operator is very common in React. It is a short way to write if else statement. In React we use ternary operator in many cases.
To generalize, ternary operator is another way to write conditionals.
š» Exercises
Exercises: Level 1
-
Get user input using prompt(āEnter your age:ā). If user is 18 or older , give feedback:'You are old enough to drive' but if not 18 give another feedback stating to wait for the number of years he needs to turn 18.
-
Compare the values of myAge and yourAge using if ⦠else. Based on the comparison and log the result to console stating who is older (me or you). Use prompt(āEnter your age:ā) to get the age as input.
-
If a is greater than b return 'a is greater than b' else 'a is less than b'. Try to implement it in two ways
- using if else
- ternary operator.
-
Even numbers are divisible by 2 and the remainder is zero. How do you check, if a number is even or not using JavaScript?
Exercises: Level 2
- Write a code which can give grades to students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0-49, F
- Check if the season is Autumn, Winter, Spring or Summer.
If the user input is :
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
- Check if a day is weekend day or a working day. Your script will take day as an input.
Exercises: Level 3
- Write a program which tells the number of days in a month.
- Write a program which tells the number of days in a month, now consider leap year.
5. Loops
In programming we use different loops to carry out repetitive tasks. Therefore, loop can help us to automate tedious and repetitive task. JavaScript has also different types of loops which we can use to work on repetitive task.
Imagine if your are asked to print Hello world one thousand times without a loop, it may take an hour or two to do this tedious task. However, using loop we can print it in less than a second.
Loops:
- for
- while
- do while
- for of
- forEach
- for in
A loop usually goes until the condition gets false. But sometimes we like to interrupt the loop or skip an item during iteration. We use break to interrupt the loop and continue to skip an item during iteration.
Types of Loops
1. for
We use for loop when we know how many iteration we go. Let's see the following example
This code prints from 0 to 5.
For example if we want to sum all the numbers from 0 to 100.
If we want to sum only even numbers:
This code iterates through the array
This code prints 5 to 0. Looping in reverse order
The Code below can reverse an array.
2. while
We use the while loop when we do not know how man iteration we go in advance.
3. do while
Do while run at least once if the condition is true or false
The code below runs ones though the condition is false
While loop is the least important loop in many programming languages.
4. for of
The for of loop is very handy to use it with array. If we are not interested in the index of the array a for of loop is preferable to regular for loop or forEach loop.
5. forEach
If we are interested in the index of the array forEach is preferable to for of loop. The forEach array method takes a callback function, the callback function takes three arguments: the item, the index and the array itself.
6. for in
The for in loop can be used with object literals to get the keys of the object.
Interrupting a loop and skipping an item
break
Break is used to interrupt a loop.
The above code stops if 3 found in the iteration process.
continue
We use the keyword continue to skip a certain iterations.
Conclusions
- Regular for loop can be used anywhere when the number of iteration is known.
- While loop when the number of iteration is not know
- Do while loop and while loop are almost the same but do while loop run at least once even when the condition is false
- for of is used only for array
- forEach is used for array
- for in is used for object
6. Scope
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word var, let and const. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let. Variables scopes can be:
- Window
- Global
- Local
Variable can be declared globally or locally or window scope. We will see both global and local scope. Anything declared without let, var or const is scoped at window level.
Let us image we have a scope.js file.
Window Scope
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
Global scope
A globally declared variable can be accessed every where in the same file. But the term global is relative. It can be global to the file or it can be global relative to some block of codes.
Local scope
A variable declared as local can be accessed only in certain block code.
Now, you have an understanding of scope. A variable declared with var only scoped to function but variable declared with let or const is block scope(function block, if block, loop etc). Block in JavaScript is a code in between two curly brackets ({}).
In ES6 and above there is let and const, so you will not suffer from the sneakiness of var. When we use let our variable is block scoped and it will not infect other parts of our code.
The scope let and const is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use let and const, by using let and const you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use let for any value which change, const for any constant value, and for array, object, arrow function and function expression.
7. Object
Everything can be an object and objects do have properties and properties have values, so an object is a key value pair. The order of the key is not reserved, or there is no order. To create an object literal, we use two curly brackets.
Creating an empty object
An empty object
Creating an objecting with values
Now, the person object has firstName, lastName, age, location, skills and isMarried properties. The value of properties or keys could be a string, number, boolean, an object, null, undefined or a function.
Let us see some examples of object. Each key has a value in the object.
Getting values from an object
We can access values of object using two methods:
- using . followed by key name if the key-name is a one word
- using square bracket and a quote
Creating object methods
Now, the person object has getFullName properties. The getFullName is function inside the person object and we call it an object method. The this key word refers to the object itself. We can use the word this to access the values of different properties of the object. We can not use an arrow function as object method because the word this refers to the window inside an arrow function instead of the object itself. Example of object:
Setting new key for an object
An object is a mutable data structure and we can modify the content of an object after it gets created.
Setting a new keys in an object
Object Methods
There are different methods to manipulate an object. Let us see some of the available methods.
Object.assign: To copy an object without modifying the original object
Getting object keys using Object.keys()
Object.keys: To get the keys or properties of an object as an array
Getting object values using Object.values()
Object.values:To get values of an object as an array
Getting object keys and values using Object.entries()
Object.entries:To get the keys and values in an array
Checking properties using hasOwnProperty()
hasOwnProperty: To check if a specific key or property exist in an object
š You are astonishing. Now, you are super charged with the power of objects. You have just completed day 8 challenges and you are 8 steps a head into your way to greatness. Now do some exercises for your brain and for your muscle.
š» Exercises
Exercises: Level 1
- Create an empty object called dog
- Print the the dog object on the console
- Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return woof woof
- Get name, legs, color, age and bark value from the dog object
- Set new properties the dog object: breed, getDogInfo
Exercises: Level 2
-
Find the person who has many skills in the users object.
-
Count logged in users,count users having greater than equal to 50 points from the following object.
-
Find people who are MERN stack developer from the users object
-
Set your name in the users object without modifying the original users object
-
Get all keys or properties of users object
-
Get all the values of users object
-
Use the countries object to print a country name, capital, populations and languages.
Exercises: Level 3
- Create an object literal called personAccount. It has firstName, lastName, incomes, expenses properties and it has totalIncome, totalExpense, accountInfo,addIncome, addExpense and accountBalance methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description.
- **** Questions:2, 3 and 4 are based on the following two arrays:users and products ()
Imagine you are getting the above users collection from a MongoDB database.
a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account.
b. Create a function called signIn which allows user to sign in to the application
-
The products array has three elements and each of them has six properties. a. Create a function called rateProduct which rates the product b. Create a function called averageRating which calculate the average rating of a product
-
Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked.
8. Functions
So far we have seen many builtin JavaScript functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets understand what function is and why we need function?
A function is a reusable block of code or programming statements designed to perform a certain task. A function is declared by a function key word followed by a name, followed by parentheses (). A parentheses can take a parameter. If a function take a parameter it will be called with argument. A function can also take a default parameter. To store a data to a function, a function has to return certain data types. To get the value we call or invoke a function. Function makes code:
- clean and easy to read
- reusable
- easy to test
A function can be declared or created in couple of ways:
- Declaration function
- Expression function
- Anonymous function
- Arrow function
Function Declaration
Let us see how to declare a function and how to call a function.
Function without a parameter and return
Function can be declared without a parameter.
Example:
Function returning value
Function can also return values, if a function does not return values the value of the function is undefined. Let us write the above functions with return. From now on, we return value to a function instead of printing it.
Function with a parameter
In a function we can pass different data types(number, string, boolean, object, function) as a parameter.
Function with two parameters
Function with many parameters
Function with unlimited number of parameters
Sometimes we do not know how many arguments the user going to pass. Therefore, we should know how to write a function which can take unlimited number of arguments. The way we do it has a significant difference between a function declaration(regular function) and arrow function. Let us see examples both in function declaration and arrow function.
Unlimited number of parameters in regular function
A function declaration provides a function scoped arguments array like object. Any thing we passed as argument in the function can be accessed from arguments object inside the functions. Let us see an example
Unlimited number of parameters in arrow function
Arrow function does not have the function scoped arguments object. To implement a function which takes unlimited number of arguments in an arrow function we use spread operator followed by any parameter name. Any thing we passed as argument in the function can be accessed as array in the arrow function. Let us see an example
Anonymous Function
Anonymous function or without name
Expression Function
Expression functions are anonymous functions. After we create a function without a name and we assign it to a variable. To return a value from the function we should call the variable. Look at the example below.
Self Invoking Functions
Self invoking functions are anonymous functions which do not need to be called to return a value.
Arrow Function
Arrow function is an alternative to write a function, however function declaration and arrow function have some minor differences.
Arrow function uses arrow instead of the keyword function to declare a function. Let us see both function declaration and arrow function.
The above function has only the return statement, therefore, we can explicitly return it as follows.
Function with default parameters
Sometimes we pass default values to parameters, when we invoke the function if we do not pass an argument the default value will be used. Both function declaration and arrow function can have a default value or values.
Example:
Let us see how we write the above functions with arrow functions
Example:
Function declaration versus Arrow function
It ill be covered in other time
š» Exercises
Exercises: Level 1
-
Declare a function fullName and it takes firstName, lastName as a parameter and it returns your full - name.
-
Declare a function addNumbers and it takes two two parameters and it returns sum.
-
Area of a circle is calculated as follows: area = Ļ x r x r. Write a function which calculates _areaOfCircle
-
Temperature in oC can be converted to oF using this formula: oF = (oC x 9/5) + 32. Write a function which convert oC to oF convertCelciusToFahrenheit.
-
Body mass index(BMI) is calculated as follows: bmi = weight in Kg / (height x height) in m2. Write a function which calculates bmi. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is underweight, normal, overweight or obese based the information given below.
- The same groups apply to both men and women.
- Underweight: BMI is less than 18.5
- Normal weight: BMI is 18.5 to 24.9
- Overweight: BMI is 25 to 29.9
- Obese: BMI is 30 or more
-
Write a function called checkSeason, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer.
Exercises: Level 2
-
Quadratic equation is calculated as follows: ax2 + bx + c = 0. Write a function which calculates value or values of a quadratic equation, solveQuadEquation.
-
Declare a function name printArray. It takes array as a parameter and it prints out each value of the array.
-
Write a function name showDateTime which shows time in this format: 08/01/2020 04:08 using the Date object.
-
Declare a function name swapValues. This function swaps value of x to y.
-
Declare a function name reverseArray. It takes array as a parameter and it returns the reverse of the array (don't use method).
-
Declare a function name capitalizeArray. It takes array as a parameter and it returns the - capitalizedarray.
-
Declare a function name addItem. It takes an item parameter and it returns an array after adding the item
-
Declare a function name removeItem. It takes an index parameter and it returns an array after removing an ite
-
Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
- Write a function which takes any number of arguments and return the sum of the arguments
- Declare a function name userIdGenerator. When this function is called it generates seven character id. The function return the id.
Exercises: Level 3
-
Declare a function name userIdGeneratedByUser. It doesnāt take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
-
Write a function generateColors which can generate any number of hexa or rgb colors.
-
Call your function shuffleArray, it takes an array as a parameter and it returns a shuffled array
-
Call your function factorial, it takes a whole number as a parameter and it return a factorial of the number
-
Call your function isEmpty, it takes a parameter and it checks if it is empty or not
-
Write a function called average, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not give return reasonable feedback.
9. Higher Order Function
Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.
Callback
A callback is a function which can be passed as parameter to other function. See the example below.
Returning function
Higher order functions return function as a value ā
Let us see were we use call back functions.For instance the forEach method uses call back.
The above example can be simplified as follows:
setting time
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.
- setInterval
- setTimeout
setInterval
In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.
setTimeout
In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
10. Destructuring and Spreading
What is Destructuring?
Destructuring is a way to unpack arrays, and objects and assigning to a distinct variable. Destructuring allows us to write clean and readable code.
What can we destructure?
- Arrays
- Objects
1. Destructuring arrays
Arrays are a list of different data types ordered by their index. Let's see an example of arrays:
We can access an item from an array using a certain index by iterating through the loop or manually as shown in the example below.
Accessing array items using a loop
Accessing array items manually
Most of the time the size of an array is big and we use a loop to iterate through each item of the arrays. Sometimes, we may have short arrays. If the array size is very short it is ok to access the items manually as shown above but today we will see a better way to access the array item which is destructuring.
Accessing array items using destructuring
During destructuring each variable should match with the index of the desired item in the array. For instance, the variable fin matches to index 0 and the variable nor matches to index 2. What would be the value of den if you have a variable den next nor?
If you tried the above task you confirmed that the value is undefined. Actually, we can pass a default value to the variable, and if the value of that specific index is undefined the default value will be used.
Destructuring Nested arrays
Skipping an Item during destructuring
During destructuring if we are not interested in every item, we can omit a certain item by putting a comma at that index. Let's get only Finland, Iceland, and Denmark from the array. See the example below for more clarity:
Getting the rest of the array using the spread operator We use three dots(...) to spread or get the rest of an array during destructuring
There many cases in which we use array destructuring, let's see the following example:
Destructuring when we loop through arrays
What do you think about the code snippet below? If you have started React Hooks already it may remind you of the useState hook.
What is the value of x? And what is the value of y(x)? I leave this for you to figure out.
If you have used react hooks you are very familiar with this and as you may imagine it is destructuring. The initial value of count is 0 and the setCount is a method that changes the value of count.
Now, you know how to destructure arrays. Let's move on to destructuring objects.
2. Destructuring objects
An object literal is made of key and value pairs. A very simple example of an object:
We access the value of an object using the following methods:
But today, we will see how to access the value of an object using destructuring.
When we destructure an object the name of the variable should be exactly the same as the key or property of the object. See the example below.
What will be the value of we try to access a key which not in the object.
The value of the perimeter in the above example is undefined.
Default value during object destructuring
Similar to the array, we can also use a default value in object destructuring.
Renaming variable names
Let's also destructure, nested objects. In the example below, we have nested objects and we can destructure it in two ways.
We can just destructure step by step
- We can destructure it one step
Destructuring during loop through an array
Destructuring function parameter
Exercises
Create a function called getPersonInfo. The getPersonInfo function takes an object parameter. The structure of the object and the output of the function is given below. Try to use both a regular way and destructuring and compare the cleanness of the code. If you want to compare your solution with my solution, check this link.
Spread or Rest Operator
When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread arr elements to another array.
Spread operator to get the rest of array elements
Spread operator to copy array
Spread operator to copy object
We can copy an object using a spread operator
Modifying or changing the object while copying
Spread operator with arrow function
Whenever we like to write an arrow function which takes unlimited number of arguments we use a spread operator. If we use a spread operator as a parameter, the argument passed when we invoke a function will change to an array.
11. Functional Programming
In this article, I will try to help you to have a very good understanding of the most common feature of JavaScript, functional programming.
Functional programming allows you to write shorter code, clean code, and also to solve complicated problems which might be difficult to solve in a traditional way.
In this article we will cover all JS functional programming methods:
- forEach
- map
- filter
- reduce
- find
- findIndex
- some
- every
1. forEach
We use forEach when we like to iterate through an array of items. The forEach is a higher-order function and it takes call-back as a parameter. The forEach method is used only with array and we use forEach if you are interested in each item or index or both.
The call back function could be a function declaration or an arrow function.
Let see different examples
If there is no much code inside the code block we can use an arrow function and we can write it without a curly bracket. The index and the array parameters are optional, we can omit them.
For example if we like to change each country to uppercase and store it back to an array we write it as follows.
Let us see more examples. For instance if we want to sum an array of numbers we can use forEach or reduce. Let us see how we use forEach to sum all numbers in an array.
Let us move to the next functional programming method which is going to be a map.
2. map
We use the map method whenever we like to modify an array. We use the map method only with arrays and it always returns an array.
Now, let us modify the countries array using the map method. The index is an optional parameter
As you can see that map is very handy to modify an array and to get an array back. Now, let us create an array of the length of the countries from the countries array.
Let us see another more example
3. filter
As you may understand from the literal meaning of filter, it filters out items based on some criteria. The filter method like forEach and map is used with an array and it returns an array of the filtered items.
For instance if we want to filter out countries containing a substring land from an array of countries. See the example below:
How about if we want to filter out countries not containing the substring land. We use negation to achieve that.
Let's see an additional example about the filter, let us filter even or odd numbers from an array of numbers
Now, you know how to filter let us move on to the next functional programming, reduce.
4. reduce
Like forEach, map, and filter, reduce is also used with an array and it returns a single value. You can associate reduce with a blender. You put different fruits to a blend and you get a mix of fruit juice. The juice is the output from the reduction process.
We use the reduce method to sum all numbers in an array together, or to multiply items in an array or to concatenate items in an array. Let us see the following different example to make this explanation more clear.
The default initial value is 0. We can change the initial value if we want to change it.
For instance if we want to add all items in an array and if all the items are numbers we can use reduce.
Reduce has a default initial value which is zero. Now, let us use a different initial value which is 5 in this case.
Let us concatenate strings using reduce
We can multiply items of an array using reduce and we will return the value.
Let us try it with an initial value
5. find
If we are interested in the first occurrence of a certain item or element in an array we can use find method. Unlike map and filter, find just return the first occurrence of an item instead of an array.
Let find the first even number and the first odd number in the numbers array.
Let us find the first country which contains a substring way
Let us find the first country which has only six characters
Let us find the first country in the array which has the letter 'o'
6. findIndex
The findIndex method works like find but findIndex returns the index of the item. If we are interested in the index of a certain item or element in an array we can use findIndex. The findIndex return the index of the first occurrence of an item.
Let us find the index of the first even number and the index of the first odd number in the numbers array.
Let us find the index of the first country in the array which has exactly six characters
Let us find the index of the first country in the array which has the letter 'o'.
Let us move on to the next functional programming, some.
7. some
The some method is used with array and return a boolean. If one or some of the items satisfy the criteria the result will be true else it will be false. Let us see it with an example.
In the following array some numbers are even and some are odd, so if I ask you a question, are there even numbers in the array then your answer will be yes. If I ask you also another question, are there odd numbers in the array then your answer will be yes. On the contrary, if I ask you, are all the numbers even or odd then your answer will be no because all the numbers are not even or odd.
Let us another example
Now, let us see one more functional programming, every.
8. every
The method every is somehow similar to some but every item must satisfy the criteria. The method every like some returns a boolean.
Exercises
-
Print the price of each product using forEach
-
Print the product items as follows using forEach
-
Calculate the sum of all the prices using forEach
-
Create an array of prices using map and store it in a variable prices
-
Filter products with prices
-
Use method chaining to get the sum of the prices(map, filter, reduce)
-
Calculate the sum of all the prices using reduce only
-
Find the first product which doesn't have a price value
-
Find the index of the first product which does not have price value
-
Check if some products do not have a price value
-
Check if all the products have price value
-
Explain the difference between forEach, map, filter and reduce
-
Explain the difference between filter, find and findIndex
-
Explain the difference between some and every
12. Classes
JavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
Once we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation.
In the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code.
Defining a classes
To define a class in JavaScript we need the keyword class , the name of a class in CamelCase and block code(two curly brackets). Let us create a class name Person.
Example:
We have created an Person class but it does not have any thing inside.
Class Instantiation
Instantiation class means creating an object from a class. We need the keyword new and we call the name of the class after the word new.
Let us create a dog object from our Person class.
As you can see, we have created a person object. Since the class did not have any properties yet the object is also empty.
Let use the class constructor to pass different properties for the class.
Class Constructor
The constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use the this keyword to attach the constructor parameters with the class.
The following Person class constructor has firstName and lastName property. These properties are attached to the Person class using this keyword. This refers to the class itself.
All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.
As we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class.
Using the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class.
Default values with constructor
The constructor function properties may have a default value like other regular functions.
Class methods
The constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.
Properties with initial value
When we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time.
A method could be regular method or a getter or a setter. Let us see, getter and setter.
getter
The get method allow us to access value from the object. We write a get method using keyword get followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow
setter
The setter method allow us to modify the value of certain properties. We write a setter method using keyword set followed by a function. See the example bellow.
Do not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class.
Static method
The static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method is Date.now(). The now method is called directly from the class.
The static methods are methods which can be used as utility functions.
Inheritance
Using inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc.
Let us create a Student child class from Person parent class.
Overriding methods
As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
Now, the getPersonInfo method has been overridden and it identifies if the person is male or female.
Exercises
Exercises Level 1
- Create an Animal class. The class will have name, age, color, legs properties and create different methods
- Create a Dog and Cat child class from the Animal Class.
Exercises Level 2
- Override the method you create in Animal class
Exercises Level 3
- Let's try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below.
13 Document Object Model(DOM)
HTML document is structured as a JavaScript Object. Every HTML element has a different properties which can help us to manipulate it. It is possible to get, create, append or remove HTML elements using JavaScript.
When it comes to React we do not directly manipulate the DOM instead React Virtual DOM will take care of update all necessary changes.
So do not directly manipulate the DOM if you are using react. The only place we directly touch the DOM is here at the index.html. React is a single page application because all the components will be rendered on the index.html page and there will not be any other HTML in the entire React Application. You don't have to know DOM very well to use react but recommended to know.
Check out there result on codepen
š You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now you are a JavaScript Ninja and ready to dive into React.
š CONGRATULATIONS ! š