Press ESC to close

Learn JavaScript

0 1555

Learn javascript by studying the basic concepts.

JavaScript is a language used in client-side web programming. This means that the scripts are interpreted by the web browser on each user’s computer.

Recall that server-side web languages ‚Äč‚Äčinstead contain code that runs on the server (where the website is hosted). That is, after processing the code, it is sent to the browser of the user who requested it.

In the last lesson we talked about how to integrate JavaScript code into our web pages and therefore which embedding method should be used rather than another. In this lesson we will explore some concepts, including that of function.

Learn JavaScript – What is a function?

A function is a block of code where to insert instructions and is executed when it is invoked (called).

Typically, a function is called on a web page via a button or when a certain event occurs.

A function in JavaScript has a name and can also have parameters enclosed in two round brackets.

The instructions to be executed are instead indicated in curly brackets.

So let’s take some examples to better understand how it works:



function hour() { 
    var day = new Date();
    var hour = day.toLocaleTimeString();
    alert(hour);
}

Learn JavaScript – Code development

First of all, we note that we are using new Date() to create an object of type Date.

The Date object is used to work with dates and times. The toLocaleTimeString method returns the time.

Within the function hour(), which has no parameters enclosed in round brackets, we store the time in a variable and call the alert method. Recall that the alert() method is used to create a window that opens in the browser. In our specific case it will show the time.

Then we insert a call to the function created in JavaScript at the desired point on our website.

For example, you can insert a button that calls the function now when clicked.

<input onclick="hour()" value="Shows the time" type="button">

You can see the result by clicking on the button below: ‘show time’. It will show you the current time.

Learn JavaScript – Second example

Let’s do the same example but displaying the message in the html page, rather than in a dialog box. We use the simple document.write method for this purpose, as in the example below:



function hour() { 
	var hours = new Date();
	var hour = hours.toLocaleTimeString();
	document.write("Another way to view a message!");
	document.write("

Hours: " + hour + "

") }

Conclusion

The purpose of this guide is to learn JavaScript with lots of fun exercises. In the next lessons we will see many other examples.

Try entering this code to view the time on your web page to see the result.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

Variables JavaScript

Next Story

Introduction to JavaScript

Previous Story