https://github.com/asabeneh/javascript-for-everyone
A step by step guide to learn JavaScript and programming. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
https://github.com/asabeneh/javascript-for-everyone
30daysofjavascript 30daysofreact arrays arrow-functions cookies dom es5 es6 es7 functional-programming javascript javascript-for-everyone js-challenges js-questions js-quiz localstorage webdesign
Last synced: about 1 year ago
JSON representation
A step by step guide to learn JavaScript and programming. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
- Host: GitHub
- URL: https://github.com/asabeneh/javascript-for-everyone
- Owner: Asabeneh
- Created: 2019-02-19T22:57:53.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-08-25T08:50:42.000Z (almost 3 years ago)
- Last Synced: 2025-04-08T12:04:10.589Z (about 1 year ago)
- Topics: 30daysofjavascript, 30daysofreact, arrays, arrow-functions, cookies, dom, es5, es6, es7, functional-programming, javascript, javascript-for-everyone, js-challenges, js-questions, js-quiz, localstorage, webdesign
- Language: JavaScript
- Homepage:
- Size: 9.06 MB
- Stars: 1,139
- Watchers: 51
- Forks: 297
- Open Issues: 3
-
Metadata Files:
- Readme: readMe.md
Awesome Lists containing this project
README

- [Introduction](#introduction)
- [Setup](#setup)
- [Requirements](#requirements)
- [Setup](#setup-1)
- [Install Node.js](#install-nodejs)
- [Browser](#browser)
- [Installing Google Chrome](#installing-google-chrome)
- [Opening Google Chrome Console](#opening-google-chrome-console)
- [Writing Code on browser Console](#writing-code-on-browser-console)
- [Console.log](#consolelog)
- [Console.log with multiple arguments](#consolelog-with-multiple-arguments)
- [Comment](#comment)
- [Syntax](#syntax)
- [Arithmetics](#arithmetics)
- [Code Editor](#code-editor)
- [Installing Visual Studio Code](#installing-visual-studio-code)
- [How to use visual studio code](#how-to-use-visual-studio-code)
- [Adding JavaScript to a web page](#adding-javascript-to-a-web-page)
- [Inline Script](#inline-script)
- [Internal script](#internal-script)
- [External script](#external-script)
- [Exercises:Setting Up your machine](#exercisessetting-up-your-machine)
- [Variables](#variables)
- [Exercise - 1 : Variables](#exercise---1--variables)
- [Comments](#comments)
- [Exercise: Comments](#exercise-comments)
- [Data types](#data-types)
- [Primitive Data Types](#primitive-data-types)
- [Non-Primitive Data Types](#non-primitive-data-types)
- [Numbers](#numbers)
- [Declaring number data types](#declaring-number-data-types)
- [Math Object](#math-object)
- [Random number generator](#random-number-generator)
- [Strings](#strings)
- [String Concatenation](#string-concatenation)
- [Concatenating using addition operator](#concatenating-using-addition-operator)
- [Long Literal Strings](#long-literal-strings)
- [Escape Sequences in string](#escape-sequences-in-string)
- [Template Literals(Template Strings)](#template-literalstemplate-strings)
- [String Methods](#string-methods)
- [Checking Data types and Casting](#checking-data-types-and-casting)
- [Checking data types](#checking-data-types)
- [Changing data type(Casting)](#changing-data-typecasting)
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [Exercises: Data Types](#exercises-data-types)
- [Exercise: String](#exercise-string)
- [Booleans](#booleans)
- [Exercise: Booleans](#exercise-booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Exercise - 6 : Data types](#exercise---6--data-types)
- [Operators](#operators)
- [Arithmetic Operators](#arithmetic-operators)
- [Exercises : Arithmetic Operators](#exercises--arithmetic-operators)
- [Logical Operators](#logical-operators)
- [Exercises: Logical Operators](#exercises-logical-operators)
- [Comparison Operators](#comparison-operators)
- [Exercise: Comparison Operators](#exercise-comparison-operators)
- [Conditionals](#conditionals)
- [if](#if)
- [if else](#if-else)
- [if else if else](#if-else-if-else)
- [switch](#switch)
- [Ternary Operators](#ternary-operators)
- [Exercise: Conditionals](#exercise-conditionals)
- [While loop](#while-loop)
- [Do while loop](#do-while-loop)
- [Exercises:Loops](#exercisesloops)
- [Arrays](#arrays)
- [Exercise : Arrays](#exercise--arrays)
- [More on Arrays](#more-on-arrays)
- [Exercise -10 : Array Methods](#exercise--10--array-methods)
- [Functions](#functions)
- [Function Declaration](#function-declaration)
- [Function Expression](#function-expression)
- [Anonymous Function](#anonymous-function)
- [Arrow Function](#arrow-function)
- [Arrow Function vs Declaration Function](#arrow-function-vs-declaration-function)
- [Exercise - 10 : Functions](#exercise---10--functions)
- [Object](#object)
- [Object Methods](#object-methods)
- [Date Object](#date-object)
- [Exercises: Date Object](#exercises-date-object)
- [Exercises:Objects](#exercisesobjects)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [Returning function](#returning-function)
- [setting time](#setting-time)
- [setInterval](#setinterval)
- [setTimeout](#settimeout)
- [Exercises Level 3](#exercises-level-3)
- [Functional Programming](#functional-programming)
- [Exercises](#exercises-1)
- [Destructuring and Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing--arrays)
- [Destructuring Object](#destructuring-object)
- [Renaming during structuring](#renaming-during-structuring)
- [Spread or Rest Operator](#spread-or-rest-operator)
- [Exercise: Destructuring](#exercise-destructuring)
- [Map and Set](#map-and-set)
- [Set](#set)
- [Creating a set](#creating-a-set)
- [Adding an element to a set](#adding-an-element-to-a-set)
- [Deleting an element a set](#deleting-an-element-a-set)
- [Checking an element in the set](#checking-an-element-in-the-set)
- [Clearing the set](#clearing-the-set)
- [Set](#set-1)
- [Creating an empty set](#creating-an-empty-set)
- [Creating set from array](#creating-set-from-array)
- [Adding an element to a set](#adding-an-element-to-a-set-1)
- [Deleting an element a set](#deleting-an-element-a-set-1)
- [Checking an element in the set](#checking-an-element-in-the-set-1)
- [Clearing the set](#clearing-the-set-1)
- [Union of sets](#union-of-sets)
- [Intersection of sets](#intersection-of-sets)
- [Difference of sets](#difference-of-sets)
- [Map](#map)
- [Creating an empty Map](#creating-an-empty-map)
- [Creating an Map from array](#creating-an-map-from-array)
- [Adding values to the Map](#adding-values-to-the-map)
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises: Set and Map](#exercises-set-and-map)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
- [Document Object Model (DOM)](#document-object-model-dom)
- [Getting Element](#getting-element)
- [Getting elements by tag name](#getting-elements-by-tag-name)
- [Getting elements by class name](#getting-elements-by-class-name)
- [Getting an element by id](#getting-an-element-by-id)
- [Getting elements by using querySelector using tag, class and id:](#getting-elements-by-using-queryselector-using-tag-class-and-id)
- [Adding attribute](#adding-attribute)
- [Adding attribute using setAttribute](#adding-attribute-using-setattribute)
- [Adding attribute without setAttribute](#adding-attribute-without-setattribute)
- [Adding class using classList](#adding-class-using-classlist)
- [Adding Text content](#adding-text-content)
- [Adding style](#adding-style)
- [Creating an Element](#creating-an-element)
- [Creating elements](#creating-elements)
- [Appending to a parent element](#appending-to-a-parent-element)
- [Event Listeners](#event-listeners)
- [Getting value from an input element](#getting-value-from-an-input-element)
- [Exercises:Document Object Model](#exercisesdocument-object-model)
- [DOM: Mini Projects](#dom-mini-projects)
- [Classes](#classes)
- [Defining a classes](#defining-a-classes)
- [Class Instantiation](#class-instantiation)
- [Class Constructor](#class-constructor)
- [Default values with constructor](#default-values-with-constructor)
- [Class methods](#class-methods)
- [Properties with initial value](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Static method](#static-method)
- [Inheritance](#inheritance)
- [Overriding methods](#overriding-methods)
- [Exercises](#exercises-2)
- [Exercises Level 1](#exercises-level-1-1)
- [Exercises Level 2](#exercises-level-2-1)
- [Exercises Level 3](#exercises-level-3-1)
- [Regular Expressions](#regular-expressions)
- [RegEx parameters](#regex-parameters)
- [Pattern](#pattern)
- [Flags](#flags)
- [Creating a pattern with RegEx Constructor](#creating-a-pattern-with-regex-constructor)
- [Creating a pattern without RegEx Constructor](#creating-a-pattern-without-regex-constructor)
- [RegExp Object Methods](#regexp-object-methods)
- [Testing for a match](#testing-for--a-match)
- [Array containing all of the match](#array-containing-all-of-the-match)
- [Replacing a substring](#replacing-a-substring)
- [Square Bracket](#square-bracket)
- [Escape character(\\) in RegEx](#escape-character-in-regex)
- [One or more times(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero or more times(*)](#zero-or-more-times)
- [Zero or one times(?)](#zero-or-one-times)
- [Quantifier in RegEx](#quantifier-in-regex)
- [Cart ^](#cart-)
- [Exact match](#exact-match)
- [đź’» Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1-2)
- [Exercises: Level 2](#exercises-level-2-2)
- [Exercises: Level 3](#exercises-level-3-2)
- [Async and Await](#async-and-await)
- [localStorage](#localstorage)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises:Local Storage](#exerciseslocal-storage)
- [Cookies](#cookies)
- [Exercises:Cookies](#exercisescookies)
- [JavaScript Interview Questions](#javascript-interview-questions)
- [JavaScript Tests](#javascript-tests)
- [JavaScript Test 1](#javascript-test-1)
- [JavaScript Test 2](#javascript-test-2)
- [JavaScript Test 3](#javascript-test-3)
## Introduction
**_JavaScript for Everyone_** is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript. **_Congratulations_** for deciding to learn JavaScript, the language of the browser.
In this step by step tutorial, you will learn JavaScript, the most popular programming language in the history of mankind.
You use JavaScript **_to add interactivity to websites, to develop mobile apps, desktop applications, games_** and nowadays JavaScript can be used for **_machine learning_** and **_AI_**.
**_JavaScript (JS)_** has increased in popularity in recent years and has been the leading
programming language for four consecutive years and is the most used programming language on
Github.
## Setup
First thing first, lets install text or code editor. Install code editor, it could be [vscode](https://code.visualstudio.com/), [atom](https://atom.io/), [bracket](http://brackets.io/), [notepad++](https://notepad-plus-plus.org/) or others. I recommend vscode.
Install either [Chrome](https://www.google.com/chrome/) or [Firefox](https://www.mozilla.org/en-US/firefox/new/?v=b) if you didn't have yet.
If you want help, you may join the [telegram](https://t.me/JavaScriptforEveryone) channel.
## Requirements
No prior knowledge of programming is required to follow this guide. You need only:
1. Motivation
2. Computer
3. Internet
4. Browser
5. Code Editor
## Setup
I believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything.
### Install Node.js
You may not need it right now but you may need it for later. Install [node.js](https://nodejs.org/en/).

After downloading double click and install

We can check if node is installed in our local machine by opening our device terminal or command prompt.
```sh
asabeneh $ node -v
v12.14.0
```
I am using node version 12.14.0, which is the recommended version of node.
### Browser
There are many browsers out there. However, I strongly recommend Google Chrome.
#### Installing Google Chrome
Install [google chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications.

#### Opening Google Chrome Console
You can open Google Chrome either by clicking three dots at the top right corner of the Chrome browser or using a shortcut. I prefer using shortcuts.

To open the Chrome console using a short cut.
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I
```

After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console part. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code.
Let us write a JavaScript code on the Google Chrome console:

#### Writing Code on browser Console
We can write any JavaScript code on the Google console or any browser console. However, for this challenge, we only focus on Google Chrome console. Open the console using:
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I
```
##### Console.log
To write our first JavaScript code, we used a builtin function **console.log()**. We passed an argument as input data, and the function displays the output. We passed 'Hello, World' as input data or argument in the console.log() function.
```js
console.log('Hello, World!')
```
##### Console.log with multiple arguments
The console.log(param1, param2, param3), can take multiple arguments.

```js
console.log('Hello', 'World', '!')
console.log('HAPPY', 'NEW', 'YEAR', 2020)
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')
```
As you can see from the above snippet code, *console.log()* can take multiple arguments.
Congratulations! You wrote your first JavaScript code using *console.log()*.
##### Comment
We add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. Any text starts with // in JavaScript is a comment or anything enclose like this /* */ is a comment.
**Example: Single Line Comment**
// This is the first comment
// This is the second comment
// I am a single line comment
**Example: Multiline Comment**
/*
This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
*/
##### Syntax
JavaScript is a programming language. As a result, it has its syntax like other programming languages. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors.

I made a deliberate mistake. As a result, the console raises a syntax error. Actually, the syntax is very informative. It informs what type of mistake we made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors:
```js
console.log("Hello, World!")
console.log('Hello, World!')
```
So far, we saw how to display text using a *console.log()*. If we are printing text or string using *console.log()*, the text has to be under the single, double, or backtick.
**Example:**
```js
console.log("Hello, World!")
console.log('Hello, World!')
console.log(`Hello, World!`)
```
#### Arithmetics
Now, let us practice more writing JavaScript codes using *console.log()* on google chrome console for number data types.
In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.

```js
console.log(2 + 3) // Addition
console.log(3 - 2) // Subtraction
console.log(2 * 3) // Multiplication
console.log(3 / 2) // Division
console.log(3 % 2) // Modulus - finding remainder
console.log(3 ** 2) // Exponential
```
### Code Editor
We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days python JavaScript challenge, we will use visual studio code.
#### Installing Visual Studio Code
Visual studio code is a very popular open-source text editor. I would recommend to [download](https://code.visualstudio.com/) visual studio code, but if you are in favor of other editors, feel free to follow with what you have.

If you installed visual studio code, let us start using it.
#### How to use visual studio code
Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.






### Adding JavaScript to a web page
JavaScript can be added to a web page in three ways:
- **_Inline script_**
- **_Internal script_**
- **_External script_**
The following sections show different ways of adding JavaScript code to your web page.
#### Inline Script
Create a folder on your desktop or in any location and create an **_index.html_** file in your folder. Then paste the following code and open it in a browser, either in [Chrome](https://www.google.com/chrome/) or [Firefox](https://www.mozilla.org/en-US/firefox/new/?v=b).
```html
JavaScript for Everyone
Click Me
```
#### Internal script
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.
- Internal script at the head
```html
JavaScript for Everyone
console.log("Welcome to JavaScript for Everyone");
```
- Internal script at the body
```html
JavaScript for Everyone
console.log("Welcome to JavaScript for Everyone");
```
#### External script
The external script link can be on the head or body but it is preferred to put it in the body.
- External script at the head
```html
JavaScript for Everyone
JavaScript for Everyone
//it could be in the header or in the body
// Here is the recommended place to put the script
b}`)
```
```sh
2 is greater than 3: false
```
### String Methods
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
1. *length*: The string *length* method returns the number of characters in a string included empty space.
**Example:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string.

Let us access different characters in 'JavaScript' string.
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: this method changes the string to uppercase letters.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: this method changes the string to lowercase letters.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*: It takes two arguments, the starting index and number of characters to slice.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index.
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*: The split method splits a string at a specified place.
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // ["30 Days Of JavaScript"]
console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // ["Asabeneh"]
console.log(firstName.split('')) // ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) // Â ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Removes trailing space in the beginning or the end of a string.
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim())
```
```sh
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
```
9. *includes()*: It takes a substring argument and it check if substring argument exists in the string. *includes()* returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist.
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
```
10. *replace()*: takes to parameter the old substring and new substring.
```js
string.replace(oldsubstring, newsubstring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Takes index and it returns the value at that index
```js
string.charAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*: Takes index and it returns char code(ASCII number) of the value at that index
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII number is 51
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
```
13. *indexOf()*: Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
```js
string.indexOf(substring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*: Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: it takes many substrings and creates concatenation.
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in this world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*: it takes a substring as an argument and it returns the index of the first match.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
```
19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
```js
let string = 'love'
let patternOne = /love/ // with out any flag
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
```
Match syntax
```js
// syntax
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Let us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section.
```js
let txt = 'In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge'
let regEx = /\d+/
// d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: it takes a number argument and it returned the repeated version of the string.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Checking Data types and Casting
### Checking data types
- Check Data types: To check the data type of a certain data type we use the _typeof_ and we also change one data type to another.
**Example:**
```js
// Different javascript data types
// Let's declare different data types
let firstName = 'Asabeneh' // string
let lastName = 'Yetayeh' // string
let country = 'Finland' // string
let city = 'Helsinki' // string
let age = 250 // number, it is not my real age, do not worry about it
let job // undefined, because a value was not assigned
console.log(typeof 'Asabeneh') // string
console.log(typeof firstName) // string
console.log(typeof 10) // number
console.log(typeof 3.14) // number
console.log(typeof true) // boolean
console.log(typeof false) // boolean
console.log(typeof NaN) // number
console.log(typeof job) // undefined
console.log(typeof undefined) // undefined
console.log(typeof null) // object
```
### Changing data type(Casting)
- Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
#### String to Int
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
We can convert string to number using the following methods:
- parseInt()
- Number()
- Plus sign(+)
```js
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = Number(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = +num
console.log(numInt) // 10
```
#### String to Float
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
We can convert string float to number using the following methods:
- parseFloat()
- Number()
- Plus sign(+)
```js
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = +num
console.log(numInt) // 9.81
```
#### Float to Int
We can convert float numbers to integers.
We use the following method to convert float to int:
- parseInt()
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
### Exercises: Data Types
1. Declare variables and assign string, boolean, undefined and null data types
1. The JavaScript ***typeof*** operator uses to check different data types. Check the data type of each variables from question number 1.
#### Exercise: String
1. Declare a variable name company and assign it to an initial value **'Coding Academy'**.
1. Print the string on the browser console using __console.log()__
1. Print the __length__ of the string on the browser console using _console.log()_
1. Change all the string to capital letters using __toUpperCase()__ method
1. Change all the string to lowercase letters using __toLowerCase()__ method
1. Cut(slice) out the first word of the string using __slice__, __substr()__ or __substring()__ method
1. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
1. Check if the string contains a word __Academy__ using __includes()__ method
1. Split the __string__ into __array__ using __split()__ method
1. Split the string Coding Academy at the space using __split()__ method
1. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
1. Change Coding Academy to Microsoft Academy using __replace()__ method.
1. What is character at index 10 in 'Coding Academy' string use __charAt()__ method.
1. What is the character code of A in 'Coding Academy' string using __charCodeAt()__
1. Use __indexOf__ to determine the position of the first occurrence of c in Coding Academy
1. Use __lastIndexOf__ to determine the position of the last occurrence of c in Coding Academy.
1. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
1. Use __lastIndexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
1. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
1. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' Coding Academy '.
1. Use __startsWith()__ method with the string Coding Academy make the result true
1. Use __endsWith()__ method with the string Coding Academy make the result true
1. Use __match()__ method to find all the c’s in Coding Academy
1. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
1. Use __concat()__ and merge 'Coding' and 'Academy' to a single string, 'Coding Academy'
1. Use __repeat()__ method to print Coding Academy 5 times
1. Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
### Booleans
Boolean value is either true or false. Any comparisons return a boolean value which is either true or false.
```js
let isLightOn = true;
let isRaining = false;
let hungry = false;
let isMarried = true;
```
#### Exercise: Booleans
Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
1. Write three JavaScript statement which provide falsy value.
1. Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===.
Which are true or which are false ?
1. 4 > 3
1. 4 >= 3
1. 4 < 3
1. 4 <= 3
1. 4 == 4
1. 4 === 4
1. 4 != 4
1. 4 !== 4
1. 4 != '4'
1. 4 == '4'
1. 4 === '4'
### Undefined
```js
let firstName;
console.log(firstName); //not defined, because it is not assigned to a value yet
```
### Null
```js
let empty = null;
console.log(empty); // -> null , means no value
```
### Exercise - 6 : Data types
String, number, boolean, null, undefined and symbol(ES6) are JavaScript primitive data types.
1. The JavaScript *typeof* operator uses to check different data types. Check the data type of each variables from question number 1.
## Operators
### Arithmetic Operators
Arithmetic operators are mathematical operators:+, -, _, /, _
```js
let numOne = 4;
let numTwo = 3;
let sum = numOne + numTwo;
let diff = numOne - numTwo;
let mult = numOne * numTwo;
let div = numOne / numTwo;
let remainder = numOne % numTwo;
console.log(sum, diff, mult, div, remainder); // ->7,1,12,1.33,1
let PI = 3.14;
let radius = 100; // length in meter
const gravity = 9.81; // in m/s2
let mass = 72; // in Kilogram
const boilingPoint = 100; // temperature in oC, boiling point of water
const bodyTemp = 37; // body temperature in oC
// Lets calculate area of a circle
const areaOfCircle = PI * radius * radius;
console.log(areaOfCircle); // -> 314 m
// Lets calculate weight of a substance
const weight = mass * gravity;
console.log(weight); // -> 706.32 N(Newton)
// ConcatEnating string with numbers using string interpolation
/*
The boiling point of water is 100 oC.
Human body temperature is 37 oC.
The gravity of earth is 9.81 m/s2.
*/
console.log(
`The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${body} oC.\nThe gravity of earth is ${gravity} m / s2.`
);
```
### Exercises : Arithmetic Operators
JavaScript arithmetic operators are addition(+), subtraction(-), multiplication(\*), division(/), modulus(%), increment(++) and decrement(--).
```js
let operandOne = 4;
let operandTwo = 3;
```
Using the above operands apply different JavaScript arithmetic operators
### Logical Operators
The following symbols are the common logical operators:
&&(ampersand) , ||(pipe) and !(negation).
&& gets true only if the two operands are true.
|| gets true either of the operand is true.
! negates true to false, false to true.
```js
// && ampersand example
const check = 4 > 3 && 10 > 5; // true and true -> true
const check = 4 > 3 && 10 < 5; // true and false -> false
const check = 4 < 3 && 10 < 5; // false and false -> false
// || pipe or, example
const check = 4 > 3 || 10 > 5; // true and true -> true
const check = 4 > 3 || 10 < 5; // true and false -> true
const check = 4 < 3 || 10 < 5; // false and false -> false
// ! Negation examples
let check = 4 > 3; // -> true
let check = !(4 > 3); // -> false
let isLightOn = true; // -> true
let isLightOff = !isLightOn; // -> false
let isMarried = !false; // -> true
```
### Exercises: Logical Operators
Which are true or which are false ?
1. 4 > 3 && 10 < 12
1. 4 > 3 && 10 > 12
1. 4 > 3 || 10 < 12
1. 4 > 3 || 10 > 12
1. !(4 > 3)
1. !(4 < 3)
1. !(false)
1. !(4 > 3 && 10 < 12)
1. !(4 > 3 && 10 > 12)
1. !(4 === '4')
### Comparison Operators
```js
4 > 3;
4 >= 4;
4 < 3;
4 <= 3;
4 != 3;
4 !== '4';
4 == '4';
4 === '4';
4 === 4;
```
### Exercise: Comparison Operators
Boolean value is either true or false. Any comparison return a boolean either true or false.
Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===.
Which are true or which are false ?
1. 4 > 3
1. 4 >= 3
1. 4 < 3
1. 4 <= 3
1. 4 == 4
1. 4 === 4
1. 4 != 4
1. 4 !== 4
1. 4 != '4'
1. 4 == '4'
1. 4 === '4'
## Conditionals
### if
We use if condition to check only on condition.
```js
if (condition) {
// code goes here
}
let isRaining = true;
if (isRaining) {
console.log('Remember to take your rain coat.');
}
```
### if else
When we have more than one condition we use the if and else condition.
```js
if (condition) {
// if the condition meets, this block of code runs
} else {
// if condition doesn't meet, this block code runs
}
let isRaining = true;
if (isRaining) {
console.log('You need a rain coat.');
} else {
console.log('No need for a rain coat.');
}
```
### if else if else
Whenever we have multiple conditions.
```js
// 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 an alternative for if else if else
```js
var 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.');
break;
}
// Switch More Examples
var dayUserInput = prompt('What day is it ?');
var 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.');
break;
}
```
### Ternary Operators
Another way to write conditionals is using ternary operators.
```js
let isRaining = true;
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.');
```
### Exercise: Conditionals
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 feedback to wait for the years he supposed to wait for.
Output:
```sh
Enter your age: 30
You are old enough to drive.
```
Output:
```sh
Enter your age:15
You are left with 3 years to drive.
```
1. Compare the values of myAge and yourAge using if … else. Based on the comparison log to console who is older (me or you). Use prompt(“Enter your age:”) to get the age as input.
Output:
```sh
Enter your age: 30
You are 5 years older than me.
```
1. If a is greater than b return a is greater than b else a is less than b.
Output:
```sh
let a = 4
let b = 3
4 is greater than 3
```
1. Write a code which give grade students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0 -49, F
1. 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
## Loops
In programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.
### For Loop
```js
// for loop structure
for(initialization, condition, increment/decrement){
// code goes here
}
for(let i = 0; i <= 5; i++){
console.log(i)
}
```
### While loop
```js
let i = 0;
while (i <= 5) {
console.log(i);
i++;
}
```
### Do while loop
```js
let i = 0;
do {
console.log(i);
i++;
} while (i <= 5);
```
### Exercises:Loops
1. Iterate 0 to 10 using for loop, do the same using while and do while loop.
1. Iterate 10 to 0 using for loop, do the same using while and do while loop.
1. Write a loop that makes seven calls to console.log to output the following triangle:
```js
#
##
###
####
#####
######
#######
```
1. Iterate the array, ['HTML', 'CSS', 'JavaScript'] using a for loop and print out the items.
1. Use for loop to iterate from 0 to 100 and print only even numbers
1. Use for loop to iterate from 0 to 100 and print only odd numbers
1. Use for loop to iterate from 0 to 100 and print and print the sum of all numbers.
```js
The sum all numbers is 5050.
```
1. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
```js
The sum of all evens is 2550. And the sum of all odds is 2500.
```
## Arrays
In contrast to variables 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 last element is less by one from the length of the array.
```js
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
```
### Exercise : Arrays
1. Declare an _empty_ array;
1. Declare an array with more than 5 number of items
1. Find the length of your array
1. Get the first item, the middle item and the last item of the array
1. Declare an array called _mixedDataTypes_,put different data types and in your array and the array size should be greater than 5
1. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.
1. Print the array using _console.log()_
1. Print the number of companies in the array
1. Print the first company, middle and last company
1. Print out each company
1. Change companies to uppercase and print them out
1. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
1. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is _not found_.
1. Filter out companies which have more than one 'o' without the filter method
1. Sort the array using _sort()_ method
1. Reverse the array without _reverse_ method
1. Reverse the array using _reverse()_ method
1. Slice out the first 3 companies from the array
1. Slice out the last 3 companies from the array
1. Slice out the middle IT company or companies from the array
1. Remove the first IT company from the array
1. Remove the middle IT company or companies from the array
1. Remove the last IT company from the array
1. Remove all IT companies
## More on Arrays
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:To create an array.
```js
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]
```
- *fill*: Fill all the array elements with a static value
```js
const arr = Array(); // creates an an empty array
console.log(arr);
const eightXvalues = Array(8).fill('X'); // it creates eight element values
console.log(eightXvalues); // ['X', 'X','X','X','X','X','X','X']
```
- *concat*: To concatenate two arrays.
```js
const firstList = [1, 2, 3];
const secondList = [4, 5, 6];
const thirdList = firstList.concat(secondList);
console.log(thirdList); // [1,2,3,4,5,6]
```
- *length*: To know the size of the array
```js
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.length); // -> 5
```
- *indexOf*: To check if an item exist in an array. If it exist it returns the index else it returns -1.
```js
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
```
- *lastIndexOf* :Give the position of the last item in the array. If it exist it returns the index else it returns -1.
```js
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.
```js
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
```
- *isArray*: To check if the data type is an array
```js
const numbers = [1, 2, 3, 4, 5];
console.log(Array.isArray(numbers)); // -> true
const number = 100;
console.log(Array.isArray(number)); // -> false
```
- *toString*: Converts array to string
```js
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
```
join:To join the elements of the array, the argument passed in the join method will be joined in the array and return as a string.
```js
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
```
Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position
```js
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.indexOf(0, numbers.length)) // it copies all item
console.log(numbers.slice(1,4)) // -> [2,3,4] // it doesn't include the ending position
```
Splice: It takes three parameters:Starting position, number of times to be removed and number items to be added.
```js
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.splice() // -> remove all items
console.log(numbers.splice(0,1)) // remove the first item
console.log(numbers.splice(3, 3, 6, 7, 8)) // -> [1,2,6,7,8] //it removes two item and replace three items
```
- *push*: adding item in the end
```js
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]
```
- *pop*: Removing item in the end
```js
const numbers = [1, 2, 3, 4, 5];
numbers.pop(); // -> remove one item from the end
console.log(numbers); // -> [1,2,3,4]
```
- *shift*: Removing item in the beginning
```js
const numbers = [1, 2, 3, 4, 5];
numbers.shift(); // -> remove one item from the beginning
console.log(numbers); // -> [2,3,4,5]
```
- *unshift*: Adding item in the beginning
```js
const numbers = [1, 2, 3, 4, 5];
numbers.unshift(0); // -> remove one item from the beginning
console.log(numbers); // -> [0,1,2,3,4,5]
```
---
### Exercise -10 : Array Methods
```js
const shoppingCart = ['Milk','Coffee','Tea', 'Honey'];
const todoList = [
{
task:'Learn JavaScript',
time:'4/3/2019 8:30',
completed:true
},
{
task:'Help some in need',
time:'4/3/2019 4:00',
completed:false
},
{
task:'Do some physical exercises',
time:'4/3/2019 6:00',
completed:false
}
]
```
## Functions
A function is a block of code 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.
A function can be declared or created in couple of ways:
- _Declaration function_
- _Expression function_
- _Anonymous function_
- _Arrow function_
### Function Declaration
```js
//function without parameter
function functionName(){
// code goes here
}
functionName() // calling function by its name and with parentheses
//function without parameter
function addTwoNumbers() {
var numOne = 10;
var numTwo = 20;
var sum = numOne + numTwo;
console.log(sum);
}
addTwoNumbers(); // function has to be called to be executed by it name
// 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 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 parameter with parameter
function sumTwoNumbers(numOne, numTwo) {
var 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 sumTwoNumbersAndReturn(numOne, numTwo) {
var sum = numOne + numTwo;
return sum;
}
console.log(sumTwoNumbersAndReturn(10, 20));
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`;
}
console.log(printFullName('Asabeneh', 'Yetayeh'));
console.log(printFullName('Dean', 'Phan'));
// function with multiple parameters
function functionName(parm1, parm2, parm3,...){
//code goes ther
}
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) {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
const numbers = [1, 2, 3, 4, 5];
console.log(sumArrayValues(numbers));
const areaOfCircle = (radius) => {
let area = Math.PI * radius * radius;
return area;
}
console.log(areaOfCircle(10))
```
### Function Expression
```js
//Declaration function
function square(n) {
return n * n;
}
console.log(square(2)); // -> 4
// Function expression
const square = function(n) {
return n * n;
};
console.log(square(2)); // -> 4
```
### Anonymous Function
```js
// Self invoking functions
(function(n) {
return n * n;
})(2);
const x = (function(n) {
return n * n;
})(2);
console.log(x) // 4
```
### Arrow Function
```js
const square = n => {
return n * n;
};
console.log(square(2)); // -> 4
// if we have only one line, it can be written as follows
// Explicit return
const square = n => n * n; // -> 4
```
### Arrow Function vs Declaration Function
Arrow function and regular functions are not exactly the same.
```js
```
### Exercise - 10 : Functions
1. Declare a function _fullName_ and it print out your full name.
1. Declare a function _fullName_ and now it takes firstName, lastName as a parameter and it returns your full - name.
1. Declare a function _addNumbers_ and it takes two two parameters and it returns sum.
1. An area of a rectangle is calculated as follows: _area = length x width_. Write a function which calculates _areaOfRectangle_.
1. A perimeter of a rectangle is calculated as follows: _perimeter= 2x(length + width)_. Write a function which calculates _perimeterOfRectangle_.
1. A volume of a rectangular prism is calculated as follows: _volume = length x width x height_. Write a function which calculates _volumeOfRectPrism_.
1. Area of a circle is calculated as follows: _area = π x r x r_. Write a function which calculates _areaOfCircle_
1. Circumference of a circle is calculated as follows: _circumference = 2Ď€r_. Write a function which calculates _circumOfCircle_
1. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.
1. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_.
1. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.
1. 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_.
1. 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
1. Write a function called _checkSeason_, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer.
1. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method.
```js
console.log(findMax(0, 10, 5));
10;
console.log(findMax(0, -10, -2));
0;
```
1. Linear equation is calculated as follows: _ax + b = c_. Write a function which calculates value of a linear equation, _solveLinEquation_.
1. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_.
1. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.
1. Declare a function name _swapValues_. This function swaps value of x to y.
```js
swapValues(3, 4); // x => 4, y=>3
swapValues(4, 5); // x = 5, y = 4
```
1. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method).
```js
console.log(reverseArray([1, 2, 3, 4, 5]));
[5, 4, 3, 2, 1];
console.log(reverseArray(['A', 'B', 'C']));
['C', 'B', 'A'];
```
1. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.
1. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item
1. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item
1. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.
1. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.
1. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.
1. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
```sh
evensAndOdds(100);
The number of odds are 50.
The number of evens are 51.
```
1. Write a function which takes any number of arguments and return the sum of the arguments
```js
sum(1, 2, 3); // -> 6
sum(1, 2, 3, 4); // -> 10
```
1. Writ a function which generates a _randomUserIp_.
1. Write a function which generates a _randomMacAddress_
1. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
```sh
console.log(randomHexaNumberGenerator());
'#ee33df'
```
1. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id.
```sh
console.log(userIdGenerator());
41XTDbE
```
1. Modify question number n . 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.
```sh
userIdGeneratedByUser()
'kcsy2
SMFYb
bWmeq
ZXOYh
2Rgxf
'
userIdGeneratedByUser()
'1GCSgPLMaBAVQZ26
YD7eFwNQKNs7qXaT
ycArC5yrRupyG00S
UbGxOFI7UXSWAyKN
dIV0SSUTgAdKwStr
'
```
1. Write a function name _rgbColorGenerator_ and it generates rgb colors.
```sh
rgbColorGenerator()
rgb(125,244,255)
```
1. Write a function ***arrayOfHexaColors*** which return any number of hexadecimal colors in an array.
1. Write a function ***arrayOfRgbColors*** which return any number of RGB colors in an array.
1. Write a function ***convertHexaToRgb*** which converts hexa color to rgb and it returns an rgb color.
1. Write a function ***convertRgbToHexa*** which converts rgb to hexa color and it returns an hexa color.
1. Write a function ***generateColors*** which can generate any number of hexa or rgb colors.
```js
generateColors('hexa', 3)
['#a3e12f','#03ed55','#eb3d2b']
generateColors('hexa', 1)
'#b334ef'
generateColors('rgb', 3)
['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
generateColors('rgb', 1)
'rgb(33,79, 176)'
```
1. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array
1. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number
1. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not
1. Call your function _sum_, it takes any number of arguments and it returns the sum.
1. Write a function called _sumOfArrayItems_, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not give return reasonable feedback.
1. 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.
1. Write a function called _modifyArray_ takes array as parameter and modifies the fifth item of the array and return the array. If the array length is less than five it return 'item not found'.
```js
console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);
// →['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']);
// →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']);
// →'Not Found'
```
1. Write a function called *isPrime*, which checks if a number is prime number.
1. Write a functions which checks if all items are unique in the array.
1. Write a function which checks if all the items of the array are the same data type.
1. JavaScript variable name does not support special characters or symbols except $ or _. Write a function ***isValidVariable** which check if a variable is valid or invalid variable.
1. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
```js
sevenRandomNumbers()[(1, 4, 5, 7, 9, 8, 0)];
```
## Object
Everything can be an object and objects do have properties and properties have values.
Creating an object literal. To create an object literal, we use two curly brackets.
An empty object
```js
const person = {};
```
Now, the person object has firstName, lastName, age, location, skills and getFullName properties. The getFullName is function inside the person object and we call it method. The _this_ key word refers to the object itself.Example of object:
```js
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 100,
location: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
getFullName: function() {
return `${this.firstName}${this.lastName}`;
}
};
const rectangle = {
length: 20,
width: 20,
getArea: function() {
return this.length * this.width;
},
getPerimeter: function() {
return 2 * (this.length + this.width);
}
};
```
Getting values from an object:
```js
const person = {
firstName:'Asabeneh',
lastName:'Yetayeh',
age:100,
location:'Helsinki',
skills:['HTML', 'CSS', 'JavaScript', 'React','Node','MongoDB', 'Python', 'D3.js']
getFullName:function() {
return `${this.firstName}${this.lastName}`
}
}
console.log(person.firstName);
console.log(person.lastName);
console.log(person.getFullName());
// value can be accessed
console.log(person['age');
console.log(person['location']);
```
Setting a new keys in an object
```js
const person = {
firstName:'Asabeneh',
lastName:'Yetayeh',
age:100,
location:'Helsinki',
skills:['HTML', 'CSS', 'JavaScript', 'React','Node','MongoDB', 'Python', 'D3.js']
getFullName:function() {
return `${this.firstName}${this.lastName}`
}
}
person.nationality = 'Ethiopian'
person.live = 'Finland';
console.log(person)
```
### Object Methods
_Object.assign_: To copy an object without modifying the original object
```js
const person = {
name: 'Asabeneh',
age: 200,
country: 'Finland',
skills: ['HTML', 'CSS', 'JS'],
address: {
street: 'Heitamienkatu 16',
pobox: 2002,
city: 'Helsinki'
},
getPersonInfo: function() {
return `I am ${this.name} and I live in ${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);
```
_Object.keys_: To get keys of an objet as an array
```js
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']
```
_Object.values_:To get values of an object as an array
```js
const values = Object.values(copyPerson);
console.log(values);
```
_Object.entries_:To get the keys and values in an array
```js
const entries = Object.entries(copyPerson);
console.log(entries);
```
_hasOwnProperty_: To check if a specific key or property exist in an object
```js
console.log(copyPerson.hasOwnProperty('name'));
console.log(copyPerson.hasOwnProperty('score'));
```
### Date Object
In JavaScript current time and date is created using JavaScript Date Object.
Some of the methods to extract date object values:*getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes*
```js
const now = new Date ();
const year = now.getFullYear(); // return year
const month = now.getMonth() + 1; // return month(0 - 11)
const date = now.getDate(); // return date (1 - 31)
const hours = now.getHours(); // return number (0 - 23)
const minutes = now.getMinutes();// return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`)
```
#### Exercises: Date Object
1. Use the new Date() object to get _month, date, year, hour_ and _minute_.
1. Write a function name _displayDateTime_ which display time in this format: 10/03/2019 04:08
```sh
displayDateTime()
10/03/2019 04:08
```
### Exercises:Objects
1. Create an empty object called dog
1. Print the the dog object on the console
1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return *woof woof*
1. Get name, legs, color, age and bark value from the dog object
1. Set new properties the dog object: breed, getDogInfo
1. 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 the same for expenses.
1. Count logged in users,count users having greater than equal to 50 points from the following object.
```js
const users = {
Alex: {
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: 'asab@asab.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: 'daniel@daniel.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: 'daniel@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: 'john@john.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
point: 50
},
Thomas: {
email: 'thomas@thomas.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
}
};
```
1. Set your name in the users object without modifying the original users object
1. Get all keys or properties of users object
1. Get all the values of users object
1. ** Develop a small JavaScript library.
## JSON
JSON stands for JavaScript Object Notation. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text or string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
**Example:**
```js
{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}
```
The above JSON example is not much different for a normal object. Then, what is the difference ? The difference is the key of a JSON object should be with double quotes or it should be a string. JavaScript Object and JSON are very similar that we can change JSON to Object and Object to JSON.
Let us see the above example in more detail, it starts with a curly bracket. Inside the curly bracket, there is "users" key which has a value array. Inside the array we have different objects and each objects has keys, each keys has to have double quotes. For instance, we use "firstNaMe" instead of just firstName, however in object we use keys without double quotes. This is the major difference between an object and a JSON. Let's see more examples about JSON.
**Example:**
```js
{
"Alex": {
"email": "alex@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"age": 20,
"isLoggedIn": false,
"points": 30
},
"Asab": {
"email": "asab@asab.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Redux",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 25,
"isLoggedIn": false,
"points": 50
},
"Brook": {
"email": "daniel@daniel.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux"
],
"age": 30,
"isLoggedIn": true,
"points": 50
},
"Daniel": {
"email": "daniel@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"John": {
"email": "john@john.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux",
"Node.js"
],
"age": 20,
"isLoggedIn": true,
"points": 50
},
"Thomas": {
"email": "thomas@thomas.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"Paul": {
"email": "paul@paul.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 20,
"isLoggedIn": false,
"points": 40
}
}
```
### Converting JSON to JavaScript Object
Mostly we fetch JSON data from HTTP response or from a file, but we can store the JSON as a string and we can change to Object for sake of demonstration. In JavaScript the keyword _JSON_ has _parse()_ and _stringify()_ methods. When we want to change the JSON to an object we parse the JSON using _JSON.parse()_. When we want to change the object to JSON we use _JSON.stringify()_.
#### JSON.parse()
```js
JSON.parse(json[, reviver])
// json or text , the data
// reviver is an optional callback function
```
```js
const usersText = `{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}`
const usersObj = JSON.parse(usersText, undefined, 4)
console.log(usersObj)
```
### Using a reviver function with JSON.parse()
To use the reviver function as a formatter, we put the keys we want to format first name and last name value. Let us say, we are interested to format the firstName and lastName of the JSON data .
```js
const usersText = `{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}`
const usersObj = JSON.parse(usersText, (key, value) => {
let newValue =
typeof value == 'string' && key != 'email' ? value.toUpperCase() : value
return newValue
})
console.log(usersObj)
```
The _JSON.parse()_ is very handy to use. You do not have to pass optional parameter, you can just use it with the required parameter and you will achieve quite a lot.
### Converting Object to JSON
When we want to change the object to JSON we use _JSON.stringify()_. The stringify method takes one required parameter and two optional parameters. The replacer is used as filter and the space is an indentations. If we do not want to filter out any of the keys from the object we can just pass undefined.
```js
JSON.stringify(obj, replacer, space)
// json or text , the data
// reviver is an optional callback function
```
Let us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.
```js
const users = {
Alex: {
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: 'asab@asab.com',
skills: [
'HTML',
'CSS',
'JavaScript',
'Redux',
'MongoDB',
'Express',
'React',
'Node'
],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: 'daniel@daniel.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: 'daniel@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: 'john@john.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
points: 50
},
Thomas: {
email: 'thomas@thomas.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
},
Paul: {
email: 'paul@paul.com',
skills: [
'HTML',
'CSS',
'JavaScript',
'MongoDB',
'Express',
'React',
'Node'
],
age: 20,
isLoggedIn: false,
points: 40
}
}
const txt = JSON.stringify(users, undefined, 4)
console.log(txt) // text means JSON- because json is a string form of an object.
```
```sh
{
"Alex": {
"email": "alex@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"age": 20,
"isLoggedIn": false,
"points": 30
},
"Asab": {
"email": "asab@asab.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Redux",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 25,
"isLoggedIn": false,
"points": 50
},
"Brook": {
"email": "daniel@daniel.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux"
],
"age": 30,
"isLoggedIn": true,
"points": 50
},
"Daniel": {
"email": "daniel@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"John": {
"email": "john@john.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux",
"Node.js"
],
"age": 20,
"isLoggedIn": true,
"points": 50
},
"Thomas": {
"email": "thomas@thomas.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"Paul": {
"email": "paul@paul.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 20,
"isLoggedIn": false,
"points": 40
}
}
```
### Using a Filter Array with JSON.stringify
Now, lets use the replacer as a filter. The user object has long list of keys but we are interested only in few of them. We put the keys we want to keep in array as show in the example and use it the place of the replacer.
```js
const user = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
country: 'Finland',
city: 'Helsinki',
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'],
age: 250,
isLoggedIn: false,
points: 30
}
const txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4)
console.log(txt)
```
```sh
{
"firstName": "Asabeneh",
"lastName": "Yetayeh",
"country": "Finland",
"city": "Helsinki",
"age": 250
}
```
### Exercises
```js
const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']
let age = 250;
let isMarried = true
const student = {
firstName:'Asabeneh',
lastName:'Yetayehe',
age:250,
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
}
const txt = `{
"Alex": {
"email": "alex@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript"
],
"age": 20,
"isLoggedIn": false,
"points": 30
},
"Asab": {
"email": "asab@asab.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Redux",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 25,
"isLoggedIn": false,
"points": 50
},
"Brook": {
"email": "daniel@daniel.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux"
],
"age": 30,
"isLoggedIn": true,
"points": 50
},
"Daniel": {
"email": "daniel@alex.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"John": {
"email": "john@john.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React",
"Redux",
"Node.js"
],
"age": 20,
"isLoggedIn": true,
"points": 50
},
"Thomas": {
"email": "thomas@thomas.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"React"
],
"age": 20,
"isLoggedIn": false,
"points": 40
},
"Paul": {
"email": "paul@paul.com",
"skills": [
"HTML",
"CSS",
"JavaScript",
"MongoDB",
"Express",
"React",
"Node"
],
"age": 20,
"isLoggedIn": false,
"points": 40
}
}
`
```
### Exercises Level 1
1. Change skills array to JSON using JSON.stringify()
1. Stringify the age variable
1. Stringify the isMarried variable
1. Stringify the student object
### Exercises Level 2
1. Stringify the students object with only firstName, lastName and skills properties
## 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.
```js
// a callback function, the function could be any name
const callback = (n) => {
return n ** 2
}
​
// function take other function as a callback
function cube(callback, n) {
return callback(n) * n
}
​
console.log(cube(callback, 3))
```
### Returning function
Higher order functions return function as a value
​
```js
// Higher order function returning an other function
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
​
return doSomething
}
console.log(higherOrder(2)(3)(10))
`
