Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Get Started

Chapter 2 17 mins

Learning outcomes:

  1. The <script> tag
  2. Writing your first JavaScript code
  3. External JavaScript files
  4. Understanding the code
  5. Deciding between the two ways

Before writing JavaScript

Now that you know what is JavaScript from the previous JavaScript Introduction chapter, we can move on to actually begin writing it.

Recall the fact that JavaScript doesn't require any installations on your side to be put into action. It simply runs on your web browser, be it Google Chrome, Firefox, Safari, etc. The browser has a whole engine constructed by software engineers which serves to parse and execute the JavaScript code you write.

So where exactly do we write JavaScript code?

Well, let's find it out.

The <script> tag

HTML provides us with numerous tags to do numerous things.

For example, <p> is used to give margined paragraphs, <b> is used to make text bold, <audio> is used to embed audio files on a webpage and so on.

Similarly, the <script> tag is used to define a block of JavaScript code for the respective webpage it appears in.

The <script> tag defines a block of JavaScript code.

The <script> tag can go inside <head>, as shown below:

<!DOCTYPE html>
<html lang="en">
<head>
<script></script> </head> <body></body> </html>

Or it can go inside the <body> tag, as follows:

<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<script></script> </body> </html>

Which of these to use totally depends on your application setup and sometimes preference too. We'll consider this in detail in the upcoming chapters.

For now, it's sufficient to know that it's the <script> tag that allows us to use JavaScript on a webpage.

While parsing the HTML of a webpage (which is the very first step as soon as the response is received from the server), as soon as a <script> tag is encountered, the browser fires up its JavaScript engine to handle the JavaScript code put forward by the <script> tag.

As stated before, every browser has a built-in engine to parse and execute JavaScript code — you don't need to worry about setting up environments, compilers, interpreters, or just about anything yourself; it's all managed by the browser itself.

So now that we've learnt about the <script> tag, let's write our very first JavaScript code.

Your first JavaScript

For our very first program, we'll simply output the text 'Hello World!'.

Outputting the text 'Hello World!' is pretty standard across the entire world as being the very first program built by a newbie who's beginning to learn a new computer language.

We'll use the document.write() method, and pass it the text 'Hello World!', encapsulated in single quotes (''). document.write() merely takes a piece of text and writes it to the web page.

And don't worry, we'll explain everything in detail later on in this chapter.

We start by creating a new HTML document called greetings.html. Next, we write some basic HTML markup in it along with the <script> tag inside <body> as shown below:

greetings.html
<!DOCTYPE html>
<html lang="en">
<body>
   <script></script>
</body>
</html>

After this, inside the <script> element, we write the JavaScript code to make the desired 'Hello World!' output:

greetings.html
<!DOCTYPE html>
<html lang="en">
<body>
   <script>
document.write('Hello World!'); </script> </body> </html>

Then finally we run this file in the browser (which is simply by opening up the webpage).

And we get the following output:

Hello World!

Congradulations! You've written your first JavaScript code!

Now at this moment, you might have tons of questions in your mind such as:

  • What is a method?
  • What is document.write()?
  • What is 'Hello World!'?
  • What are the ( and ) characters?

Although each of these questions could get definite answers only after you know about the respective concepts in detail, it's still not impossible to get a gist of them on the outskirts.

In fact, this would help you build your foundations on JavaScript very well.

So, let's jump straight into understanding everything in the single line of code above.

Understanding the program

Let's review our JavaScript code:

document.write('Hello World!');

So what is happening over here? Let's go step-by-step.

The first word document is called an object.

What is an object?

An object, in JavaScript, is an entity with properties and methods. You could think of an object in JavaScript as an object in the real world.

For example, consider a toaster oven. It's an object. It has certain properties, such as color, weight, power rating, manufacturer, model no. and so on and so forth. Properties can be thought of as 'characteristics' of an object which is exactly what the word 'property' means in English.

Apart from these, the oven could also have methods. Methods are 'actions' performed on or by an object.

For instance, we could switch on the oven, or switch it off; take the temperature all the way up to 350C or all the way down to 100C; turn on the fan; and so on. The oven is itself able to switch off when its timer runs out. These are all methods of the oven.

Objects in JavaScript work in a similar fashion.

More specifically, document is an object that represents the current HTML document. And it too has certain properties and methods.

To access a property/method of an object, we use the dot (.) character after by the name of the object.

In the statement above, document. (with the dot) simply means that we are about to access a property/method of document. And what we access on document is write.

write is a method of document. It literally writes out something on the HTML document.

The ( and ) parentheses following write are used to call — or better to say, invoke — it.

'Calling' means to execute the code written inside the method. In this case, calling write, via write(), means to execute whatever is defined within the method (which is done by browser vendors themselves).

As stated before, document.write() outputs stuff on the webpage. It could be passed some data to output on the page, inside the pair of parentheses (()). Formally, this data is referred to as an argument of the method.

In this case, 'Hello World' is the argument to the write() method of document. And it is a string.

What is a string?

A string is simply a sequence of textual characters.

It is used wherever pieces of text are needed in a program, such as in outputting stuff to the document, sending data to the server, etc.

In JavaScript, a string could be denoted using a pair of single quotes (''). There are other ways to denote strings as well, but we'll explore them later on, in detail, in the JavaScript Strings unit.

The piece of text associated with a string is written inside these quotes. This makes sure that the JavaScript parser doesn't interpret the text as actual code — rather, it treats it literally as some arbitrary text.

Altogether, this code outputs the text 'Hello World!' out on the HTML document.

So was it all easy to understand?

Now, just to put a little bit of curiosity in you, note that the explanation above was an extremely simplified one for the given piece of code.

For instance, we didn't sepcify that write is also a property of document but with a function definition as its value, which makes it a method; or that document is specifically a DOM object where 'DOM' stands for 'Document Object Model'; and so on and so forth.

Explaining literally everything at this point while you're beginning to learn JavaScript would have lead to just one thing — you wouldn't have been able to understand a single thing! All the minute terminologies and ideas would've confused you way more than help you.

But be rest assured, we'll explain all of these minute details throughout this course. After all, each and every small detail matters.

External JavaScript files

When the JavaScript for a web application becomes large and complex enough such that it gets difficult to manage it along with the HTML markup, it's desireable to shift the code into a separate file.

Such a file has a .js extension (which you could guess stands for what) and is called a JavaScript file:

A JavaScript file contains JavaScript code and has a .js extension.

In order to link to this file in the original webpage, we use the same <script> tag we saw earlier.

But this time, we aren't required to put anything within the tag — rather we have to set the src attribute on the element.

The src attribute of the <script> tag specifies the path to an external JavaScript file. That path, as with any other paths given in similar HTML attributes of other elements, could be relative or absolute. It could even be a complete URL.

In a relative path, we begin from the current directory and traverse all the way up or down to a given resource. In contrast, in an absolute path, we specify the full path to a resource starting from the root directory.

Below shown is an example.

First, let's create a new HTML file called greetings.html, with a <script> tag in its <body> just as before:

greetings.html
<!DOCTYPE html>
<html lang="en">
<body>
   <script></script>
</body>
</html>

Next, let's create a new JavaScript file and name it greetings.js:

greetings.js
 

Then, let's add the same document.write() statement to the file that we saw above, as follows:

greetings.js
document.write('Hello World!');

Finally, let's go back to greetings.html, where we want to embed this JavaScript file.

Inside the <script> tag, we add the src attribute and point it to the greeting.js file (that exists in the same directory as greetings.html) using a relative path:

<!DOCTYPE html>
<html lang="en">
<body>
   <script src="greetings.js"></script>
</body>
</html>

And we're done. Now, it's time to open up the webpage and see the output.

Hello World!

Voila! We get the exact same output as before. Our external JavaScript file was successfully retrieved, then parsed, and ultimately executed.

Deciding between these two

At this point, we know that JavaScript code can go either directly inside the <script> tag or it can go inside a separate JavaScript file thereafter linked to the webpage using these same <script> tag. Great.

Now a question arises and a fair one: what to use when?

That is, should we write JavaScript directly inside <script> or should we create separate files for it?

Well, the answer to this is pretty much the same as for writing CSS, which can be written directly inside <style> tags or in separate CSS files linked via <link> tags.

So let's understand the distinction...

A JavaScript file is a very handy way to write JavaScript.

Benefits of using JavaScript files

First of all, it can be cached, which means that once we link to a given file, subsequent calls could be satisfied from the cached version in disk, not having to make a network roundtrip. This definitely improves the loading times of the linking webpage.

In addition to this, files can be used to create portable scripts that can be delivered from one server to multiple clients.

For example, suppose we are on the webpage example.com/home. Using an external JavaScript file, we can easily embed the JavaScript stored at example2.com/scripts/main.js (which is on another server) on example.com/home. This is NOT possible using internal JavaScript.

Furthermore, writing all our JavaScript in one single file and then linking to this file across a site has the benefit that if we want to make any changes to the JavaScript, we have to do it in one single place. This eases managing our JavaScript code.

If we were to instead put the code directly inside a <script> tag, and then the tag repeated on every single page, that would've defeated this benefit completely. A change on a given page won't obviously apply to the other.

JavaScript files, just like CSS files, help us separate concerns. In particular, they help us separate logic from representation. CSS files, on the other hand, help us separate styles from representation.

But all this doesn't mean that internal JavaScript in the <script> tag directly isn't used just about anywhere. In fact, it does have certain advantages as well.

For instance, if we want to have code specific to a given webpage, it's clearly much better to write that code directly inside the webpage, inside the <script> tags. Creating a file is, of course, possible but would be just too much for such a simple problem.

Keep in mind that loading separate files involves a whole network roundtrip, which adds latency to the webpage's loading times.

Most websites today use a combination of both of these approaches.

So coming back to the question 'what to use when?', the answer to this is completely use-oriented. It completely depends on what we want to achieve.

For example, if we want to develop a JavaScript library (a program providing helper utilities), we'll obviously write the code inside a separate JavaScript file, as it needs to be portable and used by possibly third-parties.

No one would ever develop a library directly inside the <script> tags!