{"id":15037680,"url":"https://github.com/asabeneh/javascript-for-everyone","last_synced_at":"2025-04-08T12:04:22.408Z","repository":{"id":38006516,"uuid":"171563505","full_name":"Asabeneh/JavaScript-for-Everyone","owner":"Asabeneh","description":"A step by step guide to learn JavaScript and programming. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw","archived":false,"fork":false,"pushed_at":"2023-08-25T08:50:42.000Z","size":9498,"stargazers_count":1139,"open_issues_count":3,"forks_count":297,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-04-08T12:04:10.589Z","etag":null,"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"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Asabeneh.png","metadata":{"files":{"readme":"readMe.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-02-19T22:57:53.000Z","updated_at":"2025-04-04T13:14:42.000Z","dependencies_parsed_at":"2024-10-15T11:43:15.777Z","dependency_job_id":"3a3f7253-cf62-4693-822e-b3ff2c28f9d7","html_url":"https://github.com/Asabeneh/JavaScript-for-Everyone","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Asabeneh%2FJavaScript-for-Everyone","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Asabeneh%2FJavaScript-for-Everyone/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Asabeneh%2FJavaScript-for-Everyone/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Asabeneh%2FJavaScript-for-Everyone/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Asabeneh","download_url":"https://codeload.github.com/Asabeneh/JavaScript-for-Everyone/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247838441,"owners_count":21004580,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["30daysofjavascript","30daysofreact","arrays","arrow-functions","cookies","dom","es5","es6","es7","functional-programming","javascript","javascript-for-everyone","js-challenges","js-questions","js-quiz","localstorage","webdesign"],"created_at":"2024-09-24T20:35:19.085Z","updated_at":"2025-04-08T12:04:22.382Z","avatar_url":"https://github.com/Asabeneh.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n  \u003ch1\u003e JavaScript for Everyone\u003c/h1\u003e\n  \u003ca class=\"header-badge\" target=\"_blank\" href=\"https://www.linkedin.com/in/asabeneh/\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn\u0026logo=linkedin\u0026style=social\"\u003e\n  \u003c/a\u003e\n  \u003ca class=\"header-badge\" target=\"_blank\" href=\"https://twitter.com/Asabeneh\"\u003e\n  \u003cimg alt=\"Twitter Follow\" src=\"https://img.shields.io/twitter/follow/asabeneh?style=social\"\u003e\n  \u003c/a\u003e\n\n  \u003csub\u003eAuthor:\n  \u003ca href=\"https://www.linkedin.com/in/asabeneh/\" target=\"_blank\"\u003eAsabeneh Yetayeh\u003c/a\u003e\u003cbr\u003e\n  \u003csmall\u003e January, 2018\u003c/small\u003e\n  \u003c/sub\u003e\n\u003c/div\u003e\n\n\u003cdiv\u003e\n\n\u003csmall\u003eSupport the **author** to create more educational materials\u003c/small\u003e  \n\u003ca href = \"https://www.paypal.me/asabeneh\"\u003e\u003cimg src='./images/paypal_lg.png' alt='Paypal Logo' style=\"width:10%\"/\u003e\u003c/a\u003e\n\n\u003c/div\u003e \n\n![JS](./images/javascript_for_everyone.png)\n- [Introduction](#introduction)\n- [Setup](#setup)\n- [Requirements](#requirements)\n- [Setup](#setup-1)\n  - [Install Node.js](#install-nodejs)\n  - [Browser](#browser)\n    - [Installing Google Chrome](#installing-google-chrome)\n    - [Opening Google Chrome Console](#opening-google-chrome-console)\n    - [Writing Code on browser Console](#writing-code-on-browser-console)\n      - [Console.log](#consolelog)\n      - [Console.log with multiple arguments](#consolelog-with-multiple-arguments)\n      - [Comment](#comment)\n      - [Syntax](#syntax)\n    - [Arithmetics](#arithmetics)\n  - [Code Editor](#code-editor)\n    - [Installing Visual Studio Code](#installing-visual-studio-code)\n    - [How to use visual studio code](#how-to-use-visual-studio-code)\n  - [Adding JavaScript to a web page](#adding-javascript-to-a-web-page)\n    - [Inline Script](#inline-script)\n    - [Internal script](#internal-script)\n    - [External script](#external-script)\n  - [Exercises:Setting Up your machine](#exercisessetting-up-your-machine)\n- [Variables](#variables)\n  - [Exercise - 1 : Variables](#exercise---1--variables)\n- [Comments](#comments)\n  - [Exercise: Comments](#exercise-comments)\n- [Data types](#data-types)\n  - [Primitive Data Types](#primitive-data-types)\n  - [Non-Primitive Data Types](#non-primitive-data-types)\n- [Numbers](#numbers)\n  - [Declaring number data types](#declaring-number-data-types)\n  - [Math Object](#math-object)\n    - [Random number generator](#random-number-generator)\n- [Strings](#strings)\n  - [String Concatenation](#string-concatenation)\n    - [Concatenating using addition operator](#concatenating-using-addition-operator)\n    - [Long Literal Strings](#long-literal-strings)\n    - [Escape Sequences in string](#escape-sequences-in-string)\n    - [Template Literals(Template Strings)](#template-literalstemplate-strings)\n  - [String Methods](#string-methods)\n- [Checking Data types and Casting](#checking-data-types-and-casting)\n  - [Checking data types](#checking-data-types)\n  - [Changing data type(Casting)](#changing-data-typecasting)\n    - [String to Int](#string-to-int)\n    - [String to Float](#string-to-float)\n    - [Float to Int](#float-to-int)\n  - [Exercises: Data Types](#exercises-data-types)\n    - [Exercise: String](#exercise-string)\n  - [Booleans](#booleans)\n    - [Exercise: Booleans](#exercise-booleans)\n  - [Undefined](#undefined)\n  - [Null](#null)\n  - [Exercise - 6 : Data types](#exercise---6--data-types)\n- [Operators](#operators)\n  - [Arithmetic Operators](#arithmetic-operators)\n  - [Exercises : Arithmetic Operators](#exercises--arithmetic-operators)\n  - [Logical Operators](#logical-operators)\n  - [Exercises: Logical Operators](#exercises-logical-operators)\n  - [Comparison Operators](#comparison-operators)\n  - [Exercise: Comparison Operators](#exercise-comparison-operators)\n- [Conditionals](#conditionals)\n  - [if](#if)\n  - [if else](#if-else)\n  - [if else if else](#if-else-if-else)\n  - [switch](#switch)\n  - [Ternary Operators](#ternary-operators)\n  - [Exercise: Conditionals](#exercise-conditionals)\n  - [While loop](#while-loop)\n  - [Do while loop](#do-while-loop)\n  - [Exercises:Loops](#exercisesloops)\n- [Arrays](#arrays)\n  - [Exercise : Arrays](#exercise--arrays)\n- [More on Arrays](#more-on-arrays)\n  - [Exercise -10 : Array Methods](#exercise--10--array-methods)\n- [Functions](#functions)\n  - [Function Declaration](#function-declaration)\n  - [Function Expression](#function-expression)\n  - [Anonymous Function](#anonymous-function)\n  - [Arrow Function](#arrow-function)\n  - [Arrow Function vs Declaration Function](#arrow-function-vs-declaration-function)\n  - [Exercise - 10 : Functions](#exercise---10--functions)\n- [Object](#object)\n  - [Object Methods](#object-methods)\n  - [Date Object](#date-object)\n    - [Exercises: Date Object](#exercises-date-object)\n  - [Exercises:Objects](#exercisesobjects)\n- [JSON](#json)\n  - [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)\n    - [JSON.parse()](#jsonparse)\n  - [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)\n  - [Converting Object to JSON](#converting-object-to-json)\n  - [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)\n  - [Exercises](#exercises)\n  - [Exercises Level 1](#exercises-level-1)\n  - [Exercises Level 2](#exercises-level-2)\n- [Higher Order Function](#higher-order-function)\n  - [Callback](#callback)\n  - [Returning function](#returning-function)\n  - [setting time](#setting-time)\n    - [setInterval](#setinterval)\n    - [setTimeout](#settimeout)\n  - [Exercises Level 3](#exercises-level-3)\n- [Functional Programming](#functional-programming)\n  - [Exercises](#exercises-1)\n- [Destructuring and Spread](#destructuring-and-spread)\n  - [Destructing  Arrays](#destructing--arrays)\n    - [Destructuring Object](#destructuring-object)\n    - [Renaming during structuring](#renaming-during-structuring)\n  - [Spread or Rest Operator](#spread-or-rest-operator)\n    - [Exercise: Destructuring](#exercise-destructuring)\n- [Map and Set](#map-and-set)\n- [Set](#set)\n  - [Creating a set](#creating-a-set)\n  - [Adding an element to a set](#adding-an-element-to-a-set)\n  - [Deleting an element a set](#deleting-an-element-a-set)\n  - [Checking an element in the set](#checking-an-element-in-the-set)\n  - [Clearing the set](#clearing-the-set)\n- [Set](#set-1)\n  - [Creating an empty set](#creating-an-empty-set)\n  - [Creating set from array](#creating-set-from-array)\n  - [Adding an element to a set](#adding-an-element-to-a-set-1)\n  - [Deleting an element a set](#deleting-an-element-a-set-1)\n  - [Checking an element in the set](#checking-an-element-in-the-set-1)\n  - [Clearing the set](#clearing-the-set-1)\n  - [Union of sets](#union-of-sets)\n  - [Intersection of sets](#intersection-of-sets)\n  - [Difference of sets](#difference-of-sets)\n- [Map](#map)\n  - [Creating an empty Map](#creating-an-empty-map)\n  - [Creating an Map from array](#creating-an-map-from-array)\n  - [Adding values to the Map](#adding-values-to-the-map)\n  - [Getting a value from Map](#getting-a-value-from-map)\n  - [Checking key in Map](#checking-key-in-map)\n  - [Exercises: Set and Map](#exercises-set-and-map)\n  - [Exercises:Level 1](#exerciseslevel-1)\n  - [Exercises:Level 2](#exerciseslevel-2)\n  - [Exercises:Level 3](#exerciseslevel-3)\n- [Document Object Model (DOM)](#document-object-model-dom)\n  - [Getting Element](#getting-element)\n    - [Getting elements by tag name](#getting-elements-by-tag-name)\n    - [Getting elements by class name](#getting-elements-by-class-name)\n    - [Getting an element by id](#getting-an-element-by-id)\n    - [Getting elements by using querySelector using tag, class and id:](#getting-elements-by-using-queryselector-using-tag-class-and-id)\n  - [Adding attribute](#adding-attribute)\n    - [Adding attribute using setAttribute](#adding-attribute-using-setattribute)\n    - [Adding attribute without setAttribute](#adding-attribute-without-setattribute)\n    - [Adding class using classList](#adding-class-using-classlist)\n  - [Adding Text content](#adding-text-content)\n  - [Adding style](#adding-style)\n  - [Creating an Element](#creating-an-element)\n  - [Creating elements](#creating-elements)\n  - [Appending to a parent element](#appending-to-a-parent-element)\n  - [Event Listeners](#event-listeners)\n  - [Getting value from an input element](#getting-value-from-an-input-element)\n    - [Exercises:Document Object Model](#exercisesdocument-object-model)\n    - [DOM: Mini Projects](#dom-mini-projects)\n- [Classes](#classes)\n  - [Defining a classes](#defining-a-classes)\n  - [Class Instantiation](#class-instantiation)\n  - [Class Constructor](#class-constructor)\n  - [Default values with constructor](#default-values-with-constructor)\n  - [Class methods](#class-methods)\n  - [Properties with initial value](#properties-with-initial-value)\n  - [getter](#getter)\n  - [setter](#setter)\n  - [Static method](#static-method)\n- [Inheritance](#inheritance)\n  - [Overriding methods](#overriding-methods)\n- [Exercises](#exercises-2)\n  - [Exercises Level 1](#exercises-level-1-1)\n  - [Exercises Level 2](#exercises-level-2-1)\n  - [Exercises Level 3](#exercises-level-3-1)\n- [Regular Expressions](#regular-expressions)\n  - [RegEx parameters](#regex-parameters)\n    - [Pattern](#pattern)\n    - [Flags](#flags)\n  - [Creating a pattern with RegEx Constructor](#creating-a-pattern-with-regex-constructor)\n  - [Creating a pattern without RegEx Constructor](#creating-a-pattern-without-regex-constructor)\n  - [RegExp Object Methods](#regexp-object-methods)\n    - [Testing for  a match](#testing-for--a-match)\n    - [Array containing all of the match](#array-containing-all-of-the-match)\n    - [Replacing a substring](#replacing-a-substring)\n  - [Square Bracket](#square-bracket)\n  - [Escape character(\\\\) in RegEx](#escape-character-in-regex)\n  - [One or more times(+)](#one-or-more-times)\n  - [Period(.)](#period)\n  - [Zero or more times(*)](#zero-or-more-times)\n  - [Zero or one times(?)](#zero-or-one-times)\n  - [Quantifier in RegEx](#quantifier-in-regex)\n  - [Cart ^](#cart-)\n  - [Exact match](#exact-match)\n- [💻 Exercises](#-exercises)\n  - [Exercises: Level 1](#exercises-level-1-2)\n  - [Exercises: Level 2](#exercises-level-2-2)\n  - [Exercises: Level 3](#exercises-level-3-2)\n- [Async and Await](#async-and-await)\n- [localStorage](#localstorage)\n  - [Setting item to the localStorage](#setting-item-to-the-localstorage)\n  - [Getting item from localStorage](#getting-item-from-localstorage)\n  - [Clearing the localStorage](#clearing-the-localstorage)\n  - [Exercises:Local Storage](#exerciseslocal-storage)\n- [Cookies](#cookies)\n  - [Exercises:Cookies](#exercisescookies)\n- [JavaScript Interview Questions](#javascript-interview-questions)\n  - [JavaScript Tests](#javascript-tests)\n  - [JavaScript Test 1](#javascript-test-1)\n  - [JavaScript Test 2](#javascript-test-2)\n  - [JavaScript Test 3](#javascript-test-3)\n\n## Introduction\n\n**_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.\n\nIn this step by step tutorial, you will learn JavaScript, the most popular programming language in the history of mankind.\nYou 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_**.\n**_JavaScript (JS)_** has increased in popularity in recent years and has been the leading\nprogramming language for four consecutive years and is the most used programming language on\nGithub.\n\n## Setup\n\nFirst 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.\nInstall 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.\n\nIf you want help, you may join the [telegram](https://t.me/JavaScriptforEveryone) channel.\n\n## Requirements\n\nNo prior knowledge of programming is required to follow this guide. You need only:\n\n1. Motivation\n2. Computer\n3. Internet\n4. Browser\n5. Code Editor\n\n## Setup\n\nI believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything.\n\n### Install Node.js\n\nYou may not need it right now but you may need it for later. Install [node.js](https://nodejs.org/en/).\n\n![Node download](images/download_node.png)\n\nAfter downloading double click and install\n\n ![Install node](images/install_node.png)\n\nWe can check if node is installed in our local machine by opening our device terminal or command  prompt.\n\n```sh\nasabeneh $ node -v\nv12.14.0\n```\n\nI am using node version 12.14.0, which is the recommended version of node.\n\n### Browser\n\nThere are many browsers out there. However, I strongly recommend Google Chrome.\n\n#### Installing Google Chrome\n\nInstall [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.\n\n![Google Chrome](images/google_chrome.png)\n\n#### Opening Google Chrome Console\n\nYou 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.\n\n![Opening chrome](images/opening_developer_tool.png)\n\nTo open the Chrome console using a short cut.\n\n```sh\nMac\nCommand+Option+I\n\nWindows:\nCtl+Shift+I\n```\n\n![Opening console](images/opening_chrome_console_shortcut.png)\n\nAfter 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.\nLet us write a JavaScript code on the Google Chrome console:\n\n![write code on console](./images/js_code_on_chrome_console.png)\n\n#### Writing Code on browser Console\n\nWe 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:\n\n```sh\nMac\nCommand+Option+I\n\nWindows:\nCtl+Shift+I\n```\n\n##### Console.log\n\nTo 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.\n\n```js\nconsole.log('Hello, World!')\n```\n\n##### Console.log with multiple arguments\n\nThe console.log(param1, param2, param3), can take multiple arguments.\n\n![console log multiple arguments](./images/console_log_multipl_arguments.png)\n\n```js\nconsole.log('Hello', 'World', '!')\nconsole.log('HAPPY', 'NEW', 'YEAR', 2020)\nconsole.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')\n```\n\nAs you can see from the above snippet code, *console.log()* can take multiple arguments.\n\nCongratulations! You wrote your first JavaScript code using *console.log()*.\n\n##### Comment\n\nWe 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.\n\n**Example: Single Line Comment**\n\n // This is the first comment  \n // This is the second comment  \n // I am a single line comment  \n\n**Example: Multiline Comment**\n\n  /*\n  This is a multiline comment  \n  Multiline comments can take multiple lines  \n  JavaScript is the language of the web  \n  */\n\n##### Syntax\n\nJavaScript 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.\n\n![Error](images/raising_syntax_error.png)\n\nI 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:\n\n```js\nconsole.log(\"Hello, World!\")\nconsole.log('Hello, World!')\n```\n\nSo 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.\n**Example:**\n\n```js\nconsole.log(\"Hello, World!\")\nconsole.log('Hello, World!')\nconsole.log(`Hello, World!`)\n```\n\n#### Arithmetics\n\nNow, let us practice more writing JavaScript codes using *console.log()* on google chrome console for number data types.\nIn addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.\n\n![Arithmetic](images/arithmetic.png)\n\n```js\nconsole.log(2 + 3)   // Addition\nconsole.log(3 - 2)   // Subtraction\nconsole.log(2 * 3)   // Multiplication  \nconsole.log(3 / 2)   // Division\nconsole.log(3 % 2)   // Modulus - finding remainder\nconsole.log(3 ** 2)  // Exponential\n```\n\n### Code Editor\n\nWe 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.\n\n#### Installing Visual Studio Code\n\nVisual 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.\n\n![Vscode](images/vscode.png)\n\nIf you installed visual studio code, let us start using it.\n\n#### How to use visual studio code\n\nOpen 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.\n\n![Vscode ui](./images/vscode_ui.png)\n\n![Vscode add project](./images/adding_project_to_vscode.png)\n\n![Vscode open project](./images/opening_project_on_vscode.png)\n\n![script file](images/scripts_on_vscode.png)\n\n![running script](./images/running_script.png)\n\n![coding running](./images/launched_on_new_tab.png)\n\n\n### Adding JavaScript to a web page\n\nJavaScript can be added to a web page in three ways:\n\n- **_Inline script_**\n- **_Internal script_**\n- **_External script_**\n\nThe following sections show different ways of adding JavaScript code to your web page.\n\n#### Inline Script\n\nCreate 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).\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n      \u003cbutton onclick=\"alert('Welcome to JavaScript!');\"\u003eClick Me\u003c/button\u003e\n    \u003c/body\u003e\n  \u003c/html\u003e\n```\n\n#### Internal script\n\nInternal script can be written in the _head_ or the _body_ but it is preferred to put it on the body of the html document.\n\n- Internal script  at the head\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone\u003c/title\u003e\n      \u003cscript\u003e\n        console.log(\"Welcome to JavaScript for Everyone\");\n      \u003c/script\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n  \n    \u003c/body\u003e\n  \u003c/html\u003e\n```\n\n- Internal script  at the body\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n      \u003cscript\u003e\n        console.log(\"Welcome to JavaScript for Everyone\");\n      \u003c/script\u003e\n    \u003c/body\u003e\n  \u003c/html\u003e\n```\n\n#### External script\n\nThe external script link can be on the head or body but it is preferred to put it in the body.\n\n- External script  at the head\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone\u003c/title\u003e\n      \u003cscript src=\"introduction.js\"\u003e\u003c/script\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n    \u003c/body\u003e\n    \u003c/html\n```\n\n- External script at the body\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n      //it could be in the header or in the body\n      // Here is the recommended place to put the script\n      \u003cscript src=\"introduction.js\"\u003e\u003c/script\u003e\n    \u003c/body\u003e\n    \u003c/html\n```\n\n### Exercises:Setting Up your machine\n\n## Variables\n\nVariables are _containers_ of data. Variables _store_ data in a memory location. When a variable is declared a memory location is reserved and when it is assigned to a value, the memory space will be filled. To declare a variable we use, _var_, _let_ or _const_ key words. For a variable which changes at different time we use _let_ but if the data doesn't change at all we use _const_. For example PI, country name, gravity.\n\n- A JavaScript variable name  shouldn't begin with a number\n- A JavaScript variable name does not allow special characters except dollar sign and underscore. \n- A JavaScript variable name follow a camelCase convention.\n- A JavaScript variable name shouldn't have space between words. The following are valid examples of JavaScript variables.\n\nValid variables in JavaScript:\n\n```js\n    firstName\n    lastName\n    country\n    city\n    capitalCity\n    age\n    isMarried\n\n    first_name\n    last_name\n    is_married\n    capital_city\n\n    num1\n    num_1\n    _num_1\n    $num1\n    year2019\n    year_2019\n```\n\nCamel case(camelCase) or the first way of declaring is conventional in JavaScript. In this material, camelCase variables will be used.\n\nInvalid variable:\n\n```sh\n  first-name\n  1_num\n  num_#_1\n```\n\nDeclaring variables\n\n```js\n// Declaring different variables of different data types\n\nlet firstName = 'Asabeneh'; // first name of a person\nlet lastName = 'Yetayeh';   // last name of a person\nlet country = 'Finland';    // country\nlet city = 'Helsinki';      // capital city\nlet age = 100;              // age in years\nlet isMarried = true;\nconsole.log(firstName, lastName, country, city, age, isMarried); // Asabeneh, Yetayeh, Finland, Helsinki, 100, True\n\n// Declaring variables with number values\n\nconst gravity = 9.81;                    // earth gravity  in m/s2\nconst boilingPoint = 100;                // water boiling point, temperature in oC\nconst PI = 3.14;                         // geometrical constant\nconsole.log(gravity, boilingPoint, PI);  // 9.81, 100, 3.14\n\n// Variables can also be declaring in one line separated by comma\n\nlet name = 'Asabeneh', //name of a person\n  job = 'teacher',\n  live = 'Finland';\nconsole.log(name, job, live);\n```\n\n### Exercise - 1 : Variables\n\n1. Declare four variables without assigning values\n2. Declare four variables with assigning values\n3. Declare variables to store your first name, last name, marital status, country and age in multiple lines\n4. Declare variables to store your first name, last name, marital status, country and age in a single line\n5. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to browser console.\n   Output:\n\n   ```sh\n   I am 25 years old.\n   You are 30 years old.\n   ```\n\n## Comments\n\nCommenting in JavaScript is similar to other programming languages. Comments can help to make code more readable.\nThere are two ways of commenting:\n\n- _Single line commenting_\n- _Multiline commenting_\n\n```js\n// let firstName = 'Asabeneh'; single line comment\n// let lastName = 'Yetayeh'; single line comment\n```\n\nMultiline commenting:\n\n```js\n/*\n    let location = 'Helsinki';\n    let age = 100;\n    let isMarried = true;\n    This is a Multiple line comment\n    */\n```\n\n### Exercise: Comments\n\n1. Write a single line comment which says, _comments can make code readable_\n1. Write a multiline comment which says, _comments can make code readable, easy to use_\n   _and informative_\n\n## Data types\n\nIn the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two\n\n1. Primitive data types\n2. Non-primitive data types(Object References)\n\n### Primitive Data Types\n\nPrimitive data types in JavaScript includes:\n\n 1. Numbers - Integers, floats\n 2. Strings - Any data under single or double quote\n 3. Booleans - true or false value\n 4. Null - empty value or no value\n 5. Undefined - a declared variable without a value\n\nNon-primitive data types in JavaScript includes:\n\n1. Objects\n2. Functions\n3. Arrays\n\nNow, let us see what exactly mean primitive and non-primitive data types.\n*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we can not modify it.\n**Example:**\n\n```js\nlet word = 'JavaScript'\n```\n\nIf we try to modify the string stored in variable *word*, JavaScript will raise an error. Any data type under a single quote, double-quote, or backtick is a string data type.\n\n```js\nword[0] = 'Y'\n```\n\nThis expression does not change the string stored in the variable *word*. So, we can say that strings are not modifiable or immutable.\nPrimitive data types are compared by its values. Let us compare different data values. See the example below:\n\n```js\nlet numOne = 3\nlet numTwo = 3\n\nconsole.log(numOne == numTwo)      // true\n\nlet js = 'JavaScript'\nlet py = 'Python'\n\nconsole.log(js == py)             //false \n\nlet lightOn = true\nlet lightOff = false\n\nconsole.log(lightOn == lightOff) // false\n```\n\n### Non-Primitive Data Types\n\n*Non-primitive* data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created.\nLet us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc.\n\n```js\nlet nums = [1, 2, 3]\nnums[0] = 10\n\nconsole.log(nums)  // [10, 2, 3]\n```\n\nAs you can see, an array in which a non-primitive data type is mutable. Non-primitive data types can not be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.\n\n```js\nlet nums = [1, 2, 3]\nlet numbers = [1, 2, 3]\n\nconsole.log(nums == numbers)  // false\n\nlet userOne = {\nname:'Asabeneh',\nrole:'teaching',\ncountry:'Finland'\n}\n\nlet userTwo = {\nname:'Asabeneh',\nrole:'teaching',\ncountry:'Finland'\n}\n\nconsole.log(userOne == userTwo) // false\n```\n\nRule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object.\nNon-primitive values are referred to as reference types because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.\n\n```js\nlet nums = [1, 2, 3]\nlet numbers = nums\n\nconsole.log(nums == numbers)  // true\n\nlet userOne = {\nname:'Asabeneh',\nrole:'teaching',\ncountry:'Finland'\n}\n\nlet userTwo = userOne\n\nconsole.log(userOne == userTwo)  // true\n```\n\nIf you have a hard time understanding the difference between primitive data types and non-primitive data types, you are not the only one. Calm down and just go to the next section and try to come back after some time. Now let us start the data types by number type.\n\n## Numbers\n\nNumbers are integers and decimal values which can do all the arithmetic operations.\nLets' see some examples of Numbers.\n\n### Declaring number data types\n\n```js\nlet age = 35\nconst gravity = 9.81  //we use const for non-changing values, gravitational constant in  m/s2\nlet mass = 72         // mass in Kilogram\nconst PI = 3.14       // pi a geometrical constant\n\n//More Examples\nconst boilingPoint = 100 // temperature in oC, boiling point of water which is a constant\nconst bodyTemp = 37      // oC average human body temperature, which is a constant\n\nconsole.log(age, gravity, mass, PI, boilingPoint, bodyTemp)\n```\n\n### Math Object\n\nIn JavaScript the Math Object provides a lots of methods to work with numbers.\n\n```js\nconst PI = Math.PI\n\nconsole.log(PI)                           // 3.141592653589793\n\n// Rounding to the closest number\n// if above .5 up if less 0.5 down rounding\n\nconsole.log(Math.round(PI))               // 3 to round values to the nearest number\n\nconsole.log(Math.round(9.81))             // 10\n\nconsole.log(Math.floor(PI))               // 3 rounding down\n\nconsole.log(Math.ceil(PI))                // 4 rounding up\n\nconsole.log(Math.min(-5, 3, 20, 4,5, 10)) // -5, returns the minimum value\n\nconsole.log(Math.max(-5, 3, 20, 4,5, 10)) // 20, returns the maximum value\n\nconst randNum = Math.random() // creates random number between 0 to 0.999999\nconsole.log(randNum)\n\n// Let us  create random number between 0 to 10\n\nconst num = Math.floor(Math.random () * 11) // creates random number between 0 and 10\nconsole.log(num)\n\n//Absolute value\nconsole.log(Math.abs(-10))      //10\n\n//Square root\nconsole.log(Math.sqrt(100))     // 10\n\nconsole.log(Math.sqrt(2))      //1.4142135623730951\n\n// Power\nconsole.log(Math.pow(3, 2)) // 9\n\nconsole.log(Math.E) // 2.718\n\n// Logarithm\n//Returns the natural logarithm of base E of x, Math.log(x)\nconsole.log(Math.log(2))    // 0.6931471805599453\nconsole.log(Math.log(10))   // 2.302585092994046\n\n// Trigonometry\nMath.sin(0)\nMath.sin(60)\n\nMath.cos(0)\nMath.cos(60)\n```\n\n#### Random number generator\n\nThe JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...\n\n```js\nlet randomNum = Math.random() // generates 0 to 0.999\n```\n\nNow, let us see how we can use random() method to generate a random number between 0 and 10 inclusive.\n\n```js\nlet randomNum = Math.random()         // generates 0 to 0.999\nlet numBtnZeroAndTen = randomNum * 11\n\nconsole.log(numBtnZeroAndTen)         // this gives: min 0 and max 10.99\n\nlet randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)\nconsole.log(randomNumRoundToFloor)    // this gives between 0 and 10\n```\n\n## Strings\n\nStrings are texts, which are under **_single_** or **_double_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double-quote, or backtick.\nLets' see some examples of string:\n\n```js\nlet space = ' '           // an empty space string\nlet firstName = 'Asabeneh'\nlet lastName = 'Yetayeh'\nlet country = 'Finland'\nlet city = 'Helsinki'\nlet language = 'JavaScript'\nlet job = 'teacher'\n```\n\n### String Concatenation\n\nConnect two or more strings together is called concatenation.\n\n```js\n// Declaring different variables of different data types\nlet space = ' '\nlet firstName = 'Asabeneh'\nlet lastName = 'Yetayeh'\nlet country = 'Finland'\nlet city = 'Helsinki'\nlet language = 'JavaScript'\nlet job = 'teacher'\n```\n\n```js\nlet fullName = firstName + space + lastName; // concatenation, merging two string together.\nconsole.log(fullName);\n```\n\n```sh\nAsabeneh Yetayeh\n```\n\nWe can concatenate string in different ways.\n\n#### Concatenating using addition operator\n\nConcatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the second way.\n\n```js\n// Declaring different variables of different data types\nlet space = ' '\nlet firstName = 'Asabeneh'\nlet lastName = 'Yetayeh'\nlet country = 'Finland'\nlet city = 'Helsinki'\nlet language = 'JavaScript'\nlet job = 'teacher'\nlet age = 250\nlet fullName = firstName + space + lastName\n\nlet personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5\n\nconsole.log(personInfoOne)\n```\n\n```sh\nAsabeneh Yetayeh. I am 250. I live in Finland\n```\n\n#### Long Literal Strings\n\nA string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\\\\) at the end of each line to indicate that the string will continue on the next line.\n**Example:**\n\n```js\nconst paragraph = \"My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\\\nI am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \\\nNode.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \\\nIn the end of 2019, I was thinking to expand my teaching and to reach \\\nto global audience and I started a Python challenge from November 20 - December 19.\\\nIt was one of the most rewarding and inspiring experience.\\\nNow, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \\\nI hope you are enjoying too.\"\nconsole.log(paragraph)\n```\n\n#### Escape Sequences in string\n\nIn JavaScript and other programming language \\ followed by some characters is  an escape sequence. Let's see the most common escape characters:\n\n- \\n: new line\n- \\t: Tab means(8 spaces)\n- \\\\\\\\: Back slash\n- \\\\': Single quote (')\n- \\\\\":Double quote (\")\n  \n```js\nconsole.log('I hope every one is enjoying the 30 Days Of JavaScript challenge.\\nDo you ?') // line break\nconsole.log('Days\\tTopics\\tExercises')\nconsole.log('Day 1\\t3\\t5')\nconsole.log('Day 2\\t3\\t5')\nconsole.log('Day 3\\t3\\t5')\nconsole.log('Day 4\\t3\\t5')\nconsole.log('This is a back slash  symbol (\\\\)') // To write a back slash\nconsole.log('In every programming language it starts with \\\"Hello, World!\\\"')\nconsole.log(\"In every programming language it starts with \\'Hello, World!\\'\")\nconsole.log('The saying \\'Seeing is Believing\\' is\\'t correct in 2020')\n```\n\n#### Template Literals(Template Strings)\n\nTo create a template string, we use two backticks. We can inject data as expression inside a template string. To inject data, we enclose the expression with a curly bracket({}) followed by a $ sign. See the syntax below.\n\n```js\n//Syntax\n`String literal text`\n`String literal text ${expression}`\n```\n\n**Example: 1**\n\n```js\nconsole.log(`The sum of 2 and 3 is 5`)              // statically writing the data\nlet a = 2\nlet b = 3\nconsole.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically\n```\n\n**Example:2**\n\n```js\nlet firstName = 'Asabeneh'\nlet lastName = 'Yetayeh'\nlet country = 'Finland'\nlet city = 'Helsinki'\nlet language = 'JavaScript'\nlet job = 'teacher'\nlet age = 250\nlet fullName = firstName + ' ' + lastName\n\nlet personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method\nlet personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`\nconsole.log(personInfoTwo)\nconsole.log(personInfoThree)\n```\n\n```sh\nI am Asabeneh Yetayeh. I am 250. I live in Finland.\nI am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.\n```\n\nUsing a string template or string interpolation method, we can add expression, which could be a value or some operations(comparison, arithmetic operations, ternary operation).\n\n```js\nlet a = 2\nlet b = 3\nconsole.log(`${a} is greater than ${b}: ${a \u003e b}`)\n```\n\n```sh\n2 is greater than 3: false\n```\n\n### String Methods\n\nEverything 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.\n\n1. *length*: The string *length* method returns the number of characters in a string included empty space.\n  **Example:**\n\n   ```js\n   let js = 'JavaScript'\n   console.log(js.length)         // 10\n   let firstName = 'Asabeneh'\n   console.log(firstName.length)  // 8\n   ```\n\n2. *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.\n\n  ![Accessing sting by index](./images/string_indexes.png)\n  \nLet us access different characters in 'JavaScript' string.\n\n```js\nlet string = 'JavaScript'\nlet firstLetter = string[0]\n\nconsole.log(firstLetter)           // J\n\nlet secondLetter = string[1]       // a\nlet thirdLetter = string[2]\nlet lastLetter = string[9]\n\nconsole.log(lastLetter)            // t\n\nlet lastIndex = string.length - 1\n\nconsole.log(lastIndex)  // 9\nconsole.log(string[lastIndex])    // t\n```\n\n3. *toUpperCase()*: this method changes the string to uppercase letters.\n\n```js\nlet string = 'JavaScript'\n\nconsole.log(string.toUpperCase())     // JAVASCRIPT\n\nlet firstName = 'Asabeneh'\n\nconsole.log(firstName.toUpperCase())  // ASABENEH\n\nlet country = 'Finland'\n\nconsole.log(country.toUpperCase())    // FINLAND\n```\n\n4. *toLowerCase()*: this method changes the string to lowercase letters.\n\n```js\nlet string = 'JavasCript'\n\nconsole.log(string.toLowerCase())     // javascript\n\nlet firstName = 'Asabeneh'\n\nconsole.log(firstName.toLowerCase())  // asabeneh\n\nlet country = 'Finland'\n\nconsole.log(country.toLowerCase())   // finland\n```\n\n5. *substr()*: It takes two arguments, the starting index and number of characters to slice.\n\n```js\nlet string = 'JavaScript'\nconsole.log(string.substr(4,6))    // Script\n\nlet country = 'Finland'\nconsole.log(country.substr(3, 4))   // land\n```\n\n6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index.\n\n```js\nlet string = 'JavaScript'\n\nconsole.log(string.substring(0,4))     // Java\nconsole.log(string.substring(4,10))    // Script\nconsole.log(string.substring(4))       // Script\n\nlet country = 'Finland'\n\nconsole.log(country.substring(0, 3))   // Fin\nconsole.log(country.substring(3, 7))   // land\nconsole.log(country.substring(3))      // land\n```\n\n7. *split()*: The split method splits a string at a specified place.\n\n```js\nlet string = '30 Days Of JavaScript'\n\nconsole.log(string.split())     // [\"30 Days Of JavaScript\"]\nconsole.log(string.split(' '))  // [\"30\", \"Days\", \"Of\", \"JavaScript\"]\n\nlet firstName = 'Asabeneh'\n\nconsole.log(firstName.split())    // [\"Asabeneh\"]\nconsole.log(firstName.split(''))  // [\"A\", \"s\", \"a\", \"b\", \"e\", \"n\", \"e\", \"h\"]\n\nlet countries = 'Finland, Sweden, Norway, Denmark, and Iceland'\n\nconsole.log(countries.split(','))  // [\"Finland\", \" Sweden\", \" Norway\", \" Denmark\", \" and Iceland\"]\nconsole.log(countries.split(', ')) //  [\"Finland\", \"Sweden\", \"Norway\", \"Denmark\", \"and Iceland\"]\n```\n\n8. *trim()*: Removes trailing space in the beginning or the end of a string.\n\n```js\nlet string = '   30 Days Of JavaScript   '\n\nconsole.log(string)     \nconsole.log(string.trim(' '))\n\nlet firstName = ' Asabeneh '\n\nconsole.log(firstName)\nconsole.log(firstName.trim())\n```\n\n```sh\n   30 Days Of JavasCript   \n30 Days Of JavasCript\n  Asabeneh \nAsabeneh\n```\n\n9. *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.\n\n```js\nlet string = '30 Days Of JavaScript'\n\nconsole.log(string.includes('Days'))     // true\nconsole.log(string.includes('days'))     // false\nconsole.log(string.includes('Script'))   // true\nconsole.log(string.includes('script'))   // false\nconsole.log(string.includes('java'))     // false\nconsole.log(string.includes('Java'))     // true\n\nlet country = 'Finland'\n\nconsole.log(country.includes('fin'))     // false\nconsole.log(country.includes('Fin'))     // true\nconsole.log(country.includes('land'))    // true\nconsole.log(country.includes('Land'))    // false\n```\n\n10. *replace()*: takes to parameter the old substring and new substring.\n\n```js\nstring.replace(oldsubstring, newsubstring)\n```\n\n```js\nlet string = '30 Days Of JavaScript'\nconsole.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python\n\nlet country = 'Finland'\nconsole.log(country.replace('Fin', 'Noman'))       // Nomanland\n```\n\n11. *charAt()*: Takes index and it returns the value at that index\n\n```js\nstring.charAt(index)\n```\n\n```js\nlet string = '30 Days Of JavaScript'\nconsole.log(string.charAt(0))        // 3\n\nlet lastIndex = string.length - 1\nconsole.log(string.charAt(lastIndex)) // t\n```\n\n12. *charCodeAt()*: Takes index and it returns char code(ASCII number) of the value at that index\n\n```js\nstring.charCodeAt(index)\n```\n\n```js\nlet string = '30 Days Of JavaScript'\nconsole.log(string.charCodeAt(3))        // D ASCII number is 51\n\nlet lastIndex = string.length - 1\nconsole.log(string.charCodeAt(lastIndex)) // t ASCII is 116\n\n```\n\n13.  *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\n\n```js\nstring.indexOf(substring)\n```\n\n```js\nlet string = '30 Days Of JavaScript'\n\nconsole.log(string.indexOf('D'))          // 3\nconsole.log(string.indexOf('Days'))       // 3\nconsole.log(string.indexOf('days'))       // -1\nconsole.log(string.indexOf('a'))          // 4\nconsole.log(string.indexOf('JavaScript')) // 11\nconsole.log(string.indexOf('Script'))     //15\nconsole.log(string.indexOf('script'))     // -1\n```\n\n14.  *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\n\n```js\n//syntax\nstring.lastIndexOf(substring)\n```\n\n```js\nlet string = 'I love JavaScript. If you do not love JavaScript what else can you love.'\n\nconsole.log(string.lastIndexOf('love'))       // 67\nconsole.log(string.lastIndexOf('you'))        // 63\nconsole.log(string.lastIndexOf('JavaScript')) // 38\n```\n\n15. *concat()*: it takes many substrings and creates concatenation.\n\n```js\nstring.concat(substring, substring, substring)\n```\n\n```js\nlet string = '30'\nconsole.log(string.concat(\"Days\", \"Of\", \"JavaScript\")) // 30DaysOfJavaScript\n\nlet country = 'Fin'\nconsole.log(country.concat(\"land\")) // Finland\n```\n\n16. *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).\n\n```js\n//syntax\nstring.startsWith(substring)\n```\n\n```js\nlet string = 'Love is the best to in this world'\n\nconsole.log(string.startsWith('Love'))   // true\nconsole.log(string.startsWith('love'))   // false\nconsole.log(string.startsWith('world'))  // false\n\nlet country = 'Finland'\n\nconsole.log(country.startsWith('Fin'))   // true\nconsole.log(country.startsWith('fin'))   // false\nconsole.log(country.startsWith('land'))  //  false\n```\n\n17. *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).\n\n```js\nstring.endsWith(substring)\n```\n\n```js\nlet string = 'Love is the best to in this world'\n\nconsole.log(string.endsWith('world'))         // true\nconsole.log(string.endsWith('love'))          // false\nconsole.log(string.endsWith('in this world')) // true\n\nlet country = 'Finland'\n\nconsole.log(country.endsWith('land'))         // true\nconsole.log(country.endsWith('fin'))          // false\nconsole.log(country.endsWith('Fin'))          //  false\n```\n\n18. *search*: it takes a substring as an argument and it returns the index of the first match.\n\n```js\nstring.search(substring)\n```\n\n```js\nlet string = 'I love JavaScript. If you do not love JavaScript what else can you love.'\nconsole.log(string.search('love')) // 2\n```\n\n19. *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.\n\n```js\nlet string = 'love'\nlet patternOne = /love/     // with out any flag\nlet patternTwo = /love/gi   // g-means to search in the whole text, i - case insensitive\n```\n\nMatch syntax\n\n```js\n// syntax\nstring.match(substring)\n```\n\n```js\nlet string = 'I love JavaScript. If you do not love JavaScript what else can you love.'\nconsole.log(string.match('love'))\n```\n\n```sh\n[\"love\", index: 2, input: \"I love JavaScript. If you do not love JavaScript what else can you love.\", groups: undefined]\n```\n\n```js\nlet pattern = /love/gi\nconsole.log(string.match(pattern))   // [\"love\", \"love\", \"love\"]\n```\n\nLet us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section.\n\n```js\nlet txt = 'In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge'\nlet regEx = /\\d+/\n\n// d with escape character means d not a normal d instead acts a digit\n// + means one or more digit numbers,\n// if there is g after that it means global, search everywhere.\n\nconsole.log(txt.match(regEx))  // [\"2\", \"0\", \"1\", \"9\", \"3\", \"0\", \"2\", \"0\", \"2\", \"0\"]\nconsole.log(txt.match(/\\d+/g)) // [\"2019\", \"30\", \"2020\"]\n```\n\n20.   *repeat()*: it takes a number argument and it returned the repeated version of the string.\n\n```js\nstring.repeat(n)\n```\n\n```js\nlet string = 'love'\nconsole.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove\n```\n\n## Checking Data types and Casting\n\n### Checking data types\n\n- 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.\n  **Example:**\n\n```js\n// Different javascript data types\n// Let's declare different data types\n\nlet firstName = 'Asabeneh'      // string\nlet lastName = 'Yetayeh'        // string\nlet country = 'Finland'         // string\nlet city = 'Helsinki'           // string\nlet age = 250                   // number, it is not my real age, do not worry about it\nlet job                         // undefined, because a value was not assigned\n\nconsole.log(typeof 'Asabeneh')  // string\nconsole.log(typeof firstName)   // string\nconsole.log(typeof 10)          // number\nconsole.log(typeof 3.14)        // number\nconsole.log(typeof true)        // boolean\nconsole.log(typeof false)       // boolean\nconsole.log(typeof NaN)         // number\nconsole.log(typeof job)         // undefined\nconsole.log(typeof undefined)   // undefined\nconsole.log(typeof null)        // object\n```\n\n### Changing data type(Casting)\n\n- Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_\n  When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.\n\n#### String to Int\n\nWe 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.\nWe can convert string to number using the following methods:\n\n- parseInt()\n- Number()\n- Plus sign(+)\n\n```js\nlet num = '10'\nlet numInt = parseInt(num)\nconsole.log(numInt) // 10\n```\n\n```js\nlet num = '10'\nlet numInt = Number(num)\n\nconsole.log(numInt) // 10\n```\n\n```js\nlet num = '10'\nlet numInt = +num\n\nconsole.log(numInt) // 10\n```\n\n#### String to Float\n\nWe 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.\nWe can convert string float to number using the following methods:\n\n- parseFloat()\n- Number()\n- Plus sign(+)\n\n```js\nlet num = '9.81'\nlet numFloat = parseFloat(num)\n\nconsole.log(numFloat) // 9.81\n```\n\n```js\nlet num = '9.81'\nlet numFloat = Number(num)\n\nconsole.log(numFloat) // 9.81\n```\n\n```js\nlet num = '9.81'\nlet numFloat = +num\n\nconsole.log(numInt) // 9.81\n```\n\n#### Float to Int\n\nWe can convert float numbers to integers.\nWe use the following method to convert float to int:\n\n- parseInt()\n  \n```js\nlet num = 9.81\nlet numInt = parseInt(num)\n\nconsole.log(numInt) // 9\n```\n\n\n### Exercises: Data Types\n\n1. Declare variables and assign string, boolean, undefined and null data types\n1. The JavaScript ***typeof*** operator uses to check different data types. Check the data type of each variables from question number 1.\n\n#### Exercise: String\n\n1. Declare a variable name company and assign it to an initial value **'Coding Academy'**.\n1. Print the string on the browser console using __console.log()__\n1. Print the __length__ of the string on the browser console using _console.log()_\n1. Change all the string to capital letters using __toUpperCase()__ method\n1. Change all the string to lowercase letters using __toLowerCase()__ method\n1. Cut(slice) out the first word of the string using __slice__, __substr()__ or __substring()__ method\n1. 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'__\n1. Check if the string contains a word __Academy__ using __includes()__ method\n1. Split the __string__ into __array__ using __split()__ method\n1. Split the string Coding Academy at the space using __split()__ method\n1. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.\n1. Change Coding Academy to Microsoft Academy using __replace()__ method.\n1. What is character at index 10 in 'Coding Academy' string use __charAt()__ method.\n1. What is the character code of A in 'Coding Academy' string using __charCodeAt()__\n1. Use __indexOf__ to determine the position of the first occurrence of c in Coding Academy\n1. Use __lastIndexOf__ to determine the position of the last occurrence of c in Coding Academy.\n1. 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'__\n1. 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'__\n1. 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'__\n1. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' Coding Academy '.\n1. Use __startsWith()__ method with the string Coding Academy make the result true\n1. Use __endsWith()__ method with the string Coding Academy make the result true\n1. Use __match()__ method to find all the c’s in Coding Academy\n1. 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'__\n1. Use __concat()__ and merge 'Coding' and 'Academy' to a single string, 'Coding Academy'\n1. Use __repeat()__ method to print Coding Academy 5 times\n1. 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.'\n\n### Booleans\n\nBoolean value is either true or false. Any comparisons return a boolean value which is either true or false.\n\n```js\nlet isLightOn = true;\nlet isRaining = false;\nlet hungry = false;\nlet isMarried = true;\n```\n\n#### Exercise: Booleans\n\nBoolean value is either true or false.\n\n1. Write three JavaScript statement which provide truthy value.\n1. Write three JavaScript statement which provide falsy value.\n1. Use all the following comparison operators to compare the following values: \u003e, \u003c \u003e=, \u003c=, !=, !==,===.\n   Which are true or which are false ?\n   1. 4 \u003e 3\n   1. 4 \u003e= 3\n   1. 4 \u003c 3\n   1. 4 \u003c= 3\n   1. 4 == 4\n   1. 4 === 4\n   1. 4 != 4\n   1. 4 !== 4\n   1. 4 != '4'\n   1. 4 == '4'\n   1. 4 === '4'\n\n### Undefined\n\n```js\nlet firstName;\nconsole.log(firstName); //not defined, because it is not assigned to a value yet\n```\n\n### Null\n\n```js\nlet empty = null;\nconsole.log(empty); // -\u003e null , means no value\n```\n\n### Exercise - 6 : Data types\n\nString, number, boolean, null, undefined and symbol(ES6) are JavaScript primitive data types.\n\n1. The JavaScript *typeof* operator uses to check different data types. Check the data type of each variables from question number 1.\n\n## Operators\n\n### Arithmetic Operators\n\nArithmetic operators are mathematical operators:+, -, _, /, _\n\n```js\nlet numOne = 4;\nlet numTwo = 3;\nlet sum = numOne + numTwo;\nlet diff = numOne - numTwo;\nlet mult = numOne * numTwo;\nlet div = numOne / numTwo;\nlet remainder = numOne % numTwo;\n\nconsole.log(sum, diff, mult, div, remainder); // -\u003e7,1,12,1.33,1\n\nlet PI = 3.14;\nlet radius = 100;          // length in meter\n\nconst gravity = 9.81;      // in m/s2\nlet mass = 72;             // in Kilogram\nconst boilingPoint = 100;  // temperature in oC, boiling point of water\nconst bodyTemp = 37;       // body temperature in oC\n\n// Lets calculate area of a circle\n\nconst areaOfCircle = PI * radius * radius;\nconsole.log(areaOfCircle); // -\u003e 314 m\n\n// Lets calculate weight of a substance\nconst weight = mass * gravity;\nconsole.log(weight); // -\u003e 706.32 N(Newton)\n\n// ConcatEnating string with numbers using string interpolation\n/*\n The boiling point of water is 100 oC.\n Human body temperature is 37 oC.\n The gravity of earth is 9.81 m/s2.\n */\nconsole.log(\n  `The boiling point of water is ${boilingPoint} oC.\\nHuman body temperature is ${body} oC.\\nThe gravity of earth is ${gravity} m / s2.`\n);\n```\n\n### Exercises : Arithmetic Operators\n\nJavaScript arithmetic operators are addition(+), subtraction(-), multiplication(\\*), division(/), modulus(%), increment(++) and decrement(--).\n\n```js\nlet operandOne = 4;\nlet operandTwo = 3;\n```\n\nUsing the above operands apply different JavaScript arithmetic operators\n\n### Logical Operators\n\nThe following symbols are the common logical operators:\n\u0026\u0026(ampersand) , ||(pipe) and !(negation).\n\u0026\u0026 gets true only if the two operands are true.\n|| gets true either of the operand is true.\n! negates true to false, false to true.\n\n```js\n// \u0026\u0026 ampersand example\n\nconst check = 4 \u003e 3 \u0026\u0026 10 \u003e 5; // true and true -\u003e true\nconst check = 4 \u003e 3 \u0026\u0026 10 \u003c 5; // true and false -\u003e false\nconst check = 4 \u003c 3 \u0026\u0026 10 \u003c 5; // false and false -\u003e false\n\n// || pipe or, example\n\nconst check = 4 \u003e 3 || 10 \u003e 5; // true and true -\u003e true\nconst check = 4 \u003e 3 || 10 \u003c 5; // true and false -\u003e true\nconst check = 4 \u003c 3 || 10 \u003c 5; // false and false -\u003e false\n\n// ! Negation examples\n\nlet check = 4 \u003e 3;           // -\u003e true\nlet check = !(4 \u003e 3);        // -\u003e false\nlet isLightOn = true;        // -\u003e true\nlet isLightOff = !isLightOn; // -\u003e false\nlet isMarried = !false;      // -\u003e true\n```\n\n### Exercises: Logical Operators\n\nWhich are true or which are false ?\n\n1. 4 \u003e 3 \u0026\u0026 10 \u003c 12\n1. 4 \u003e 3 \u0026\u0026 10 \u003e 12\n1. 4 \u003e 3 || 10 \u003c 12\n1. 4 \u003e 3 || 10 \u003e 12\n1. !(4 \u003e 3)\n1. !(4 \u003c 3)\n1. !(false)\n1. !(4 \u003e 3 \u0026\u0026 10 \u003c 12)\n1. !(4 \u003e 3 \u0026\u0026 10 \u003e 12)\n1. !(4 === '4')\n\n### Comparison Operators\n\n```js\n4 \u003e 3;\n4 \u003e= 4;\n4 \u003c 3;\n4 \u003c= 3;\n4 != 3;\n4 !== '4';\n4 == '4';\n4 === '4';\n4 === 4;\n```\n\n### Exercise: Comparison Operators\n\nBoolean value is either true or false. Any comparison return a boolean either true or false.\nUse all the following comparison operators to compare the following values: \u003e, \u003c \u003e=, \u003c=, !=, !==,===.\nWhich are true or which are false ?\n\n1. 4 \u003e 3\n1. 4 \u003e= 3\n1. 4 \u003c 3\n1. 4 \u003c= 3\n1. 4 == 4\n1. 4 === 4\n1. 4 != 4\n1. 4 !== 4\n1. 4 != '4'\n1. 4 == '4'\n1. 4 === '4'\n\n## Conditionals\n\n### if\n\nWe use if condition to check only on condition.\n\n```js\nif (condition) {\n  // code goes here\n}\n\nlet isRaining = true;\nif (isRaining) {\n  console.log('Remember to take your rain coat.');\n}\n```\n\n### if else\n\nWhen we have more than one condition we use the if and else condition.\n\n```js\nif (condition) {\n  // if the condition meets, this block of code runs\n} else {\n  // if condition doesn't meet, this block code runs\n}\n\nlet isRaining = true;\nif (isRaining) {\n  console.log('You need a rain coat.');\n} else {\n  console.log('No need for a rain coat.');\n}\n```\n\n### if else if else\n\nWhenever we have multiple conditions.\n\n```js\n// if else if else\nlet weather = 'sunny';\nif (weather === 'rainy') {\n  console.log('You need a rain coat.');\n} else if (weather === 'cloudy') {\n  console.log('It might be cold, you need a jacket.');\n} else if (weather === 'sunny') {\n  console.log('Go out freely.');\n} else {\n  console.log('No need for rain coat.');\n}\n```\n\n### switch\n\nSwitch an alternative for if else if else\n\n```js\nvar weather = 'cloudy';\nswitch (weather) {\n  case 'rainy':\n    console.log('You need a rain coat.');\n    break;\n  case 'cloudy':\n    console.log('It might be cold, you need a jacket.');\n    break;\n  case 'sunny':\n    console.log('Go out freely.');\n    break;\n  default:\n    console.log(' No need for rain coat.');\n    break;\n}\n// Switch More Examples\nvar dayUserInput = prompt('What day is it ?');\nvar day = dayUserInput.toLowerCase();\nswitch (day) {\n  case 'monday':\n    console.log('Today is Monday');\n    break;\n  case 'tuesday':\n    console.log('Today is Tuesday');\n    break;\n  case 'wednesday':\n    console.log('Today is Wednesday');\n    break;\n  case 'thursday':\n    console.log('Today is Thursday');\n    break;\n  case 'friday':\n    console.log('Today is Friday');\n    break;\n  case 'saturday':\n    console.log('Today is Saturday');\n    break;\n  case 'sunday':\n    console.log('Today is Sunday');\n    break;\n\n  default:\n    console.log('It is not a week day.');\n    break;\n}\n```\n\n### Ternary Operators\n\nAnother way to write conditionals is using ternary operators.\n\n```js\nlet isRaining = true;\nisRaining\n  ? console.log('You need a rain coat.')\n  : console.log('No need for a rain coat.');\n```\n\n### Exercise: Conditionals\n\n1. 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.\n   Output:\n\n   ```sh\n   Enter your age: 30\n   You are old enough to drive.\n   ```\n\n   Output:\n  \n   ```sh\n   Enter your age:15\n   You are left with 3 years to drive.\n   ```\n\n1. 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.\n   Output:\n  \n   ```sh\n   Enter your age: 30\n   You are 5 years older than me.\n   ```\n\n1. If a is greater than b return a is greater than b else a is less than b.\n   Output:\n\n   ```sh\n    let a = 4\n    let b = 3\n    4 is greater than 3\n    ```\n  \n1. Write a code which give grade students according to theirs scores:\n   - 80-100, A\n   - 70-89, B\n   - 60-69, C\n   - 50-59, D\n   - 0 -49, F\n1. Check if the season is Autumn, Winter, Spring or Summer.\n   If the user input is:\n   - September, October or November, the season is Autumn.\n   - December, January or February, the season is Winter.\n   - March, April or May, the season is Spring\n   - June, July or August, the season is Summer\n\n## Loops\n\nIn programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.\n\n### For Loop\n\n```js\n// for loop structure\nfor(initialization, condition, increment/decrement){\n  // code goes here\n}\nfor(let i = 0; i \u003c= 5; i++){\n  console.log(i)\n}\n\n```\n\n### While loop\n\n```js\nlet i = 0;\nwhile (i \u003c= 5) {\n  console.log(i);\n  i++;\n}\n```\n\n### Do while loop\n\n```js\nlet i = 0;\ndo {\n  console.log(i);\n  i++;\n} while (i \u003c= 5);\n```\n\n### Exercises:Loops\n\n1. Iterate 0 to 10 using for loop, do the same using while and do while loop.\n1. Iterate 10 to 0 using for loop, do the same using while and do while loop.\n1. Write a loop that makes seven calls to console.log to output the following triangle:\n\n   ```js\n       #\n       ##\n       ###\n       ####\n       #####\n       ######\n       #######\n   ```\n\n1. Iterate the array, ['HTML', 'CSS', 'JavaScript'] using a for loop and print out the items.\n1. Use for loop to iterate from 0 to 100 and print only even numbers\n1. Use for loop to iterate from 0 to 100 and print only odd numbers\n1. Use for loop to iterate from 0 to 100 and print and print the sum of all numbers.\n\n   ```js\n   The sum all numbers is 5050.\n   ```\n\n1. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.\n\n   ```js\n   The sum of all evens is 2550. And the sum of all odds is 2500.\n   ```\n\n## Arrays\n\nIn 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.\n\n```js\nconst numbers = [0, 3.14, 9.81, 37, 98.6, 100]; // set of numbers\n\nconsole.log(numbers.length) // =\u003e to know the size of the array, which is 6\nconsole.log(numbers)        // -\u003e [0, 3.14, 9.81, 37, 98.6, 100]\nconsole.log(numbers[0])     //  -\u003e 0\nconsole.log(numbers[5])     //  -\u003e 100\n\nlet lastIndex = numbers.length - 1;\nconsole.log(numbers[lastIndex]) -\u003e 100\nconst webTechs = [\n  'HTML',\n  'CSS',\n  'JavaScript',\n  'React',\n  'Redux',\n  'Node',\n  'MongoDB'\n]; // List of web technologies\n\nconsole.log(webTechs)        // all the array items\nconsole.log(webTechs.length) // =\u003e to know the size of the array, which is 7\nconsole.log(webTechs[0])     //  -\u003e HTML\nconsole.log(webTechs[6])     //  -\u003e MongoDB\n\nlet lastIndex = webTechs.length - 1;\nconsole.log(webTechs[lastIndex]) -\u003e MongoDB\nconst countries = [\n  'Albania',\n  'Bolivia',\n  'Canada',\n  'Denmark',\n  'Ethiopia',\n  'Finland',\n  'Germany',\n  'Hungary',\n  'Ireland',\n  'Japan',\n  'Kenya'\n]; // List of countries;\n\nconsole.log(countries)     // -\u003e all countries in array\nconsole.log(countries[0])  //  -\u003e Albania\nconsole.log(countries[10]) //  -\u003e Kenya\n\nlet lastIndex = countries.length - 1;\nconsole.log(countries[lastIndex]) -\u003e // Kenya\n\nconst shoppingCart = [\n  'Milk',\n  'Mango',\n  'Tomato',\n  'Potato',\n  'Avocado',\n  'Meat',\n  'Eggs',\n  'Sugar'\n]; // List of food products\n\nconsole.log(shoppingCart)     // -\u003e all shoppingCart in array\nconsole.log(shoppingCart[0])  //  -\u003e Milk\nconsole.log(shoppingCart[7])  //  -\u003e Sugar\n\nlet lastIndex = shoppingCart.length - 1;\nconsole.log(shoppingCart[lastIndex]) -\u003e // Sugar\n```\n\n### Exercise : Arrays\n\n1. Declare an _empty_ array;\n1. Declare an array with more than 5 number of items\n1. Find the length of your array\n1. Get the first item, the middle item and the last item of the array\n1. Declare an array called _mixedDataTypes_,put different data types and in your array and the array size should be greater than 5\n1. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.\n1. Print the array using _console.log()_\n1. Print the number of companies in the array\n1. Print the first company, middle and last company\n1. Print out each company\n1. Change companies to uppercase and print them out\n1. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.\n1. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is _not found_.\n1. Filter out companies which have more than one 'o' without the filter method\n1. Sort the array using _sort()_ method\n1. Reverse the array without _reverse_ method\n1. Reverse the array using _reverse()_ method\n1. Slice out the first 3 companies from the array\n1. Slice out the last 3 companies from the array\n1. Slice out the middle IT company or companies from the array\n1. Remove the first IT company from the array\n1. Remove the middle IT company or companies from the array\n1. Remove the last IT company from the array\n1. Remove all IT companies\n\n## More on Arrays\n\nThere 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_\nArray:To create an array.\n\n```js\nconst arr = Array(); // creates an an empty array\nconsole.log(arr);\n\nconst eightEmptyValues = Array(8); // it creates eight empty values\nconsole.log(eightEmptyValues);     // [empty x 8]\n```\n\n- *fill*: Fill all the array elements with a static value\n\n```js\nconst arr = Array();                     // creates an an empty array\nconsole.log(arr);\nconst eightXvalues = Array(8).fill('X'); // it creates eight element values\nconsole.log(eightXvalues);               // ['X', 'X','X','X','X','X','X','X']\n```\n\n- *concat*: To concatenate two arrays.\n\n```js\nconst firstList = [1, 2, 3];\nconst secondList = [4, 5, 6];\nconst thirdList = firstList.concat(secondList);\n\nconsole.log(thirdList); // [1,2,3,4,5,6]\n```\n\n- *length*: To know the size of the array\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nconsole.log(numbers.length); // -\u003e 5\n```\n\n- *indexOf*: To check if an item exist in an array. If it exist it returns the index else it returns -1.\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\n\nconsole.log(numbers.indexOf(5));  // -\u003e 4\nconsole.log(numbers.indexOf(0));  // -\u003e -1\nconsole.log(numbers.indexOf(1));  // -\u003e 0\nconsole.log(numbers.indexOf(6));  // -\u003e -1\n```\n\n- *lastIndexOf* :Give the position of the last item in the array. If it exist it returns the index else it returns -1.\n\n```js\nconst numbers = [1, 2, 3, 4, 5, 3, 1, 2];\n\nconsole.log(numbers.lastIndexOf(2));  // -\u003e 7\nconsole.log(numbers.lastIndexOf(0));  // -\u003e -1\nconsole.log(numbers.lastIndexOf(1));  // -\u003e 6\nconsole.log(numbers.lastIndexOf(4));  // -\u003e 3\nconsole.log(numbers.lastIndexOf(6));  // -\u003e -1\n```\n\n*includes*: To check if an item exist in an array. If it exist it returns the true else it returns false.\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\n\nconsole.log(numbers.includes(5)); // -\u003e true\nconsole.log(numbers.includes(0)); // -\u003e false\nconsole.log(numbers.includes(1)); // -\u003e true\nconsole.log(numbers.includes(6)); // -\u003e false\n```\n\n- *isArray*:  To check if the data type is an array\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nconsole.log(Array.isArray(numbers)); // -\u003e true\n\nconst number = 100;\nconsole.log(Array.isArray(number)); // -\u003e false\n```\n\n- *toString*: Converts array to string\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nconsole.log(numbers.toString()); // 1,2,3,4,5\n\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconsole.log(names.toString()); // Asabeneh,Mathias,Elias,Brook\n```\n\njoin: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.\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nconsole.log(numbers.join());        // 1,2,3,4,5\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconsole.log(names.join());          // Asabeneh,Mathias,Elias,Brook\nconsole.log(names.join(''));        //AsabenehMathiasEliasBrook\nconsole.log(names.join(' '));       //Asabeneh Mathias Elias Brook\nconsole.log(names.join(', '));      //Asabeneh, Mathias, Elias, Brook\nconsole.log(names.join(' # '));     //Asabeneh # Mathias # Elias # Brook\n```\n\nSlice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position\n\n```js\n  const numbers = [1,2,3,4,5];\n  console.log(numbers.slice()        // -\u003e it copies all  item\n  console.log(numbers.slice(0)       // -\u003e it copies all  item\n  console.log(numbers.indexOf(0, numbers.length)) // it copies all  item\n  console.log(numbers.slice(1,4))    // -\u003e [2,3,4] // it doesn't include the ending position\n```\n\nSplice: It takes three parameters:Starting position, number of times to be removed and number items to be added.\n\n```js\n  const numbers = [1, 2, 3, 4, 5];\n  console.log(numbers.splice()      // -\u003e remove all items\n  console.log(numbers.splice(0,1))  // remove the first item\n  console.log(numbers.splice(3, 3, 6, 7, 8)) // -\u003e [1,2,6,7,8] //it removes two item and replace three items\n\n```\n\n- *push*: adding item in the end\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nnumbers.push(6);\n\nconsole.log(numbers);  // -\u003e [1,2,3,4,5,6]\n\nnumbers.pop();         // -\u003e remove one item from the end\nconsole.log(numbers);  // -\u003e [1,2,3,4,5]\n```\n\n- *pop*: Removing item in the end\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nnumbers.pop(); // -\u003e remove one item from the end\n\nconsole.log(numbers); // -\u003e [1,2,3,4]\n```\n\n- *shift*: Removing item in the beginning\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nnumbers.shift(); // -\u003e remove one item from the beginning\n\nconsole.log(numbers); // -\u003e [2,3,4,5]\n```\n\n- *unshift*: Adding item in the beginning\n\n```js\nconst numbers = [1, 2, 3, 4, 5];\nnumbers.unshift(0);             // -\u003e remove one item from the beginning\nconsole.log(numbers);           // -\u003e [0,1,2,3,4,5]\n```\n\n---\n\n### Exercise -10 : Array Methods\n\n```js\nconst shoppingCart = ['Milk','Coffee','Tea', 'Honey'];\nconst todoList = [\n  {\n    task:'Learn JavaScript',\n    time:'4/3/2019 8:30',\n    completed:true\n  },\n  {\n    task:'Help some in need',\n    time:'4/3/2019 4:00',\n    completed:false\n  },\n  {\n    task:'Do some physical exercises',\n    time:'4/3/2019 6:00',\n    completed:false\n  }\n]\n```\n\n## Functions\n\nA function is a block of code designed to perform a certain task.\nA 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.\nA function can be declared or created in couple of ways:\n\n- _Declaration function_\n- _Expression function_\n- _Anonymous function_\n- _Arrow function_\n\n### Function Declaration\n\n```js\n//function without parameter\n\nfunction functionName(){\n// code goes here\n}\nfunctionName() // calling function by its name and with parentheses\n\n//function without parameter\n\nfunction addTwoNumbers() {\n  var numOne = 10;\n  var numTwo = 20;\n  var sum = numOne + numTwo;\n  console.log(sum);\n}\naddTwoNumbers(); // function has to be called to be executed by it name\n\n// function with one parameter\n\nfunction functionName(parm1){\n  //code goes her\n}\nfunctionName(parm1); // during calling or invoking one argument needed\n\nfunction areaOfCircle(r){\n  let area = Math.PI * r * r;\n  return area;\n}\nconsole.log(areaOfCircle(10)) // should be called with one argument\n\nfunction square(number) {\n  return number * number;\n}\nconsole.log(square(10));\n\n// function with two parameters\nfunction functionName(parm1, parm2){\n  //code goes her\n}\nfunctionName(parm1,parm2); // during calling or invoking two arguments needed\n\n// Function without parameter doesn't take input, so lets make a parameter with parameter\nfunction sumTwoNumbers(numOne, numTwo) {\n  var sum = numOne + numTwo;\n  console.log(sum);\n}\nsumTwoNumbers(10, 20); // calling functions\n\n// If a function doesn't return it doesn't store data, so it should return\nfunction sumTwoNumbersAndReturn(numOne, numTwo) {\n  var sum = numOne + numTwo;\n  return sum;\n}\nconsole.log(sumTwoNumbersAndReturn(10, 20));\n\nfunction printFullName(firstName, lastName) {\n  return `${firstName} ${lastName}`;\n}\nconsole.log(printFullName('Asabeneh', 'Yetayeh'));\nconsole.log(printFullName('Dean', 'Phan'));\n\n// function with multiple parameters\nfunction functionName(parm1, parm2, parm3,...){\n  //code goes ther\n}\nfunctionName(parm1,parm2,parm3,...) // during calling or invoking three arguments needed\n\n\n// this function takes array as a parameter and sum up the numbers in the array\nfunction sumArrayValues(arr) {\n  var sum = 0;\n  for (var i = 0; i \u003c arr.length; i++) {\n    sum = sum + numbers[i];\n  }\n  return sum;\n}\nconst numbers = [1, 2, 3, 4, 5];\nconsole.log(sumArrayValues(numbers));\n  \n\nconst areaOfCircle = (radius) =\u003e {\n      let area = Math.PI * radius * radius;\n      return area;\n    }\nconsole.log(areaOfCircle(10))\n```\n\n### Function Expression\n\n```js\n//Declaration function\nfunction square(n) {\n  return n * n;\n}\nconsole.log(square(2)); // -\u003e 4\n// Function expression\nconst square = function(n) {\n  return n * n;\n};\nconsole.log(square(2)); // -\u003e 4\n```\n\n### Anonymous Function\n\n```js\n// Self invoking functions\n(function(n) {\n  return n * n;\n})(2);\n\nconst x = (function(n) {\n  return n * n;\n})(2);\nconsole.log(x) // 4\n\n```\n\n### Arrow Function\n\n```js\nconst square = n =\u003e {\n  return n * n;\n};\nconsole.log(square(2)); // -\u003e 4\n\n// if we have only one line, it can be written as follows\n// Explicit return\nconst square = n =\u003e n * n; // -\u003e 4\n```\n\n### Arrow Function vs Declaration Function\n\nArrow function and regular functions are not exactly the same.\n\n```js\n\n```\n\n### Exercise - 10 : Functions\n\n1. Declare a function _fullName_ and it print out your full name.\n1. Declare a function _fullName_ and now it takes firstName, lastName as a parameter and it returns your full - name.\n1. Declare a function _addNumbers_ and it takes two two parameters and it returns sum.\n1. An area of a rectangle is calculated as follows: _area = length x width_. Write a function which calculates _areaOfRectangle_.\n1. A perimeter of a rectangle is calculated as follows: _perimeter= 2x(length + width)_. Write a function which calculates _perimeterOfRectangle_.\n1. A volume of a rectangular prism is calculated as follows: _volume = length x width x height_. Write a function which calculates _volumeOfRectPrism_.\n1. Area of a circle is calculated as follows: _area = π x r x r_. Write a function which calculates _areaOfCircle_\n1. Circumference of a circle is calculated as follows: _circumference = 2πr_. Write a function which calculates _circumOfCircle_\n1. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.\n1. 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_.\n1. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.\n1. 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_.\n1. 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.\n   - The same groups apply to both men and women.\n   - _Underweight_: BMI is less than 18.5\n   - _Normal weight_: BMI is 18.5 to 24.9\n   - _Overweight_: BMI is 25 to 29.9\n   - _Obese_: BMI is 30 or more\n1. Write a function called _checkSeason_, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer.\n1. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method.\n\n   ```js\n   console.log(findMax(0, 10, 5));\n   10;\n   console.log(findMax(0, -10, -2));\n   0;\n   ```\n\n1. Linear equation is calculated as follows: _ax + b = c_. Write a function which calculates value of a linear equation, _solveLinEquation_.\n1. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_.\n1. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.\n1. Declare a function name _swapValues_. This function swaps value of x to y.\n\n   ```js\n   swapValues(3, 4); // x =\u003e 4, y=\u003e3\n   swapValues(4, 5); // x = 5, y = 4\n   ```\n\n1. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method).\n\n   ```js\n   console.log(reverseArray([1, 2, 3, 4, 5]));\n   [5, 4, 3, 2, 1];\n   console.log(reverseArray(['A', 'B', 'C']));\n   ['C', 'B', 'A'];\n   ```\n\n1. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.\n1. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item\n1. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item\n1. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.\n1. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.\n1. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.\n1. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.\n\n   ```sh\n   evensAndOdds(100);\n   The number of odds are 50.\n   The number of evens are 51.\n   ```\n\n1. Write a function which takes any number of arguments and return the sum of the arguments\n\n   ```js\n   sum(1, 2, 3); // -\u003e 6\n   sum(1, 2, 3, 4); // -\u003e 10\n   ```\n\n1. Writ a function which generates a _randomUserIp_.\n1. Write a function which generates a _randomMacAddress_\n1. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.\n\n   ```sh\n   console.log(randomHexaNumberGenerator());\n   '#ee33df'\n   ```\n  \n1. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id.\n\n   ```sh\n   console.log(userIdGenerator());\n   41XTDbE\n   ```\n\n1. 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.\n\n   ```sh\n   userIdGeneratedByUser()\n   'kcsy2\n   SMFYb\n   bWmeq\n   ZXOYh\n   2Rgxf\n   '\n   userIdGeneratedByUser()\n   '1GCSgPLMaBAVQZ26\n   YD7eFwNQKNs7qXaT\n   ycArC5yrRupyG00S\n   UbGxOFI7UXSWAyKN\n   dIV0SSUTgAdKwStr\n   '\n   ```\n\n1. Write a function name _rgbColorGenerator_ and it generates rgb colors.\n\n   ```sh\n   rgbColorGenerator()\n   rgb(125,244,255)\n   ```\n\n1. Write a function ***arrayOfHexaColors*** which return any number of hexadecimal colors in an array.\n1. Write a function ***arrayOfRgbColors*** which return any number of RGB colors in an array.\n1. Write a function ***convertHexaToRgb*** which converts hexa color to rgb and it returns an rgb color.\n1. Write a function ***convertRgbToHexa*** which converts rgb to hexa color  and it returns an hexa color.\n1. Write a function ***generateColors*** which can generate any number of hexa or rgb colors.\n\n    ```js\n      generateColors('hexa', 3)\n      ['#a3e12f','#03ed55','#eb3d2b']\n      generateColors('hexa', 1)\n      '#b334ef'\n\n      generateColors('rgb', 3)\n      ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']\n      generateColors('rgb', 1)\n      'rgb(33,79, 176)'\n    ```\n\n1. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array\n1. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number\n1. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not\n1. Call your function _sum_, it takes any number of arguments and it returns the sum.\n1. 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.\n1. 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.\n1. 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'.\n\n    ```js\n    console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);\n    // →['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']\n    console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft',  'IBM']);\n    // →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT',  'IBM']\n    console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']);\n    // →'Not Found'\n    ```\n\n1. Write a function called *isPrime*, which checks if a number is prime number.\n1. Write a functions which checks if all items are unique in the array.\n1. Write a function which checks if all the items of the array are the same data type.\n1. 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.\n1. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.\n\n   ```js\n   sevenRandomNumbers()[(1, 4, 5, 7, 9, 8, 0)];\n   ```\n\n## Object\n\nEverything can be an object and objects do have properties and properties have values.\nCreating an object literal. To create an object literal, we use two curly brackets.\nAn empty object\n\n```js\nconst person = {};\n```\n\nNow, 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:\n\n```js\nconst person = {\n  firstName: 'Asabeneh',\n  lastName: 'Yetayeh',\n  age: 100,\n  location: 'Helsinki',\n  skills: [\n    'HTML',\n    'CSS',\n    'JavaScript',\n    'React',\n    'Node',\n    'MongoDB',\n    'Python',\n    'D3.js'\n  ],\n  getFullName: function() {\n    return `${this.firstName}${this.lastName}`;\n  }\n};\n\nconst rectangle = {\n  length: 20,\n  width: 20,\n  getArea: function() {\n    return this.length * this.width;\n  },\n  getPerimeter: function() {\n    return 2 * (this.length + this.width);\n  }\n};\n```\n\nGetting values from an object:\n\n```js\n  const person = {\n    firstName:'Asabeneh',\n    lastName:'Yetayeh',\n    age:100,\n    location:'Helsinki',\n    skills:['HTML', 'CSS', 'JavaScript', 'React','Node','MongoDB', 'Python', 'D3.js']\n    getFullName:function() {\n      return `${this.firstName}${this.lastName}`\n    }\n  }\n  console.log(person.firstName);\n  console.log(person.lastName);\n  console.log(person.getFullName());\n  // value can be accessed\n  console.log(person['age');\n  console.log(person['location']);\n```\n\nSetting a new keys in an object\n\n```js\n  const person = {\n    firstName:'Asabeneh',\n    lastName:'Yetayeh',\n    age:100,\n    location:'Helsinki',\n    skills:['HTML', 'CSS', 'JavaScript', 'React','Node','MongoDB', 'Python', 'D3.js']\n    getFullName:function() {\n      return `${this.firstName}${this.lastName}`\n    }\n  }\n  person.nationality = 'Ethiopian'\n  person.live = 'Finland';\n  console.log(person)\n```\n\n### Object Methods\n\n_Object.assign_: To copy an object without modifying the original object\n\n```js\nconst person = {\n  name: 'Asabeneh',\n  age: 200,\n  country: 'Finland',\n  skills: ['HTML', 'CSS', 'JS'],\n  address: {\n    street: 'Heitamienkatu 16',\n    pobox: 2002,\n    city: 'Helsinki'\n  },\n  getPersonInfo: function() {\n    return `I am ${this.name} and I live in ${this.country}. I am ${this.age}.`;\n  }\n};\n\n//Object methods: Object.assign, Object.keys, Object.values, Object.entries\n//hasOwnProperty\n\nconst copyPerson = Object.assign({}, person);\nconsole.log(copyPerson);\n```\n\n_Object.keys_: To get keys of an objet as an array\n\n```js\nconst keys = Object.keys(copyPerson);\nconsole.log(keys); //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']\nconst address = Object.keys(copyPerson.address);\nconsole.log(address); //['street', 'pobox', 'city']\n```\n\n_Object.values_:To get values of an object as an array\n\n```js\nconst values = Object.values(copyPerson);\nconsole.log(values);\n```\n\n_Object.entries_:To get the keys and values in an array\n\n```js\nconst entries = Object.entries(copyPerson);\nconsole.log(entries);\n```\n\n_hasOwnProperty_: To check if a specific key or property exist in an object\n\n```js\nconsole.log(copyPerson.hasOwnProperty('name'));\nconsole.log(copyPerson.hasOwnProperty('score'));\n```\n\n### Date Object\n\nIn JavaScript current time and date is created using JavaScript Date Object.\nSome of the methods to extract date object values:*getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes*\n\n```js\nconst now = new Date ();\nconst year = now.getFullYear(); // return year\nconst month = now.getMonth() + 1; // return month(0 - 11)\nconst date = now.getDate(); // return date (1 - 31)\nconst hours = now.getHours(); // return number (0 - 23)\nconst minutes = now.getMinutes();// return number (0 -59)\nconsole.log(`${date}/${month}/${year} ${hours}:${minutes}`)\n```\n\n#### Exercises: Date Object\n\n1. Use the new Date() object to get _month, date, year, hour_ and _minute_.\n1. Write a function name _displayDateTime_ which display time in this format: 10/03/2019 04:08\n\n   ```sh\n   displayDateTime()\n   10/03/2019 04:08\n   ```\n\n### Exercises:Objects\n\n1. Create an empty object called dog\n1. Print the the dog object on the console\n1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return *woof woof*\n1. Get name, legs, color, age and bark value from the dog object\n1. Set new properties the dog object: breed, getDogInfo\n1. 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.\n1. Count logged in users,count users having greater than equal to 50 points from the following object.\n\n      ```js\n      const users = {\n        Alex: {\n          email: 'alex@alex.com',\n          skills: ['HTML', 'CSS', 'JavaScript'],\n          age: 20,\n          isLoggedIn: false,\n          points: 30\n        },\n        Asab: {\n          email: 'asab@asab.com',\n          skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],\n          age: 25,\n          isLoggedIn: false,\n          points: 50\n        },\n        Brook: {\n          email: 'daniel@daniel.com',\n          skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],\n          age: 30,\n          isLoggedIn: true,\n          points: 50\n        },\n        Daniel: {\n          email: 'daniel@alex.com',\n          skills: ['HTML', 'CSS', 'JavaScript', 'Python'],\n          age: 20,\n          isLoggedIn: false,\n          points: 40\n        },\n        John: {\n          email: 'john@john.com',\n          skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],\n          age: 20,\n          isLoggedIn: true,\n          point: 50\n        },\n        Thomas: {\n          email: 'thomas@thomas.com',\n          skills: ['HTML', 'CSS', 'JavaScript', 'React'],\n          age: 20,\n          isLoggedIn: false,\n          points: 40\n        }\n      };\n    ```\n\n1. Set your name in the users object without modifying the original users object\n1. Get all keys or properties of users object\n1. Get all the values of users object\n1. ** Develop a small JavaScript library.\n\n## JSON\n\nJSON 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.\n\n**Example:**\n\n```js\n{\n\"users\":[\n  {\n    \"firstName\":\"Asabeneh\",\n    \"lastName\":\"Yetayeh\",\n    \"age\":250,\n    \"email\":\"asab@asb.com\"\n  },\n  {\n    \"firstName\":\"Alex\",\n    \"lastName\":\"James\",\n    \"age\":25,\n    \"email\":\"alex@alex.com\"\n  },\n  {\n  \"firstName\":\"Lidiya\",\n  \"lastName\":\"Tekle\",\n  \"age\":28,\n  \"email\":\"lidiya@lidiya.com\"\n  }\n]\n}\n```\n\nThe 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.\n\nLet 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.\n\n**Example:**\n\n```js\n{\n    \"Alex\": {\n        \"email\": \"alex@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 30\n    },\n    \"Asab\": {\n        \"email\": \"asab@asab.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Redux\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 25,\n        \"isLoggedIn\": false,\n        \"points\": 50\n    },\n    \"Brook\": {\n        \"email\": \"daniel@daniel.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\"\n        ],\n        \"age\": 30,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Daniel\": {\n        \"email\": \"daniel@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Python\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"John\": {\n        \"email\": \"john@john.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\",\n            \"Node.js\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Thomas\": {\n        \"email\": \"thomas@thomas.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"Paul\": {\n        \"email\": \"paul@paul.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    }\n}\n```\n\n### Converting JSON to JavaScript Object\n\nMostly 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()_.\n\n#### JSON.parse()\n\n```js\nJSON.parse(json[, reviver])\n// json or text , the data\n// reviver is an optional callback function\n```\n\n```js\nconst usersText = `{\n\"users\":[\n  {\n    \"firstName\":\"Asabeneh\",\n    \"lastName\":\"Yetayeh\",\n    \"age\":250,\n    \"email\":\"asab@asb.com\"\n  },\n  {\n    \"firstName\":\"Alex\",\n    \"lastName\":\"James\",\n    \"age\":25,\n    \"email\":\"alex@alex.com\"\n  },\n  {\n  \"firstName\":\"Lidiya\",\n  \"lastName\":\"Tekle\",\n  \"age\":28,\n  \"email\":\"lidiya@lidiya.com\"\n  }\n]\n}`\n\nconst usersObj = JSON.parse(usersText, undefined, 4)\nconsole.log(usersObj)\n```\n\n### Using a reviver function with JSON.parse()\n\nTo 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 .\n\n```js\nconst usersText = `{\n\"users\":[\n  {\n    \"firstName\":\"Asabeneh\",\n    \"lastName\":\"Yetayeh\",\n    \"age\":250,\n    \"email\":\"asab@asb.com\"\n  },\n  {\n    \"firstName\":\"Alex\",\n    \"lastName\":\"James\",\n    \"age\":25,\n    \"email\":\"alex@alex.com\"\n  },\n  {\n  \"firstName\":\"Lidiya\",\n  \"lastName\":\"Tekle\",\n  \"age\":28,\n  \"email\":\"lidiya@lidiya.com\"\n  }\n]\n}`\n\nconst usersObj = JSON.parse(usersText, (key, value) =\u003e {\n  let newValue =\n    typeof value == 'string' \u0026\u0026 key != 'email' ? value.toUpperCase() : value\n  return newValue\n})\nconsole.log(usersObj)\n```\n\nThe _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.\n\n### Converting Object to JSON\n\nWhen 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.\n\n```js\nJSON.stringify(obj, replacer, space)\n// json or text , the data\n// reviver is an optional callback function\n```\n\nLet us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.\n\n```js\nconst users = {\n  Alex: {\n    email: 'alex@alex.com',\n    skills: ['HTML', 'CSS', 'JavaScript'],\n    age: 20,\n    isLoggedIn: false,\n    points: 30\n  },\n  Asab: {\n    email: 'asab@asab.com',\n    skills: [\n      'HTML',\n      'CSS',\n      'JavaScript',\n      'Redux',\n      'MongoDB',\n      'Express',\n      'React',\n      'Node'\n    ],\n    age: 25,\n    isLoggedIn: false,\n    points: 50\n  },\n  Brook: {\n    email: 'daniel@daniel.com',\n    skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],\n    age: 30,\n    isLoggedIn: true,\n    points: 50\n  },\n  Daniel: {\n    email: 'daniel@alex.com',\n    skills: ['HTML', 'CSS', 'JavaScript', 'Python'],\n    age: 20,\n    isLoggedIn: false,\n    points: 40\n  },\n  John: {\n    email: 'john@john.com',\n    skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],\n    age: 20,\n    isLoggedIn: true,\n    points: 50\n  },\n  Thomas: {\n    email: 'thomas@thomas.com',\n    skills: ['HTML', 'CSS', 'JavaScript', 'React'],\n    age: 20,\n    isLoggedIn: false,\n    points: 40\n  },\n  Paul: {\n    email: 'paul@paul.com',\n    skills: [\n      'HTML',\n      'CSS',\n      'JavaScript',\n      'MongoDB',\n      'Express',\n      'React',\n      'Node'\n    ],\n    age: 20,\n    isLoggedIn: false,\n    points: 40\n  }\n}\n\nconst txt = JSON.stringify(users, undefined, 4)\nconsole.log(txt) // text means JSON- because json is a string form of an object.\n```\n\n```sh\n{\n    \"Alex\": {\n        \"email\": \"alex@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 30\n    },\n    \"Asab\": {\n        \"email\": \"asab@asab.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Redux\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 25,\n        \"isLoggedIn\": false,\n        \"points\": 50\n    },\n    \"Brook\": {\n        \"email\": \"daniel@daniel.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\"\n        ],\n        \"age\": 30,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Daniel\": {\n        \"email\": \"daniel@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Python\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"John\": {\n        \"email\": \"john@john.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\",\n            \"Node.js\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Thomas\": {\n        \"email\": \"thomas@thomas.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"Paul\": {\n        \"email\": \"paul@paul.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    }\n}\n```\n\n### Using a Filter Array with JSON.stringify\n\nNow, 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.\n\n```js\nconst user = {\n  firstName: 'Asabeneh',\n  lastName: 'Yetayeh',\n  country: 'Finland',\n  city: 'Helsinki',\n  email: 'alex@alex.com',\n  skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'],\n  age: 250,\n  isLoggedIn: false,\n  points: 30\n}\n\nconst txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4)\nconsole.log(txt)\n```\n\n```sh\n{\n    \"firstName\": \"Asabeneh\",\n    \"lastName\": \"Yetayeh\",\n    \"country\": \"Finland\",\n    \"city\": \"Helsinki\",\n    \"age\": 250\n}\n```\n\n### Exercises\n\n```js\nconst skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']\nlet age = 250;\nlet isMarried = true\nconst student = {\n  firstName:'Asabeneh',\n  lastName:'Yetayehe',\n  age:250,\n  isMarried:true,\n  skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]\n}\nconst txt = `{\n    \"Alex\": {\n        \"email\": \"alex@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 30\n    },\n    \"Asab\": {\n        \"email\": \"asab@asab.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Redux\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 25,\n        \"isLoggedIn\": false,\n        \"points\": 50\n    },\n    \"Brook\": {\n        \"email\": \"daniel@daniel.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\"\n        ],\n        \"age\": 30,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Daniel\": {\n        \"email\": \"daniel@alex.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"Python\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"John\": {\n        \"email\": \"john@john.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\",\n            \"Redux\",\n            \"Node.js\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": true,\n        \"points\": 50\n    },\n    \"Thomas\": {\n        \"email\": \"thomas@thomas.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"React\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    },\n    \"Paul\": {\n        \"email\": \"paul@paul.com\",\n        \"skills\": [\n            \"HTML\",\n            \"CSS\",\n            \"JavaScript\",\n            \"MongoDB\",\n            \"Express\",\n            \"React\",\n            \"Node\"\n        ],\n        \"age\": 20,\n        \"isLoggedIn\": false,\n        \"points\": 40\n    }\n}\n`\n```\n\n### Exercises Level 1\n\n1. Change skills array to JSON using JSON.stringify()\n1. Stringify the age variable\n1. Stringify the isMarried variable\n1. Stringify the student object\n\n### Exercises Level 2\n\n1. Stringify the students object with only firstName, lastName and skills properties\n\n\n## Higher Order Function\n\nHigher 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.\n\n### Callback\n\nA callback is a function which can be passed as parameter to other function. See the example below.\n\n```js\n// a callback function, the function could be any name\nconst callback = (n) =\u003e {\n  return n ** 2\n}\n​\n// function take other function as a callback\nfunction cube(callback, n) {\n  return callback(n) * n\n}\n​\nconsole.log(cube(callback, 3))\n```\n\n### Returning function\n\nHigher order functions return function as a value\n​\n\n```js\n// Higher order function returning an other function\nconst higherOrder = n =\u003e {\n  const doSomething = m =\u003e {\n    const doWhatEver = t =\u003e {\n      return 2 * n + 3 * m + t\n    }\n    return doWhatEver\n  }\n​\n  return doSomething\n}\nconsole.log(higherOrder(2)(3)(10))\n```\n\nLet us see were we use call back functions.For instance the _forEach_ method uses call back.\n\n```js\nconst numbers = [1, 2, 3, 4]\n​\nconst sumArray = arr =\u003e {\n  let sum = 0\n  const callBack = function(element) {\n    sum += element\n  }\n  numbers.forEach(callback)\n  return sum\n\n}\nconsole.log(sumArray(numbers))\n```\n\n```sh\n15\n```\n\nThe above example can be simplified as follows:\n\n```js\nconst numbers = [1, 2, 3, 4]\n​\nconst sumArray = arr =\u003e {\n  let sum = 0\n  numbers.forEach(function(element) {\n    sum += element\n  })\n  return sum\n\n}\nconsole.log(sumArray(numbers))\n```\n\n```sh\n15\n```\n\n### setting time\n\nIn JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.\n\n- setInterval\n- setTimeout\n\n#### setInterval\n\nIn JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.\n\n```js\n// syntax\nfunction callBack() {\n  // code goes here\n}\nsetInterval(callback, duration)\n```\n\n```js\nfunction sayHello() {\n  console.log('Hello')\n}\nsetInterval(sayHello, 2000) // it prints hello in every 2 seconds\n```\n\n#### setTimeout\n\nIn JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.\n\n```js\n// syntax\nfunction callback() {\n  // code goes here\n}\nsetTimeout(callback, duration) // duration in milliseconds\n```\n\n```js\nfunction sayHello() {\n  console.log('Hello')\n}\nsetTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.\n```\n\n### Exercises Level 3\n\n1. Parse the *txt* JSON to object.\n2. Find the the user who has many skills from the variable stored in *txt*.\n\n## Functional Programming\n\n- *forEach*: Iterate an array elements and use for array. It takes a callback function with elements and index parameter.\n\n```js\narr.forEach(function(element, index){\n  console.log(index, element)\n})\n// The above code can be written using arrow function\narr.forEach((element, index) =\u003e {\n  console.log(index, element)\n})\n// The above code can be written using arrow function and explicit return\narr.forEach((element, index) =\u003e console.log(index, element));\n```\n\n- *map*: Iterate an array elements and modify the array elements. It takes a callback function with elements and index parameter and return the modified array.\n\n```js\nconst modifiedArray = arr.map(function(element,index){\n  return element\n});\n/*Arrow function and explicit return\nconst modifiedArray = arr.map((element,index) =\u003e element);\n*/\n//Example\nconst numbers = [1,2,3,4,5];\nconst numbersSquare = numbers.map((num) =\u003e num * num) \nconsole.log(numbersSquare) // [1,4,9,16,25]\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconst namesToUpperCase = names.map((name) =\u003e name.toUpperCase());\nconsole.log(namesToUpperCase) //['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']\nconst countries = [\n  'Albania',\n  'Bolivia',\n  'Canada',\n  'Denmark',\n  'Ethiopia',\n  'Finland',\n  'Germany',\n  'Hungary',\n  'Ireland',\n  'Japan',\n  'Kenya'\n];\nconst countriesToUpperCase = countries.map(function(country){\n  return country.toUpperCase();\n});\nconsole.log(countriesToUpperCase)\n// ['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']\n/*\n// Arrow function\nconst countriesToUpperCase = countries.map((country) =\u003e {\n  return country.toUpperCase();\n})\n//Explicit return arrow function\nconst countriesToUpperCase = countries.map(country =\u003e country.toUpperCase());\n*/\n```\n\n- *Filter*: Filter out items which full fill filtering conditions\n\n```js\n\n// Filter countries containing land\nconst countriesContainingLand = countries.filter(country =\u003e country.includes('land'));\nconsole.log(countriesContainingLand )  //['Finland', 'Ireland']\n\nconst countriesEndByia = countries.filter(country =\u003e country.includes('ia'));\nconsole.log(countriesEndByia) //['Albania', 'Bolivia','Ethiopia']\n\nconst countriesHaveFiveLetters = countries.filter(country =\u003e country.length === 5);\nconsole.log(countriesHaveFiveLetters ) //  ['Japan', 'Kenya']\n\nconst scores = [{name:'Asabeneh', score:95},{name:'Mathias', score:80},{name:'Elias', score:50},{name:'Martha', score:85},{name:'John', score:100}];\n\nconst scoresGreaterEight = scores.filter((score) =\u003e score.score \u003e 80);\nconsole.log(scoresGreaterEight) //[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}]\n```\n\n- *reduce*: Reduce takes a callback function. The call back function takes accumulator and current value as a parameter and returns a single value:\n\n```js\n  const numbers = [1,2,3,4,5];\n  const sum = numbers.reduce((accum, curr)=\u003e accum + curr);\n\n  console.log(sum); // 15\n```\n\n- *every*: Check if all the elements are similar in one aspect. It returns boolean\n\n```js\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconst bools = [true, true, true, true];\nconst result = bools.every((b)=\u003e {\n  return b === true;\n});\n\nconsole.log(result) //true\n\nconst checkType = names.every((name) =\u003e typeof name ==='string');\n\nconsole.log(checkDataTypes) // true;\n```\n\n- *some*: Check if some of the elements are similar in one aspect. It returns boolean\n\n```js\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconst bools = [true, true, true, true];\nconst result = bools.some((b)=\u003e {\n  return b === true;\n});\nconsole.log(result) //true\nconst checkType = names.some((name) =\u003e typeof name ==='number');\nconsole.log(checkDataTypes) // false\n```\n\n- *find*: Return the first element which satisfies the condition\n\n```js\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconst ages = [24, 22,25,32,35,18];\nconst result = names.find(name =\u003e  name.length \u003e 7);\nconsole.log(result) // Asabeneh\nconst age = ages.find((age) =\u003e age \u003c 20);\nconsole.log(age) // 18\n```\n\n- *findIndex*: Return the position of the first element which satisfies the condition\n\n```js\nconst names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\nconst ages = [24, 22,25,32,35,18];\nconst result = names.findIndex(name =\u003e  name.length \u003e 7);\nconsole.log(result) // 0\n\nconst age = ages.findIndex((age) =\u003e age \u003c 20);\nconsole.log(age) // 5\n```\n\n- *sort*: The sort methods arranges the array elements either ascending or descending order. By default, the ***sort()*** method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array.  It is recommended to copy the original document before you start sorting.\n\n- *Sorting string values*\n\n```js\nconst products = ['Milk', 'Coffee', 'Sugar', 'Honey', 'Apple', 'Carrot'];\nconsole.log(products.sort()) // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar']\n//Now the original products array  is also sorted\n```\n\n- *Sorting Numeric  values*\n\nAs you can see in the example below, 100 came first after sorted in ascending order. Sort converts items to string , since '100' and other numbers compared, 1 which the beginning of the string '100' became the smallest.  To avoid this, we use a compare call back function inside the sort method, which return a negative, zero or positive.\n\n```js\nconst numbers = [9.81, 3.14, 100, 37]\n// Using sort method to sort number items provide a wrong result. see below\nconsole.log(numbers.sort()) //[100, 3.14, 37, 9.81]\nnumbers.sort(function(a, b) {\nreturn a - b;\n})\n\nconsole.log(numbers) // [3.14, 9.81, 37, 100]\nnumbers.sort(function(a, b) {\nreturn b - a;\n});\nconsole.log(numbers) //[100, 37, 9.81, 3.14]\n\n```\n\n- *Sorting Object Arrays*\n\nWhen ever we sort objects in an array. We use the object key to compare. Lets see the example below.\n\n```js\nobjArr.sort(function(a, b) {\n  if (a.key \u003c b.key) return -1;\n  if (a.key \u003e b.key) return 1;\n  return 0;\n});\n\n// or\n\nobjArr.sort(function(a, b) {\n  if (a['key'] \u003c b['key']) return -1;\n  if (a['key'] \u003e b['key']) return 1;\n  return 0;\n});\n\nconst users = [{name:'Asabeneh', age:150}, {name:'Brook', age:50}, {name:'Eyo', age:100},{name:'Elias', age:22}];\nusers.sort((a, b) =\u003e {\n  if (a.age \u003c b.age) return -1;\n  if (a.age \u003e b.age) return 1;\n  return 0;\n});\n\nconsole.log(users); // sorted ascending\n//[{…}, {…}, {…}, {…}]\n```\n\n### Exercises\n\n```js\n  const countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand'];\n  const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'];\n  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n1. Explain the difference between ***forEach, map, filter, and reduce***.\n2. Define a call function before you them in forEach, map, filter or reduce.\n3. Use ***forEach*** to console.log each country in the countries array.\n4. Use ***forEach*** to console.log each name in the names array.\n5. Use ***forEach*** to console.log each number in the numbers array.\n6. Use ***map*** to create a new array  by changing each country to uppercase in the countries array;\n7. Use ***map*** to create a new array  by changing each number to square in the numbers array\n8. Use ***map*** to change to each name to uppercase in the names array\n9. Use ***filter*** to filter out countries containing ***land***.\n10. Use ***filter*** to filter out countries having six character.\n11. Use ***filter*** to filter out countries containing six letters and more in the country array.\n12. Use ***filter*** to filter out country start with 'E';\n13. Chain two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))\n14. Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.\n15. Use ***reduce*** to sum all the numbers in the numbers array.\n16. Use ***reduce*** to concatenate all the countries and to produce this sentence: ***Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries***\n17. Explain the difference between ***some*** and ***every***\n18. Use ***some*** to check if some names' length greater than seven in names array\n19. Use ***every*** to check if all the countries contain the word land\n20. Explain the difference between ***find*** and ***findIndex***.\n21. Use ***find*** to find the first country containing only six letters in the countries array\n22. Use ***findIndex*** to find the position of the first country containing only six letters in the countries array\n23. Use ***findIndex*** to find the position of ***Norway*** if it doesn't exist in the array you will get -1.\n24. Use ***findIndex*** to find the position of ***Russia*** if it doesn't exist in the array you will get -1.\n25. Declare a function called ***categorizeCountries*** which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).\n26. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.\n27. Declare a ***getFirstTenCountries*** function and return an array of ten countries. Use different functional programming to work on the countries.js array\n28. Declare a ***getLastTenCountries*** function which which returns the last ten countries in the countries array.\n29. Find out which *letter* is used many *times* as initial for a country name from the countries array (eg. Finland, Fiji, France etc)\n30. Use the countries information, in the data folder. Sort countries by name, by capital, by population\n31. Sort out the ten most spoken languages by location.\n32. Sort out the ten most populated countries.\n\n## Destructuring and Spread\n\nDestructuring is a way to unpack arrays, and objects and assigning to a distinct variable.\n\n### Destructing  Arrays\n\n```js\n  const numbers = [1, 2,3];\n  let [numOne, numTwo, numThree] = numbers;\n  console.log(numOne, numTwo, numThree) // 1,2,3\n  const names = ['Asabeneh', 'Brook', 'David', 'John']\n  let [firstPerson, secondPerson, ThirdPerson, fourth Person] = names;\n  console.log(firstName, secondPerson,thirdPerson, fourthPerson) //Asabeneh, Brook, David, John\n  const scientificConstants = [2.72, 3.14, 9.81, 37, 100];\n  let [e, pi, gravity, bodyTemp, boilingTemp] = scientificConstants\n  console.log(e,pi,gravity, bodyTemp, boilingTemp) //2.72, 3.14, 9.81, 37, 100\n```\n\nIf we like to skip on of the values in the array we use additional comma. The comma helps to omit the value at that index\n\n```js\n  const numbers = [1, 2,3];\n  let [numOne, , , numThree] = numbers; //2 is omitted\n  console.log(numOne,, numThree) // 1,2,3\n  const names = ['Asabeneh', 'Brook', 'David', 'John']\n  let [, secondPerson, , fourth Person] = name; // first and third person is omitted\n  console.log(secondPerson, fourthPerson) //Brook, John\n```\n\nWe can use default value in case the value of array for that index is undefined:\n\n```js\nconst names = [undefined, 'Brook', 'David'];\nlet [firstPerson = 'Asabeneh', secondPerson, thirdPerson, fourthPerson = 'John' ] = names;\nconsole.log(firstPerson, secondPerson, thirdPerson, fourthPerson) // Asabeneh Brook David John\n```\n\n#### Destructuring Object\n\nWhen we destructure the name of the variable we use to destructure should be exactly the same us the key or property of the object. See example below.\n\n```js\nconst rectangle = {\n  width: 20,\n  height:10,\n  area: 200\n}\nlet {width, height, area, perimeter} = rectangle;\nconsole.log(width, height, area, perimeter) //20 10 200 undefined\n```\n\n#### Renaming during structuring\n\n```js\nconst rectangle = {\n  width: 20,\n  height:10,\n  area: 200\n}\nlet {width:w, heigh:h, area:a, perimeter:p} = rectangle;\nconsole.log(w, h, a, p) //20 10 200 undefined\n```\n\nIf the key is not found in the object the variable will be assigned to undefined. In case, the key is not in the object we can give a default value during declaration. See the example.\n\n```js\nconst rectangle = {\n  width: 20,\n  height:10,\n  area: 200\n}\nlet {width, heigh, area, perimeter = 60} = rectangle;\nconsole.log(width, height, area, perimeter)  //20 10 200 60\n\n//Lets modify the object:width to 30 and perimeter to 80\nconst rectangle = {\n  width: 30,\n  height:10,\n  area: 200,\n  perimeter:80\n}\nlet {width, heigh, area, perimeter = 60} = rectangle;\nconsole.log(width, height, area, perimeter) //20 10 200 80\n```\n\nDestructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.\n\n```js\n    // Without destructuring\n    const rect = {\n      width:20,\n      height:10\n    }\n    const calculatePerimeter = (rectangle) =\u003e {\n      return 2 * (rectangle.width + rectangle.height)\n    }\n    console.log(calculatePerimeter(rect)) // 60\n    //with destructuring\n\n     const calculatePerimeter = ({width, height}) =\u003e {\n      return 2 * (width + height)\n    }\n\n    console.log(calculatePerimeter(rect)) // 60\n\n    //Another Example\nconst person = {\n  firstName: 'Asabeneh',\n  lastName: 'Yetayeh',\n  age: 200,\n  country: 'Finland',\n  job: 'Instructor and Developer',\n  skills: [\n    'HTML',\n    'CSS',\n    'JavaScript',\n    'React',\n    'Redux',\n    'Node',\n    'MongoDB',\n    'Python',\n    'D3.js'\n  ],\n  languages: ['Amharic', 'English', 'Suomi(Finnish)']\n};\n// Lets create a function which give information about the person object without destructuring\n\nconst getPersonInfo = obj =\u003e {\n  const skills = obj.skills;\n  const formattedSkills = skills.slice(0, -1).join(', ');\n  const languages = obj.languages;\n  const formattedLanguages = languages.slice(0, -1).join(', ');\n\n  return `${obj.firstName} ${obj.lastName} lives in ${obj.country}. He is  ${\n    obj.age\n  } years old. He is an ${obj.job}. He teaches ${formattedSkills} and ${\n    skills[skills.length - 1]\n  }. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`;\n};\nconsole.log(getPersonInfo(person));\n// Lets create a function which give information about the person object with destructuring\n\nconst getPersonInfo = ({\n  firstName,\n  lastName,\n  age,\n  country,\n  job,\n  skills,\n  languages\n}) =\u003e {\n  const formattedSkills = skills.slice(0, -1).join(', ');\n  const formattedLanguages = languages.slice(0, -1).join(', ');\n\n  return `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${skills[skills.length - 1]}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`;\n};\nconsole.log(getPersonInfo(person))\n/*\nAsabeneh Yetayeh lives in Finland. He is  200 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)\n*/\n```\n\n### Spread or Rest Operator\n\n#### Exercise: Destructuring\n\n   ```js\n   const constants = [2.72, 3.14, 9.81,37, 100]\n   const countries = ['Finland', 'Estonia', 'Sweden', 'Denmark', 'Norway']\n\n   const rectangle = {\n     width:20,\n     height:10,\n     area:200,\n     perimeter:60\n   }\n   ```\n\n   1. Assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.\n   2. Assign the elements of countries array to fin, est, sw, den, nor\n   3. Destructure the rectangle object by its properties or keys.\n\n## Map and Set\n\n## Set\n\nSet is a collection of unique elements. Lets see how to create a set\n\n### Creating a set\n\n```js\n  const companies = new Set()\n```\n\n### Adding an element to a set\n\n```js\n  console.log(companies.size) // 0\n  companies.add('Google') // add element to the set\n  companies.add('Facebook')\n  companies.add('Amazon')\n  companies.add('Oracle')\n  companies.add('Microsoft')\n  console.log(companies.size) // 5 elements in the set\n```\n\n### Deleting an element a set\n\n```js\nconsole.log(companies.delete('Google'))\nconsole.log(companies.size) // 4 elements left in the set\n```\n\n### Checking an element in the set\n\n```js\nconsole.log(companies.has('Google')) // false\nconsole.log(companies.has('Facebook')) // true\n```\n\n### Clearing the set\n\nIt removes all the elements\n\n```js\n  companies.clear()\n```\n\nSee the example below to learn how to use set.\n\n```js\n\nconst languages = [\n  'English',\n  'Finnish',\n  'English',\n  'French',\n  'Spanish',\n  'English',\n  'French'\n]\nconst langSet = new Set(languages)\nconsole.log(langSet)\nconsole.log(langSet.size)\n\nconst counts = []\nconst count = {}\n\nfor (const l of langSet) {\n  const filteredLang = languages.filter(lng =\u003e lng === l)\n  console.log(filteredLang)\n  counts.push({ lang: l, count: filteredLang.length })\n}\nconsole.log(counts)\n```\n\n## Set\n\nSet is a collection a collection of elements. Set can only contains unique elements.\nLets see how to create a set\n\n### Creating an empty set\n\n```js\nconst companies = new Set()\nconsole.log(companies)\n```\n\n```sh\n{}\n```\n\n### Creating set from array\n\n```js\nconst languages = [\n  'English',\n  'Finnish',\n  'English',\n  'French',\n  'Spanish',\n  'English',\n  'French'\n]\n\nconst setOfLangauges = new Set(languages)\nconsole.log(setOfLangauges)\n```\n\n```sh\nSet(4) {\"English\", \"Finnish\", \"French\", \"Spanish\"}\n```\n\nSet is an iterable object and we can iterate through each elements.\n\n```js\nconst languages = [\n  'English',\n  'Finnish',\n  'English',\n  'French',\n  'Spanish',\n  'English',\n  'French'\n]\n\nconst setOfLangauges = new Set(languages)\n\nfor (const language of setOfLangauges) {\n  console.log(language)\n}\n```\n\n```sh\n  English\n  Finnish\n  French\n  Spanish\n```\n\n### Adding an element to a set\n\n```js\nconst companies = new Set() // creating an empty set\nconsole.log(companies.size) // 0\n\ncompanies.add('Google') // add element to the set\ncompanies.add('Facebook')\ncompanies.add('Amazon')\ncompanies.add('Oracle')\ncompanies.add('Microsoft')\n\nconsole.log(companies.size) // 5 elements in the set\nconsole.log(companies)\n```\n\n```sh\nSet(5) {\"Google\", \"Facebook\", \"Amazon\", \"Oracle\", \"Microsoft\"}\n```\n\nWe can also use loop to add element to a set.\n\n```js\nconst companies = ['Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft']\nsetOfCompanies = new Set()\nfor (const company of companies) {\n  setOfCompanies.add(company)\n}\n```\n\n```sh\nSet(5) {\"Google\", \"Facebook\", \"Amazon\", \"Oracle\", \"Microsoft\"}\n\n```\n\n### Deleting an element a set\n\nWe can delete an element from a set using a delete method.\n\n```js\nconsole.log(companies.delete('Google'))\nconsole.log(companies.size) // 4 elements left in the set\n```\n\n### Checking an element in the set\n\nThe has method can help to know if a certain element exists in a set.\n\n```js\nconsole.log(companies.has('Apple')) // false\nconsole.log(companies.has('Facebook')) // true\n```\n\n### Clearing the set\n\nIt removes all the elements from a set.\n\n```js\ncompanies.clear()\n\nconsole.log(companies)\n```\n\n```sh\n{}\n\n```\n\nSee the example below to learn how to use set.\n\n```js\nconst languages = [\n  'English',\n  'Finnish',\n  'English',\n  'French',\n  'Spanish',\n  'English',\n  'French'\n]\nconst langSet = new Set(languages)\nconsole.log(langSet) // Set(4) {\"English\", \"Finnish\", \"French\", \"Spanish\"}\nconsole.log(langSet.size) // 4\n\nconst counts = []\nconst count = {}\n\nfor (const l of langSet) {\n  const filteredLang = languages.filter(lng =\u003e lng === l)\n  console.log(filteredLang) // [\"English\", \"English\", \"English\"]\n  counts.push({ lang: l, count: filteredLang.length })\n}\nconsole.log(counts)\n```\n\n```js\n[\n  { lang: 'English', count: 3 },\n  { lang: 'Finnish', count: 1 },\n  { lang: 'French', count: 2 },\n  { lang: 'Spanish', count: 1 }\n]\n```\n\nOther use case of set. For instance to count unique item in an array.\n\n```js\nconst numbers = [5, 3, 2, 5, 5, 9, 4, 5]\nconst setOfNumbers = new Set(numbers)\n\nconsole.log(setOfNumbers)\n```\n\n```sh\nSet(5) {5, 3, 2, 9, 4}\n```\n\n### Union of sets\n\nTo find a union to two sets can be achieved using spread operator. Lets find the union of set A and set B (A U B)\n\n```js\nlet a = [1, 2, 3, 4, 5]\nlet b = [3, 4, 5, 6]\nlet c = [...a, ...b]\n\nlet A = new Set(a)\nlet B = new Set(b)\nlet C = new Set(c)\n\nconsole.log(C)\n```\n\n```sh\nSet(6) {1, 2, 3, 4, 5,6}\n\n```\n\n### Intersection of sets\n\nTo find an intersection of two sets can be achieved using filter. Lets find the union of set A and set B (A ∩ B)\n\n```js\nlet a = [1, 2, 3, 4, 5]\nlet b = [3, 4, 5, 6]\n\nlet A = new Set(a)\nlet B = new Set(b)\n\nlet c = a.filter(num =\u003e B.has(num))\nlet C = new Set(c)\n\nconsole.log(C)\n```\n\n```sh\nSet(3) {3, 4, 5}\n\n```\n\n### Difference of sets\n\nTo find an the difference between two sets can be achieved using filter. Lets find the different of set A and set B (A \\ B)\n\n```js\nlet a = [1, 2, 3, 4, 5]\nlet b = [3, 4, 5, 6]\n\nlet A = new Set(a)\nlet B = new Set(b)\n\nlet c = a.filter(num =\u003e !B.has(num))\nlet C = new Set(c)\n\nconsole.log(C)\n```\n\n```sh\nSet(2) {1, 2}\n\n```\n\n## Map\n\n### Creating an empty Map\n\n```js\nconst map = new Map()\nconsole.log(map)\n```\n\n```sh\nMap(0) {}\n```\n\n### Creating an Map from array\n\n```js\ncountries = [\n  ['Finland', 'Helsinki'],\n  ['Sweden', 'Stockholm'],\n  ['Norway', 'Oslo']\n]\nconst map = new Map(countries)\nconsole.log(map)\nconsole.log(map.size)\n```\n\n```sh\nMap(3) {\"Finland\" =\u003e \"Helsinki\", \"Sweden\" =\u003e \"Stockholm\", \"Norway\" =\u003e \"Oslo\"}\n3\n```\n\n### Adding values to the Map\n\n```js\nconst countriesMap = new Map()\nconsole.log(countriesMap.size) // 0\ncountriesMap.set('Finland', 'Helsinki')\ncountriesMap.set('Sweden', 'Stockholm')\ncountriesMap.set('Norway', 'Oslo')\nconsole.log(countriesMap)\nconsole.log(countriesMap.size)\n```\n\n```sh\nMap(3) {\"Finland\" =\u003e \"Helsinki\", \"Sweden\" =\u003e \"Stockholm\", \"Norway\" =\u003e \"Oslo\"}\n3\n```\n\n### Getting a value from Map\n\n```js\nconsole.log(countriesMap.get('Finland'))\n```\n\n```sh\nHelsinki\n```\n\n### Checking key in Map\n\nCheck if a key exist in a map using *has* method. It returns *true* or *false*.\n\n```js\nconsole.log(countriesMap.has('Finland'))\n```\n\n```sh\ntrue\n```\n\nGetting all values from map using loop\n\n```js\nfor (const country of countriesMap) {\n  console.log(country)\n}\n```\n\n```sh\n(2) [\"Finland\", \"Helsinki\"]\n(2) [\"Sweden\", \"Stockholm\"]\n(2) [\"Norway\", \"Oslo\"]\n```\n\n```sh\nfor (const [country, city] of countriesMap){\nconsole.log(country, city)\n}\n```\n\n```sh\nFinland Helsinki\nSweden Stockholm\nNorway Oslo\n```\n\n### Exercises: Set and Map\n\n### Exercises:Level 1\n\n```js\nconst a = {4, 5, 8, 9}\nconst b = {3, 4, 5, 7}\nconst countries = ['Finland', 'Sweden', 'Norway']\n```\n\n1. create an empty set\n2. Create a set containing 0 to 10 using loop\n3. Remove an element from a set\n4. Clear a set\n5. Create a set of 5 string elements from array\n6. Create a map of countries and number of characters of a country\n\n### Exercises:Level 2\n\n1. Find a union b\n2. Find a intersection b\n3. Find a with b\n\n### Exercises:Level 3\n\n1. How many languages are there in the countries object file.\n\n1. \\*\\*\\* Use the countries data to find the 10 most spoken languages:\n\n   ````js\n   // Your output should look like this\n   console.log(mostSpokenLanguages(countries, 10))\n   [\n   {'English':91},\n   {'French':45},\n   {'Arabic':25},\n   {'Spanish':24},\n   {'Russian':9},\n   {'Portuguese':9},\n   {'Dutch':8},\n   {'German':7},\n   {'Chinese':5},\n   {'Swahili':4},\n   {'Serbian':4}]\n\n   // Your output should look like this\n   console.log(mostSpokenLanguages(countries, 3))\n\n  [\n   {'English':91},\n   {'French':45},\n   {'Arabic':25}\n   ]````\n\n## Document Object Model (DOM)\n\nHTML document is structured as a JavaScript Object. Every HTML element has a different properties which can help to manipulate it. It is possible to get, create, append or remove HTML elements using JavaScript. Check the examples below. Selecting HTML element using JavaScript is similar to select CSS. To select an HTML element, we use tag name, id, class name. To create an HTML element we use tag name.\n\n### Getting Element\n\n```html\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eDocument Object Model/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n     \u003ch1 class='title' id='first-title'\u003eFirst Title\u003c/h1\u003e\n     \u003ch1 class='title' id='second-title'\u003eSecond Title\u003c/h1\u003e\n     \u003ch1 class='title' id='third-title'\u003eThird Title\u003c/h1\u003e\n     \u003ch1\u003e\u003c/h1\u003e\n    \u003c/body\u003e\n  \u003c/html\u003e\n```\n\n#### Getting elements by tag name\n\n***getElementsByTagName()*** method returns an HTMLCollection object. An HTMLCollection is an array like list of HTML elements. The length property provides the size of the collection.\n\n```js\nconst allTitles = document.getElementsByTagName('h1');\nconsole.log(allTitles) //HTMCollections\nconsole.log(allTitles.length) // 4\nfor(let i = 0; i \u003c allTitles.length; i++){\n  console.log(allTitles[i]) // prints each elements in the HTMLCollection\n}\n```\n\n#### Getting elements by class name\n\n***getElementsByClassName()*** method returns an HTMLCollection object. An HTMLCollection is an array like list of HTML elements. The length property provides the size of the collection. It is possible to loop through all the HTMLCollection elements. See the example below\n\n```js\nconst allTitles = document.getElementsByClassName('title');\nconsole.log(allTitles) //HTMCollections\nconsole.log(allTitles.length) // 4\nfor(let i = 0; i \u003c allTitles.length; i++){\n  console.log(allTitles[i]) // prints each elements in the HTMLCollection\n}\n```\n\n#### Getting an element by id\n\n***getElementsById()***  targets a single HTML element. We pass the id without # as an argument.\n\n```js\nlet firstTitle = document.getElementById('first-title');\nconsole.log(firstTitle) // \u003ch1\u003eFirst Title\u003c/h1\u003e\n```\n\n#### Getting elements by using querySelector using tag, class and id:\n\n***querySelector***: can be used to select HTML element by its tag name, id or class. If the tag name is used it selects only the first element.\n\n```js\nlet firstTitle = document.querySelect('h1');// select the first available h2 element\nlet firstTitle = document.querySelector('#first-title'); // select id with first-title\nlet firstTitle = document.querySelector('.title'); // select the first available h2 element with class title\n```\n\n***querySelectorAll***: can be used to select html element by its tag name or class. It return a nodeList which is an array like object which support array methods. We can use ***for loop*** or ***forEach*** to loop through each nodeList elements.\n\n```js\nconst allTitles = document.querySelectAll('h1');\nconsole.log(allTitles.length) // 4\nfor(let i = 0; i \u003c allTitles.length; i++){\n  console.log(allTitles[i]);\n}\nallTitles.forEach(title =\u003e console.log(title))\nconst allTitles = document.querySelectorAll('.title'); // the same goes for selecting using class\n```\n\n### Adding attribute\n\nAn attribute is added in the opening tag of HTML which gives additional information about the element. Common HTML attributes: id, class, src, style, href,disabled, title, alt. Lets add id and class for the fourth title.\n\n#### Adding attribute using setAttribute\n\nThe ***setAttribute()*** method set any html attribute. It takes two parameters the type of the attribute and the name of the attribute. \nLet's add class and id attribute for the fourth title.\n\n```js\nconst titles = document.querySelectorAll('h1');\ntitles[3].setAttribute('class', 'title');\ntitles[3].setAttribute('id', 'fourth-title');\n```\n\n#### Adding attribute without setAttribute\n\nSome attributes are DOM object property and they can be set directly. For instance id and class\n\n```js\n//another way to setting an attribute\ntitles[3].className = 'title';\ntitles[3].id = 'fourth-title';\n```\n\n#### Adding class using classList\n\nThe class list method is a good method to append additional class. It doesn't override the original class if a class exists\n\n```js\n//another way to setting an attribute: append the class, doesn't over ride\ntitles[3].classList.add('title', 'header-title')\n```\n\n### Adding Text content\n\n```js\nconst titles = document.querySelectorAll('h1');\ntitles[3].textContent = 'Fourth Title';\n```\n\n### Adding style\n\nLets add some style to our titles. If the element has even index we give it green color else red.\n\n```js\nconst titles = document.querySelectorAll('h1');\ntitles.forEach((title,i) =\u003e {\n  title.fontSize = '24px'; // all titles will have 24px font size\n  if(i % 2 === 0){\n    title.style.color = 'green';\n  }\n  else {\n    title.style.color = 'red';\n  }\n})\n\n```\n\n### Creating an Element\n\n```js\nlet title = document.createElement('h1');\nlet firstTitle = document.getElementById('first-title');\n```\n\n### Creating elements\n\n```js\nlet firstTitle = document.getElementById('first-title');\nlet title\nfor(let i = 0; i \u003c 3; i++){\n  title = document.createElement('h1');\n  title.className = 'title';\n  title.style.fontSize = '24px';\n}\n```\n\n### Appending to a parent element\n\n```js\n// creating multiple elements and appending to parent element\nlet title;\nfor(let i = 0; i \u003c 3; i++){\n  title = document.createElement('h1');\n  title.className = 'title';\n  title.style.fontSize = '24px';\n  document.body.appendChild(title);\n}\n```\n\n### Event Listeners\n\nCommon HTML events:onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.\nWe can add event listener method to any DOM object. Use use ***addEventListener()*** method to listen different event types on HTML elements.\nThe following is an example of click type event.\n\n```js\nconst button = document.querySelector('button');\nbutton.addEventListener('click', e =\u003e {\n  console.log(e.target);\n});\n```\n\n### Getting value from an input element\n\nWe usually fill forms and forms accept data. Form fields are created using input HTML element.\n\n```html\n\u003cinput type ='text' placeholder = 'Mass in Kilogram' /\u003e\n\u003cinput type = 'text' placeholder = 'Height in meters' /\u003e\n\u003cbutton\u003eCalculate BMI\u003c/button\u003e\n```\n\n```js\nconst mass = document.querySelector('#mass');\nconst height = document.querySelector('#height');\nconst button = document.querySelector('button');\nlet bmi;\nbutton.addEventListen('click', ()=\u003e{\n  bmi = mass.value * height.value;\n});\n\nconsole.log(bmi)\n```\n\n#### Exercises:Document Object Model\n\n```html\n  \u003c!-- index.html --\u003e\n\u003c!DOCTYPE html\u003e\n  \u003chtml\u003e\n    \u003chead\u003e\n      \u003ctitle\u003eJavaScript for Everyone:DOM\u003c/title\u003e\n    \u003c/head\u003e\n    \u003cbody\u003e\n    \u003cp\u003eFirst Paragraph\u003c/p\u003e\n    \u003cp\u003eSecond Paragraph\u003c/p\u003e\n    \u003cp\u003eThird Paragraph\u003c/p\u003e\n    \u003cp\u003e\u003c/p\u003e\n    \u003c/body\u003e\n  \u003c/html\u003e\n```\n\n  1. Create an index.html file and put four p elements as above: Get the first paragraph by using ***document.querySelector(tagname)*** and tag name\n  2. Get get each of the the paragraph using ***document.querySelector('#id')*** and by their id\n  3. Get all the p as nodeList using ***document.querySelectorAll(tagname)*** and by their tag name\n  4. Loop through the nodeList and get the text content of each paragraph\n  5. Set a text content to paragraph the fourth paragraph,***Fourth Paragraph***\n  6. Set id and class attribute for all the paragraphs using different attribute setting methods\n  7. Change stye of each paragraph using JavaScript(eg. color, background, border, font-size, font-family)\n  8. Select all paragraphs and loop through each elements and give the first and third paragraph a color of color, and the second and the fourth paragraph a red color\n  9. Remove all the paragraph and create them using JavaScript\n  10. Set text content, id and class to each paragraph\n  11. Create a div container on HTML document and create 100 numbers dynamically and append to the container div. Put each number in 150px by 150px box. If the number is even the background will be lightgreen else lightblue.\n  12. Use the rgb color generator function or hexaColor generator to create 10 divs with random background colors\n  13. Use the countries.js to visualize all the countries on the HTML document. You need one wrapper div and box for each countries. In the box display, the letter the country starts with, the name of the country and the number of characters for the country name.\n\n#### DOM: Mini Projects\n\n1. BMI calculator\n2. Hexadecimal or RGB color Generator\n3. World Countries List\n\n## Classes\n\nJavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a \"blueprint\" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.\n\nOnce we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation.\n\nIn the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code.\n\n### Defining a classes\n\nTo define a class in JavaScript we need the keyword _class_ , the name of a class in **CamelCase** and block code(two curly brackets). Let us create a class name Person.\n\n```sh\n// syntax\nclass ClassName {\n    //  code goes here\n}\n\n```\n\n**Example:**\n\n```js\nclass Person {\n  // code goes here\n}\n```\n\nWe have created an Person class but it does not have any thing inside.\n\n### Class Instantiation\n\nInstantiation class means creating an object from a class. We need the keyword _new_ and we call the name of the class after the word new.\n\nLet us create a dog object from our Person class.\n\n```js\nclass Person {\n  // code goes here\n}\nconst person = new Person()\nconsole.log(person)\n```\n\n```sh\nPerson {}\n```\n\nAs you can see, we have created a person object. Since the class did not have any properties yet the object is also empty.\n\nLet use the class constructor to pass different properties for the class.\n\n### Class Constructor\n\nThe constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use the _this_ keyword to attach the constructor parameters with the class.\n\nThe following Person class constructor has firstName and lastName property. These properties are attached to the Person class using _this_ keyword. _This_ refers to the class itself.\n\n```js\nclass Person {\n  constructor(firstName, lastName) {\n    console.log(this) // Check the output from here\n    this.firstName = firstName\n    this.lastName = lastName\n  }\n}\n\nconst person = new Person()\n\nconsole.log(person)\n```\n\n```sh\nPerson {firstName: undefined, lastName}\n```\n\nAll the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.\n\n```js\nclass Person {\n  constructor(firstName, lastName) {\n    this.firstName = firstName\n    this.lastName = lastName\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh')\n\nconsole.log(person1)\n```\n\n```sh\nPerson {firstName: \"Asabeneh\", lastName: \"Yetayeh\"}\n```\n\nAs we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class.\n\n```js\nclass Person {\n  constructor(firstName, lastName) {\n    console.log(this) // Check the output from here\n    this.firstName = firstName\n    this.lastName = lastName\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh')\nconst person2 = new Person('Lidiya', 'Tekle')\nconst person3 = new Person('Abraham', 'Yetayeh')\n\nconsole.log(person1)\nconsole.log(person2)\nconsole.log(person3)\n```\n\n```sh\nPerson {firstName: \"Asabeneh\", lastName: \"Yetayeh\"}\nPerson {firstName: \"Lidiya\", lastName: \"Tekle\"}\nPerson {firstName: \"Abraham\", lastName: \"Yetayeh\"}\n```\n\nUsing the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    console.log(this) // Check the output from here\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\n\nconsole.log(person1)\n```\n\n```sh\nPerson {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: 250, country: \"Finland\", city: \"Helsinki\"}\n```\n\n### Default values with constructor\n\nThe constructor function properties may have a default value like other regular functions.\n\n```js\nclass Person {\n  constructor(\n    firstName = 'Asabeneh',\n    lastName = 'Yetayeh',\n    age = 250,\n    country = 'Finland',\n    city = 'Helsinki'\n  ) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n  }\n}\n\nconst person1 = new Person() // it will take the default values\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\n\nconsole.log(person1)\nconsole.log(person2)\n```\n\n```sh\nPerson {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: 250, country: \"Finland\", city: \"Helsinki\"}\nPerson {firstName: \"Lidiya\", lastName: \"Tekle\", age: 28, country: \"Finland\", city: \"Espoo\"}\n```\n\n### Class methods\n\nThe constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\n\nconsole.log(person1.getFullName())\nconsole.log(person2.getFullName())\n```\n\n```sh\nAsabeneh Yetayeh\ntest.js:19 Lidiya Tekle\n```\n\n### Properties with initial value\n\nWhen we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n    this.score = 0\n    this.skills = []\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\n\nconsole.log(person1.score)\nconsole.log(person2.score)\n\nconsole.log(person1.skills)\nconsole.log(person2.skills)\n```\n\n```sh\n0\n0\n[]\n[]\n```\n\nA method could be regular method or a getter or a setter. Let us see, getter and setter.\n\n### getter\n\nThe get method allow us to access value from the object. We write a get method using keyword _get_ followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n    this.score = 0\n    this.skills = []\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n  get getscore() {\n    return this.score\n  }\n  get getSkills() {\n    return this.skills\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\n\nconsole.log(person1.getScore) // We do not need parenthesis to call a getter method\nconsole.log(person2.getScore)\n\nconsole.log(person1.getSkills)\nconsole.log(person2.getSkills)\n```\n\n```sh\n0\n0\n[]\n[]\n```\n\n### setter\n\nThe setter method allow us to modify the value of certain properties. We write a setter method using keyword _set_ followed by a function. See the example bellow.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n    this.score = 0\n    this.skills = []\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n  get getScore() {\n    return this.score\n  }\n  get getSkills() {\n    return this.skills\n  }\n  set setScore(score) {\n    this.score += score\n  }\n  set setSkill(skill) {\n    this.skills.push(skill)\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\n\nperson1.setScore = 1\nperson1.setSkill = 'HTML'\nperson1.setSkill = 'CSS'\nperson1.setSkill = 'JavaScript'\n\nperson2.setScore = 1\nperson2.setSkill = 'Planning'\nperson2.setSkill = 'Managing'\nperson2.setSkill = 'Organizing'\n\nconsole.log(person1.score)\nconsole.log(person2.score)\n\nconsole.log(person1.skills)\nconsole.log(person2.skills)\n```\n\n```sh\n1\n1\n[\"HTML\", \"CSS\", \"JavaScript\"]\n[\"Planning\", \"Managing\", \"Organizing\"]\n```\n\nDo not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n    this.score = 0\n    this.skills = []\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n  get getScore() {\n    return this.score\n  }\n  get getSkills() {\n    return this.skills\n  }\n  set setScore(score) {\n    this.score += score\n  }\n  set setSkill(skill) {\n    this.skills.push(skill)\n  }\n  getPersonInfo() {\n    let fullName = this.getFullName()\n    let skills =\n      this.skills.length \u003e 0 \u0026\u0026\n      this.skills.slice(0, this.skills.length - 1).join(', ') +\n        ` and ${this.skills[this.skills.length - 1]}`\n    let formattedSkills = skills ? `He knows ${skills}` : ''\n\n    let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`\n    return info\n  }\n}\n\nconst person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')\nconst person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')\nconst person3 = new Person('John', 'Doe', 50, 'Mars', 'Mars city')\n\nperson1.setScore = 1\nperson1.setSkill = 'HTML'\nperson1.setSkill = 'CSS'\nperson1.setSkill = 'JavaScript'\n\nperson2.setScore = 1\nperson2.setSkill = 'Planning'\nperson2.setSkill = 'Managing'\nperson2.setSkill = 'Organizing'\n\nconsole.log(person1.getScore)\nconsole.log(person2.getScore)\n\nconsole.log(person1.getSkills)\nconsole.log(person2.getSkills)\nconsole.log(person3.getSkills)\n\nconsole.log(person1.getPersonInfo())\nconsole.log(person2.getPersonInfo())\nconsole.log(person3.getPersonInfo())\n```\n\n```sh\n1\n1\n[\"HTML\", \"CSS\", \"JavaScript\"]\n[\"Planning\", \"Managing\", \"Organizing\"]\n[]\nAsabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScript\nLidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and Organizing\nJohn Doe is 50. He lives Mars city, Mars.\n```\n\n### Static method\n\nThe static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method is _Date.now()_. The _now_ method is called directly from the class.\n\n```js\nclass Person {\n  constructor(firstName, lastName, age, country, city) {\n    this.firstName = firstName\n    this.lastName = lastName\n    this.age = age\n    this.country = country\n    this.city = city\n    this.score = 0\n    this.skills = []\n  }\n  getFullName() {\n    const fullName = this.firstName + ' ' + this.lastName\n    return fullName\n  }\n  get getScore() {\n    return this.score\n  }\n  get getSkills() {\n    return this.skills\n  }\n  set setScore(score) {\n    this.score += score\n  }\n  set setSkill(skill) {\n    this.skills.push(skill)\n  }\n  getPersonInfo() {\n    let fullName = this.getFullName()\n    let skills =\n      this.skills.length \u003e 0 \u0026\u0026\n      this.skills.slice(0, this.skills.length - 1).join(', ') +\n        ` and ${this.skills[this.skills.length - 1]}`\n\n    let formattedSkills = skills ? `He knows ${skills}` : ''\n\n    let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`\n    return info\n  }\n  static favoriteSkill() {\n    const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']\n    const index = Math.floor(Math.random() * skills.length)\n    return skills[index]\n  }\n  static showDateTime() {\n    let now = new Date()\n    let year = now.getFullYear()\n    let month = now.getMonth() + 1\n    let date = now.getDate()\n    let hours = now.getHours()\n    let minutes = now.getMinutes()\n    if (hours \u003c 10) {\n      hours = '0' + hours\n    }\n    if (minutes \u003c 10) {\n      minutes = '0' + minutes\n    }\n\n    let dateMonthYear = date + '.' + month + '.' + year\n    let time = hours + ':' + minutes\n    let fullTime = dateMonthYear + ' ' + time\n    return fullTime\n  }\n}\n\nconsole.log(Person.favoriteSkill())\nconsole.log(Person.showDateTime())\n```\n\n```sh\nNode\n15.1.2020 23:56\n```\n\nThe static methods are methods which can be used as utility functions.\n\n## Inheritance\n\nUsing inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc.\n\n```js\n// syntax\nclass ChildClassName extends {\n // code goes here\n}\n```\n\nLet us create a Student child class from Person parent class.\n\n```js\nclass Student extends Person {\n  saySomething() {\n    console.log('I am a child of the person class')\n  }\n}\n\nconst s1 = new Student('Asabeneh', 'Yetayeh', 'Finland', 250, 'Helsinki')\nconsole.log(s1)\nconsole.log(s1.saySomething())\nconsole.log(s1.getFullName())\nconsole.log(s1.getPersonInfo())\n```\n\n```sh\nStudent {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: \"Finland\", country: 250, city: \"Helsinki\", …}\nI am a child of the person class\nAsabeneh Yetayeh\nStudent {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: \"Finland\", country: 250, city: \"Helsinki\", …}\nAsabeneh Yetayeh is Finland. He lives Helsinki, 250.\n```\n\n### Overriding methods\n\nAs you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.\n\n```js\nclass Student extends Person {\n  constructor(firstName, lastName, age, country, city, gender) {\n    super(firstName, lastName, age, country, city)\n    this.gender = gender\n  }\n\n  saySomething() {\n    console.log('I am a child of the person class')\n  }\n  getPersonInfo() {\n    let fullName = this.getFullName()\n    let skills =\n      this.skills.length \u003e 0 \u0026\u0026\n      this.skills.slice(0, this.skills.length - 1).join(', ') +\n        ` and ${this.skills[this.skills.length - 1]}`\n\n    let formattedSkills = skills ? `He knows ${skills}` : ''\n    let pronoun = this.gender == 'Male' ? 'He' : 'She'\n\n    let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}`\n    return info\n  }\n}\n\nconst s1 = new Student(\n  'Asabeneh',\n  'Yetayeh',\n  250,\n  'Finland',\n  'Helsinki',\n  'Male'\n)\nconst s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female')\ns1.setScore = 1\ns1.setSkill = 'HTML'\ns1.setSkill = 'CSS'\ns1.setSkill = 'JavaScript'\n\ns2.setScore = 1\ns2.setSkill = 'Planning'\ns2.setSkill = 'Managing'\ns2.setSkill = 'Organizing'\n\nconsole.log(s1)\n\nconsole.log(s1.saySomething())\nconsole.log(s1.getFullName())\nconsole.log(s1.getPersonInfo())\n\nconsole.log(s2.saySomething())\nconsole.log(s2.getFullName())\nconsole.log(s2.getPersonInfo())\n```\n\n```sh\nStudent {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: 250, country: \"Finland\", city: \"Helsinki\", …}\nStudent {firstName: \"Lidiya\", lastName: \"Tekle\", age: 28, country: \"Finland\", city: \"Helsinki\", …}\nI am a child of the person class\nAsabeneh Yetayeh\nStudent {firstName: \"Asabeneh\", lastName: \"Yetayeh\", age: 250, country: \"Finland\", city: \"Helsinki\", …}\nAsabeneh Yetayeh is 250. He lives in Helsinki, Finland. He knows HTML, CSS and JavaScript\nI am a child of the person class\nLidiya Tekle\nStudent {firstName: \"Lidiya\", lastName: \"Tekle\", age: 28, country: \"Finland\", city: \"Helsinki\", …}\nLidiya Tekle is 28. She lives in Helsinki, Finland. He knows Planning, Managing and Organizing\n```\n\nNow, the getPersonInfo method has been overridden and it identifies if the person is male or female.\n\n## Exercises\n\n### Exercises Level 1\n\n1. Create an Animal class. The class will have name, age, color, legs properties and create different methods\n2. Create a Dog and Cat child class from the Animal Class.\n\n### Exercises Level 2\n\n1. Override the method you create in Animal class\n\n### Exercises Level 3\n\n1. Let's try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below.\n\n```JS\nages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]\n\nconsole.log('Count:', statistics.count()) // 25\nconsole.log('Sum: ', statistics.sum()) // 744\nconsole.log('Min: ', statistics.min()) // 24\nconsole.log('Max: ', statistics.max()) // 38\nconsole.log('Range: ', statistics.range() // 14\nconsole.log('Mean: ', statistics.mean()) // 30\nconsole.log('Median: ',statistics.median()) // 29\nconsole.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}\nconsole.log('Variance: ',statistics.var()) // 17.5\nconsole.log('Standard Deviation: ', statistics.std()) // 4.2\nconsole.log('Variance: ',statistics.var()) // 17.5\nconsole.log('Frequency Distribution: ',statistics.freqDist()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]\n```\n\n```sh\n// you output should look like this\nconsole.log(statistics.describe())\nCount: 25\nSum:  744\nMin:  24\nMax:  38\nRange:  14\nMean:  30\nMedian:  29\nMode:  (26, 5)\nVariance:  17.5\nStandard Deviation:  4.2\nFrequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]\n```\n\n1. Create a class 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 also a set of expenses and its description.\n\n## Regular Expressions\n\nA regular expression or RegEx is a small programming language that helps to find pattern in data. A RegEx can be used to check if some pattern exists in a different data types. To use RegEx in JavaScript either we use RegEx constructor or we can declare a RegEx pattern using two forward slashes followed by a flag. We can create a pattern in two ways.\n\nTo declare a string we use a single quote, double quote a backtick to declare a regular expression we use two forward slashes and an optional flag. The flag could be g, i, m, s, u or y.\n\n### RegEx parameters\n\nA regular expression takes two parameters. One required search pattern and an optional flag.\n\n#### Pattern\n\nA pattern could be a text or any form of pattern which some sort of similarity. For instance the word spam in an email could be a pattern we are interested to look for in an email or a phone number format number might be our interest to look for.\n\n#### Flags\n\nFlags are optional parameters in a regular expression which determine the type of searching. Let see some of the flags:\n\n- g:is a global flag which means looking for a pattern in whole text\n- i: case insensitive flag(it searches for both lowercase and uppercase)\n- m: multiline\n\n### Creating a pattern with RegEx Constructor\n\nDeclaring regular expression without global flag and case insensitive flag.\n\n```js\n// without flag\nlet pattern = 'love'\nlet regEx = new RegEx(pattern)\n```\n\nDeclaring regular expression with global flag and case insensitive flag.\n\n```js\nlet pattern = 'love'\nlet flag = 'gi'\nlet regEx = new RegEx(pattern, flag)\n```\n\nDeclaring a regex pattern using RegEx object. Writing the pattern and the flag inside the RegEx constructor\n\n```js\nlet regEx = new RegEx('love','gi')\n```\n\n### Creating a pattern without RegEx Constructor\n\nDeclaring regular expression with global flag and case insensitive flag.\n\n```js\nlet regEx= /love/gi\n```\n\nThe above regular expression is the same as the one which we created with RegEx constructor\n\n```js\nlet regEx= new RegEx('love','gi')\n```\n\n### RegExp Object Methods\n\nLet see some of RegEx methods\n\n#### Testing for  a match\n\n*test()*:Tests for a match in a string. It returns true or false.\n\n```js\nconst str = 'I love JavaScript'\nconst pattern = /love/\nconst result = pattern.test(str)\nconsole.log(result)\n```\n\n```sh\ntrue\n```\n\n#### Array containing all of the match\n\n*match()*:Returns an array containing all of the matches, including capturing groups, or null if no match is found.\nIf we do not use a global flag, match() returns an array containing the pattern, index, input and group.\n\n```js\nconst str = 'I love JavaScript'\nconst pattern = /love/\nconst result = str.match(pattern)\nconsole.log(result)\n```\n\n```sh\n[\"love\", index: 2, input: \"I love JavaScript\", groups: undefined]\n```\n\n```js\nconst str = 'I love JavaScript'\nconst pattern = /love/g\nconst result = str.match(pattern)\nconsole.log(result)\n```\n\n```sh\n[\"love\"]\n```\n\n*search()*: Tests for a match in a string. It returns the index of the match, or -1 if the search fails.\n\n```js\nconst str = 'I love JavaScript'\nconst pattern = /love/g\nconst result = str.search(pattern)\nconsole.log(result)\n```\n\n```sh\n2\n```\n\n#### Replacing a substring\n\n*replace()*: Executes a search for a match in a string, and replaces the matched substring with a replacement substring.\n\n```js\nconst txt = 'Python is the most beautiful language that a human begin has ever created.\\\nI recommend python for a first programming language'\n\nmatchReplaced = txt.replace(/Python|python/, 'JavaScript')\nconsole.log(matchReplaced)\n```\n\n```sh\nJavaScript is the most beautiful language that a human begin has ever created.I recommend python for a first programming language\n```\n\n```js\nconst txt = 'Python is the most beautiful language that a human begin has ever created.\\\nI recommend python for a first programming language'\n\nmatchReplaced = txt.replace(/Python|python/g, 'JavaScript')\nconsole.log(matchReplaced)\n```\n\n```sh\nJavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language\n```\n\n```js\nconst txt = 'Python is the most beautiful language that a human begin has ever created.\\\nI recommend python for a first programming language'\n\nmatchReplaced = txt.replace(/Python/gi, 'JavaScript')\nconsole.log(matchReplaced)\n```\n\n```sh\nJavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language\n```\n\n```js\n\nconst txt = '%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\\\nT%he%re i%s n%o%th%ing as m%ore r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing \\\np%e%o%ple.\\\nI fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\\\nD%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'\n\nmatches = txt.replace(/%/g, '')\nconsole.log(matches)  \n```\n\n```sh\nI am teacher and  I love teaching.There is nothing as more rewarding as educating and empowering people.I found teaching more interesting than any other jobs.Does this motivate you to be a teacher.\n```\n\n* []:  A set of characters\n  * [a-c] means, a or b or c\n  * [a-z] means, any letter a to z\n  * [A-Z] means, any character A to Z\n  * [0-3] means, 0 or 1 or 2 or 3\n  * [0-9] means any number 0 to 9\n  * [A-Za-z0-9] any character which is a to z, A to Z, 0 to 9\n* \\\\:  uses to escape special characters\n  * \\d mean:match where the string contains digits (numbers from 0-9)\n  * \\D mean: match where the string does not contain digits\n* . : any character except new line character(\\n)\n* ^: starts with\n  * r'^substring' eg r'^love', a sentence which starts with a word love\n  * r'[^abc] mean not a, not b, not c.\n* $: ends with\n  * r'substring$' eg r'love$', sentence ends with a word love\n* *: zero or more times\n  * r'[a]*' means a optional or it can be occur many times.\n* +: one or more times\n  * r'[a]+' mean at least once or more times\n* ?: zero or one times\n  *  r'[a]?' mean zero times or once\n* {3}: Exactly 3 characters\n* {3,}: At least 3 character\n* {3,8}: 3 to 8 characters\n* |: Either or\n  * r'apple|banana' mean either of an apple or a banana\n* (): Capture and group\n\n![Regular Expression cheat sheet](./images/regex.png)\n\nLet's use example to clarify the above meta characters\n\n### Square Bracket\n\nLet's use square bracket to include lower and upper case\n\n```js\nconst pattern = '[Aa]pple' // this square bracket mean either A or a\nconst txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  \n```\n\n```sh\n[\"Apple\", index: 0, input: \"Apple and banana are fruits. An old cliche says an…by a banana a day keeps the doctor far far away. \", groups: undefined]\n\n```\n\n```js\nconst pattern = /[Aa]pple/g // this square bracket mean either A or a\nconst txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  \n```\n\n```sh\n[\"Apple\", \"apple\"]\n```\n\nIf we want to look for the banana, we write the pattern as follows:\n\n```js\nconst pattern = /[Aa]pple|[Bb]anana/g // this square bracket mean either A or a\nconst txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. Banana is easy to eat too.'\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  \n```\n\n```sh\n[\"Apple\", \"banana\", \"apple\", \"banana\", \"Banana\"]\n```\n\nUsing the square bracket and or operator , we manage to extract Apple, apple, Banana and banana.\n\n### Escape character(\\\\) in RegEx\n\n```js\nconst pattern = /\\d/g  // d is a special character which means digits\nconst txt = 'This regular expression example was made in January 12,  2020.'\nconst matches = txt. match(pattern)\n\nconsole.log(matches)  // [\"1\", \"2\", \"2\", \"0\", \"2\", \"0\"], this is not what we want\n```\n\n```js\nconst pattern = /\\d+/g  // d is a special character which means digits\nconst txt = 'This regular expression example was made in January 12,  2020.'\nconst matches = txt. match(pattern)\n\nconsole.log(matches)  // [\"12\", \"2020\"], this is not what we want\n```\n\n### One or more times(+)\n\n```js\nconst pattern = /\\d+/g  // d is a special character which means digits\nconst txt = 'This regular expression example was made in January 12,  2020.'\nconst matches = txt. match(pattern)\nconsole.log(matches)  // [\"12\", \"2020\"], this is not what we want\n```\n\n### Period(.)\n\n```js\nconst pattern = /[a]./g  // this square bracket means a and . means any character except new line\nconst txt = 'Apple and banana are fruits'\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  // [\"an\", \"an\", \"an\", \"a \", \"ar\"]\n```\n\n```js\nconst pattern = /[a].+/g  // . any character, + any character one or more times \nconst txt = 'Apple and banana are fruits'\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  // ['and banana are fruits']\n```\n\n### Zero or more times(*)\n\nZero or many times. The pattern could may not occur or it can occur many times.\n\n```js\n\nconst pattern = /[a].*/g  //. any character, + any character one or more times \nconst txt = 'Apple and banana are fruits'\nconst matches = txt.match(pattern)\n\nconsole.log(matches)  // ['and banana are fruits']\n\n```\n\n### Zero or one times(?)\n\nZero or one times. The pattern could may not occur or it may occur once.\n\n```js\nconst txt = 'I am not sure if there is a convention how to write the word e-mail.\\\nSome people write it email others may write it as Email or E-mail.'\nconst pattern = /[Ee]-?mail/g  // ? means optional\nmatches = txt.match(pattern)\n\nconsole.log(matches)  // [\"e-mail\", \"email\", \"Email\", \"E-mail\"]\n\n```\n\n### Quantifier in RegEx\n\nWe can specify the length of the substring we look for in a text, using a curly bracket. Lets imagine, we are interested in substring that their length are 4 characters\n\n```js\nconst txt = 'This regular expression example was made in December 6,  2019.'\nconst pattern = /\\d{4}/g  // exactly four times\nconst matches = txt.match(pattern)\nconsole.log(matches)  // ['2019']\n```\n\n```js\nconst txt = 'This regular expression example was made in December 6,  2019.'\nconst pattern = /\\d{1,4}/g   // 1 to 4\nconst matches = txt.match(pattern)\nconsole.log(matches)  // ['6', '2019']\n```\n\n### Cart ^\n\n- Starts with\n  \n```js\nconst txt = 'This regular expression example was made in December 6,  2019.'\nconst pattern = /^This/ // ^ means starts with\nconst matches = txt.match(pattern)\nconsole.log(matches)  // ['This']\n```\n\n- Negation\n\n```js\nconst txt = 'This regular expression example was made in December 6,  2019.'\nconst pattern = /[^A-Za-z,. ]+/g  // ^ in set character means negation, not A to Z, not a to z, no space, no coma no period\nconst matches = txt.match(pattern)\nconsole.log(matches)  // [\"6\", \"2019\"]\n```\n\n### Exact match\n\nIt should have ^ starting and $ which is an end.\n\n```js\nlet pattern = /^[A-Z][a-z]{3,12}$/;\nlet name = 'Asabeneh';\nlet result = pattern.test(name)\n\nconsole.log(result) // true\n```\n\n## 💻 Exercises\n\n### Exercises: Level 1\n\n1. Calculate the total annual income of the person from the following text. ‘He earns 4000 euro from salary per month, 10000 euro annual bonus, 5500 euro online courses per month.’\n1. The position of some particles on the horizontal x-axis -12, -4, -3 and  -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers and find the distance between the two furthest particles.\n\n```js\npoints = ['-1', '2', '-4', '-3', '-1', '0', '4', '8']\nsortedPoints =  [-4, -3, -1, -1, 0, 2, 4, 8]\ndistance = 12\n```\n\n1. Write a pattern which identify if a string is a valid JavaScript variable\n\n    ```sh\n    is_valid_variable('first_name') # True\n    is_valid_variable('first-name') # False\n    is_valid_variable('1first_name') # False\n    is_valid_variable('firstname') # True\n    ```\n\n### Exercises: Level 2\n\n1. Write a function called *tenMostFrequentWords* which get the ten most frequent word from a string?\n\n    ```js\n        paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`\n        console.log(tenMostFrequentWords(paragraph))\n    ```\n\n    ```sh\n        [\n        {word:'love', count:6},\n        {word:'you', count:5},\n        {word:'can', count:3},\n        {word:'what', count:2},\n        {word:'teaching', count:2},\n        {word:'not', count:2},\n        {word:'else', count:2},\n        {word:'do', count:2},\n        {word:'I', count:2},\n        {word:'which', count:1},\n        {word:'to', count:1},\n        {word:'the', count:1},\n        {word:'something', count:1},\n        {word:'if', count:1},\n        {word:'give', count:1},\n        {word:'develop',count:1},\n        {word:'capabilities',count:1},\n        {word:'application', count:1},\n        {word:'an',count:1},\n        {word:'all',count:1},\n        {word:'Python',count:1},\n        {word:'If',count:1}]\n    ```\n\n    ```js\n    console.log(tenMostFrequentWords(paragraph, 10))\n    ```\n\n    ```sh\n   [{word:'love', count:6},\n    {word:'you', count:5},\n    {word:'can', count:3},\n    {word:'what', count:2},\n    {word:'teaching', count:2},\n    {word:'not', count:2},\n    {word:'else', count:2},\n    {word:'do', count:2},\n    {word:'I', count:2},\n    {word:'which', count:1}\n    ]\n    ```\n\n### Exercises: Level 3\n\n1. Writ a function which cleans text. Clean the following text. After cleaning, count three most frequent words in the string.\n  \n  ```js\n    sentence = `%I $am@% a %tea@cher%, \u0026and\u0026 I lo%#ve %tea@ching%;. There $is nothing; \u0026as\u0026 mo@re rewarding as educa@ting \u0026and\u0026 @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?`\n\n   console.log(cleanText(sentence))\n   ```\n\n   ```sh\n    I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher\n    ```\n1. Write a function which find the most frequent words. After cleaning, count three most frequent words in the string.\n\n    ```js\n    console.log(mostFrequentWords(cleanedText))\n    [{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]\n    ```\n\n\n## Promises and Callbacks\n\nFrom the following code blocks you will notice, the difference between callback and promises:\n\n  ```js\n      //Callback\n    const doSomething = callback =\u003e {\n    setTimeout(() =\u003e {\n      const skills = ['HTML', 'CSS', 'JS']\n      callback('It didnt go well', skills)\n    }, 2000)\n  }\n\n  doSomething((err, result) =\u003e {\n    if (err) {\n      return console.log(err)\n    }\n    return console.log(result)\n  })\n  // after 2 seconds it will print\n  // =\u003e It didnt go well\n\n    const doSomething = callback =\u003e {\n    setTimeout(() =\u003e {\n      const skills = ['HTML', 'CSS', 'JS']\n      callback(false, skills)\n    }, 2000)\n  }\n\n  doSomething((err, result) =\u003e {\n    if (err) {\n      return console.log(err)\n    }\n    return console.log(result)\n  })\n  // after 2 seconds it will print the skills\n  // =\u003e [\"HTML\", \"CSS\", \"JS\"]\n\n  ```\n\n  ```js\n   // Promise\n    const doPromise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e {\n    const skills = ['HTML', 'CSS', 'JS']\n    if (skills.length \u003e 0) {\n      resolve(skills)\n    } else {\n      reject('Something wrong has happened')\n    }\n  }, 2000)\n})\n\ndoPromise\n  .then(result =\u003e {\n    console.log(result)\n  })\n  .catch(error =\u003e console.log(error))\n\nconst myPromise = n =\u003e {\n  return new Promise((resolve, reject) =\u003e {\n    if (n) {\n      resolve(n * n)\n    } else {\n      reject('You need to pass an argument')\n    }\n  })\n}\n\nconst square = async n =\u003e {\n  let value = await myPromise(n)\n  return value\n}\n\nsquare()\n  .then(res =\u003e {\n    console.log(res)\n  })\n  .catch(err =\u003e console.log(err))\nconsole.log(square(10))\n ```\n\n## Async and Await\n\n```js\n    const url = 'https://restcountries.eu/rest/v2/alll'\n  fetch(url)\n    .then(response =\u003e response.json())\n    .then(data =\u003e {\n      console.log(data)\n    })\n    .catch(error =\u003e console.log(error))\n\n  const fetchData = async () =\u003e {\n    try {\n      const response = await fetch(url)\n      const countries = await response.json()\n      console.log(countries)\n    } catch (err) {\n      console.log(err)\n    }\n  }\n  console.log('===== async and await')\n  fetchData()\n  ```\n\n## localStorage\n\nLocal storage is the para of the web storage API which is used to store data on the browser with no expiration data. The data will be available on the browser even after the browser is closed. There are five methods to work on local storage:\n_setItem(), getItem(), removeItem(), clear(), key()_\n\n### Setting item to the localStorage\n\nWhen we set data to be stored in a localStorage, it will be stored as a string.  If we are storing an array or an object, we should stringify it first to keep the format unless otherwise we lose the array structure or the object structure of the original data\n\n```js\nlocalStorage.setItem('name', 'Asabeneh');\nconsole.log(localStorage) //Storage {name: 'Asabeneh', length: 1}\nlocalStorage.setItem('age', 200);\nconsole.log(localStorage) //Storage {age: '200', name: 'Asabeneh', length: 2}\nconst skills = ['HTML', 'CSS', 'JS', 'React'];\n//Skills array has to be stringified first to keep the format.\nconst skillsJSON = JSON.stringify(skills,undefined, 4)\nlocalStorage.setItem('skills', skillsJSON);\nconsole.log(localStorage) //Storage {age: '200', name: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3}\n```\n\nIf we are storing an array, an object or object array, we should stringify the object first. See the example below.\n\n```js\nlet skills = [\n  { tech: 'HTML', level: 10 },\n  { tech: 'CSS', level: 9 },\n  { tech: 'JS', level: 8 },\n  { tech: 'React', level: 9 },\n  { tech: 'Redux', level: 10 },\n  { tech: 'Node', level: 8 },\n  { tech: 'MongoDB', level: 8 }\n];\n\nlet skillJSON = JSON.stringify(skills);\nlocalStorage.setItem('skills', skillJSON);\n```\n\n### Getting item from localStorage\n\n```js\nlet name = localStorage.getItem('name');\nlet age = localStorage.getItem('age');\nlet skills = localStorage.getItem('skills');\n\nconsole.log(name, age, skills) // 'Asabeneh', '200', '['HTML','CSS','JS','React']'\n\nlet skillsObj = JSON.parse(localStorage.getItem('skills'), undefined, 4);\nconsole.log(skillsObj);\n```\n\n### Clearing the localStorage\n\nThe clear method, will clear everything stored in the local storage\n\n```js\nlocalStorage.clear();\n```\n\n### Exercises:Local Storage\n\n## Cookies\n\n### Exercises:Cookies\n\n## JavaScript Interview Questions\n\n### [JavaScript Tests](https://github.com/Asabeneh/JavaScript-for-Everyone/wiki/JavaScript-Tests)\n\n### [JavaScript Test 1](https://github.com/Asabeneh/JavaScript-for-Everyone/wiki/JavaScript-Test-1)\n\n### [JavaScript Test 2](https://github.com/Asabeneh/JavaScript-for-Everyone/wiki/JavaScript-Test-2)\n\n### [JavaScript Test 3](https://github.com/Asabeneh/JavaScript-for-Everyone/wiki/JavaScript-Test-3)\n\n- [JavaScript Test 3: Solutions](https://github.com/Asabeneh/JavaScript-for-Everyone/blob/master/solutions/javascript-test-3.js)\nJavaScript-Test-4)\n- [JavaScript Test 4: Solutions](https://github.com/Asabeneh/JavaScript-for-Everyone/blob/master/solutions/javascript-test-4.js)\n","funding_links":["https://www.paypal.me/asabeneh"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fasabeneh%2Fjavascript-for-everyone","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fasabeneh%2Fjavascript-for-everyone","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fasabeneh%2Fjavascript-for-everyone/lists"}