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. Excited? Well we are!

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, like Google Chrome, Firefox,etc. The browser has a whole engine constructed by software developers and engineers which serves to parse and execute the JavaScript code you write.

Anyways moving on let's now see where can you actually write JavaScript, apart from where can it be parsed and executed.

The examples below show HTML code therefore it is recommended that before learning JavaScript you must know HTML.

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.

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.

JavaScript code can be placed inside this <script> tag. Upon executing <script>, the browser parses the code within it, followed by executing it.

As stated before, every browser has a built-in engine which could understand JS code and execute it — you don't need to worry about setting up environments and interpreters yourself; it's all managed by the browser.

External .js 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, external script, or external file, or external JS, or JS file etc.

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 it — rather we have to set the src attribute on the element.

src specifies the path to the external .js file. The path as with any other paths given in HTML attributes, could be relative or absolute.

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 we create a new file and name it greetings.js.

greetings.js

For now, we keep the file empty.

Then we head over to the webpage where we want to put — or better to say, embed — this script. On the webpage, we create a <script> tag and point its src attribute to "greetings.js".

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

In this case, we suppose that greetings.js is in the same folder as the webpage.

If the JS file was in the parent directory, we'd write .. as follows:

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

../ first takes us to the parent directory and then greetings.js fetches this JS file from here.

Your first JavaScript

Now that we know where to write JavaScript, it's time to actually write our first script.

So are you excited?

We'll make the famous greeting 'Hello World!', which is pretty standard as the first lesson taught in any programming course.

For this, we'll use the document.write() method, and pass it the text 'Hello World' (encapsulated in single quotes). The method takes a string and outputs it to the web page.

We'll create this program in both the ways discussed above.

First, let's see how to accomplish this inside the <script> tag.

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 put the JavaScript code to make the desired output:

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

Now run this file in the browser.

You should get the following output:

Hello World!

Congradulations! You've written your first JavaScript code!

Don't worry if you don't understand this single piece of code at this point. We'll explain everything but first let's consider the second way to create this same web page.

For the second way, create an HTML file called greetings2.html and put the same basic markup in it as you did before.

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

We'll return to this HTML file in a while — a JS file ought to be created first.

Go ahead, create a new file in the same directory as greetings2.html and call it greetings.js.

Inside this JS file, write the same piece of code you did above inside the <script> tags.

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

Coming back to the HTML file, with the external script created, now we are left to link to it via the src attribute on the given <script> element.

This is accomplished below:

greetings2.html
<!DOCTYPE html>
<html lang="en">
<body>
    <script src="greetings.js"></script>
</body>
</html>
Once again, since greetings.js is in the same directory as greetings.html, we write "greetings.js" as-is inside src.

Run this HTML file in the browser. As before, you should get the following output:

Hello World!

Amazing job!

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

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

Although each of these question could get definite answers only after you know about the respective concepts in detail, it's still not totally impossible to get a gist of tehm 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 everything

From this point onwards, whenever we'd want to consider some JavaScript code, such as the one above, we'll write it directly without specifying whether it's inside a <script> tag or an external file.

Usually, it would be inside <script>, but it could be inside the latter as well. In this case, we'll mention beforehand that we're using an external file.

So, for instance, while considering the single output statement above, we'd just write:

document.write('Hello World!');

It'll be assumed that this piece of code is insdie a <script> tag which would be inside an HTML document.

Doing so helps prevent the jargon of other HTML tags and keep the focus right on the JavaScript code.

Anyways, so here's our code:

document.write('Hello World!');

The first word document is called an object. An object, in JavaScript, is an entity with properties and methods. You could think of an object in JS as an object in the real world.

For example, consider a toaster oven. It's an object with some 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.

In a similar fashion, objects work in JavaScript.

document is an object that represents the HTML document. It too has properties and methods.

write is a method of document. It writes something to the HTML document — simple as that!

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, document.write() executes whatever is inside document.write.

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 called an argument.

In this case, 'Hello World' is the argument to document.write().

'Hello World' is a string.

A string is simply a sequence of textual characters.

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

In JavaScript, a string could be denoted using 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.

Any piece of text is written inside these quotes. This makes sure that the JavaScript interpreter doesn't interpret the text as actual code — rather, it treats it literally as text.

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

What looks simple, has a ton full of concepts to explore.

Alright, just to put a slight level 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 on 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.

Literally explaining 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 that help you.

But be rest assured, we'll explain everything in detail — this time, literally in detail — throughout the course. By the end of it, you'll be able to interview professional JS developers.

Seriously!

This course captures all about JavaScript and teaches everything in plain and simple words.

Deciding between these two

So at this point you know that javascript code can go either in the script tag directly or inside a .js file that can be linked via the src attribute. Now a question arises and a fairly genuine that what to use when?

  1. Tag: The tag is usually and most preferably used when oe want to write code for a specific page. The code you put there wouldn't obviously be repeated on several pages - it is specfic to the webpage it dwells in.
  2. Separate file: The file should be used when you know that the code will be used on several pages. It seems reasonable to put repeating code under a separate file so that if an error occurs you only have to make changes in one file.
    Consider having code inside a script tag that is copy pasted on six pages. Now if an error occurs you would have to manually go to every page and rectify the issue. Seems complicated and time consuming. Huh?

Most of the websites made today use a combination of both.

Frankly speaking, the answer to this question is also fairly use-oriented i.e it depends on what you want to do and how you want to do it. For example if you're to develop a library you'll obviously write its code inside a separate .js file, but if you're to say hello to the users on your home page then you'll probably go with the <script> tag.

Fortunately for now you shouldn't be worrying about all these details as they'll come to you naturally with time, experience and as you progress through this course. At most for now you just need to appreciate the fact that JavaScript can go in two locations - the tag and a separate file.