Absolute Beginner's Guide to Learn JavaScript, Part-3
Tags: javascript, webdev, beginners, tutorial
Published: 2022-08-21 20:38:00

Over the course of this series "Start with Me", I am writing about the heavily used concepts of JavaScript that as a web-developer, you are expected to know. I am giving the tools in my posts so that you can feel less overwhelmed while it comes to build the UI and UX, or adding different functionalities in the website. 

If you followed till now, you know about the DOM trees of a web page and how to access the objects of the trees, how to debug your code by writing messages and types in console.log() , how to manipulate arrays and objects with various methods etc. Today, we will learn how to handle the events that needs handling, or “Event Handling” in JavaScript, what is “this” keyword, arrow functions and how to set an interval or timeout for a specific action in JavaScript. Let’s get to it.


## 6. Event handling

In the first post I talked about HTML elements. Think about an element, button. What do you do with a button in a website? You either use it to submit something or click it to see something. Let’s write a code to put a button in a web page:

```Javascript
<!DOCTYPE html>
<html>

<body>

	<h1>Event Handling</h1>
	<div>
		<button>Click me!</button>
	</div>
</body>
<script>


</script>

</html>

```
It will look like the following:


![Output 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7vl81kxnoaim0ov6ns1.png)

Nothing will happen if you click the button, because it's a static HTML element. We need to do something about it. How about if we click, we will change the text of the paragraph below, to "Hello World"? 

How to do that?

Clicking the button is an event, therefore we have to attach an action to this event which will handle the event of clicking the button. We will write a function in JavaScript named **clickFunc** like the following:

```Javascript
...
<script>

function clickFunc(){
      document.getElementById("paragraph").innerHTML = "Hello World"
}

</script>

```
 **The onclick event occurs when the user clicks on the button element.** In order to do this, in the button event we will write in the onclick property:

```Javascript
...

	<div>
           <button onclick="clickFunc()">Click me!</button>
		<p id="paragraph">meow</p>
	</div>
</body>
...

</html>

```

That's it. Now if we click the button, we will see that the text meow is now changed. 


![Output 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/40jci57qidv9yp0efsew.gif)

**Event Handling means dealing with the events that the HTML elements can cause in a web page. HTML elements need JavaScript to handle their events.** If you think of ordering food online when you are hungry, that is an event handling. Being hungry is your event, and to handle this event you are ordering food online. 

You could write the following code in another way, with addEventListener() method. This method takes an event and a function and attaches an event handler to an element. The code will be like the following:

```Javascript

<!DOCTYPE html>
<html>

<body>

	<h1>Event Handling</h1>
	<div>
		<button id="btn">Click me!</button>
		<p id="paragraph">meow</p>
	</div>
</body>
<script>

const element = document.getElementById("btn");
element.addEventListener("click", function() {
  document.getElementById("paragraph").innerHTML = "Hello World";
});

</script>

</html>

```

Notice how there's no name of function that we wrote here. It's an anonymous function, meaning **"A function has no name"**. 

Let's handle another event; text change in the input box. Put an input element in the web page like the following:

```Javascript
<body>

	<h1>Event Handling</h1>
	<div>
	   <input type="text 
                      onchange="changeFunc(this.value)" value=""/>
	
		<p id="paragraph"></p>
	</div>
</body>

```

The event that we will be handling now is "onchange". We will write a function that will take whatever we write in the box and print in the paragraph tag beneath. The text we will write will be captured via the **value** property of input tag, as a result, we are passing the value in the **changeFunc function** as an argument. Notice that we wrote "this.value" instead of value as the argument. We will talk about what this means in the following section of this post. 

Now, let's write the changeFunc body:

```
function changeFunc(val){
	document.getElementById("paragraph").innerHTML = val
}

</script>

```

The output should look like the following if you write a text and hit enter:


![Output 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fe8e8ohe5vvvgd9cvqeq.gif)

These are some of the most used event handling in JavaScript. Refer to this link of [W3Schools](https://www.w3schools.com/js/js_events.asp) to see the list of events. If you want to learn more, you can read [this blog of Eloquent JavaScript](https://eloquentjavascript.net/15_event.html). 


## 7. this keyword, bind() method and Getting Smart with ES6:

In the previous section, we saw "this.value" as an argument. **this** keyword refers to an object in JavaScript. What does that mean? Well, this attaches itself to the way it is being used. In our context, we wanted the text that we wrote in input element. Writing something in input is an event, and here **this** refers to the element that received the event. Input element received our **text event** in its value property, therefore we wrote **this.value** as the function argument. 

Usually, this refers to the global object, and it's also true in the case of a function. In an object method, this refers to the object. 

Let's write an object that has the count of your animals:

```Javascript

const animal = {
	"cat": 2,
	"dog": 5,

  }

  
}

</script>

```

We then write an object method that will show the count in the paragraph tag:

```Javascript

const animal = {
	"cat": 2,
	"dog": 5,
	count : function() {
    return this.cat + " " + this.dog;
  }

  
}
document.getElementById("paragraph").innerHTML = animal.count();

</script>

```

You can see the count 2 and 5 below:


![Output 6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zrutwio8zguhguew9mhd.png)

So far, we have learned what **this** means. **This** can refer to an object or a function. In order to bind a specific object or function which has its own **this**, to another entity, we use bind() method in JavaScript. 

I think I have come across the best explanation about bind() from this stackoverflow link - [What is bind() in JS](https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method). Based on an answer which has 89 upvotes, I used bind() to bind an object with a function like the following:

```Javascript

var ourFunc = function(value){
	console.log(this[value])
}

var obj = {
    x : 5,
    y : 10
};

obj.log = ourFunc.bind(obj)

obj.log('x')  // Output: 5

```
JavaScript has a major revision in ES6 which stands for ECMAScript 6. The foundation of React JS is on ES6. In ES6 the function is written as an arrow function like the following:

```Javascript

hello = () => {

}
```

Or 

```Javascript

() => {

}
```

This syntax is concise, and if you use {} you do not have to write "return" to return something. This arrow function is not hoisted, which means it must be defined before it is used. Another interesting fact is, arrow function doe not have **this** attached, which makes it not suitable for object methods, otherwise, it's my go to way to define functions in React JS because I don't have to worry about binding. ES6 ups your game once you master Vanilla JS and move on to learning a JavaScript framework. This link covers the basics of ES6 if you want to learn more - [W3Schools](https://www.w3schools.com/js/js_es6.asp)

## 8. setTimeout() and setInterval()

Sometimes, it may so happen that you want to run a particular piece of your code or a function to run for a certain time. That's when you use setTimeout() method. The first parameter is the code or the function, and the second parameter is the amount of time after you which the execution stops. Time is calculated in milliseconds so 1 second = 1000 miliseconds.

```Javascript

<script>

const timeout = setTimeout(hello, 10000);

function hello(){
	document.getElementById("paragraph").innerHTML = "Hello World"
}

</script>

```

Output is shown after 10 seconds:

![Output 9](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7iljbq503t26czr9qnr.gif)

There is another method named setInterval(), which is used to execute something after the time in milliseconds that is passed in it. If you run the following code:

```Javascript

<script>

const interVal = setInterval(hello, 10000);

function hello(){
	document.getElementById("paragraph").innerHTML += "Meow"
}

</script>

```

You will see that the browser has Meow printed every 1 second:



![Output 10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1fen72y1q4wjt1w3i4f.gif)


That's a wrap for today. Hopefully, I will write about JavaScript Promise in the upcoming post. Till then, tata!