I would like to recommend you to read about operator precendence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
I would like to recommend you to read about operator precedence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
1. Calculate the slope, x-intercept and y-intercept of y = 2x -2
1. Slope is (m = y2-y1/x2-x1). Find the slope between point (2, 2) and point(6,10)
1. Slope is m = (y<sub>2</sub>-y<sub>1</sub>)/(x<sub>2</sub>-x<sub>1</sub>). Find the slope between point (2, 2) and point(6,10)
1. Compare the slope of above two questions.
1. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Calculate the value of y (y = x<sup>2</sup> + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Writ a script that prompt a user to enter hours and rate per hour. Calculate pay of the person?
1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:'You are old enough to drive' but if not 18 give another feedback stating to wait for the number of years he neds to turn 18.
1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:'You are old enough to drive' but if not 18 give another feedback stating to wait for the number of years he needs to turn 18.
// console.log(arguments), arguments object not found in arrow function
// instead we use an a parameter followed by spread operator
// instead we use a parameter followed by spread operator (...)
console.log(args)
}
@ -523,7 +523,7 @@ It Will be covered in other section.
9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.
10. 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_.
11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.
12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelciusToFahrenheit_.
12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelsiusToFahrenheit_.
13. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below.
- [Setting new key for an object](#setting-new-key-for-an-object)
- [Object Methods](#object-methods)
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 8
## Scope
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let.
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can be declared at different scope. In this section, we will see the scope variables, scope of variables when we use var or let.
Variables scopes can be:
- Window
- Global
- Local
Variable can be declared globally or locally or window scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at window level.
Variable can be declared globally or locally scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at global level.
Let us imagine that we have a scope.js file.
### Window Scope
### Window Global Object
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
```js
//scope.js
a = 'JavaScript' // is a window scope this found anywhere
b = 10 // this is a window scope variable
a = 'JavaScript' // declaring a variable without let or const make it available in window object and this found anywhere
b = 10 // this is a global scope variable and found in the window object
function letsLearnScope() {
console.log(a, b)
if (true) {
@ -96,13 +95,18 @@ console.log(a, b) // JavaScript 10, accessible
A variable declared as local can be accessed only in certain block code.
- Block Scope
- Function Scope
```js
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
// Function scope
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let value = false
// block scope
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
@ -111,7 +115,7 @@ function letsLearnScope() {
let c = 30
let d = 40
value = !value
console.log(a, b, c) // Python 20 30
console.log(a, b, c, value) // Python 20 30 true
}
// we can not access c because c's scope is only the if block
console.log(a, b, value) // JavaScript 10 true
@ -138,9 +142,9 @@ if (true){
console.log(gravity) // 9.81
for(var i = 0; i <3;i++){
console.log(i) // 1, 2, 3
console.log(i) // 0, 1, 2
}
console.log(i)
console.log(i) // 3
```
@ -163,13 +167,13 @@ if (true){
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
for(let i = 0; i <3;i++){
console.log(i) // 1, 2, 3
console.log(i) // 0, 1, 2
}
// console.log(i), Uncaught ReferenceError: i is not defined
```
The scope *let* and *const*is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use *let* for any value which change, *const* for any constant value, and for array, object, arrow function and function expression.
The scope *let* and *const*are the same. The difference is only reassigning. We can not change or reassign the value of the `const` variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will write clean code and avoid hard to debug mistakes. As a rule of thumb, you can use *let* for any value which change, *const* for any constant value, and for an array, object, arrow function and function expression.
## 📔 Object
@ -252,14 +256,14 @@ const person = {
console.log(person.firstName)
console.log(person.lastName)
console.log(person.age)
console.log(person.location)
console.log(person.location) // undefined
// value can be accessed using square bracket and key name
console.log(person['firstName'])
console.log(person['lastName'])
console.log(person['age'])
console.log(person['age'])
console.log(person['location'])
console.log(person['location']) // undefined
// for instance to access the phone number we only use the square bracket method
@ -132,7 +132,7 @@ In JavaScript we can execute some activities in a certain interval of time or we
- setInterval
- setTimeout
#### Setting Interaval using a setInterval function
#### Setting Interval using a setInterval function
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.
@ -571,7 +571,7 @@ const products = [
```
1. Explain the difference between **_forEach, map, filter, and reduce_**.
2. Define a call function before you them in forEach, map, filter or reduce.
2. Define a callback function before you use it in forEach, map, filter or reduce.
3. Use **_forEach_** to console.log each country in the countries array.
4. Use **_forEach_** to console.log each name in the names array.
5. Use **_forEach_** to console.log each number in the numbers array.
![Thirty Days Of JavaScript](../images/banners/day_1_16.png)
- [Day 16](#day-16)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
# Day 16
@ -63,7 +63,7 @@ JSON stands for JavaScript Object Notation. The JSON syntax is derived from Java
}
```
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.
The above JSON example is not much different from 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.
@ -177,6 +177,10 @@ Mostly we fetch JSON data from HTTP response or from a file, but we can store th
![Thirty Days Of JavaScript](../images/banners/day_1_17.png)
- [Day 17](#day-17)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Use case of Web Storages](#use-case-of-web-storages)
- [HTML5 Web Storage Objects](#html5-web-storage-objects)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Use case of Web Storages](#use-case-of-web-storages)
- [HTML5 Web Storage Objects](#html5-web-storage-objects)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 17
@ -77,7 +77,7 @@ For the examples mentioned above, it makes sense to use localStorage. You may be
In cases, we want to to get rid of the data as soon as the window is closed. Or, perhaps, if we do not want the application to interfere with the same application that’s open in another window. These scenarios are served best with sessionStorage.
Now, let use how use make use of these Web Storage APIs.
Now, let us see how make use of these Web Storage APIs.
## HTML5 Web Storage Objects
@ -90,7 +90,7 @@ Web Storage objects:
- _localStorage_ - to display the localStorage object
- _localStorage.clear()_ - to remove everything in the local storage
- _localStorage.setItem()_ - to storage data in the localStorage. It takes a key and a value parameters.
- _localStorage.setItem()_ - to store data in the localStorage. It takes a key and a value parameters.
- _localStorage.getItem()_ - to display data stored in the localStorage. It takes a key as a parameter.
- _localStorage.removeItem()_ - to remove stored item form a localStorage. It takes key as a parameter.
- _localStorage.key()_ - to display a data stored in a localStorage. It takes index as a parameter.
We can create a promise using the Promise constructor. We can create a new promise using the key word new followed by the word Promise and followed by a parenthesis. Inside the parenthesis it it takes a callback function. The promise callback function has two parameters which are the _resolve_ and _reject_ functions.
We can create a promise using the Promise constructor. We can create a new promise using the key word `new` followed by the word `Promise` and followed by a parenthesis. Inside the parenthesis, it takes a `callback` function. The promise callback function has two parameters which are the _`resolve`_ and _`reject`_ functions.
```js
// syntax
@ -244,7 +244,7 @@ console.log('===== async and await')
fetchData()
```
🌕 You are real and you kept your promise and your reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps ahead to your way to greatness. Now do some exercises for your brain and for your muscle.
🌕 You are real and you kept your promise and you reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps ahead to your way to greatness. Now do some exercises for your brain and muscles.
By now you are very familiar function declaration, expression function, arrow function and anonymous function. In this challenge we tend to use arrow function instead of other functions. Arrow function is not a replacement for other functions. In addition, arrow functions and function declarations are not exactly the same. So you should know when to use and when not. I will cover the difference in detail in other sections. We will use explicit return instead of implicit return if the function is one liner
The `new Dat().toLocaleString()` can also be used to display current date time. The `toLocaleString()` methods takes different arguments. You may learn more about date and time from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
#### Loops
We coverer many types of loops in this challenges. The regular for loop, while loop, do while loop, for of loop, forEach loop and for in loop.
@ -133,9 +133,9 @@ The _document.querySelector_ method can select an HTML or HTML elements by tag n
**_querySelector_**: can be used to select HTML element by its tag name, id or class. If the tag name is used it selects only the first element.
```js
let firstTitle = document.querySelector('h1') // select the first available h2 element
let firstTitle = document.querySelector('h1') // select the first available h1 element
let firstTitle = document.querySelector('#first-title') // select id with first-title
let firstTitle = document.querySelector('.title') // select the first available h2 element with class title
let firstTitle = document.querySelector('.title') // select the first available h1 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 use **_for loop_** or **_forEach_** to loop through each nodeList elements.
@ -158,7 +158,7 @@ An attribute is added in the opening tag of HTML which gives additional informat
🌕 Your journey to greatness completed successfully. You reached high level of greatness. Now, you are much greater than ever before. I knew what it takes to reach to this level and you made to this point. You are a real hero. Now, it is time to celebrate your success with a friend or with a family. I am looking forward to seeing you in an other challenge.
## Testimony
Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/)
When making this tutorial I was using Node version 12.14.0, but now the recommended version of Node.js for download is v14.17.6.
When making this tutorial I was using Node version 12.14.0, but now the recommended version of Node.js for download is v14.17.6, by the time you use this material you may have a higher Node.js version.
### Browser
@ -198,7 +198,7 @@ Ctl+Shift+I
##### Console.log
To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed 'Hello, World' as input data or argument in the console.log() function.
To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed `'Hello, World'` as input data or argument in the console.log() function.
```js
console.log('Hello, World!')
@ -206,7 +206,7 @@ console.log('Hello, World!')
##### Console.log with Multiple Arguments
The **console.log()** function can take multiple parameters separated by commas. The syntax looks like as follows:**console.log(param1, param2, param3)**
The **`console.log()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`**
As you can see from the snippet code above, _console.log()_ can take multiple arguments.
As you can see from the snippet code above, _`console.log()`_ can take multiple arguments.
Congratulations! You wrote your first JavaScript code using _console.log()_.
Congratulations! You wrote your first JavaScript code using _`console.log()`_.
##### Comments
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.In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this /\* \*/ is also a comment.
We can 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.In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment.
**Example: Single Line Comment**
```js
// This is the first comment
// This is the second comment
// I am a single line comment
// This is the second comment
// I am a single line comment
```
**Example: Multiline Comment**
```js
/*
This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
*/
```
##### Syntax
@ -251,7 +255,7 @@ console.log('Hello, World!')
console.log('Hello, World!')
```
So far, we saw how to display text using the _console.log()_. If we are printing text or string using _console.log()_, the text has to be inside the single quotes, double quotes, or a backtick quotes.
So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a backtick.
**Example:**
```js
@ -262,9 +266,9 @@ console.log(`Hello, World!`)
#### Arithmetics
Now, let us practice more writing JavaScript codes using _console.log()_ on google chrome console for number data types.
Now, let us practice more writing JavaScript codes using _`console.log()`_ on Google Chrome console for number data types.
In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.
The console can directly take arguments without the **_console.log()_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console.
It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console.
We can write our codes on the browser console, but it won't do for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days JavaScript challenge, we will be using Visual Studio Code.
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 of JavaScript challenge, we will be using Visual Studio Code.
#### Installing Visual Studio Code
Visual studio code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have.
Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have.
![Vscode](images/vscode.png)
@ -320,7 +324,7 @@ The following sections show different ways of adding JavaScript code to your web
### Inline Script
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_index.html_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/).
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/).
```html
<!DOCTYPE html>
@ -334,11 +338,11 @@ Create a project folder on your desktop or in any location, name it 30DaysOfJS a
</html>
```
Now, you just wrote your first inline script. We can create a pop up alert message using the _alert()_ built-in function.
Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function.
### Internal Script
The internal script can be written in the _head_ or the _body_, but it is preferred to put it on the body of the HTML document.
The internal script can be written in the _`head`_ or the _`body`_, but it is preferred to put it on the body of the HTML document.
First, let us write on the head part of the page.
```html
@ -354,7 +358,7 @@ First, let us write on the head part of the page.
</html>
```
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the console.log()
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`.
```html
<!DOCTYPE html>
@ -371,7 +375,7 @@ This is how we write an internal script most of the time. Writing the JavaScript
</html>
```
Open the browser console to see the output from the console.log()
Open the browser console to see the output from the `console.log()`.
![js code from vscode](./images/js_code_vscode.png)
@ -406,19 +410,19 @@ External scripts in the _body_:
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!--it could be in the header or in the body -->
<!--Here is the recommended place to put the external script -->
<!--JavaScript external link could be in the header or in the body -->
<!--Before the closing tag of the body is the recommended place to put the external JavaScript script -->
<scriptsrc="introduction.js"></script>
</body>
</html>
```
Open the browser console to see the output of the console.log()
Open the browser console to see the output of the `console.log()`.
### Multiple External Scripts
We can also link multiple external JavaScript files to a web page.
Create a helloworld.js file inside the 30DaysOfJS folder and write the following code.
Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code.
```js
console.log('Hello, World!')
@ -443,7 +447,7 @@ _Your main.js file should be below all other scripts_. It is very important to r
## Introduction to Data types
In JavaScript and also other programming languages, there are different kinds of data types. The following are JavaScript primitive data types:_String, Number, Boolean, undefined, Null_, and _Symbol_.
In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types:_String, Number, Boolean, undefined, Null_, and _Symbol_.
### Numbers
@ -457,16 +461,20 @@ In JavaScript and also other programming languages, there are different kinds of
### Strings
A collection of one or more characters between two single quotes, double quotes, or backticks.
**Example:**
```js
'a'
'Asabeneh'
"Asabeneh"
'Finland'
'JavaScript is a beautiful programming language'
'I love teaching'
'I hope you are enjoying the first day'
`We can also create a string using a backtick`
'A string could be just as small as one character as big as many pages'
'A string could be just as small as one character or as big as many pages'
'Any data type under a single quote, double quote or backtick is a string'
```
### Booleans
@ -533,7 +541,6 @@ Multiline commenting:
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
```
@ -574,11 +581,11 @@ year2020
year_2020
```
The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables.
The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section.
Example of invalid variables:
```sh
```js
first-name
1_num
num_#_1
@ -591,6 +598,8 @@ Let us declare variables with different data types. To declare a variable, we ne
let nameOfVariable = value
```
The nameOfVriable is the name that stores different data of value. See below for detail examples.