javascript_refresher
- 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.
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">Click Me</button>
</body>
</html>
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.
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</head>
<body></body>
</html>
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()
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
<script>
console.log('Welcome to 30DaysOfJavaScript')
</script>
</body>
</html>
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.
console.log('Welcome to 30DaysOfJavaScript')
External scripts in the head:
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
External scripts in the body:
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
//it could be in the header or in the body // Here is the recommended place
to put the external script
<script src="introduction.js"></script>
</body>
</html>
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.
console.log('Hello, World!')
<!DOCTYPE html>
<html>
<head>
<title>Multiple External Scripts</title>
</head>
<body>
<script src="./helloworld.js"></script>
<script src="./introduction.js"></script>
</body>
</html>
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.
let firstName = 'Asabeneh'
firstName = 'Eyob'
const PI = 3.14 // Not allowed to reassign PI to a new value
// PI = 3.
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
// syntax
const arr = Array()
// or
// let arr = new Array()
console.log(arr) // []
- Using square brackets([])
// syntax
// This the most recommended way to create an empty list
const arr = []
console.log(arr)
How to create an array with values
Array with initial values. We use length property to find the length of an array.
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of strings, fruits
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of strings, vegetables
const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // array of strings, products
const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // array of web technologies
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // array of strings, countries
// Print the array and its length
console.log('Numbers:', numbers)
console.log('Number of numbers:', numbers.length)
console.log('Fruits:', fruits)
console.log('Number of fruits:', fruits.length)
console.log('Vegetables:', vegetables)
console.log('Number of vegetables:', vegetables.length)
console.log('Animal products:', animalProducts)
console.log('Number of animal products:', animalProducts.length)
console.log('Web technologies:', webTechs)
console.log('Number of web technologies:', webTechs.length)
console.log('Countries:', countries)
console.log('Number of countries:', countries.length)
Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
Number of numbers: 6
Fruits: ['banana', 'orange', 'mango', 'lemon']
Number of fruits: 4
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
Number of vegetables: 5
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
Number of animal products: 4
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
Number of web technologies: 7
Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
Number of countries: 5
- Array can have items of different data types
const arr = [
'Asabeneh',
250,
true,
{ country: 'Finland', city: 'Helsinki' },
{ skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] },
] // arr containing different data types
console.log(arr)
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.
let js = 'JavaScript'
const charsInJavaScript = js.split('')
console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'
const companies = companiesString.split(',')
console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"]
let txt =
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
const words = txt.split(' ')
console.log(words)
// the text has special characters think how you can just get only the words
// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"]
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.
const fruits = ['banana', 'orange', 'mango', 'lemon']
let firstFruit = fruits[0] // we are accessing the first item using its index
console.log(firstFruit) // banana
secondFruit = fruits[1]
console.log(secondFruit) // orange
let lastFruit = fruits[3]
console.log(lastFruit) // lemon
// Last index can be calculated as follows
let lastIndex = fruits.length - 1
lastFruit = fruits[lastIndex]
console.log(lastFruit) // lemon
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // set of numbers
console.log(numbers.length) // => to know the size of the array, which is 6
console.log(numbers) // -> [0, 3.14, 9.81, 37, 98.6, 100]
console.log(numbers[0]) // -> 0
console.log(numbers[5]) // -> 100
let lastIndex = numbers.length - 1
console.log(numbers[lastIndex]) // -> 100
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
] // List of web technologies
console.log(webTechs) // all the array items
console.log(webTechs.length) // => to know the size of the array, which is 7
console.log(webTechs[0]) // -> HTML
console.log(webTechs[6]) // -> MongoDB
let lastIndex = webTechs.length - 1
console.log(webTechs[lastIndex]) // -> MongoDB
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
] // List of countries
console.log(countries) // -> all countries in array
console.log(countries[0]) // -> Albania
console.log(countries[10]) // -> Kenya
let lastIndex = countries.length - 1
console.log(countries[lastIndex]) // -> Kenya
const shoppingCart = [
'Milk',
'Mango',
'Tomato',
'Potato',
'Avocado',
'Meat',
'Eggs',
'Sugar',
] // List of food products
console.log(shoppingCart) // -> all shoppingCart in array
console.log(shoppingCart[0]) // -> Milk
console.log(shoppingCart[7]) // -> Sugar
let lastIndex = shoppingCart.length - 1
console.log(shoppingCart[lastIndex]) // -> Sugar
Modifying array element
An array is mutable(modifiable). Once an array is created, we can modify the contents of the array elements.
const numbers = [1, 2, 3, 4, 5]
numbers[0] = 10 // changing 1 at index 0 to 10
numbers[1] = 20 // changing 2 at index 1 to 20
console.log(numbers) // [10, 20, 3, 4, 5]
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
]
countries[0] = 'Afghanistan' // Replacing Albania by Afghanistan
let lastIndex = countries.length - 1
countries[lastIndex] = 'Korea' // Replacing Kenya by Korea
console.log(countries)
["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"]
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.
const arr = Array() // creates an an empty array
console.log(arr)
const eightEmptyValues = Array(8) // it creates eight empty values
console.log(eightEmptyValues) // [empty x 8]
Creating static values with fill
fill: Fill all the array elements with a static value
const arr = Array() // creates an an empty array
console.log(arr)
const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X'
console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X']
const eight0values = Array(8).fill(0) // it creates eight element values filled with '0'
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]
const four4values = Array(4).fill(4) // it creates 4 element values filled with '4'
console.log(four4values) // [4, 4, 4, 4]
Concatenating array using concat
concat:To concatenate two arrays.
const firstList = [1, 2, 3]
const secondList = [4, 5, 6]
const thirdList = firstList.concat(secondList)
console.log(thirdList) // [1, 2, 3, 4, 5, 6]
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables
const fruitsAndVegetables = fruits.concat(vegetables) // concatenate the two arrays
console.log(fruitsAndVegetables)
["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
Getting array length
Length:To know the size of the array
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.length) // -> 5 is 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.
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.indexOf(5)) // -> 4
console.log(numbers.indexOf(0)) // -> -1
console.log(numbers.indexOf(1)) // -> 0
console.log(numbers.indexOf(6)) // -> -1
Check an element if it exist in an array.
- Check items in a list
// let us check if a banana exist in the array
const fruits = ['banana', 'orange', 'mango', 'lemon']
let index = fruits.indexOf('banana') // 0
if (index != -1) {
console.log('This fruit does exist in the array')
} else {
console.log('This fruit does not exist in the array')
}
// This fruit does exist in the array
// we can use also ternary here
index != -1
? console.log('This fruit does exist in the array')
: console.log('This fruit does not exist in the array')
// let us check if a avocado exist in the array
let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
if (indexOfAvocado != -1) {
console.log('This fruit does exist in the array')
} else {
console.log('This fruit does not exist in the array')
}
// This fruit does not exist in the array
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.
const numbers = [1, 2, 3, 4, 5, 3, 1, 2]
console.log(numbers.lastIndexOf(2)) // 7
console.log(numbers.lastIndexOf(0)) // -1
console.log(numbers.lastIndexOf(1)) // 6
console.log(numbers.lastIndexOf(4)) // 3
console.log(numbers.lastIndexOf(6)) // -1
includes:To check if an item exist in an array. If it exist it returns the true else it returns false.
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.includes(5)) // true
console.log(numbers.includes(0)) // false
console.log(numbers.includes(1)) // true
console.log(numbers.includes(6)) // false
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
] // List of web technologies
console.log(webTechs.includes('Node')) // true
console.log(webTechs.includes('C')) // false
Checking array
Array.isArray:To check if the data type is an array
const numbers = [1, 2, 3, 4, 5]
console.log(Array.isArray(numbers)) // true
const number = 100
console.log(Array.isArray(number)) // false
Converting array to string
toString:Converts array to string
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.toString()) // 1,2,3,4,5
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook
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.
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.join()) // 1,2,3,4,5
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
console.log(names.join()) // Asabeneh,Mathias,Elias,Brook
console.log(names.join('')) //AsabenehMathiasEliasBrook
console.log(names.join(' ')) //Asabeneh Mathias Elias Brook
console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook
console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
] // List of web technologies
console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB"
console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB"
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.
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.slice()) // -> it copies all item
console.log(numbers.slice(0)) // -> it copies all item
console.log(numbers.slice(0, numbers.length)) // it copies all item
console.log(numbers.slice(1, 4)) // -> [2,3,4] // 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.
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice()) // -> remove all items
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice(0, 1)) // remove the first item
const numbers = [1, 2, 3, 4, 5, 6]
console.log(numbers.splice(3, 3, 7, 8, 9)) // -> [1, 2, 3, 7, 8, 9] //it removes three item and replace three items
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.
// syntax
const arr = ['item1', 'item2', 'item3']
arr.push('new item')
console.log(arr)
// ['item1', 'item2','item3','new item']
const numbers = [1, 2, 3, 4, 5]
numbers.push(6)
console.log(numbers) // -> [1,2,3,4,5,6]
numbers.pop() // -> remove one item from the end
console.log(numbers) // -> [1,2,3,4,5]
let fruits = ['banana', 'orange', 'mango', 'lemon']
fruits.push('apple')
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple']
fruits.push('lime')
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
Removing the end element using pop
pop: Removing item in the end.
const numbers = [1, 2, 3, 4, 5]
numbers.pop() // -> remove one item from the end
console.log(numbers) // -> [1,2,3,4]
Removing an element from the beginning
shift: Removing one array element in the beginning of the array.
const numbers = [1, 2, 3, 4, 5]
numbers.shift() // -> remove one item from the beginning
console.log(numbers) // -> [2,3,4,5]
Add an element from the beginning
unshift: Adding array element in the beginning of the array.
const numbers = [1, 2, 3, 4, 5]
numbers.unshift(0) // -> add one item from the beginning
console.log(numbers) // -> [0,1,2,3,4,5]
Reversing array order
reverse: reverse the order of an array.
const numbers = [1, 2, 3, 4, 5]
numbers.reverse() // -> reverse array order
console.log(numbers) // [5, 4, 3, 2, 1]
numbers.reverse()
console.log(numbers) // [1, 2, 3, 4, 5]
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.
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
]
webTechs.sort()
console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"]
webTechs.reverse() // after sorting we can reverse it
console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]
Array of arrays
Array can store different data types including an array itself. Let us create an array of arrays
const firstNums = [1, 2, 3]
const secondNums = [1, 4, 9]
const arrayOfArray = [
[1, 2, 3],
[1, 2, 3],
]
console.log(arrayOfArray[0]) // [1, 2, 3]
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
const backEnd = ['Node', 'Express', 'MongoDB']
const fullStack = [frontEnd, backEnd]
console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
console.log(fullStack.length) // 2
console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"]
console.log(fullStack[1]) // ["Node", "Express", "MongoDB"]
💻 Exercise
Exercise: Level 1
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
]
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
]
- 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
let text =
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
console.log(words)
console.log(words.length)["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
13 -
In the following shopping cart add, remove, edit items
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
- 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.
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
const backEnd = ['Node', 'Express', 'MongoDB']
console.log(fullStack)["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
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({}).
// syntax
if (condition) {
//this part of code runs for truthy condition
}
Example:
let num = 3
if (num > 0) {
console.log(`${num} is a positive number`)
}
// 3 is a positive number
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.
let isRaining = true
if (isRaining) {
console.log('Remember to take your rain coat.')
}
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.
// syntax
if (condition) {
// this part of code runs for truthy condition
} else {
// this part of code runs for false condition
}
let num = 3
if (num > 0) {
console.log(`${num} is a positive number`)
} else {
console.log(`${num} is a negative number`)
}
// 3 is a positive number
num = -3
if (num > 0) {
console.log(`${num} is a positive number`)
} else {
console.log(`${num} is a negative number`)
}
// -3 is a negative number
let isRaining = true
if (isRaining) {
console.log('You need a rain coat.')
} else {
console.log('No need for a rain coat.')
}
// You need a rain coat.
isRaining = false
if (isRaining) {
console.log('You need a rain coat.')
} else {
console.log('No need for a rain coat.')
}
// No need for a rain coat.
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.
// syntax
if (condition) {
// code
} else if (condition) {
// code
} else {
// code
}
Example:
let a = 0
if (a > 0) {
console.log(`${a} is a positive number`)
} else if (a < 0) {
console.log(`${a} is a negative number`)
} else if (a == 0) {
console.log(`${a} is zero`)
} else {
console.log(`${a} is not a number`)
}
// if else if else
let weather = 'sunny'
if (weather === 'rainy') {
console.log('You need a rain coat.')
} else if (weather === 'cloudy') {
console.log('It might be cold, you need a jacket.')
} else if (weather === 'sunny') {
console.log('Go out freely.')
} else {
console.log('No need for rain coat.')
}
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.
switch (caseValue) {
case 1:
// code
break
case 2:
// code
break
case 3:
// code
default:
// code
}
let weather = 'cloudy'
switch (weather) {
case 'rainy':
console.log('You need a rain coat.')
break
case 'cloudy':
console.log('It might be cold, you need a jacket.')
break
case 'sunny':
console.log('Go out freely.')
break
default:
console.log(' No need for rain coat.')
}
// Switch More Examples
let dayUserInput = prompt('What day is today ?')
let day = dayUserInput.toLowerCase()
switch (day) {
case 'monday':
console.log('Today is Monday')
break
case 'tuesday':
console.log('Today is Tuesday')
break
case 'wednesday':
console.log('Today is Wednesday')
break
case 'thursday':
console.log('Today is Thursday')
break
case 'friday':
console.log('Today is Friday')
break
case 'saturday':
console.log('Today is Saturday')
break
case 'sunday':
console.log('Today is Sunday')
break
default:
console.log('It is not a week day.')
}
// Examples to use conditions in the cases
let num = prompt('Enter number')
switch (true) {
case num > 0:
console.log('Number is positive')
break
case num == 0:
console.log('Numbers is zero')
break
case num < 0:
console.log('Number is negative')
break
default:
console.log('Entered value was not a number')
}
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.
let isRaining = true
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.')
💻 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.
Enter your age: 30
You are old enough to drive.
Enter your age:15
You are left with 3 years to drive. -
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.
Enter your age: 30
You are 5 years older than me. -
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.
let a = 4
let b = 34 is greater than 3
-
Even numbers are divisible by 2 and the remainder is zero. How do you check, if a number is even or not using JavaScript?
Enter a number: 2
2 is an even number
Enter a number: 9
9 is is an odd number.
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.
What is the day today? Saturday
Saturday is a weekend.
What is the day today? saturDaY
Saturday is a weekend.
What is the day today? Friday
Friday is a working day.
What is the day today? FrIDAy
Friday is a working day.
Exercises: Level 3
- Write a program which tells the number of days in a month.
Enter a month: January
January has 31 days.
Enter a month: JANUARY
January has 31 day
Enter a month: February
February has 28 days.
Enter a month: FEbruary
February has 28 days.
- 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
// for loop syntax
for (initialization, condition, increment/decrement) {
code goes here
}
This code prints from 0 to 5.
for (let i = 0; i < 6; i++) {
console.log(i)
}
For example if we want to sum all the numbers from 0 to 100.
let sum = 0
for (let i = 0; i < 101; i++) {
sum += i
}
console.log(sum)
If we want to sum only even numbers:
let sum = 0
for (let i = 0; i < 101; i += 2) {
sum += i
}
console.log(sum)
// or another way
let total = 0
for (let i = 0; i < 101; i++) {
if (i % 2 == 0) {
total += i
}
}
console.log(total)
This code iterates through the array
const nums = [1, 2, 3, 4, 5]
for (let i = 0; i < 6; i++) {
console.log(nums[i])
}
This code prints 5 to 0. Looping in reverse order
for (let i = 5; i >= 0; i--) {
console.log(i)
}
The Code below can reverse an array.
const nums = [1, 2, 3, 4, 5]
const lastIndex = nums.length - 1
const newArray = []
for (let i = lastIndex; i >= 0; i--) {
newArray.push(nums[i])
}
console.log(newArray)
2. while
We use the while loop when we do not know how man iteration we go in advance.
let count = prompt('Enter a positive number: ')
while (count > 0) {
console.log(count)
count--
}
3. do while
Do while run at least once if the condition is true or false
let count = 0
do {
console.log(count)
count++
} while (count < 11)
The code below runs ones though the condition is false
let count = 11
do {
console.log(count)
count++
} while (count < 11)
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.
const numbers = [1, 2, 3, 4, 5]
for (const number of numbers) {
console.log(number)
}
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
for (const country of countries) {
console.log(country.toUpperCase())
}
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.
const numbers = [1, 2, 3, 4, 5]
numbers.forEach((number, i) => {
console.log(number, i)
})
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
countries.forEach((country, i, arr) => {
console.log(i, country.toUpperCase())
})
6. for in
The for in loop can be used with object literals to get the keys of the object.
const user = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
skills: ['HTML', 'CSS', 'JS', 'React', 'Node', 'Python', 'D3.js'],
}
for (const key in user) {
console.log(key, user[key])
}
Interrupting a loop and skipping an item
break
Break is used to interrupt a loop.
for (let i = 0; i <= 5; i++) {
if (i == 3) {
break
}
console.log(i)
}
// 0 1 2
The above code stops if 3 found in the iteration process.
continue
We use the keyword continue to skip a certain iterations.
for (let i = 0; i <= 5; i++) {
if (i == 3) {
continue
}
console.log(i)
}
// 0 1 2 4 5
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.
//scope.js
a = 'JavaScript' // is a window scope this found anywhere
b = 10 // this is a window scope variable
function letsLearnScope() {
console.log(a, b)
if (true) {
console.log(a, b)
}
}
console.log(a, b) // accessible
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.
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
if (true) {
let a = 'Python'
let b = 100
console.log(a, b) // Python 100
}
console.log(a, b)
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
Local scope
A variable declared as local can be accessed only in certain block code.
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let c = 30
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
let a = 'Python'
let b = 20
let d = 40
console.log(a, b, c) // Python 20 30
}
// we can not access c because c's scope is only the if block
console.log(a, b) // JavaScript 10
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
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 ({}).
//scope.js
function letsLearnScope() {
var gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true) {
var gravity = 9.81
console.log(gravity) // 9.81
}
console.log(gravity) // 9.81
for (var i = 0; i < 3; i++) {
console.log(i) // 1, 2, 3
}
console.log(i)
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.
//scope.js
function letsLearnScope() {
// you can use let or const, but gravity is constant I prefer to use const
const gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true) {
const gravity = 9.81
console.log(gravity) // 9.81
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
for (let i = 0; i < 3; i++) {
console.log(i) // 1, 2, 3
}
// console.log(i), Uncaught ReferenceError: gravity is not defined
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
const person = {}
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.
const rectangle = {
length: 20,
width: 20,
}
console.log(rectangle) // {length: 20, width: 20}
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js',
],
isMarried: true,
}
console.log(person)
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
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js',
],
getFullName: function () {
return `${this.firstName}${this.lastName}`
},
'phone number': '+3584545454545',
}
// accessing values using .
console.log(person.firstName)
console.log(person.lastName)
console.log(person.age)
console.log(person.location)
// value can be accessed using square bracket and key name
console.log(person['firstName'])
console.log(person['lastName'])
console.log(person['age'])
console.log(person['age'])
console.log(person['location'])
// for instance to access the phone number we only use the square bracket method
console.log(person['phone number'])
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:
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js',
],
getFullName: function () {
return `${this.firstName} ${this.lastName}`
},
}
console.log(person.getFullName())
// Asabeneh Yetayeh
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
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js',
],
getFullName: function () {
return `${this.firstName} ${this.lastName}`
},
}
person.nationality = 'Ethiopian'
person.country = 'Finland'
person.title = 'teacher'
person.skills.push('Meteor')
person.skills.push('SasS')
person.isMarried = true
person.getPersonInfo = function () {
let skillsWithoutLastSkill = this.skills
.slice(0, this.skills.length - 1)
.join(', ')
let lastSkill = this.skills.slice(this.skills.length - 1)[0]
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
let fullName = this.getFullName()
let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.`
return statement
}
console.log(person)
console.log(person.getPersonInfo())
Asabeneh Yetayeh is a teacher.
He lives in Finland.
He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS.
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
const person = {
firstName: 'Asabeneh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: ['HTML', 'CSS', 'JS'],
title: 'teacher',
address: {
street: 'Heitamienkatu 16',
pobox: 2002,
city: 'Helsinki',
},
getPersonInfo: function () {
return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.`
},
}
//Object methods: Object.assign, Object.keys, Object.values, Object.entries
//hasOwnProperty
const copyPerson = Object.assign({}, person)
console.log(copyPerson)
Getting object keys using Object.keys()
Object.keys: To get the keys or properties of an object as an array
const keys = Object.keys(copyPerson)
console.log(keys) //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']
const address = Object.keys(copyPerson.address)
console.log(address) //['street', 'pobox', 'city']
Getting object values using Object.values()
Object.values:To get values of an object as an array
const values = Object.values(copyPerson)
console.log(values)
Getting object keys and values using Object.entries()
Object.entries:To get the keys and values in an array
const entries = Object.entries(copyPerson)
console.log(entries)
Checking properties using hasOwnProperty()
hasOwnProperty: To check if a specific key or property exist in an object
console.log(copyPerson.hasOwnProperty('name'))
console.log(copyPerson.hasOwnProperty('score'))
🌕 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.
const users = {
Alex: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
points: 50
},
Thomas: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
},
Paul: {
email: '[email protected]',
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
age: 20,
isLoggedIn: false,
points: 40
}
}``` -
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 ()
const users = [
{
_id: 'ab12ex',
username: 'Alex',
email: '[email protected]',
password: '123123',
createdAt: '08/01/2020 9:00 AM',
isLoggedIn: false,
},
{
_id: 'fg12cy',
username: 'Asab',
email: '[email protected]',
password: '123456',
createdAt: '08/01/2020 9:30 AM',
isLoggedIn: true,
},
{
_id: 'zwf8md',
username: 'Brook',
email: '[email protected]',
password: '123111',
createdAt: '08/01/2020 9:45 AM',
isLoggedIn: true,
},
{
_id: 'eefamr',
username: 'Martha',
email: '[email protected]',
password: '123222',
createdAt: '08/01/2020 9:50 AM',
isLoggedIn: false,
},
{
_id: 'ghderc',
username: 'Thomas',
email: '[email protected]',
password: '123333',
createdAt: '08/01/2020 10:00 AM',
isLoggedIn: false,
},
]
const products = [
{
_id: 'eedfcf',
name: 'mobile phone',
description: 'Huawei Honor',
price: 200,
ratings: [
{ userId: 'fg12cy', rate: 5 },
{ userId: 'zwf8md', rate: 4.5 },
],
likes: [],
},
{
_id: 'aegfal',
name: 'Laptop',
description: 'MacPro: System Darwin',
price: 2500,
ratings: [],
likes: ['fg12cy'],
},
{
_id: 'hedfcg',
name: 'TV',
description: 'Smart TV:Procaster',
price: 400,
ratings: [{ userId: 'fg12cy', rate: 5 }],
likes: ['fg12cy'],
},
]
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.
//declaring a function without a parameter
function functionName() {
// code goes here
}
functionName() // calling function by its name and with parentheses
Function without a parameter and return
Function can be declared without a parameter.
Example:
// function without parameter, a function which make a number square
function square() {
let num = 2
let sq = num * num
console.log(sq)
}
square() // 4
// function without parameter
function addTwoNumbers() {
let numOne = 10
let numTwo = 20
let sum = numOne + numTwo
console.log(sum)
}
addTwoNumbers() // a function has to be called by its name to be executed
function printFullName() {
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
console.log(fullName)
}
printFullName() // calling a function
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 printFullName() {
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(printFullName())
function addTwoNumbers() {
let numOne = 2
let numTwo = 3
let total = numOne + numTwo
return total
}
console.log(addTwoNumbers())
Function with a parameter
In a function we can pass different data types(number, string, boolean, object, function) as a parameter.
// function with one parameter
function functionName(parm1) {
//code goes her
}
functionName(parm1) // during calling or invoking one argument needed
function areaOfCircle(r) {
let area = Math.PI * r * r
return area
}
console.log(areaOfCircle(10)) // should be called with one argument
function square(number) {
return number * number
}
console.log(square(10))
Function with two parameters
// function with two parameters
function functionName(parm1, parm2) {
//code goes her
}
functionName(parm1, parm2) // during calling or invoking two arguments needed
// Function without parameter doesn't take input, so lets make a function with parameters
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
console.log(sum)
}
sumTwoNumbers(10, 20) // calling functions
// If a function doesn't return it doesn't store data, so it should return
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
return sum
}
console.log(sumTwoNumbers(10, 20))
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'))
Function with many parameters
// function with multiple parameters
function functionName(parm1, parm2, parm3,...){
//code goes here
}
functionName(parm1,parm2,parm3,...) // during calling or invoking three arguments needed
// this function takes array as a parameter and sum up the numbers in the array
function sumArrayValues(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
const numbers = [1, 2, 3, 4, 5];
//calling a function
console.log(sumArrayValues(numbers));
const areaOfCircle = (radius) => {
let area = Math.PI * radius * radius;
return area;
}
console.log(areaOfCircle(10))
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
// Let us access the arguments object
function sumAllNums() {
console.log(arguments)
}
sumAllNums(1, 2, 3, 4))
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// function declaration
function sumAllNums() {
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173