1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
2. In above countries array, check if there is a country or countries containing the word 'land'. If there are countries containing 'land', print it as array. If there is no country containing the word 'land', print 'All these countries are without land'.
```sh
['Finland', 'Iceland']
['Finland','Ireland', 'Iceland']
```
3. In above countries array, check if there is a country or countries end with a substring 'ia'. If there are countries end with, print it as array. If there is no country containing the word 'ai', print 'These are countries ends without ia'.
@ -502,10 +502,13 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
### Function declaration versus Arrow function
It ill be covered in other time
It Will be covered in other section.
🌕 You are a rising star, now you knew function . Now, you are super charged with the power of functions. You have just completed day 7 challenges and you are 7 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 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/)
## 💻 Exercises
### Exercises: Level 1
@ -617,7 +620,7 @@ It ill be covered in other time
### Exercises: Level 3
1. Modify question number n . Declare a function name _userIdGeneratedByUser_. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
1. Modify the _userIdGenerator_ function. Declare a function name _userIdGeneratedByUser_. It doesn’t take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
Variable can be declared globally or locally or window scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at window level.
Let us image we have a scope.js file.
Let us imagine that we have a scope.js file.
### Window Scope
@ -102,23 +102,25 @@ let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let c = 30
let value = false
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
let a = 'Python'
let b = 20
let c = 30
let d = 40
value = !value
console.log(a, b, c) // Python 20 30
}
// we can not access c because c's scope is only the if block
console.log(a, b) // JavaScript 10
console.log(a, b, value) // JavaScript 10 true
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
```
Now, you have an understanding of scope. A variable declared with *var* only scoped to function but variable declared with *let* or *const* is block scope(function block, if block, loop etc). Block in JavaScript is a code in between two curly brackets ({}).
Now, you have an understanding of scope. A variable declared with *var* only scoped to function but variable declared with *let* or *const* is block scope(function block, if block, loop block, etc). Block in JavaScript is a code in between two curly brackets ({}).
```js
//scope.js
@ -163,7 +165,7 @@ if (true){
for(let i = 0; i <3;i++){
console.log(i) // 1, 2, 3
}
// console.log(i), Uncaught ReferenceError: gravity is not defined
// console.log(i), Uncaught ReferenceError: i is not defined
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.
In JavaScript we can execute some activities in a certain interval of time or we can schedule(wait) for sometime to execute some activities.
- setInterval
- setTimeout
#### setInterval
#### Setting Interaval 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.
setInterval(sayHello, 2000) // it prints hello in every 2 seconds
setInterval(sayHello, 1000) // it prints hello in every second, 1000ms is 1s
```
#### setTimeout
#### Setting a time using a setTimeout
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.
const areAllStr = names.some((name) => typeof name === 'number')
const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
console.log(areAllStr) // false
```
@ -556,7 +549,7 @@ users.sort((a, b) => {
return 0
})
console.log(users) // sorted ascending
//[{…}, {…}, {…}, {…}]
//[{…}, {…}, {…}, {…}]
```
🌕 You are doing great.Never give up because great things take time. You have just completed day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
Web Storage(sessionStorage and localStorage) is a new HTML5 API offering important benefits over traditional cookies. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. The data storage limit of cookies in many web browsers is about 4 KB per cookie. We Storages can store far larger data (at least 5MB) and never transferred to the server. All sites from the same or one origin can store and access the same data.
The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. The are are two Web Storage objects:
The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. There are two Web Storage objects:
We human give or receive a promise to do some activity at some point in time. If we keep the promise we make others happy but if we do not keep the promise, it may lead discontentment. Promise in JavaScript has something in common with the above examples.
We human give or receive a promise to do some activity at some point in time. If we keep the promise we make others happy but if we do not keep the promise, it may lead discontentment. Promise in JavaScript has something in common with the above examples.
A Promise is a way to handle asynchronous operations in JavaScript. It allows handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
@ -52,10 +52,10 @@ As the Promise.prototype.then() and Promise.prototype.catch() methods return pro
To understand promise very well let us understand callback first. Let's see the following callbacks. From the following code blocks you will notice, the difference between callback and promises.
- call back
Let us see a callback function which can take two parameters. The first parameter is err and the second is result. If the err parameter is false, there will not be error other wise it will return an error.
Let us see a callback function which can take two parameters. The first parameter is err and the second is result. If the err parameter is false, there will not be error other wise it will return an error.
In this case the err has a value and it will return the err block.
In this case the err is false and it will return the else block which is the result.
In this case the err is false and it will return the else block which is the result.
```js
const doSomething = callback => {
@ -106,7 +105,7 @@ doSomething((err, result) => {
### Promise constructor
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 it takes a callback function. The promise callback function has two parameters which are the _resolve_ and _reject_ functions.
```js
// syntax
@ -134,21 +133,21 @@ doPromise
console.log(result)
})
.catch(error => console.log(error))
```
```
```sh
["HTML", "CSS", "JS"]
```
```sh
["HTML", "CSS", "JS"]
```
The above promise has been settled with resolve.
Let us another example when the promise is settled with reject.
The above promise has been settled with resolve.
Let us another example when the promise is settled with reject.
```js
// Promise
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.indexOf('Node') !== -1) {
if (skills.icludes('Node')) {
resolve('fullstack developer')
} else {
reject('Something wrong has happened')
@ -160,26 +159,26 @@ doPromise
.then(result => {
console.log(result)
})
.catch(error => console.log(error))
```
.catch(error => console.error(error))
```
```sh
Something wrong has happened
```
```sh
Something wrong has happened
```
## Fetch API
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. In this challenge we will use fetch to request url and APIS. In addition to that let us see demonstrate use case of promises in accessing network resources using the fetch API.
```js
const url = 'https://restcountries.com/v2/all' // countries api
fetch(url)
.then(response => response.json()) // accessing the API data as JSON
.then(data => { // getting the data
.then(data => {
// getting the data
console.log(data)
})
.catch(error => console.log(error)) // handling error if something wrong happens
.catch(error => console.error(error)) // handling error if something wrong happens
```
## Async and Await
@ -198,9 +197,9 @@ square(2)
Promise{<resolved>: 4}
```
The word *async* in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
The word _async_ in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
How do we access the value from the promise? To access the value from the promise, we will use the keyword *await*.
How do we access the value from the promise? To access the value from the promise, we will use the keyword _await_.
```js
const square = async function (n) {
@ -218,7 +217,7 @@ Now, as you can see from the above example writing async in front of a function
Let us fetch API data using both promise method and async and await method.
🌕 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/)
@ -133,7 +133,7 @@ I believe you have the motivation and a strong desire to be a developer, a compu
### Install Node.js
You may not need node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/).
You may not need Node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/).
![Node download](images/download_node.png)
@ -148,7 +148,7 @@ asabeneh $ node -v
v12.14.0
```
When making this tutorial I was using node version 12.14.0, but now the recommended version of node.js for download is 12.17.0.
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.
### Browser
@ -156,7 +156,7 @@ There are many browsers out there. However, I strongly recommend Google Chrome.
#### Installing Google Chrome
Install [google chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications.
Install [Google Chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications.
![Google Chrome](images/google_chrome.png)
@ -205,7 +205,7 @@ console.log('Hello, World!')
##### Console.log with Multiple Arguments
The **console.log()** function can take multiple parameters separated by comma. 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)**
Programming languages are similar to human languages. English or many other language uses words, phrases, sentences,compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is _the structure of statements in a computer language._ Programing languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. 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.
Programming languages are similar to human languages. English or many other language uses words, phrases, sentences,compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language.Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. 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.
![Error](images/raising_syntax_error.png)
@ -255,7 +255,7 @@ So far, we saw how to display text using the _console.log()_. If we are printing
```js
console.log('Hello, World!')
console.log('Hello, World!')
console.log("Hello, World!")
console.log(`Hello, World!`)
```
@ -377,7 +377,7 @@ Open the browser console to see the output from the console.log()
### External Script
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body.
First, we should create an external JavaScript file with .js extension. All files ending with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body.
First, we should create an external JavaScript file with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body.
```js
console.log('Welcome to 30DaysOfJavaScript')
@ -405,8 +405,8 @@ 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
<!-- it could be in the header or in the body -->
<!-- Here is the recommended place to put the external script-->
<scriptsrc="introduction.js"></script>
</body>
</html>
@ -463,21 +463,22 @@ A collection of one or more characters between two single quotes, double quotes,
'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')
'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'
```
### Booleans
A boolean value is either True or False. Any comparisons return a boolean value, which is either true or false.
A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false.
A boolean data type is either a true or false value.
**Example:**
```js
true // if the light on,the value is true
false // if the light off, the value is false
true // if the light is on,the value is true
false // if the light is off, the value is false
```
### Undefined
@ -486,7 +487,7 @@ In JavaScript, if we don't assign a value to a variable, the value is undefined.
```js
let firstName
console.log(firstName) //not defined, because it is not assigned to a value yet
console.log(firstName) // undefined, because it is not assigned to a value yet