- Notifications
You must be signed in to change notification settings - Fork305
A step by step guide to learn JavaScript and programming. These videos may help too:https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
Asabeneh/JavaScript-for-Everyone
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
- Introduction
- Setup
- Requirements
- Setup
- Variables
- Comments
- Data types
- Numbers
- Strings
- Checking Data types and Casting
- Operators
- Conditionals
- Arrays
- More on Arrays
- Functions
- Object
- JSON
- Higher Order Function
- Functional Programming
- Destructuring and Spread
- Map and Set
- Set
- Set
- Map
- Document Object Model (DOM)
- Classes
- Inheritance
- Exercises
- Regular Expressions
- 💻 Exercises
- Async and Await
- localStorage
- Cookies
- JavaScript Interview Questions
JavaScript for Everyone is a guide for both beginners and advanced JavaScript developers. Welcome to JavaScript.Congratulations for deciding to learn JavaScript, the language of the browser.
In this step by step tutorial, you will learn JavaScript, the most popular programming language in the history of mankind.You use JavaScriptto add interactivity to websites, to develop mobile apps, desktop applications, games and nowadays JavaScript can be used formachine learning andAI.JavaScript (JS) has increased in popularity in recent years and has been the leadingprogramming language for four consecutive years and is the most used programming language onGithub.
First thing first, lets install text or code editor. Install code editor, it could bevscode,atom,bracket,notepad++ or others. I recommend vscode.Install eitherChrome orFirefox if you didn't have yet.
If you want help, you may join thetelegram channel.
No prior knowledge of programming is required to follow this guide. You need only:
- Motivation
- Computer
- Internet
- Browser
- Code Editor
I believe you have the motivation and a strong desire to be a developer, computer and Internet. If you have those, then you have everything.
You may not need it right now but you may need it for later. Installnode.js.
After downloading double click and install
We can check if node is installed in our local machine by opening our device terminal or command prompt.
asabeneh $ node -vv12.14.0
I am using node version 12.14.0, which is the recommended version of node.
There are many browsers out there. However, I strongly recommend Google Chrome.
Installgoogle 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.
You can open Google Chrome either by clicking three dots at the top right corner of the Chrome browser or using a shortcut. I prefer using shortcuts.
To open the Chrome console using a short cut.
MacCommand+Option+IWindows:Ctl+Shift+I
After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console part. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code.Let us write a JavaScript code on the Google Chrome console:
We can write any JavaScript code on the Google console or any browser console. However, for this challenge, we only focus on Google Chrome console. Open the console using:
MacCommand+Option+IWindows:Ctl+Shift+I
To write our first JavaScript code, we used a builtin functionconsole.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.
console.log('Hello, World!')
The console.log(param1, param2, param3), can take multiple arguments.
console.log('Hello','World','!')console.log('HAPPY','NEW','YEAR',2020)console.log('Welcome','to',30,'Days','Of','JavaScript')
As you can see from the above snippet code,console.log() can take multiple arguments.
Congratulations! You wrote your first JavaScript code usingconsole.log().
We add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. Any text starts with // in JavaScript is a comment or anything enclose like this /* */ is a comment.
Example: Single Line Comment
// This is the first comment
// This is the second comment
// I am a single line comment
Example: Multiline Comment
/*This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
*/
JavaScript is a programming language. As a result, it has its syntax like other programming languages. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors.
I made a deliberate mistake. As a result, the console raises a syntax error. Actually, the syntax is very informative. It informs what type of mistake we made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors:
console.log("Hello, World!")console.log('Hello, World!')
So far, we saw how to display text using aconsole.log(). If we are printing text or string usingconsole.log(), the text has to be under the single, double, or backtick.Example:
console.log("Hello, World!")console.log('Hello, World!')console.log(`Hello, World!`)
Now, let us practice more writing JavaScript codes usingconsole.log() on google chrome console for number data types.In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.
console.log(2+3)// Additionconsole.log(3-2)// Subtractionconsole.log(2*3)// Multiplicationconsole.log(3/2)// Divisionconsole.log(3%2)// Modulus - finding remainderconsole.log(3**2)// Exponential
We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days python JavaScript challenge, we will use visual studio code.
Visual studio code is a very popular open-source text editor. I would recommend todownload visual studio code, but if you are in favor of other editors, feel free to follow with what you have.
If you installed visual studio code, let us start using it.
Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.
JavaScript can be added to a web page in three ways:
- Inline script
- Internal script
- External script
The following sections show different ways of adding JavaScript code to your web page.
Create a folder on your desktop or in any location and create anindex.html file in your folder. Then paste the following code and open it in a browser, either inChrome orFirefox.
<!DOCTYPE html><html><head><title>JavaScript for Everyone</title></head><body><buttononclick="alert('Welcome to JavaScript!');">Click Me</button></body></html>
Internal script can be written in thehead or thebody but it is preferred to put it on the body of the html document.
- Internal script at the head
<!DOCTYPE html><html><head><title>JavaScript for Everyone</title><script>console.log("Welcome to JavaScript for Everyone");</script></head><body></body></html>
- Internal script at the body
<!DOCTYPE html><html><head><title>JavaScript for Everyone</title></head><body><script>console.log("Welcome to JavaScript for Everyone");</script></body></html>
The external script link can be on the head or body but it is preferred to put it in the body.
- External script at the head
<!DOCTYPE html><html><head><title>JavaScript for Everyone</title><scriptsrc="introduction.js"></script></head><body></body></html
- External script at the body
<!DOCTYPE html><html><head><title>JavaScript for Everyone</title></head><body> //it could be in the header or in the body // Here is the recommended place to put the script<scriptsrc="introduction.js"></script></body></html
Variables arecontainers of data. Variablesstore 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 orconst key words. For a variable which changes at different time we uselet but if the data doesn't change at all we useconst. For example PI, country name, gravity.
- A JavaScript variable name shouldn't begin with a number
- A JavaScript variable name does not allow special characters except dollar sign and underscore.
- A JavaScript variable name follow a camelCase convention.
- A JavaScript variable name shouldn't have space between words. The following are valid examples of JavaScript variables.
Valid variables in #"auto" data-snippet-clipboard-copy-content=" firstName lastName country city capitalCity age isMarried first_name last_name is_married capital_city num1 num_1 _num_1 $num1 year2019 year_2019">
firstNamelastNamecountrycitycapitalCityageisMarriedfirst_namelast_nameis_marriedcapital_citynum1num_1_num_1$num1year2019year_2019
Camel case(camelCase) or the first way of declaring is conventional in JavaScript. In this material, camelCase variables will be used.
Invalid variable:
first-name 1_num num_#_1
Declaring variables
// Declaring different variables of different data typesletfirstName='Asabeneh';// first name of a personletlastName='Yetayeh';// last name of a personletcountry='Finland';// countryletcity='Helsinki';// capital cityletage=100;// age in yearsletisMarried=true;console.log(firstName,lastName,country,city,age,isMarried);// Asabeneh, Yetayeh, Finland, Helsinki, 100, True// Declaring variables with number valuesconstgravity=9.81;// earth gravity in m/s2constboilingPoint=100;// water boiling point, temperature in oCconstPI=3.14;// geometrical constantconsole.log(gravity,boilingPoint,PI);// 9.81, 100, 3.14// Variables can also be declaring in one line separated by commaletname='Asabeneh',//name of a personjob='teacher',live='Finland';console.log(name,job,live);
Declare four variables without assigning values
Declare four variables with assigning values
Declare variables to store your first name, last name, marital status, country and age in multiple lines
Declare variables to store your first name, last name, marital status, country and age in a single line
Declare two variablesmyAge andyourAge and assign them initial values and log to browser console.Output:
I am 25 years old.You are 30 years old.
Commenting in JavaScript is similar to other programming languages. Comments can help to make code more readable.There are two ways of commenting:
- Single line commenting
- Multiline commenting
// let firstName = 'Asabeneh'; single line comment// let lastName = 'Yetayeh'; single line comment
Multiline commenting:
/* let location = 'Helsinki'; let age = 100; let isMarried = true; This is a Multiple line comment */
- Write a single line comment which says,comments can make code readable
- Write a multiline comment which says,comments can make code readable, easy to useand informative
In 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
- Primitive data types
- Non-primitive data types(Object References)
Primitive data types in JavaScript includes:
- Numbers - Integers, floats
- Strings - Any data under single or double quote
- Booleans - true or false value
- Null - empty value or no value
- Undefined - a declared variable without a value
Non-primitive data types in JavaScript includes:
- Objects
- Functions
- Arrays
Now, let us see what exactly mean primitive and non-primitive data types.Primitive data types are immutable(non-modifiable) data types. Once a primitive data type is created we can not modify it.Example:
letword='JavaScript'
If we try to modify the string stored in variableword, JavaScript will raise an error. Any data type under a single quote, double-quote, or backtick is a string data type.
word[0]='Y'
This expression does not change the string stored in the variableword. So, we can say that strings are not modifiable or immutable.Primitive data types are compared by its values. Let us compare different data values. See the example below:
letnumOne=3letnumTwo=3console.log(numOne==numTwo)// trueletjs='JavaScript'letpy='Python'console.log(js==py)//falseletlightOn=trueletlightOff=falseconsole.log(lightOn==lightOff)// false
Non-primitive data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created.Let 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.
letnums=[1,2,3]nums[0]=10console.log(nums)// [10, 2, 3]
As 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.
letnums=[1,2,3]letnumbers=[1,2,3]console.log(nums==numbers)// falseletuserOne={name:'Asabeneh',role:'teaching',country:'Finland'}letuserTwo={name:'Asabeneh',role:'teaching',country:'Finland'}console.log(userOne==userTwo)// false
Rule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object.Non-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.
letnums=[1,2,3]letnumbers=numsconsole.log(nums==numbers)// trueletuserOne={name:'Asabeneh',role:'teaching',country:'Finland'}letuserTwo=userOneconsole.log(userOne==userTwo)// true
If 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.
Numbers are integers and decimal values which can do all the arithmetic operations.Lets' see some examples of Numbers.
letage=35constgravity=9.81//we use const for non-changing values, gravitational constant in m/s2letmass=72// mass in KilogramconstPI=3.14// pi a geometrical constant//More ExamplesconstboilingPoint=100// temperature in oC, boiling point of water which is a constantconstbodyTemp=37// oC average human body temperature, which is a constantconsole.log(age,gravity,mass,PI,boilingPoint,bodyTemp)
In JavaScript the Math Object provides a lots of methods to work with numbers.
constPI=Math.PIconsole.log(PI)// 3.141592653589793// Rounding to the closest number// if above .5 up if less 0.5 down roundingconsole.log(Math.round(PI))// 3 to round values to the nearest numberconsole.log(Math.round(9.81))// 10console.log(Math.floor(PI))// 3 rounding downconsole.log(Math.ceil(PI))// 4 rounding upconsole.log(Math.min(-5,3,20,4,5,10))// -5, returns the minimum valueconsole.log(Math.max(-5,3,20,4,5,10))// 20, returns the maximum valueconstrandNum=Math.random()// creates random number between 0 to 0.999999console.log(randNum)// Let us create random number between 0 to 10constnum=Math.floor(Math.random()*11)// creates random number between 0 and 10console.log(num)//Absolute valueconsole.log(Math.abs(-10))//10//Square rootconsole.log(Math.sqrt(100))// 10console.log(Math.sqrt(2))//1.4142135623730951// Powerconsole.log(Math.pow(3,2))// 9console.log(Math.E)// 2.718// Logarithm//Returns the natural logarithm of base E of x, Math.log(x)console.log(Math.log(2))// 0.6931471805599453console.log(Math.log(10))// 2.302585092994046// TrigonometryMath.sin(0)Math.sin(60)Math.cos(0)Math.cos(60)
The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...
letrandomNum=Math.random()// generates 0 to 0.999
Now, let us see how we can use random() method to generate a random number between 0 and 10 inclusive.
letrandomNum=Math.random()// generates 0 to 0.999letnumBtnZeroAndTen=randomNum*11console.log(numBtnZeroAndTen)// this gives: min 0 and max 10.99letrandomNumRoundToFloor=Math.floor(numBtnZeroAndTen)console.log(randomNumRoundToFloor)// this gives between 0 and 10
Strings are texts, which are undersingle ordouble quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double-quote, or backtick.Lets' see some examples of string:
letspace=' '// an empty space stringletfirstName='Asabeneh'letlastName='Yetayeh'letcountry='Finland'letcity='Helsinki'letlanguage='JavaScript'letjob='teacher'
Connect two or more strings together is called concatenation.
// Declaring different variables of different data typesletspace=' 'letfirstName='Asabeneh'letlastName='Yetayeh'letcountry='Finland'letcity='Helsinki'letlanguage='JavaScript'letjob='teacher'
letfullName=firstName+space+lastName;// concatenation, merging two string together.console.log(fullName);
Asabeneh Yetayeh
We can concatenate string in different ways.
Concatenating 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.
// Declaring different variables of different data typesletspace=' 'letfirstName='Asabeneh'letlastName='Yetayeh'letcountry='Finland'letcity='Helsinki'letlanguage='JavaScript'letjob='teacher'letage=250letfullName=firstName+space+lastNameletpersonInfoOne=fullName+'. I am '+age+'. I live in '+country;// ES5console.log(personInfoOne)
Asabeneh Yetayeh. I am 250. I livein Finland
A 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.Example:
constparagraph="My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \In the end of 2019, I was thinking to expand my teaching and to reach \to global audience and I started a Python challenge from November 20 - December 19.\It was one of the most rewarding and inspiring experience.\Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \I hope you are enjoying too."console.log(paragraph)
In JavaScript and other programming language \ followed by some characters is an escape sequence. Let's see the most common escape characters:
- \n: new line
- \t: Tab means(8 spaces)
- \\: Back slash
- \': Single quote (')
- \":Double quote (")
console.log('I hope every one is enjoying the 30 Days Of JavaScript challenge.\nDo you ?')// line breakconsole.log('Days\tTopics\tExercises')console.log('Day 1\t3\t5')console.log('Day 2\t3\t5')console.log('Day 3\t3\t5')console.log('Day 4\t3\t5')console.log('This is a back slash symbol (\\)')// To write a back slashconsole.log('In every programming language it starts with \"Hello, World!\"')console.log("In every programming language it starts with \'Hello, World!\'")console.log('The saying \'Seeing is Believing\' is\'t correct in 2020')
To 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.
//Syntax`String literal text``String literal text${expression}`
Example: 1
console.log(`The sum of 2 and 3 is 5`)// statically writing the dataleta=2letb=3console.log(`The sum of${a} and${b} is${a+b}`)// injecting the data dynamically
Example:2
letfirstName='Asabeneh'letlastName='Yetayeh'letcountry='Finland'letcity='Helsinki'letlanguage='JavaScript'letjob='teacher'letage=250letfullName=firstName+' '+lastNameletpersonInfoTwo=`I am${fullName}. I am${age}. I live in${country}.`//ES6 - String interpolation methodletpersonInfoThree=`I am${fullName}. I live in${city},${country}. I am a${job}. I teach${language}.`console.log(personInfoTwo)console.log(personInfoThree)
I am Asabeneh Yetayeh. I am 250. I livein Finland.I am Asabeneh Yetayeh. I livein Helsinki, Finland. I am a teacher. I teach JavaScript.
Using a string template or string interpolation method, we can add expression, which could be a value or some operations(comparison, arithmetic operations, ternary operation).
leta=2letb=3console.log(`${a} is greater than${b}:${a>b}`)
2 is greater than 3:false
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
length: The stringlength method returns the number of characters in a string included empty space.Example:
letjs='JavaScript'console.log(js.length)// 10letfirstName='Asabeneh'console.log(firstName.length)// 8
Accessing characters in a string: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string.
Let us access different characters in 'JavaScript' string.
letstring='JavaScript'letfirstLetter=string[0]console.log(firstLetter)// JletsecondLetter=string[1]// aletthirdLetter=string[2]letlastLetter=string[9]console.log(lastLetter)// tletlastIndex=string.length-1console.log(lastIndex)// 9console.log(string[lastIndex])// t
- toUpperCase(): this method changes the string to uppercase letters.
letstring='JavaScript'console.log(string.toUpperCase())// JAVASCRIPTletfirstName='Asabeneh'console.log(firstName.toUpperCase())// ASABENEHletcountry='Finland'console.log(country.toUpperCase())// FINLAND
- toLowerCase(): this method changes the string to lowercase letters.
letstring='JavasCript'console.log(string.toLowerCase())// javascriptletfirstName='Asabeneh'console.log(firstName.toLowerCase())// asabenehletcountry='Finland'console.log(country.toLowerCase())// finland
- substr(): It takes two arguments, the starting index and number of characters to slice.
letstring='JavaScript'console.log(string.substr(4,6))// Scriptletcountry='Finland'console.log(country.substr(3,4))// land
- substring(): It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index.
letstring='JavaScript'console.log(string.substring(0,4))// Javaconsole.log(string.substring(4,10))// Scriptconsole.log(string.substring(4))// Scriptletcountry='Finland'console.log(country.substring(0,3))// Finconsole.log(country.substring(3,7))// landconsole.log(country.substring(3))// land
- split(): The split method splits a string at a specified place.
letstring='30 Days Of JavaScript'console.log(string.split())// ["30 Days Of JavaScript"]console.log(string.split(' '))// ["30", "Days", "Of", "JavaScript"]letfirstName='Asabeneh'console.log(firstName.split())// ["Asabeneh"]console.log(firstName.split(''))// ["A", "s", "a", "b", "e", "n", "e", "h"]letcountries='Finland, Sweden, Norway, Denmark, and Iceland'console.log(countries.split(','))// ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]console.log(countries.split(', '))// ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
- trim(): Removes trailing space in the beginning or the end of a string.
letstring=' 30 Days Of JavaScript 'console.log(string)console.log(string.trim(' '))letfirstName=' Asabeneh 'console.log(firstName)console.log(firstName.trim())
30 Days Of JavasCript 30 Days Of JavasCript Asabeneh Asabeneh
- 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.
letstring='30 Days Of JavaScript'console.log(string.includes('Days'))// trueconsole.log(string.includes('days'))// falseconsole.log(string.includes('Script'))// trueconsole.log(string.includes('script'))// falseconsole.log(string.includes('java'))// falseconsole.log(string.includes('Java'))// trueletcountry='Finland'console.log(country.includes('fin'))// falseconsole.log(country.includes('Fin'))// trueconsole.log(country.includes('land'))// trueconsole.log(country.includes('Land'))// false
- replace(): takes to parameter the old substring and new substring.
string.replace(oldsubstring,newsubstring)
letstring='30 Days Of JavaScript'console.log(string.replace('JavaScript','Python'))// 30 Days Of Pythonletcountry='Finland'console.log(country.replace('Fin','Noman'))// Nomanland
- charAt(): Takes index and it returns the value at that index
string.charAt(index)
letstring='30 Days Of JavaScript'console.log(string.charAt(0))// 3letlastIndex=string.length-1console.log(string.charAt(lastIndex))// t
- charCodeAt(): Takes index and it returns char code(ASCII number) of the value at that index
string.charCodeAt(index)
letstring='30 Days Of JavaScript'console.log(string.charCodeAt(3))// D ASCII number is 51letlastIndex=string.length-1console.log(string.charCodeAt(lastIndex))// t ASCII is 116
- 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
string.indexOf(substring)
letstring='30 Days Of JavaScript'console.log(string.indexOf('D'))// 3console.log(string.indexOf('Days'))// 3console.log(string.indexOf('days'))// -1console.log(string.indexOf('a'))// 4console.log(string.indexOf('JavaScript'))// 11console.log(string.indexOf('Script'))//15console.log(string.indexOf('script'))// -1
- 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
//syntaxstring.lastIndexOf(substring)
letstring='I love JavaScript. If you do not love JavaScript what else can you love.'console.log(string.lastIndexOf('love'))// 67console.log(string.lastIndexOf('you'))// 63console.log(string.lastIndexOf('JavaScript'))// 38
- concat(): it takes many substrings and creates concatenation.
string.concat(substring,substring,substring)
letstring='30'console.log(string.concat("Days","Of","JavaScript"))// 30DaysOfJavaScriptletcountry='Fin'console.log(country.concat("land"))// Finland
- 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).
//syntaxstring.startsWith(substring)
letstring='Love is the best to in this world'console.log(string.startsWith('Love'))// trueconsole.log(string.startsWith('love'))// falseconsole.log(string.startsWith('world'))// falseletcountry='Finland'console.log(country.startsWith('Fin'))// trueconsole.log(country.startsWith('fin'))// falseconsole.log(country.startsWith('land'))// false
- 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).
string.endsWith(substring)
letstring='Love is the best to in this world'console.log(string.endsWith('world'))// trueconsole.log(string.endsWith('love'))// falseconsole.log(string.endsWith('in this world'))// trueletcountry='Finland'console.log(country.endsWith('land'))// trueconsole.log(country.endsWith('fin'))// falseconsole.log(country.endsWith('Fin'))// false
- search: it takes a substring as an argument and it returns the index of the first match.
string.search(substring)
letstring='I love JavaScript. If you do not love JavaScript what else can you love.'console.log(string.search('love'))// 2
- 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.
letstring='love'letpatternOne=/love/// with out any flagletpatternTwo=/love/gi// g-means to search in the whole text, i - case insensitive
Match syntax
// syntaxstring.match(substring)
letstring='I love JavaScript. If you do not love JavaScript what else can you love.'console.log(string.match('love'))
["love", index: 2, input:"I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
letpattern=/love/giconsole.log(string.match(pattern))// ["love", "love", "love"]
Let us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section.
lettxt='In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge'letregEx=/\d+/// d with escape character means d not a normal d instead acts a digit// + means one or more digit numbers,// if there is g after that it means global, search everywhere.console.log(txt.match(regEx))// ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]console.log(txt.match(/\d+/g))// ["2019", "30", "2020"]
- repeat(): it takes a number argument and it returned the repeated version of the string.
string.repeat(n)
letstring='love'console.log(string.repeat(10))// lovelovelovelovelovelovelovelovelovelove
- Check Data types: To check the data type of a certain data type we use thetypeof and we also change one data type to another.Example:
// Different javascript data types// Let's declare different data typesletfirstName='Asabeneh'// stringletlastName='Yetayeh'// stringletcountry='Finland'// stringletcity='Helsinki'// stringletage=250// number, it is not my real age, do not worry about itletjob// undefined, because a value was not assignedconsole.log(typeof'Asabeneh')// stringconsole.log(typeoffirstName)// stringconsole.log(typeof10)// numberconsole.log(typeof3.14)// numberconsole.log(typeoftrue)// booleanconsole.log(typeoffalse)// booleanconsole.log(typeofNaN)// numberconsole.log(typeofjob)// undefinedconsole.log(typeofundefined)// undefinedconsole.log(typeofnull)// object
- Casting: Converting one data type to another data type. We useparseInt(),parseFloat(),Number(),+ sign,str()When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.We can convert string to number using the following methods:
- parseInt()
- Number()
- Plus sign(+)
letnum='10'letnumInt=parseInt(num)console.log(numInt)// 10
letnum='10'letnumInt=Number(num)console.log(numInt)// 10
letnum='10'letnumInt=+numconsole.log(numInt)// 10
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.We can convert string float to number using the following methods:
- parseFloat()
- Number()
- Plus sign(+)
letnum='9.81'letnumFloat=parseFloat(num)console.log(numFloat)// 9.81
letnum='9.81'letnumFloat=Number(num)console.log(numFloat)// 9.81
letnum='9.81'letnumFloat=+numconsole.log(numInt)// 9.81
We can convert float numbers to integers.We use the following method to convert float to int:
- parseInt()
letnum=9.81letnumInt=parseInt(num)console.log(numInt)// 9
- Declare variables and assign string, boolean, undefined and null data types
- The JavaScripttypeof operator uses to check different data types. Check the data type of each variables from question number 1.
- Declare a variable name company and assign it to an initial value'Coding Academy'.
- Print the string on the browser console usingconsole.log()
- Print thelength of the string on the browser console usingconsole.log()
- Change all the string to capital letters usingtoUpperCase() method
- Change all the string to lowercase letters usingtoLowerCase() method
- Cut(slice) out the first word of the string usingslice,substr() orsubstring() method
- Usesubstr to slice out the phasebecause because because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
- Check if the string contains a wordAcademy usingincludes() method
- Split thestring intoarray usingsplit() method
- Split the string Coding Academy at the space usingsplit() method
- 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'split the string at the comma and change it to an array.
- Change Coding Academy to Microsoft Academy usingreplace() method.
- What is character at index 10 in 'Coding Academy' string usecharAt() method.
- What is the character code of A in 'Coding Academy' string usingcharCodeAt()
- UseindexOf to determine the position of the first occurrence of c in Coding Academy
- UselastIndexOf to determine the position of the last occurrence of c in Coding Academy.
- UseindexOf to find the position of the first occurrence of the wordbecause in the following sentence:'You cannot end a sentence with because because because is a conjunction'
- UselastIndexOf to find the position of the first occurrence of the wordbecause in the following sentence:'You cannot end a sentence with because because because is a conjunction'
- Usesearch to find the position of the first occurrence of the wordbecause in the following sentence:'You cannot end a sentence with because because because is a conjunction'
- Usetrim() to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' Coding Academy '.
- UsestartsWith() method with the string Coding Academy make the result true
- UseendsWith() method with the string Coding Academy make the result true
- Usematch() method to find all the c’s in Coding Academy
- Usematch() to count the number all because's in the following sentence:'You cannot end a sentence with because because because is a conjunction'
- Useconcat() and merge 'Coding' and 'Academy' to a single string, 'Coding Academy'
- Userepeat() method to print Coding Academy 5 times
- 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.'
Boolean value is either true or false. Any comparisons return a boolean value which is either true or false.
letisLightOn=true;letisRaining=false;lethungry=false;letisMarried=true;
Boolean value is either true or false.
- Write three JavaScript statement which provide truthy value.
- Write three JavaScript statement which provide falsy value.
- Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===.Which are true or which are false ?
- 4 > 3
- 4 >= 3
- 4 < 3
- 4 <= 3
- 4 == 4
- 4 === 4
- 4 != 4
- 4 !== 4
- 4 != '4'
- 4 == '4'
- 4 === '4'
letfirstName;console.log(firstName);//not defined, because it is not assigned to a value yet
letempty=null;console.log(empty);// -> null , means no value
String, number, boolean, null, undefined and symbol(ES6) are JavaScript primitive data types.
- The JavaScripttypeof operator uses to check different data types. Check the data type of each variables from question number 1.
Arithmetic operators are mathematical operators:+, -, _, /, _
letnumOne=4;letnumTwo=3;letsum=numOne+numTwo;letdiff=numOne-numTwo;letmult=numOne*numTwo;letdiv=numOne/numTwo;letremainder=numOne%numTwo;console.log(sum,diff,mult,div,remainder);// ->7,1,12,1.33,1letPI=3.14;letradius=100;// length in meterconstgravity=9.81;// in m/s2letmass=72;// in KilogramconstboilingPoint=100;// temperature in oC, boiling point of waterconstbodyTemp=37;// body temperature in oC// Lets calculate area of a circleconstareaOfCircle=PI*radius*radius;console.log(areaOfCircle);// -> 314 m// Lets calculate weight of a substanceconstweight=mass*gravity;console.log(weight);// -> 706.32 N(Newton)// ConcatEnating string with numbers using string interpolation/* The boiling point of water is 100 oC. Human body temperature is 37 oC. The gravity of earth is 9.81 m/s2. */console.log(`The boiling point of water is${boilingPoint} oC.\nHuman body temperature is${body} oC.\nThe gravity of earth is${gravity} m / s2.`);
JavaScript arithmetic operators are addition(+), subtraction(-), multiplication(*), division(/), modulus(%), increment(++) and decrement(--).
letoperandOne=4;letoperandTwo=3;
Using the above operands apply different JavaScript arithmetic operators
The following symbols are the common logical operators:&&(ampersand) , ||(pipe) and !(negation).&& gets true only if the two operands are true.|| gets true either of the operand is true.! negates true to false, false to true.
// && ampersand exampleconstcheck=4>3&&10>5;// true and true -> trueconstcheck=4>3&&10<5;// true and false -> falseconstcheck=4<3&&10<5;// false and false -> false// || pipe or, exampleconstcheck=4>3||10>5;// true and true -> trueconstcheck=4>3||10<5;// true and false -> trueconstcheck=4<3||10<5;// false and false -> false// ! Negation examplesletcheck=4>3;// -> trueletcheck=!(4>3);// -> falseletisLightOn=true;// -> trueletisLightOff=!isLightOn;// -> falseletisMarried=!false;// -> true
Which are true or which are false ?
- 4 > 3 && 10 < 12
- 4 > 3 && 10 > 12
- 4 > 3 || 10 < 12
- 4 > 3 || 10 > 12
- !(4 > 3)
- !(4 < 3)
- !(false)
- !(4 > 3 && 10 < 12)
- !(4 > 3 && 10 > 12)
- !(4 === '4')
4>3;4>=4;4<3;4<=3;4!=3;4!=='4';4=='4';4==='4';4===4;
Boolean value is either true or false. Any comparison return a boolean either true or false.Use all the following comparison operators to compare the following values: >, < >=, <=, !=, !==,===.Which are true or which are false ?
- 4 > 3
- 4 >= 3
- 4 < 3
- 4 <= 3
- 4 == 4
- 4 === 4
- 4 != 4
- 4 !== 4
- 4 != '4'
- 4 == '4'
- 4 === '4'
We use if condition to check only on condition.
if(condition){// code goes here}letisRaining=true;if(isRaining){console.log('Remember to take your rain coat.');}
When we have more than one condition we use the if and else condition.
if(condition){// if the condition meets, this block of code runs}else{// if condition doesn't meet, this block code runs}letisRaining=true;if(isRaining){console.log('You need a rain coat.');}else{console.log('No need for a rain coat.');}
Whenever we have multiple conditions.
// if else if elseletweather='sunny';if(weather==='rainy'){console.log('You need a rain coat.');}elseif(weather==='cloudy'){console.log('It might be cold, you need a jacket.');}elseif(weather==='sunny'){console.log('Go out freely.');}else{console.log('No need for rain coat.');}
Switch an alternative for if else if else
varweather='cloudy';switch(weather){case'rainy':console.log('You need a rain coat.');break;case'cloudy':console.log('It might be cold, you need a jacket.');break;case'sunny':console.log('Go out freely.');break;default:console.log(' No need for rain coat.');break;}// Switch More ExamplesvardayUserInput=prompt('What day is it ?');varday=dayUserInput.toLowerCase();switch(day){case'monday':console.log('Today is Monday');break;case'tuesday':console.log('Today is Tuesday');break;case'wednesday':console.log('Today is Wednesday');break;case'thursday':console.log('Today is Thursday');break;case'friday':console.log('Today is Friday');break;case'saturday':console.log('Today is Saturday');break;case'sunday':console.log('Today is Sunday');break;default:console.log('It is not a week day.');break;}
Another way to write conditionals is using ternary operators.
letisRaining=true;isRaining ?console.log('You need a rain coat.') :console.log('No need for a rain coat.');
Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:You are old enough to drive but if not 18 give feedback to wait for the years he supposed to wait for.Output:
Enter your age: 30You are old enough to drive.
Output:
Enter your age:15You are left with 3 years to drive.
Compare the values of myAge and yourAge using if … else. Based on the comparison log to console who is older (me or you). Use prompt(“Enter your age:”) to get the age as input.Output:
Enter your age: 30You are 5 years older than me.
If a is greater than b return a is greater than b else a is less than b.Output:
let a = 4let b = 3 4 is greater than 3
Write a code which give grade students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0 -49, F
Check if the season is Autumn, Winter, Spring or Summer.If the user input is:
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
In programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.
// for loop structurefor(initialization,condition,increment/decrement){// code goes here}for(leti=0;i<=5;i++){console.log(i)}
leti=0;while(i<=5){console.log(i);i++;}
leti=0;do{console.log(i);i++;}while(i<=5);
Iterate 0 to 10 using for loop, do the same using while and do while loop.
Iterate 10 to 0 using for loop, do the same using while and do while loop.
Write a loop that makes seven calls to console.log to output the following triangle:
# ## ### #### ##### ###### #######
Iterate the array, ['HTML', 'CSS', 'JavaScript'] using a for loop and print out the items.
Use for loop to iterate from 0 to 100 and print only even numbers
Use for loop to iterate from 0 to 100 and print only odd numbers
Use for loop to iterate from 0 to 100 and print and print the sum of all numbers.
Thesumallnumbersis5050.
Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
Thesumofallevensis2550.Andthesumofalloddsis2500.
In contrast to variables array can storemultiple values. Each value in an array has anindex and each index hasa reference in a memory address. Each value can be accessed by using theirindexes. The index of an array starts fromzero and the last element is less by one from the length of the array.
constnumbers=[0,3.14,9.81,37,98.6,100];// set of numbersconsole.log(numbers.length)// => to know the size of the array, which is 6console.log(numbers)// -> [0, 3.14, 9.81, 37, 98.6, 100]console.log(numbers[0])// -> 0console.log(numbers[5])// -> 100letlastIndex=numbers.length-1;console.log(numbers[lastIndex])->100constwebTechs=['HTML','CSS','JavaScript','React','Redux','Node','MongoDB'];// List of web technologiesconsole.log(webTechs)// all the array itemsconsole.log(webTechs.length)// => to know the size of the array, which is 7console.log(webTechs[0])// -> HTMLconsole.log(webTechs[6])// -> MongoDBletlastIndex=webTechs.length-1;console.log(webTechs[lastIndex])->MongoDBconstcountries=['Albania','Bolivia','Canada','Denmark','Ethiopia','Finland','Germany','Hungary','Ireland','Japan','Kenya'];// List of countries;console.log(countries)// -> all countries in arrayconsole.log(countries[0])// -> Albaniaconsole.log(countries[10])// -> KenyaletlastIndex=countries.length-1;console.log(countries[lastIndex])->// KenyaconstshoppingCart=['Milk','Mango','Tomato','Potato','Avocado','Meat','Eggs','Sugar'];// List of food productsconsole.log(shoppingCart)// -> all shoppingCart in arrayconsole.log(shoppingCart[0])// -> Milkconsole.log(shoppingCart[7])// -> SugarletlastIndex=shoppingCart.length-1;console.log(shoppingCart[lastIndex])->// Sugar
- Declare anempty array;
- Declare an array with more than 5 number of items
- Find the length of your array
- Get the first item, the middle item and the last item of the array
- Declare an array calledmixedDataTypes,put different data types and in your array and the array size should be greater than 5
- Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.
- Print the array usingconsole.log()
- Print the number of companies in the array
- Print the first company, middle and last company
- Print out each company
- Change companies to uppercase and print them out
- Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
- Check if a certain company exists in the itCompanies array. If it exist return the company else return a company isnot found.
- Filter out companies which have more than one 'o' without the filter method
- Sort the array usingsort() method
- Reverse the array withoutreverse method
- Reverse the array usingreverse() method
- Slice out the first 3 companies from the array
- Slice out the last 3 companies from the array
- Slice out the middle IT company or companies from the array
- Remove the first IT company from the array
- Remove the middle IT company or companies from the array
- Remove the last IT company from the array
- Remove all IT companies
There are different methods to manipulate an array. These are some of the available methods to deal with arrays:Array,length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshiftArray:To create an array.
constarr=Array();// creates an an empty arrayconsole.log(arr);consteightEmptyValues=Array(8);// it creates eight empty valuesconsole.log(eightEmptyValues);// [empty x 8]
- fill: Fill all the array elements with a static value
constarr=Array();// creates an an empty arrayconsole.log(arr);consteightXvalues=Array(8).fill('X');// it creates eight element valuesconsole.log(eightXvalues);// ['X', 'X','X','X','X','X','X','X']
- concat: To concatenate two arrays.
constfirstList=[1,2,3];constsecondList=[4,5,6];constthirdList=firstList.concat(secondList);console.log(thirdList);// [1,2,3,4,5,6]
- length: To know the size of the array
constnumbers=[1,2,3,4,5];console.log(numbers.length);// -> 5
- indexOf: To check if an item exist in an array. If it exist it returns the index else it returns -1.
constnumbers=[1,2,3,4,5];console.log(numbers.indexOf(5));// -> 4console.log(numbers.indexOf(0));// -> -1console.log(numbers.indexOf(1));// -> 0console.log(numbers.indexOf(6));// -> -1
- lastIndexOf :Give the position of the last item in the array. If it exist it returns the index else it returns -1.
constnumbers=[1,2,3,4,5,3,1,2];console.log(numbers.lastIndexOf(2));// -> 7console.log(numbers.lastIndexOf(0));// -> -1console.log(numbers.lastIndexOf(1));// -> 6console.log(numbers.lastIndexOf(4));// -> 3console.log(numbers.lastIndexOf(6));// -> -1
includes: To check if an item exist in an array. If it exist it returns the true else it returns false.
constnumbers=[1,2,3,4,5];console.log(numbers.includes(5));// -> trueconsole.log(numbers.includes(0));// -> falseconsole.log(numbers.includes(1));// -> trueconsole.log(numbers.includes(6));// -> false
- isArray: To check if the data type is an array
constnumbers=[1,2,3,4,5];console.log(Array.isArray(numbers));// -> trueconstnumber=100;console.log(Array.isArray(number));// -> false
- toString: Converts array to string
constnumbers=[1,2,3,4,5];console.log(numbers.toString());// 1,2,3,4,5constnames=['Asabeneh','Mathias','Elias','Brook'];console.log(names.toString());// Asabeneh,Mathias,Elias,Brook
join:To join the elements of the array, the argument passed in the join method will be joined in the array and return as a string.
constnumbers=[1,2,3,4,5];console.log(numbers.join());// 1,2,3,4,5constnames=['Asabeneh','Mathias','Elias','Brook'];console.log(names.join());// Asabeneh,Mathias,Elias,Brookconsole.log(names.join(''));//AsabenehMathiasEliasBrookconsole.log(names.join(' '));//Asabeneh Mathias Elias Brookconsole.log(names.join(', '));//Asabeneh, Mathias, Elias, Brookconsole.log(names.join(' # '));//Asabeneh # Mathias # Elias # Brook
Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position
constnumbers=[1,2,3,4,5];console.log(numbers.slice()// -> it copies all itemconsole.log(numbers.slice(0)// -> it copies all itemconsole.log(numbers.indexOf(0,numbers.length))// it copies all itemconsole.log(numbers.slice(1,4))// -> [2,3,4] // it doesn't include the ending position
Splice: It takes three parameters:Starting position, number of times to be removed and number items to be added.
constnumbers=[1,2,3,4,5];console.log(numbers.splice()// -> remove all itemsconsole.log(numbers.splice(0,1))// remove the first itemconsole.log(numbers.splice(3,3,6,7,8))// -> [1,2,6,7,8] //it removes two item and replace three items
- push: adding item in the end
constnumbers=[1,2,3,4,5];numbers.push(6);console.log(numbers);// -> [1,2,3,4,5,6]numbers.pop();// -> remove one item from the endconsole.log(numbers);// -> [1,2,3,4,5]
- pop: Removing item in the end
constnumbers=[1,2,3,4,5];numbers.pop();// -> remove one item from the endconsole.log(numbers);// -> [1,2,3,4]
- shift: Removing item in the beginning
constnumbers=[1,2,3,4,5];numbers.shift();// -> remove one item from the beginningconsole.log(numbers);// -> [2,3,4,5]
- unshift: Adding item in the beginning
constnumbers=[1,2,3,4,5];numbers.unshift(0);// -> remove one item from the beginningconsole.log(numbers);// -> [0,1,2,3,4,5]
constshoppingCart=['Milk','Coffee','Tea','Honey'];consttodoList=[{task:'Learn JavaScript',time:'4/3/2019 8:30',completed:true},{task:'Help some in need',time:'4/3/2019 4:00',completed:false},{task:'Do some physical exercises',time:'4/3/2019 6:00',completed:false}]
A function is a block of code designed to perform a certain task.A function is declared by a function key word followed by a name, followed by parentheses (). A parentheses can take a parameter. If a function take a parameter it will be called with argument. A function can also take a default parameter.A function can be declared or created in couple of ways:
- Declaration function
- Expression function
- Anonymous function
- Arrow function
//function without parameterfunctionfunctionName(){// code goes here}functionName()// calling function by its name and with parentheses//function without parameterfunctionaddTwoNumbers(){varnumOne=10;varnumTwo=20;varsum=numOne+numTwo;console.log(sum);}addTwoNumbers();// function has to be called to be executed by it name// function with one parameterfunctionfunctionName(parm1){//code goes her}functionName(parm1);// during calling or invoking one argument neededfunctionareaOfCircle(r){letarea=Math.PI*r*r;returnarea;}console.log(areaOfCircle(10))// should be called with one argumentfunctionsquare(number){returnnumber*number;}console.log(square(10));// function with two parametersfunctionfunctionName(parm1,parm2){//code goes her}functionName(parm1,parm2);// during calling or invoking two arguments needed// Function without parameter doesn't take input, so lets make a parameter with parameterfunctionsumTwoNumbers(numOne,numTwo){varsum=numOne+numTwo;console.log(sum);}sumTwoNumbers(10,20);// calling functions// If a function doesn't return it doesn't store data, so it should returnfunctionsumTwoNumbersAndReturn(numOne,numTwo){varsum=numOne+numTwo;returnsum;}console.log(sumTwoNumbersAndReturn(10,20));functionprintFullName(firstName,lastName){return`${firstName}${lastName}`;}console.log(printFullName('Asabeneh','Yetayeh'));console.log(printFullName('Dean','Phan'));// function with multiple parametersfunctionfunctionName(parm1,parm2,parm3,...){//code goes ther}functionName(parm1,parm2,parm3,...)// during calling or invoking three arguments needed// this function takes array as a parameter and sum up the numbers in the arrayfunctionsumArrayValues(arr){varsum=0;for(vari=0;i<arr.length;i++){sum=sum+numbers[i];}returnsum;}constnumbers=[1,2,3,4,5];console.log(sumArrayValues(numbers));constareaOfCircle=(radius)=>{letarea=Math.PI*radius*radius;returnarea;}console.log(areaOfCircle(10))
//Declaration functionfunctionsquare(n){returnn*n;}console.log(square(2));// -> 4// Function expressionconstsquare=function(n){returnn*n;};console.log(square(2));// -> 4
// Self invoking functions(function(n){returnn*n;})(2);constx=(function(n){returnn*n;})(2);console.log(x)// 4
constsquare=n=>{returnn*n;};console.log(square(2));// -> 4// if we have only one line, it can be written as follows// Explicit returnconstsquare=n=>n*n;// -> 4
Arrow function and regular functions are not exactly the same.
Declare a functionfullName and it print out your full name.
Declare a functionfullName and now it takes firstName, lastName as a parameter and it returns your full - name.
Declare a functionaddNumbers and it takes two two parameters and it returns sum.
An area of a rectangle is calculated as follows:area = length x width. Write a function which calculatesareaOfRectangle.
A perimeter of a rectangle is calculated as follows:perimeter= 2x(length + width). Write a function which calculatesperimeterOfRectangle.
A volume of a rectangular prism is calculated as follows:volume = length x width x height. Write a function which calculatesvolumeOfRectPrism.
Area of a circle is calculated as follows:area = π x r x r. Write a function which calculatesareaOfCircle
Circumference of a circle is calculated as follows:circumference = 2πr. Write a function which calculatescircumOfCircle
Density of a substance is calculated as follows:density= mass/volume. Write a function which calculatesdensity.
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.
Weight of a substance is calculated as follows:weight = mass x gravity. Write a function which calculatesweight.
Temperature in oC can be converted to oF using this formula:oF = (oC x 9/5) + 32. Write a function which convert oC to oFconvertCelciusToFahrenheit.
Body mass index(BMI) is calculated as follows:bmi = weight in Kg / (height x height) in m2. Write a function which calculatesbmi. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person isunderweight, normal, overweight orobese based the information given below.
- The same groups apply to both men and women.
- Underweight: BMI is less than 18.5
- Normal weight: BMI is 18.5 to 24.9
- Overweight: BMI is 25 to 29.9
- Obese: BMI is 30 or more
Write a function calledcheckSeason, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer.
Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method.
console.log(findMax(0,10,5));10;console.log(findMax(0,-10,-2));0;
Linear equation is calculated as follows:ax + b = c. Write a function which calculates value of a linear equation,solveLinEquation.
Quadratic equation is calculated as follows:ax2 + bx + c = 0. Write a function which calculates value or values of a quadratic equation,solveQuadEquation.
Declare a function nameprintArray. It takes array as a parameter and it prints out each value of the array.
Declare a function nameswapValues. This function swaps value of x to y.
swapValues(3,4);// x => 4, y=>3swapValues(4,5);// x = 5, y = 4
Declare a function namereverseArray. It takes array as a parameter and it returns the reverse of the array (don't use method).
console.log(reverseArray([1,2,3,4,5]));[5,4,3,2,1];console.log(reverseArray(['A','B','C']));['C','B','A'];
Declare a function namecapitalizeArray. It takes array as a parameter and it returns the - capitalizedarray.
Declare a function nameaddItem. It takes an item parameter and it returns an array after adding the item
Declare a function nameremoveItem. It takes an index parameter and it returns an array after removing an item
Declare a function namesumOfNumbers. It takes a number parameter and it adds all the numbers in that range.
Declare a function namesumOfOdds. It takes a number parameter and it adds all the odd numbers in that - range.
Declare a function namesumOfEven. It takes a number parameter and it adds all the even numbers in that - range.
Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
evensAndOdds(100);The number of odds are 50.The number of evens are 51.
Write a function which takes any number of arguments and return the sum of the arguments
sum(1,2,3);// -> 6sum(1,2,3,4);// -> 10
Writ a function which generates arandomUserIp.
Write a function which generates arandomMacAddress
Declare a function namerandomHexaNumberGenerator. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
console.log(randomHexaNumberGenerator());'#ee33df'
Declare a function nameuserIdGenerator. When this function is called it generates seven character id. The function return the id.
console.log(userIdGenerator());41XTDbE
Modify question number n . Declare a function nameuserIdGeneratedByUser. 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.
userIdGeneratedByUser()'kcsy2SMFYbbWmeqZXOYh2Rgxf'userIdGeneratedByUser()'1GCSgPLMaBAVQZ26YD7eFwNQKNs7qXaTycArC5yrRupyG00SUbGxOFI7UXSWAyKNdIV0SSUTgAdKwStr'
Write a function namergbColorGenerator and it generates rgb colors.
rgbColorGenerator()rgb(125,244,255)
Write a functionarrayOfHexaColors which return any number of hexadecimal colors in an array.
Write a functionarrayOfRgbColors which return any number of RGB colors in an array.
Write a functionconvertHexaToRgb which converts hexa color to rgb and it returns an rgb color.
Write a functionconvertRgbToHexa which converts rgb to hexa color and it returns an hexa color.
Write a functiongenerateColors which can generate any number of hexa or rgb colors.
generateColors('hexa',3)['#a3e12f','#03ed55','#eb3d2b']generateColors('hexa',1)'#b334ef'generateColors('rgb',3)['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']generateColors('rgb',1)'rgb(33,79, 176)'
Call your functionshuffleArray, it takes an array as a parameter and it returns a shuffled array
Call your functionfactorial, it takes a whole number as a parameter and it return a factorial of the number
Call your functionisEmpty, it takes a parameter and it checks if it is empty or not
Call your functionsum, it takes any number of arguments and it returns the sum.
Write a function calledsumOfArrayItems, 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.
Write a function calledaverage, 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.
Write a function calledmodifyArray 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'.
console.log(modifyArray(['Avocado','Tomato','Potato','Mango','Lemon','Carrot']);// →['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']console.log(modifyArray(['Google','Facebook','Apple','Amazon','Microsoft','IBM']);// →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']console.log(modifyArray(['Google','Facebook','Apple','Amazon']);// →'Not Found'
Write a function calledisPrime, which checks if a number is prime number.
Write a functions which checks if all items are unique in the array.
Write a function which checks if all the items of the array are the same data type.
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.
Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
sevenRandomNumbers()[(1,4,5,7,9,8,0)];
Everything can be an object and objects do have properties and properties have values.Creating an object literal. To create an object literal, we use two curly brackets.An empty object
constperson={};
Now, the person object has firstName, lastName, age, location, skills and getFullName properties. The getFullName is function inside the person object and we call it method. Thethis key word refers to the object itself.Example of object:
constperson={firstName:'Asabeneh',lastName:'Yetayeh',age:100,location:'Helsinki',skills:['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'],getFullName:function(){return`${this.firstName}${this.lastName}`;}};constrectangle={length:20,width:20,getArea:function(){returnthis.length*this.width;},getPerimeter:function(){return2*(this.length+this.width);}};
Getting values from an object:
constperson={firstName:'Asabeneh',lastName:'Yetayeh',age:100,location:'Helsinki',skills:['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js']getFullName:function(){return`${this.firstName}${this.lastName}`}}console.log(person.firstName);console.log(person.lastName);console.log(person.getFullName());// value can be accessedconsole.log(person['age');console.log(person['location']);
Setting a new keys in an object
constperson={firstName:'Asabeneh',lastName:'Yetayeh',age:100,location:'Helsinki',skills:['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js']getFullName:function(){return`${this.firstName}${this.lastName}`}}person.nationality='Ethiopian'person.live='Finland';console.log(person)
Object.assign: To copy an object without modifying the original object
constperson={name:'Asabeneh',age:200,country:'Finland',skills:['HTML','CSS','JS'],address:{street:'Heitamienkatu 16',pobox:2002,city:'Helsinki'},getPersonInfo:function(){return`I am${this.name} and I live in${this.country}. I am${this.age}.`;}};//Object methods: Object.assign, Object.keys, Object.values, Object.entries//hasOwnPropertyconstcopyPerson=Object.assign({},person);console.log(copyPerson);
Object.keys: To get keys of an objet as an array
constkeys=Object.keys(copyPerson);console.log(keys);//['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']constaddress=Object.keys(copyPerson.address);console.log(address);//['street', 'pobox', 'city']
Object.values:To get values of an object as an array
constvalues=Object.values(copyPerson);console.log(values);
Object.entries:To get the keys and values in an array
constentries=Object.entries(copyPerson);console.log(entries);
hasOwnProperty: To check if a specific key or property exist in an object
console.log(copyPerson.hasOwnProperty('name'));console.log(copyPerson.hasOwnProperty('score'));
In JavaScript current time and date is created using JavaScript Date Object.Some of the methods to extract date object values:getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes
constnow=newDate();constyear=now.getFullYear();// return yearconstmonth=now.getMonth()+1;// return month(0 - 11)constdate=now.getDate();// return date (1 - 31)consthours=now.getHours();// return number (0 - 23)constminutes=now.getMinutes();// return number (0 -59)console.log(`${date}/${month}/${year}${hours}:${minutes}`)
Use the new Date() object to getmonth, date, year, hour andminute.
Write a function namedisplayDateTime which display time in this format: 10/03/2019 04:08
displayDateTime()10/03/2019 04:08
Create an empty object called dog
Print the the dog object on the console
Add name, legs, color, age and bark properties for the dog object. The bark property is a method which returnwoof woof
Get name, legs, color, age and bark value from the dog object
Set new properties the dog object: breed, getDogInfo
Create an object literal calledpersonAccount. It hasfirstName, lastName, incomes, expenses properties and it hastotalIncome, totalExpense, accountInfo,addIncome, addExpense andaccountBalance methods. Incomes is a set of incomes and its description and the same for expenses.
Count logged in users,count users having greater than equal to 50 points from the following object.
constusers={Alex:{email:'alex@alex.com',skills:['HTML','CSS','JavaScript'],age:20,isLoggedIn:false,points:30},Asab:{email:'asab@asab.com',skills:['HTML','CSS','JavaScript','React','Redux','Node.js'],age:25,isLoggedIn:false,points:50},Brook:{email:'daniel@daniel.com',skills:['HTML','CSS','JavaScript','React','Redux'],age:30,isLoggedIn:true,points:50},Daniel:{email:'daniel@alex.com',skills:['HTML','CSS','JavaScript','Python'],age:20,isLoggedIn:false,points:40},John:{email:'john@john.com',skills:['HTML','CSS','JavaScript','React','Redux','Node.js'],age:20,isLoggedIn:true,point:50},Thomas:{email:'thomas@thomas.com',skills:['HTML','CSS','JavaScript','React'],age:20,isLoggedIn:false,points:40}};
Set your name in the users object without modifying the original users object
Get all keys or properties of users object
Get all the values of users object
** Develop a small JavaScript library.
JSON stands for JavaScript Object Notation. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text or string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
Example:
{"users":[{"firstName":"Asabeneh","lastName":"Yetayeh","age":250,"email":"asab@asb.com"},{"firstName":"Alex","lastName":"James","age":25,"email":"alex@alex.com"},{"firstName":"Lidiya","lastName":"Tekle","age":28,"email":"lidiya@lidiya.com"}]}
The above JSON example is not much different for a normal object. Then, what is the difference ? The difference is the key of a JSON object should be with double quotes or it should be a string. JavaScript Object and JSON are very similar that we can change JSON to Object and Object to JSON.
Let us see the above example in more detail, it starts with a curly bracket. Inside the curly bracket, there is "users" key which has a value array. Inside the array we have different objects and each objects has keys, each keys has to have double quotes. For instance, we use "firstNaMe" instead of just firstName, however in object we use keys without double quotes. This is the major difference between an object and a JSON. Let's see more examples about JSON.
Example:
{"Alex":{"email":"alex@alex.com","skills":["HTML","CSS","JavaScript"],"age":20,"isLoggedIn":false,"points":30},"Asab":{"email":"asab@asab.com","skills":["HTML","CSS","JavaScript","Redux","MongoDB","Express","React","Node"],"age":25,"isLoggedIn":false,"points":50},"Brook":{"email":"daniel@daniel.com","skills":["HTML","CSS","JavaScript","React","Redux"],"age":30,"isLoggedIn":true,"points":50},"Daniel":{"email":"daniel@alex.com","skills":["HTML","CSS","JavaScript","Python"],"age":20,"isLoggedIn":false,"points":40},"John":{"email":"john@john.com","skills":["HTML","CSS","JavaScript","React","Redux","Node.js"],"age":20,"isLoggedIn":true,"points":50},"Thomas":{"email":"thomas@thomas.com","skills":["HTML","CSS","JavaScript","React"],"age":20,"isLoggedIn":false,"points":40},"Paul":{"email":"paul@paul.com","skills":["HTML","CSS","JavaScript","MongoDB","Express","React","Node"],"age":20,"isLoggedIn":false,"points":40}}
Mostly we fetch JSON data from HTTP response or from a file, but we can store the JSON as a string and we can change to Object for sake of demonstration. In JavaScript the keywordJSON hasparse() andstringify() methods. When we want to change the JSON to an object we parse the JSON usingJSON.parse(). When we want to change the object to JSON we useJSON.stringify().
JSON.parse(json[,reviver])// json or text , the data// reviver is an optional callback function
constusersText=`{"users":[ { "firstName":"Asabeneh", "lastName":"Yetayeh", "age":250, "email":"asab@asb.com" }, { "firstName":"Alex", "lastName":"James", "age":25, "email":"alex@alex.com" }, { "firstName":"Lidiya", "lastName":"Tekle", "age":28, "email":"lidiya@lidiya.com" }]}`constusersObj=JSON.parse(usersText,undefined,4)console.log(usersObj)
To use the reviver function as a formatter, we put the keys we want to format first name and last name value. Let us say, we are interested to format the firstName and lastName of the JSON data .
constusersText=`{"users":[ { "firstName":"Asabeneh", "lastName":"Yetayeh", "age":250, "email":"asab@asb.com" }, { "firstName":"Alex", "lastName":"James", "age":25, "email":"alex@alex.com" }, { "firstName":"Lidiya", "lastName":"Tekle", "age":28, "email":"lidiya@lidiya.com" }]}`constusersObj=JSON.parse(usersText,(key,value)=>{letnewValue=typeofvalue=='string'&&key!='email' ?value.toUpperCase() :valuereturnnewValue})console.log(usersObj)
TheJSON.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.
When we want to change the object to JSON we useJSON.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.
JSON.stringify(obj,replacer,space)// json or text , the data// reviver is an optional callback function
Let us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.
constusers={Alex:{email:'alex@alex.com',skills:['HTML','CSS','JavaScript'],age:20,isLoggedIn:false,points:30},Asab:{email:'asab@asab.com',skills:['HTML','CSS','JavaScript','Redux','MongoDB','Express','React','Node'],age:25,isLoggedIn:false,points:50},Brook:{email:'daniel@daniel.com',skills:['HTML','CSS','JavaScript','React','Redux'],age:30,isLoggedIn:true,points:50},Daniel:{email:'daniel@alex.com',skills:['HTML','CSS','JavaScript','Python'],age:20,isLoggedIn:false,points:40},John:{email:'john@john.com',skills:['HTML','CSS','JavaScript','React','Redux','Node.js'],age:20,isLoggedIn:true,points:50},Thomas:{email:'thomas@thomas.com',skills:['HTML','CSS','JavaScript','React'],age:20,isLoggedIn:false,points:40},Paul:{email:'paul@paul.com',skills:['HTML','CSS','JavaScript','MongoDB','Express','React','Node'],age:20,isLoggedIn:false,points:40}}consttxt=JSON.stringify(users,undefined,4)console.log(txt)// text means JSON- because json is a string form of an object.
{"Alex": {"email":"alex@alex.com","skills": ["HTML","CSS","JavaScript" ],"age": 20,"isLoggedIn": false,"points": 30 },"Asab": {"email":"asab@asab.com","skills": ["HTML","CSS","JavaScript","Redux","MongoDB","Express","React","Node" ],"age": 25,"isLoggedIn": false,"points": 50 },"Brook": {"email":"daniel@daniel.com","skills": ["HTML","CSS","JavaScript","React","Redux" ],"age": 30,"isLoggedIn": true,"points": 50 },"Daniel": {"email":"daniel@alex.com","skills": ["HTML","CSS","JavaScript","Python" ],"age": 20,"isLoggedIn": false,"points": 40 },"John": {"email":"john@john.com","skills": ["HTML","CSS","JavaScript","React","Redux","Node.js" ],"age": 20,"isLoggedIn": true,"points": 50 },"Thomas": {"email":"thomas@thomas.com","skills": ["HTML","CSS","JavaScript","React" ],"age": 20,"isLoggedIn": false,"points": 40 },"Paul": {"email":"paul@paul.com","skills": ["HTML","CSS","JavaScript","MongoDB","Express","React","Node" ],"age": 20,"isLoggedIn": false,"points": 40 }}
Now, lets use the replacer as a filter. The user object has long list of keys but we are interested only in few of them. We put the keys we want to keep in array as show in the example and use it the place of the replacer.
constuser={firstName:'Asabeneh',lastName:'Yetayeh',country:'Finland',city:'Helsinki',email:'alex@alex.com',skills:['HTML','CSS','JavaScript','React','Pyhton'],age:250,isLoggedIn:false,points:30}consttxt=JSON.stringify(user,['firstName','lastName','country','city','age'],4)console.log(txt)
{"firstName":"Asabeneh","lastName":"Yetayeh","country":"Finland","city":"Helsinki","age": 250}
constskills=['HTML','CSS','JS','React','Node','Python']letage=250;letisMarried=trueconststudent={firstName:'Asabeneh',lastName:'Yetayehe',age:250,isMarried:true,skills:['HTML','CSS','JS','React','Node','Python',]}consttxt=`{ "Alex": { "email": "alex@alex.com", "skills": [ "HTML", "CSS", "JavaScript" ], "age": 20, "isLoggedIn": false, "points": 30 }, "Asab": { "email": "asab@asab.com", "skills": [ "HTML", "CSS", "JavaScript", "Redux", "MongoDB", "Express", "React", "Node" ], "age": 25, "isLoggedIn": false, "points": 50 }, "Brook": { "email": "daniel@daniel.com", "skills": [ "HTML", "CSS", "JavaScript", "React", "Redux" ], "age": 30, "isLoggedIn": true, "points": 50 }, "Daniel": { "email": "daniel@alex.com", "skills": [ "HTML", "CSS", "JavaScript", "Python" ], "age": 20, "isLoggedIn": false, "points": 40 }, "John": { "email": "john@john.com", "skills": [ "HTML", "CSS", "JavaScript", "React", "Redux", "Node.js" ], "age": 20, "isLoggedIn": true, "points": 50 }, "Thomas": { "email": "thomas@thomas.com", "skills": [ "HTML", "CSS", "JavaScript", "React" ], "age": 20, "isLoggedIn": false, "points": 40 }, "Paul": { "email": "paul@paul.com", "skills": [ "HTML", "CSS", "JavaScript", "MongoDB", "Express", "React", "Node" ], "age": 20, "isLoggedIn": false, "points": 40 }}`
- Change skills array to JSON using JSON.stringify()
- Stringify the age variable
- Stringify the isMarried variable
- Stringify the student object
- Stringify the students object with only firstName, lastName and skills properties
Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.
A callback is a function which can be passed as parameter to other function. See the example below.
// a callback function, the function could be any nameconstcallback=(n)=>{returnn**2}// function take other function as a callbackfunctioncube(callback,n){returncallback(n)*n}console.log(cube(callback,3))
Higher order functions return function as a value
// Higher order function returning an other functionconsthigherOrder=n=>{constdoSomething=m=>{constdoWhatEver=t=>{return2*n+3*m+t}returndoWhatEver}returndoSomething}console.log(higherOrder(2)(3)(10))
Let us see were we use call back functions.For instance theforEach method uses call back.
constnumbers=[1,2,3,4]constsumArray=arr=>{letsum=0constcallBack=function(element){sum+=element}numbers.forEach(callback)returnsum}console.log(sumArray(numbers))
15
The above example can be simplified as follows:
constnumbers=[1,2,3,4]constsumArray=arr=>{letsum=0numbers.forEach(function(element){sum+=element})returnsum}console.log(sumArray(numbers))
15
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.
- setInterval
- setTimeout
In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.
// syntaxfunctioncallBack(){// code goes here}setInterval(callback,duration)
functionsayHello(){console.log('Hello')}setInterval(sayHello,2000)// it prints hello in every 2 seconds
In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
// syntaxfunctioncallback(){// code goes here}setTimeout(callback,duration)// duration in milliseconds
functionsayHello(){console.log('Hello')}setTimeout(sayHello,2000)// it prints hello after it waits for 2 seconds.
- Parse thetxt JSON to object.
- Find the the user who has many skills from the variable stored intxt.
- forEach: Iterate an array elements and use for array. It takes a callback function with elements and index parameter.
arr.forEach(function(element,index){console.log(index,element)})// The above code can be written using arrow functionarr.forEach((element,index)=>{console.log(index,element)})// The above code can be written using arrow function and explicit returnarr.forEach((element,index)=>console.log(index,element));
- 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.
constmodifiedArray=arr.map(function(element,index){returnelement});/*Arrow function and explicit returnconst modifiedArray = arr.map((element,index) => element);*///Exampleconstnumbers=[1,2,3,4,5];constnumbersSquare=numbers.map((num)=>num*num)console.log(numbersSquare)// [1,4,9,16,25]constnames=['Asabeneh','Mathias','Elias','Brook'];constnamesToUpperCase=names.map((name)=>name.toUpperCase());console.log(namesToUpperCase)//['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']constcountries=['Albania','Bolivia','Canada','Denmark','Ethiopia','Finland','Germany','Hungary','Ireland','Japan','Kenya'];constcountriesToUpperCase=countries.map(function(country){returncountry.toUpperCase();});console.log(countriesToUpperCase)// ['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']/*// Arrow functionconst countriesToUpperCase = countries.map((country) => { return country.toUpperCase();})//Explicit return arrow functionconst countriesToUpperCase = countries.map(country => country.toUpperCase());*/
- Filter: Filter out items which full fill filtering conditions
// Filter countries containing landconstcountriesContainingLand=countries.filter(country=>country.includes('land'));console.log(countriesContainingLand)//['Finland', 'Ireland']constcountriesEndByia=countries.filter(country=>country.includes('ia'));console.log(countriesEndByia)//['Albania', 'Bolivia','Ethiopia']constcountriesHaveFiveLetters=countries.filter(country=>country.length===5);console.log(countriesHaveFiveLetters)// ['Japan', 'Kenya']constscores=[{name:'Asabeneh',score:95},{name:'Mathias',score:80},{name:'Elias',score:50},{name:'Martha',score:85},{name:'John',score:100}];constscoresGreaterEight=scores.filter((score)=>score.score>80);console.log(scoresGreaterEight)//[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}]
- reduce: Reduce takes a callback function. The call back function takes accumulator and current value as a parameter and returns a single value:
constnumbers=[1,2,3,4,5];constsum=numbers.reduce((accum,curr)=>accum+curr);console.log(sum);// 15
- every: Check if all the elements are similar in one aspect. It returns boolean
constnames=['Asabeneh','Mathias','Elias','Brook'];constbools=[true,true,true,true];constresult=bools.every((b)=>{returnb===true;});console.log(result)//trueconstcheckType=names.every((name)=>typeofname==='string');console.log(checkDataTypes)// true;
- some: Check if some of the elements are similar in one aspect. It returns boolean
constnames=['Asabeneh','Mathias','Elias','Brook'];constbools=[true,true,true,true];constresult=bools.some((b)=>{returnb===true;});console.log(result)//trueconstcheckType=names.some((name)=>typeofname==='number');console.log(checkDataTypes)// false
- find: Return the first element which satisfies the condition
constnames=['Asabeneh','Mathias','Elias','Brook'];constages=[24,22,25,32,35,18];constresult=names.find(name=>name.length>7);console.log(result)// Asabenehconstage=ages.find((age)=>age<20);console.log(age)// 18
- findIndex: Return the position of the first element which satisfies the condition
constnames=['Asabeneh','Mathias','Elias','Brook'];constages=[24,22,25,32,35,18];constresult=names.findIndex(name=>name.length>7);console.log(result)// 0constage=ages.findIndex((age)=>age<20);console.log(age)// 5
sort: The sort methods arranges the array elements either ascending or descending order. By default, thesort() 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.
Sorting string values
constproducts=['Milk','Coffee','Sugar','Honey','Apple','Carrot'];console.log(products.sort())// ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar']//Now the original products array is also sorted
- Sorting Numeric values
As 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.
constnumbers=[9.81,3.14,100,37]// Using sort method to sort number items provide a wrong result. see belowconsole.log(numbers.sort())//[100, 3.14, 37, 9.81]numbers.sort(function(a,b){returna-b;})console.log(numbers)// [3.14, 9.81, 37, 100]numbers.sort(function(a,b){returnb-a;});console.log(numbers)//[100, 37, 9.81, 3.14]
- Sorting Object Arrays
When ever we sort objects in an array. We use the object key to compare. Lets see the example below.
objArr.sort(function(a,b){if(a.key<b.key)return-1;if(a.key>b.key)return1;return0;});// orobjArr.sort(function(a,b){if(a['key']<b['key'])return-1;if(a['key']>b['key'])return1;return0;});constusers=[{name:'Asabeneh',age:150},{name:'Brook',age:50},{name:'Eyo',age:100},{name:'Elias',age:22}];users.sort((a,b)=>{if(a.age<b.age)return-1;if(a.age>b.age)return1;return0;});console.log(users);// sorted ascending//[{…}, {…}, {…}, {…}]
constcountries=['Estonia','Finland','Sweden','Denmark','Norway','IceLand'];constnames=['Asabeneh','Mathias','Elias','Brook'];constnumbers=[1,2,3,4,5,6,7,8,9,10]
- Explain the difference betweenforEach, map, filter, and reduce.
- Define a call function before you them in forEach, map, filter or reduce.
- UseforEach to console.log each country in the countries array.
- UseforEach to console.log each name in the names array.
- UseforEach to console.log each number in the numbers array.
- Usemap to create a new array by changing each country to uppercase in the countries array;
- Usemap to create a new array by changing each number to square in the numbers array
- Usemap to change to each name to uppercase in the names array
- Usefilter to filter out countries containingland.
- Usefilter to filter out countries having six character.
- Usefilter to filter out countries containing six letters and more in the country array.
- Usefilter to filter out country start with 'E';
- Chain two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
- Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
- Usereduce to sum all the numbers in the numbers array.
- Usereduce to concatenate all the countries and to produce this sentence:Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries
- Explain the difference betweensome andevery
- Usesome to check if some names' length greater than seven in names array
- Useevery to check if all the countries contain the word land
- Explain the difference betweenfind andfindIndex.
- Usefind to find the first country containing only six letters in the countries array
- UsefindIndex to find the position of the first country containing only six letters in the countries array
- UsefindIndex to find the position ofNorway if it doesn't exist in the array you will get -1.
- UsefindIndex to find the position ofRussia if it doesn't exist in the array you will get -1.
- Declare a function calledcategorizeCountries 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')).
- 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.
- Declare agetFirstTenCountries function and return an array of ten countries. Use different functional programming to work on the countries.js array
- Declare agetLastTenCountries function which which returns the last ten countries in the countries array.
- Find out whichletter is used manytimes as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
- Use the countries information, in the data folder. Sort countries by name, by capital, by population
- Sort out the ten most spoken languages by location.
- Sort out the ten most populated countries.
Destructuring is a way to unpack arrays, and objects and assigning to a distinct variable.
constnumbers=[1,2,3];let[numOne,numTwo,numThree]=numbers;console.log(numOne,numTwo,numThree)// 1,2,3constnames=['Asabeneh','Brook','David','John']let[firstPerson,secondPerson,ThirdPerson,fourthPerson]=names;console.log(firstName,secondPerson,thirdPerson,fourthPerson)//Asabeneh, Brook, David, JohnconstscientificConstants=[2.72,3.14,9.81,37,100];let[e,pi,gravity,bodyTemp,boilingTemp]=scientificConstantsconsole.log(e,pi,gravity,bodyTemp,boilingTemp)//2.72, 3.14, 9.81, 37, 100
If 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
constnumbers=[1,2,3];let[numOne,,,numThree]=numbers;//2 is omittedconsole.log(numOne,,numThree)// 1,2,3constnames=['Asabeneh','Brook','David','John']let[,secondPerson,,fourthPerson]=name;// first and third person is omittedconsole.log(secondPerson,fourthPerson)//Brook, John
We can use default value in case the value of array for that index is undefined:
constnames=[undefined,'Brook','David'];let[firstPerson='Asabeneh',secondPerson,thirdPerson,fourthPerson='John']=names;console.log(firstPerson,secondPerson,thirdPerson,fourthPerson)// Asabeneh Brook David John
When 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.
constrectangle={width:20,height:10,area:200}let{width, height, area, perimeter}=rectangle;console.log(width,height,area,perimeter)//20 10 200 undefined
constrectangle={width:20,height:10,area:200}let{width:w,heigh:h,area:a,perimeter:p}=rectangle;console.log(w,h,a,p)//20 10 200 undefined
If 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.
constrectangle={width:20,height:10,area:200}let{width, heigh, area, perimeter=60}=rectangle;console.log(width,height,area,perimeter)//20 10 200 60//Lets modify the object:width to 30 and perimeter to 80constrectangle={width:30,height:10,area:200,perimeter:80}let{width, heigh, area, perimeter=60}=rectangle;console.log(width,height,area,perimeter)//20 10 200 80
Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.
// Without destructuringconstrect={width:20,height:10}constcalculatePerimeter=(rectangle)=>{return2*(rectangle.width+rectangle.height)}console.log(calculatePerimeter(rect))// 60//with destructuringconstcalculatePerimeter=({width, height})=>{return2*(width+height)}console.log(calculatePerimeter(rect))// 60//Another Exampleconstperson={firstName:'Asabeneh',lastName:'Yetayeh',age:200,country:'Finland',job:'Instructor and Developer',skills:['HTML','CSS','JavaScript','React','Redux','Node','MongoDB','Python','D3.js'],languages:['Amharic','English','Suomi(Finnish)']};// Lets create a function which give information about the person object without destructuringconstgetPersonInfo=obj=>{constskills=obj.skills;constformattedSkills=skills.slice(0,-1).join(', ');constlanguages=obj.languages;constformattedLanguages=languages.slice(0,-1).join(', ');return`${obj.firstName}${obj.lastName} lives in${obj.country}. He is${obj.age} years old. He is an${obj.job}. He teaches${formattedSkills} and${skills[skills.length-1]}. He speaks${formattedLanguages} and a little bit of${languages[2]}.`;};console.log(getPersonInfo(person));// Lets create a function which give information about the person object with destructuringconstgetPersonInfo=({ firstName, lastName, age, country, job, skills, languages})=>{constformattedSkills=skills.slice(0,-1).join(', ');constformattedLanguages=languages.slice(0,-1).join(', ');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]}.`;};console.log(getPersonInfo(person))/*Asabeneh 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)*/
constconstants=[2.72,3.14,9.81,37,100]constcountries=['Finland','Estonia','Sweden','Denmark','Norway']constrectangle={width:20,height:10,area:200,perimeter:60}
- Assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.
- Assign the elements of countries array to fin, est, sw, den, nor
- Destructure the rectangle object by its properties or keys.
Set is a collection of unique elements. Lets see how to create a set
constcompanies=newSet()
console.log(companies.size)// 0companies.add('Google')// add element to the setcompanies.add('Facebook')companies.add('Amazon')companies.add('Oracle')companies.add('Microsoft')console.log(companies.size)// 5 elements in the set
console.log(companies.delete('Google'))console.log(companies.size)// 4 elements left in the set
console.log(companies.has('Google'))// falseconsole.log(companies.has('Facebook'))// true
It removes all the elements
companies.clear()
See the example below to learn how to use set.
constlanguages=['English','Finnish','English','French','Spanish','English','French']constlangSet=newSet(languages)console.log(langSet)console.log(langSet.size)constcounts=[]constcount={}for(constloflangSet){constfilteredLang=languages.filter(lng=>lng===l)console.log(filteredLang)counts.push({lang:l,count:filteredLang.length})}console.log(counts)
Set is a collection a collection of elements. Set can only contains unique elements.Lets see how to create a set
constcompanies=newSet()console.log(companies)
{}
constlanguages=['English','Finnish','English','French','Spanish','English','French']constsetOfLangauges=newSet(languages)console.log(setOfLangauges)
Set(4) {"English","Finnish","French","Spanish"}
Set is an iterable object and we can iterate through each elements.
constlanguages=['English','Finnish','English','French','Spanish','English','French']constsetOfLangauges=newSet(languages)for(constlanguageofsetOfLangauges){console.log(language)}
English Finnish French Spanish
constcompanies=newSet()// creating an empty setconsole.log(companies.size)// 0companies.add('Google')// add element to the setcompanies.add('Facebook')companies.add('Amazon')companies.add('Oracle')companies.add('Microsoft')console.log(companies.size)// 5 elements in the setconsole.log(companies)
Set(5) {"Google","Facebook","Amazon","Oracle","Microsoft"}
We can also use loop to add element to a set.
constcompanies=['Google','Facebook','Amazon','Oracle','Microsoft']setOfCompanies=newSet()for(constcompanyofcompanies){setOfCompanies.add(company)}
Set(5) {"Google","Facebook","Amazon","Oracle","Microsoft"}
We can delete an element from a set using a delete method.
console.log(companies.delete('Google'))console.log(companies.size)// 4 elements left in the set
The has method can help to know if a certain element exists in a set.
console.log(companies.has('Apple'))// falseconsole.log(companies.has('Facebook'))// true
It removes all the elements from a set.
companies.clear()console.log(companies)
{}
See the example below to learn how to use set.
constlanguages=['English','Finnish','English','French','Spanish','English','French']constlangSet=newSet(languages)console.log(langSet)// Set(4) {"English", "Finnish", "French", "Spanish"}console.log(langSet.size)// 4constcounts=[]constcount={}for(constloflangSet){constfilteredLang=languages.filter(lng=>lng===l)console.log(filteredLang)// ["English", "English", "English"]counts.push({lang:l,count:filteredLang.length})}console.log(counts)
[{lang:'English',count:3},{lang:'Finnish',count:1},{lang:'French',count:2},{lang:'Spanish',count:1}]
Other use case of set. For instance to count unique item in an array.
constnumbers=[5,3,2,5,5,9,4,5]constsetOfNumbers=newSet(numbers)console.log(setOfNumbers)
Set(5) {5, 3, 2, 9, 4}
To 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)
leta=[1,2,3,4,5]letb=[3,4,5,6]letc=[...a, ...b]letA=newSet(a)letB=newSet(b)letC=newSet(c)console.log(C)
Set(6) {1, 2, 3, 4, 5,6}
To find an intersection of two sets can be achieved using filter. Lets find the union of set A and set B (A ∩ B)
leta=[1,2,3,4,5]letb=[3,4,5,6]letA=newSet(a)letB=newSet(b)letc=a.filter(num=>B.has(num))letC=newSet(c)console.log(C)
Set(3) {3, 4, 5}
To find an the difference between two sets can be achieved using filter. Lets find the different of set A and set B (A \ B)
leta=[1,2,3,4,5]letb=[3,4,5,6]letA=newSet(a)letB=newSet(b)letc=a.filter(num=>!B.has(num))letC=newSet(c)console.log(C)
Set(2) {1, 2}
constmap=newMap()console.log(map)
Map(0) {}
countries=[['Finland','Helsinki'],['Sweden','Stockholm'],['Norway','Oslo']]constmap=newMap(countries)console.log(map)console.log(map.size)
Map(3) {"Finland" =>"Helsinki","Sweden" =>"Stockholm","Norway" =>"Oslo"}3
constcountriesMap=newMap()console.log(countriesMap.size)// 0countriesMap.set('Finland','Helsinki')countriesMap.set('Sweden','Stockholm')countriesMap.set('Norway','Oslo')console.log(countriesMap)console.log(countriesMap.size)
Map(3) {"Finland" =>"Helsinki","Sweden" =>"Stockholm","Norway" =>"Oslo"}3
console.log(countriesMap.get('Finland'))
Helsinki
Check if a key exist in a map usinghas method. It returnstrue orfalse.
console.log(countriesMap.has('Finland'))
true
Getting all values from map using loop
for(constcountryofcountriesMap){console.log(country)}
(2) ["Finland","Helsinki"](2) ["Sweden","Stockholm"](2) ["Norway","Oslo"]
for (const [country, city] of countriesMap){console.log(country, city)}
Finland HelsinkiSweden StockholmNorway Oslo
consta={4,5,8,9}constb={3,4,5,7}const countries=['Finland','Sweden','Norway']
- create an empty set
- Create a set containing 0 to 10 using loop
- Remove an element from a set
- Clear a set
- Create a set of 5 string elements from array
- Create a map of countries and number of characters of a country
- Find a union b
- Find a intersection b
- Find a with b
How many languages are there in the countries object file.
*** Use the countries data to find the 10 most spoken languages:
// Your output should look like thisconsole.log(mostSpokenLanguages(countries,10))[{'English':91},{'French':45},{'Arabic':25},{'Spanish':24},{'Russian':9},{'Portuguese':9},{'Dutch':8},{'German':7},{'Chinese':5},{'Swahili':4},{'Serbian':4}]// Your output should look like thisconsole.log(mostSpokenLanguages(countries,3))
[{'English':91},{'French':45},{'Arabic':25}]````
HTML 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.
<!DOCTYPE html><html><head><title>Document Object Model/title></head><body><h1class='title'id='first-title'>First Title</h1><h1class='title'id='second-title'>Second Title</h1><h1class='title'id='third-title'>Third Title</h1><h1></h1></body></html>
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.
constallTitles=document.getElementsByTagName('h1');console.log(allTitles)//HTMCollectionsconsole.log(allTitles.length)// 4for(leti=0;i<allTitles.length;i++){console.log(allTitles[i])// prints each elements in the HTMLCollection}
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
constallTitles=document.getElementsByClassName('title');console.log(allTitles)//HTMCollectionsconsole.log(allTitles.length)// 4for(leti=0;i<allTitles.length;i++){console.log(allTitles[i])// prints each elements in the HTMLCollection}
getElementsById() targets a single HTML element. We pass the id without # as an argument.
letfirstTitle=document.getElementById('first-title');console.log(firstTitle)// <h1>First Title</h1>
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.
letfirstTitle=document.querySelect('h1');// select the first available h2 elementletfirstTitle=document.querySelector('#first-title');// select id with first-titleletfirstTitle=document.querySelector('.title');// select the first available h2 element with class title
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 usefor loop orforEach to loop through each nodeList elements.
constallTitles=document.querySelectAll('h1');console.log(allTitles.length)// 4for(leti=0;i<allTitles.length;i++){console.log(allTitles[i]);}allTitles.forEach(title=>console.log(title))constallTitles=document.querySelectorAll('.title');// the same goes for selecting using class
An 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.
ThesetAttribute() method set any html attribute. It takes two parameters the type of the attribute and the name of the attribute.Let's add class and id attribute for the fourth title.
consttitles=document.querySelectorAll('h1');titles[3].setAttribute('class','title');titles[3].setAttribute('id','fourth-title');
Some attributes are DOM object property and they can be set directly. For instance id and class
//another way to setting an attributetitles[3].className='title';titles[3].id='fourth-title';
The class list method is a good method to append additional class. It doesn't override the original class if a class exists
//another way to setting an attribute: append the class, doesn't over ridetitles[3].classList.add('title','header-title')
consttitles=document.querySelectorAll('h1');titles[3].textContent='Fourth Title';
Lets add some style to our titles. If the element has even index we give it green color else red.
consttitles=document.querySelectorAll('h1');titles.forEach((title,i)=>{title.fontSize='24px';// all titles will have 24px font sizeif(i%2===0){title.style.color='green';}else{title.style.color='red';}})
lettitle=document.createElement('h1');letfirstTitle=document.getElementById('first-title');
letfirstTitle=document.getElementById('first-title');lettitlefor(leti=0;i<3;i++){title=document.createElement('h1');title.className='title';title.style.fontSize='24px';}
// creating multiple elements and appending to parent elementlettitle;for(leti=0;i<3;i++){title=document.createElement('h1');title.className='title';title.style.fontSize='24px';document.body.appendChild(title);}
Common HTML events:onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.We can add event listener method to any DOM object. Use useaddEventListener() method to listen different event types on HTML elements.The following is an example of click type event.
constbutton=document.querySelector('button');button.addEventListener('click',e=>{console.log(e.target);});
We usually fill forms and forms accept data. Form fields are created using input HTML element.
<inputtype ='text'placeholder = 'Mass in Kilogram'/><inputtype = 'text'placeholder = 'Height in meters'/><button>Calculate BMI</button>
constmass=document.querySelector('#mass');constheight=document.querySelector('#height');constbutton=document.querySelector('button');letbmi;button.addEventListen('click',()=>{bmi=mass.value*height.value;});console.log(bmi)
<!-- index.html --><!DOCTYPE html><html><head><title>JavaScript for Everyone:DOM</title></head><body><p>First Paragraph</p><p>Second Paragraph</p><p>Third Paragraph</p><p></p></body></html>
- Create an index.html file and put four p elements as above: Get the first paragraph by usingdocument.querySelector(tagname) and tag name
- Get get each of the the paragraph usingdocument.querySelector('#id') and by their id
- Get all the p as nodeList usingdocument.querySelectorAll(tagname) and by their tag name
- Loop through the nodeList and get the text content of each paragraph
- Set a text content to paragraph the fourth paragraph,Fourth Paragraph
- Set id and class attribute for all the paragraphs using different attribute setting methods
- Change stye of each paragraph using JavaScript(eg. color, background, border, font-size, font-family)
- 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
- Remove all the paragraph and create them using JavaScript
- Set text content, id and class to each paragraph
- 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.
- Use the rgb color generator function or hexaColor generator to create 10 divs with random background colors
- 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.
- BMI calculator
- Hexadecimal or RGB color Generator
- World Countries List
JavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
Once we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation.
In the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code.
To define a class in JavaScript we need the keywordclass , the name of a class inCamelCase and block code(two curly brackets). Let us create a class name Person.
// syntaxclass ClassName { // code goes here}
Example:
classPerson{// code goes here}
We have created an Person class but it does not have any thing inside.
Instantiation class means creating an object from a class. We need the keywordnew and we call the name of the class after the word new.
Let us create a dog object from our Person class.
classPerson{// code goes here}constperson=newPerson()console.log(person)
Person {}
As you can see, we have created a person object. Since the class did not have any properties yet the object is also empty.
Let use the class constructor to pass different properties for the class.
The constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use thethis keyword to attach the constructor parameters with the class.
The following Person class constructor has firstName and lastName property. These properties are attached to the Person class usingthis keyword.This refers to the class itself.
classPerson{constructor(firstName,lastName){console.log(this)// Check the output from herethis.firstName=firstNamethis.lastName=lastName}}constperson=newPerson()console.log(person)
Person {firstName: undefined, lastName}
All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.
classPerson{constructor(firstName,lastName){this.firstName=firstNamethis.lastName=lastName}}constperson1=newPerson('Asabeneh','Yetayeh')console.log(person1)
Person {firstName:"Asabeneh", lastName:"Yetayeh"}
As we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class.
classPerson{constructor(firstName,lastName){console.log(this)// Check the output from herethis.firstName=firstNamethis.lastName=lastName}}constperson1=newPerson('Asabeneh','Yetayeh')constperson2=newPerson('Lidiya','Tekle')constperson3=newPerson('Abraham','Yetayeh')console.log(person1)console.log(person2)console.log(person3)
Person {firstName:"Asabeneh", lastName:"Yetayeh"}Person {firstName:"Lidiya", lastName:"Tekle"}Person {firstName:"Abraham", lastName:"Yetayeh"}
Using the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class.
classPerson{constructor(firstName,lastName,age,country,city){console.log(this)// Check the output from herethis.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=city}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')console.log(person1)
Person {firstName:"Asabeneh", lastName:"Yetayeh", age: 250, country:"Finland", city:"Helsinki"}
The constructor function properties may have a default value like other regular functions.
classPerson{constructor(firstName='Asabeneh',lastName='Yetayeh',age=250,country='Finland',city='Helsinki'){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=city}}constperson1=newPerson()// it will take the default valuesconstperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')console.log(person1)console.log(person2)
Person {firstName:"Asabeneh", lastName:"Yetayeh", age: 250, country:"Finland", city:"Helsinki"}Person {firstName:"Lidiya", lastName:"Tekle", age: 28, country:"Finland", city:"Espoo"}
The constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=city}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')constperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')console.log(person1.getFullName())console.log(person2.getFullName())
Asabeneh Yetayehtest.js:19 Lidiya Tekle
When we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time.
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=citythis.score=0this.skills=[]}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')constperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')console.log(person1.score)console.log(person2.score)console.log(person1.skills)console.log(person2.skills)
00[][]
A method could be regular method or a getter or a setter. Let us see, getter and setter.
The get method allow us to access value from the object. We write a get method using keywordget followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=citythis.score=0this.skills=[]}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}getgetscore(){returnthis.score}getgetSkills(){returnthis.skills}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')constperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')console.log(person1.getScore)// We do not need parenthesis to call a getter methodconsole.log(person2.getScore)console.log(person1.getSkills)console.log(person2.getSkills)
00[][]
The setter method allow us to modify the value of certain properties. We write a setter method using keywordset followed by a function. See the example bellow.
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=citythis.score=0this.skills=[]}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}getgetScore(){returnthis.score}getgetSkills(){returnthis.skills}setsetScore(score){this.score+=score}setsetSkill(skill){this.skills.push(skill)}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')constperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')person1.setScore=1person1.setSkill='HTML'person1.setSkill='CSS'person1.setSkill='JavaScript'person2.setScore=1person2.setSkill='Planning'person2.setSkill='Managing'person2.setSkill='Organizing'console.log(person1.score)console.log(person2.score)console.log(person1.skills)console.log(person2.skills)
11["HTML","CSS","JavaScript"]["Planning","Managing","Organizing"]
Do not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class.
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=citythis.score=0this.skills=[]}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}getgetScore(){returnthis.score}getgetSkills(){returnthis.skills}setsetScore(score){this.score+=score}setsetSkill(skill){this.skills.push(skill)}getPersonInfo(){letfullName=this.getFullName()letskills=this.skills.length>0&&this.skills.slice(0,this.skills.length-1).join(', ')+` and${this.skills[this.skills.length-1]}`letformattedSkills=skills ?`He knows${skills}` :''letinfo=`${fullName} is${this.age}. He lives${this.city},${this.country}.${formattedSkills}`returninfo}}constperson1=newPerson('Asabeneh','Yetayeh',250,'Finland','Helsinki')constperson2=newPerson('Lidiya','Tekle',28,'Finland','Espoo')constperson3=newPerson('John','Doe',50,'Mars','Mars city')person1.setScore=1person1.setSkill='HTML'person1.setSkill='CSS'person1.setSkill='JavaScript'person2.setScore=1person2.setSkill='Planning'person2.setSkill='Managing'person2.setSkill='Organizing'console.log(person1.getScore)console.log(person2.getScore)console.log(person1.getSkills)console.log(person2.getSkills)console.log(person3.getSkills)console.log(person1.getPersonInfo())console.log(person2.getPersonInfo())console.log(person3.getPersonInfo())
11["HTML","CSS","JavaScript"]["Planning","Managing","Organizing"][]Asabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScriptLidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and OrganizingJohn Doe is 50. He lives Mars city, Mars.
The static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method isDate.now(). Thenow method is called directly from the class.
classPerson{constructor(firstName,lastName,age,country,city){this.firstName=firstNamethis.lastName=lastNamethis.age=agethis.country=countrythis.city=citythis.score=0this.skills=[]}getFullName(){constfullName=this.firstName+' '+this.lastNamereturnfullName}getgetScore(){returnthis.score}getgetSkills(){returnthis.skills}setsetScore(score){this.score+=score}setsetSkill(skill){this.skills.push(skill)}getPersonInfo(){letfullName=this.getFullName()letskills=this.skills.length>0&&this.skills.slice(0,this.skills.length-1).join(', ')+` and${this.skills[this.skills.length-1]}`letformattedSkills=skills ?`He knows${skills}` :''letinfo=`${fullName} is${this.age}. He lives${this.city},${this.country}.${formattedSkills}`returninfo}staticfavoriteSkill(){constskills=['HTML','CSS','JS','React','Python','Node']constindex=Math.floor(Math.random()*skills.length)returnskills[index]}staticshowDateTime(){letnow=newDate()letyear=now.getFullYear()letmonth=now.getMonth()+1letdate=now.getDate()lethours=now.getHours()letminutes=now.getMinutes()if(hours<10){hours='0'+hours}if(minutes<10){minutes='0'+minutes}letdateMonthYear=date+'.'+month+'.'+yearlettime=hours+':'+minutesletfullTime=dateMonthYear+' '+timereturnfullTime}}console.log(Person.favoriteSkill())console.log(Person.showDateTime())
Node15.1.2020 23:56
The static methods are methods which can be used as utility functions.
Using inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc.
// syntaxclassChildClassNameextends{// code goes here}
Let us create a Student child class from Person parent class.
classStudentextendsPerson{saySomething(){console.log('I am a child of the person class')}}consts1=newStudent('Asabeneh','Yetayeh','Finland',250,'Helsinki')console.log(s1)console.log(s1.saySomething())console.log(s1.getFullName())console.log(s1.getPersonInfo())
Student {firstName:"Asabeneh", lastName:"Yetayeh", age:"Finland", country: 250, city:"Helsinki", …}I am a child of the person classAsabeneh YetayehStudent {firstName:"Asabeneh", lastName:"Yetayeh", age:"Finland", country: 250, city:"Helsinki", …}Asabeneh Yetayeh is Finland. He lives Helsinki, 250.
As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
classStudentextendsPerson{constructor(firstName,lastName,age,country,city,gender){super(firstName,lastName,age,country,city)this.gender=gender}saySomething(){console.log('I am a child of the person class')}getPersonInfo(){letfullName=this.getFullName()letskills=this.skills.length>0&&this.skills.slice(0,this.skills.length-1).join(', ')+` and${this.skills[this.skills.length-1]}`letformattedSkills=skills ?`He knows${skills}` :''letpronoun=this.gender=='Male' ?'He' :'She'letinfo=`${fullName} is${this.age}.${pronoun} lives in${this.city},${this.country}.${formattedSkills}`returninfo}}consts1=newStudent('Asabeneh','Yetayeh',250,'Finland','Helsinki','Male')consts2=newStudent('Lidiya','Tekle',28,'Finland','Helsinki','Female')s1.setScore=1s1.setSkill='HTML's1.setSkill='CSS's1.setSkill='JavaScript's2.setScore=1s2.setSkill='Planning's2.setSkill='Managing's2.setSkill='Organizing'console.log(s1)console.log(s1.saySomething())console.log(s1.getFullName())console.log(s1.getPersonInfo())console.log(s2.saySomething())console.log(s2.getFullName())console.log(s2.getPersonInfo())
Student {firstName:"Asabeneh", lastName:"Yetayeh", age: 250, country:"Finland", city:"Helsinki", …}Student {firstName:"Lidiya", lastName:"Tekle", age: 28, country:"Finland", city:"Helsinki", …}I am a child of the person classAsabeneh YetayehStudent {firstName:"Asabeneh", lastName:"Yetayeh", age: 250, country:"Finland", city:"Helsinki", …}Asabeneh Yetayeh is 250. He livesin Helsinki, Finland. He knows HTML, CSS and JavaScriptI am a child of the person classLidiya TekleStudent {firstName:"Lidiya", lastName:"Tekle", age: 28, country:"Finland", city:"Helsinki", …}Lidiya Tekle is 28. She livesin Helsinki, Finland. He knows Planning, Managing and Organizing
Now, the getPersonInfo method has been overridden and it identifies if the person is male or female.
- Create an Animal class. The class will have name, age, color, legs properties and create different methods
- Create a Dog and Cat child class from the Animal Class.
- Override the method you create in Animal class
- 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.
ages=[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]console.log('Count:',statistics.count())// 25console.log('Sum: ',statistics.sum())// 744console.log('Min: ',statistics.min())// 24console.log('Max: ',statistics.max())// 38console.log('Range: ',statistics.range()// 14console.log('Mean: ',statistics.mean())// 30console.log('Median: ',statistics.median())// 29console.log('Mode: ',statistics.mode())// {'mode': 26, 'count': 5}console.log('Variance: ',statistics.var())// 17.5console.log('Standard Deviation: ',statistics.std())// 4.2console.log('Variance: ',statistics.var())// 17.5console.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)]
// you output should look like thisconsole.log(statistics.describe())Count: 25Sum: 744Min: 24Max: 38Range: 14Mean: 30Median: 29Mode: (26, 5)Variance: 17.5Standard Deviation: 4.2Frequency 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)]
- 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.
A 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.
To 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.
A regular expression takes two parameters. One required search pattern and an optional flag.
A 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.
Flags are optional parameters in a regular expression which determine the type of searching. Let see some of the flags:
- g:is a global flag which means looking for a pattern in whole text
- i: case insensitive flag(it searches for both lowercase and uppercase)
- m: multiline
Declaring regular expression without global flag and case insensitive flag.
// without flagletpattern='love'letregEx=newRegEx(pattern)
Declaring regular expression with global flag and case insensitive flag.
letpattern='love'letflag='gi'letregEx=newRegEx(pattern,flag)
Declaring a regex pattern using RegEx object. Writing the pattern and the flag inside the RegEx constructor
letregEx=newRegEx('love','gi')
Declaring regular expression with global flag and case insensitive flag.
letregEx=/love/gi
The above regular expression is the same as the one which we created with RegEx constructor
letregEx=newRegEx('love','gi')
Let see some of RegEx methods
test():Tests for a match in a string. It returns true or false.
conststr='I love JavaScript'constpattern=/love/constresult=pattern.test(str)console.log(result)
true
match():Returns an array containing all of the matches, including capturing groups, or null if no match is found.If we do not use a global flag, match() returns an array containing the pattern, index, input and group.
conststr='I love JavaScript'constpattern=/love/constresult=str.match(pattern)console.log(result)
["love", index: 2, input:"I love JavaScript", groups: undefined]
conststr='I love JavaScript'constpattern=/love/gconstresult=str.match(pattern)console.log(result)
["love"]
search(): Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
conststr='I love JavaScript'constpattern=/love/gconstresult=str.search(pattern)console.log(result)
2
replace(): Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
consttxt='Python is the most beautiful language that a human begin has ever created.\I recommend python for a first programming language'matchReplaced=txt.replace(/Python|python/,'JavaScript')console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend pythonfor a first programming language
consttxt='Python is the most beautiful language that a human begin has ever created.\I recommend python for a first programming language'matchReplaced=txt.replace(/Python|python/g,'JavaScript')console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScriptfor a first programming language
consttxt='Python is the most beautiful language that a human begin has ever created.\I recommend python for a first programming language'matchReplaced=txt.replace(/Python/gi,'JavaScript')console.log(matchReplaced)
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScriptfor a first programming language
consttxt='%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\T%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 \p%e%o%ple.\I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'matches=txt.replace(/%/g,'')console.log(matches)
I 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.
- []: A set of characters
- [a-c] means, a or b or c
- [a-z] means, any letter a to z
- [A-Z] means, any character A to Z
- [0-3] means, 0 or 1 or 2 or 3
- [0-9] means any number 0 to 9
- [A-Za-z0-9] any character which is a to z, A to Z, 0 to 9
- \: uses to escape special characters
- \d mean:match where the string contains digits (numbers from 0-9)
- \D mean: match where the string does not contain digits
- . : any character except new line character(\n)
- ^: starts with
- r'^substring' eg r'^love', a sentence which starts with a word love
- r'[^abc] mean not a, not b, not c.
- $: ends with
- r'substring$' eg r'love$', sentence ends with a word love
- *: zero or more times
- r'[a]*' means a optional or it can be occur many times.
- +: one or more times
- r'[a]+' mean at least once or more times
- ?: zero or one times
- r'[a]?' mean zero times or once
- {3}: Exactly 3 characters
- {3,}: At least 3 character
- {3,8}: 3 to 8 characters
- |: Either or
- r'apple|banana' mean either of an apple or a banana
- (): Capture and group
Let's use example to clarify the above meta characters
Let's use square bracket to include lower and upper case
constpattern='[Aa]pple'// this square bracket mean either A or aconsttxt='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. 'constmatches=txt.match(pattern)console.log(matches)
["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]
constpattern=/[Aa]pple/g// this square bracket mean either A or aconsttxt='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. 'constmatches=txt.match(pattern)console.log(matches)
["Apple","apple"]
If we want to look for the banana, we write the pattern as follows:
constpattern=/[Aa]pple|[Bb]anana/g// this square bracket mean either A or aconsttxt='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.'constmatches=txt.match(pattern)console.log(matches)
["Apple","banana","apple","banana","Banana"]
Using the square bracket and or operator , we manage to extract Apple, apple, Banana and banana.
constpattern=/\d/g// d is a special character which means digitsconsttxt='This regular expression example was made in January 12, 2020.'constmatches=txt.match(pattern)console.log(matches)// ["1", "2", "2", "0", "2", "0"], this is not what we want
constpattern=/\d+/g// d is a special character which means digitsconsttxt='This regular expression example was made in January 12, 2020.'constmatches=txt.match(pattern)console.log(matches)// ["12", "2020"], this is not what we want
constpattern=/\d+/g// d is a special character which means digitsconsttxt='This regular expression example was made in January 12, 2020.'constmatches=txt.match(pattern)console.log(matches)// ["12", "2020"], this is not what we want
constpattern=/[a]./g// this square bracket means a and . means any character except new lineconsttxt='Apple and banana are fruits'constmatches=txt.match(pattern)console.log(matches)// ["an", "an", "an", "a ", "ar"]
constpattern=/[a].+/g// . any character, + any character one or more timesconsttxt='Apple and banana are fruits'constmatches=txt.match(pattern)console.log(matches)// ['and banana are fruits']
Zero or many times. The pattern could may not occur or it can occur many times.
constpattern=/[a].*/g//. any character, + any character one or more timesconsttxt='Apple and banana are fruits'constmatches=txt.match(pattern)console.log(matches)// ['and banana are fruits']
Zero or one times. The pattern could may not occur or it may occur once.
consttxt='I am not sure if there is a convention how to write the word e-mail.\Some people write it email others may write it as Email or E-mail.'constpattern=/[Ee]-?mail/g// ? means optionalmatches=txt.match(pattern)console.log(matches)// ["e-mail", "email", "Email", "E-mail"]
We 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
consttxt='This regular expression example was made in December 6, 2019.'constpattern=/\d{4}/g// exactly four timesconstmatches=txt.match(pattern)console.log(matches)// ['2019']
consttxt='This regular expression example was made in December 6, 2019.'constpattern=/\d{1,4}/g// 1 to 4constmatches=txt.match(pattern)console.log(matches)// ['6', '2019']
- Starts with
consttxt='This regular expression example was made in December 6, 2019.'constpattern=/^This/// ^ means starts withconstmatches=txt.match(pattern)console.log(matches)// ['This']
- Negation
consttxt='This regular expression example was made in December 6, 2019.'constpattern=/[^A-Za-z,.]+/g// ^ in set character means negation, not A to Z, not a to z, no space, no coma no periodconstmatches=txt.match(pattern)console.log(matches)// ["6", "2019"]
It should have ^ starting and $ which is an end.
letpattern=/^[A-Z][a-z]{3,12}$/;letname='Asabeneh';letresult=pattern.test(name)console.log(result)// true
- 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.’
- 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.
points=['-1','2','-4','-3','-1','0','4','8']sortedPoints=[-4,-3,-1,-1,0,2,4,8]distance=12
Write a pattern which identify if a string is a valid JavaScript variable
is_valid_variable('first_name')# Trueis_valid_variable('first-name')# Falseis_valid_variable('1first_name')# Falseis_valid_variable('firstname')# True
Write a function calledtenMostFrequentWords which get the ten most frequent word from a string?
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.`console.log(tenMostFrequentWords(paragraph))
[ {word:'love', count:6}, {word:'you', count:5}, {word:'can', count:3}, {word:'what', count:2}, {word:'teaching', count:2}, {word:'not', count:2}, {word:'else', count:2}, {word:'do', count:2}, {word:'I', count:2}, {word:'which', count:1}, {word:'to', count:1}, {word:'the', count:1}, {word:'something', count:1}, {word:'if', count:1}, {word:'give', count:1}, {word:'develop',count:1}, {word:'capabilities',count:1}, {word:'application', count:1}, {word:'an',count:1}, {word:'all',count:1}, {word:'Python',count:1}, {word:'If',count:1}]
console.log(tenMostFrequentWords(paragraph,10))
[{word:'love', count:6},{word:'you', count:5},{word:'can', count:3},{word:'what', count:2},{word:'teaching', count:2},{word:'not', count:2},{word:'else', count:2},{word:'do', count:2},{word:'I', count:2},{word:'which', count:1}]
- Writ a function which cleans text. Clean the following text. After cleaning, count three most frequent words in the string.
sentence=`%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @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!?`console.log(cleanText(sentence))
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 otherjobs Does this motivate you to be a teacher```1. Write afunctionwhich find the most frequent words. After cleaning, count three most frequent wordsin the string.```js console.log(mostFrequentWords(cleanedText)) [{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]```## Promises and CallbacksFrom the following code blocks you will notice, the difference between callback and promises:```js //Callback const doSomething = callback => {setTimeout(() => { const skills = ['HTML','CSS','JS'] callback('It didnt go well', skills) }, 2000)}doSomething((err, result)=> { if (err) { return console.log(err) } return console.log(result)})// after2 seconds it will print//=> It didnt go well const doSomething = callback => { setTimeout(() => { const skills = ['HTML', 'CSS', 'JS'] callback(false, skills) },2000)}doSomething((err, result) => { if (err) { return console.log(err) } return console.log(result)})// after2 seconds it will print the skills//=> ["HTML", "CSS", "JS"]
// PromiseconstdoPromise=newPromise((resolve,reject)=>{setTimeout(()=>{constskills=['HTML','CSS','JS']if(skills.length>0){resolve(skills)}else{reject('Something wrong has happened')}},2000)})doPromise.then(result=>{console.log(result)}).catch(error=>console.log(error))constmyPromise=n=>{returnnewPromise((resolve,reject)=>{if(n){resolve(n*n)}else{reject('You need to pass an argument')}})}constsquare=asyncn=>{letvalue=awaitmyPromise(n)returnvalue}square().then(res=>{console.log(res)}).catch(err=>console.log(err))console.log(square(10))
consturl='https://restcountries.eu/rest/v2/alll'fetch(url).then(response=>response.json()).then(data=>{console.log(data)}).catch(error=>console.log(error))constfetchData=async()=>{try{constresponse=awaitfetch(url)constcountries=awaitresponse.json()console.log(countries)}catch(err){console.log(err)}}console.log('===== async and await')fetchData()
Local 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:setItem(), getItem(), removeItem(), clear(), key()
When 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
localStorage.setItem('name','Asabeneh');console.log(localStorage)//Storage {name: 'Asabeneh', length: 1}localStorage.setItem('age',200);console.log(localStorage)//Storage {age: '200', name: 'Asabeneh', length: 2}constskills=['HTML','CSS','JS','React'];//Skills array has to be stringified first to keep the format.constskillsJSON=JSON.stringify(skills,undefined,4)localStorage.setItem('skills',skillsJSON);console.log(localStorage)//Storage {age: '200', name: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3}
If we are storing an array, an object or object array, we should stringify the object first. See the example below.
letskills=[{tech:'HTML',level:10},{tech:'CSS',level:9},{tech:'JS',level:8},{tech:'React',level:9},{tech:'Redux',level:10},{tech:'Node',level:8},{tech:'MongoDB',level:8}];letskillJSON=JSON.stringify(skills);localStorage.setItem('skills',skillJSON);
letname=localStorage.getItem('name');letage=localStorage.getItem('age');letskills=localStorage.getItem('skills');console.log(name,age,skills)// 'Asabeneh', '200', '['HTML','CSS','JS','React']'letskillsObj=JSON.parse(localStorage.getItem('skills'),undefined,4);console.log(skillsObj);
The clear method, will clear everything stored in the local storage
localStorage.clear();
- JavaScript Test 3: SolutionsJavaScript-Test-4)
- JavaScript Test 4: Solutions
About
A step by step guide to learn JavaScript and programming. These videos may help too:https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.