Lesson 2 - Getting started with JavaScript - First scripts
In the previous lesson, Introduction to JavaScript, we've been introduced to the JavaScript language. Today is the day we finally get to do a bit of programming! What we'll make today is more along the lines of code snippets which will do something simple and specific. Let's jump right into the first script. Keep in mind that if you want to work with JavaScript you have to at least be familiar with the elementary basics of HTML. If you aren't, I highly suggest you read through the course Make your first website, step by step (feel free to skip the CSS part). Unlike in server languages like PHP, we don't need to upload our scripts anywhere, we'll run them locally in our browser. By browser, I mean Chrome (preferably) or FireFox. Both contain the tools needed for script debugging, i.e. searching for errors in our scripts. Let's get right to it!
Create a new HTML page and edit the contents as shown below:
<!DOCTYPE html> <html lang="en-us"> <head> <meta charset="utf-8" /> <title>First web application in JavaScript</title> </head> <body> <script type="text/javascript"> document.write("Hello ICT.social!"); </script> </body> </html>
When you run the page in your browser, it should contain the text "Hello ICT.social!".
This is what is referred to as a Hello World application, which are used in
programming lectures when teaching/learning a new language. Let's go over what
we've actually done. When the browser displays the HTML page, it goes from top
to bottom. If it reaches the <script>
tag, it recognizes the
text inside of this tag as a source code for the JavaScript language and runs it
immediately. Once the tag is closed, it continues parsing the page. This could
lead to issues if we wanted to modify an element at the bottom of the page using
the JavaScript code at the top. The element would not be loaded by the browser
yet and wouldn't work. This is why JavaScript is often inserted into the page's
head and launched not before the page is fully loaded. However, we'll deal with
all of that later. We now have our first command set up:
document.write("some text");
Just so you know, document
is an object, which represents the
HTML document (our web page). Write
is its method, which writes the
given text at the specified place in the HTML page. Anything we change on the
page through JavaScript will be shown immediately. You should be able to see the
text "Hello ICT.social!" on the page. It's common to write a semicolon -
;
after each command, even if it isn't necessarily in
JavaScript.
Now we'll look how to work with the variables.
Variables
You should all know the word variable from your school. For all you
non-programmers, just know that it's a place in computer's memory where we can
store data and then work with it. Each variable has its data type. In
JavaScript, it can contain a number, text, boolean value (true
or
false
, more on this in the next lesson), or an object. Data types
are assigned to the variables by JavaScript itself according to what we're
currently storing in them. This is why we say that JavaScript is a dynamically
typed language (it dynamically changes the variables types according to their
contents).
All the variables in JavaScript are declared using the let
keyword! In the past, the var
keyword was used for these purposes,
which is now only used to maintain backward compatibility. Surely you'll find it
in older source codes. If you don't use a keyword at all, unlike in other
languages, you'll create a global variable which might not always be what you
want. Global variables are accessible from all the scripts which may cause
conflicts.
Let's create a few variables:
let a; // creates a variable named a, which is empty for now let b = 40; // creates a variable named b with a value of 40 c = 30; // creates a global variable named c with a value of 30 s = "Text"; // creates a global variable named s which contains a string
The code shown above creates a few numeric variables and a variable that
contains text. We wrap text in quotation marks so the compiler knows that it's
dealing with text and not the name of some other variable or function. Also,
we've now seen how comments are written in code. These are notes for
programmers, which the interpreter (your browser) ignores. To write comments,
you use two slashes - //
. If you'd like to write a multi-line
comment, use /*
and */
. With variables, we're able to
do lots of operations. Let's start with some basic addition. We can add numbers
and even strings (join two pieces of text together). All of this is done using
the +
operator.
We can even sum up a number and a String
. The interpreter
converts the number into a String
and then simply adds up both of
the String
s.
let a = 10; let b = 20; let c = a + b; document.write("The result of a and b added together: "); document.write(c); document.write("<br />"); // insert HTML tag for a new row let s1 = "10"; let s2 = "20"; let s3 = s1 + s2; document.write("The result of strings s1 and s2 added together: "); document.write(s3);
Result:
From the results of this program, you should now understand what the
difference is between a number and a String
We can also multiply, subtract, and
divide using the *
, \
, -
, /
operators respectively. Notice that we're still within the realm of HTML. If we
need a new line, we simply use the <br />
HTML tag to break
the current one.
Date and time
Let's go over how to work with date and time. This will be your very first
script that would actually be useful for your website. Everything we need can be
found in the Date
object, including both the date and time. We'll
show you how to create this object and how to work with it. We create it using
the new
keyword which will store it into a variable in the same way
it does with numbers or String
s:
let d = new Date(); // creates a variable which will contain the current date
A classic variable can't do much more than just carry a value.
Simply put, objects are smarter. If we store them into a variable, we can use
so-called methods on them. Remember the document
object and the
write
method. Working with dates is done similarly.
On the date object, we're able to call the following methods:
getDate()
- Returns the current numerical day of the month,1
is the first day.getMonth()
- Returns the current numerical month of the year. January is0
so you have to add 1.getFullYear()
- Returns the current year as a 4 digit number.getHours()
- Returns hours.getMinutes()
- Returns minutes.getSeconds()
- Returns seconds.getTime()
- This method returns the number of milliseconds since 1/1/1970, this format is used often in computer science (known as the UNIX TimeStamp).
The methods are not named very well, but we can't really do anything about it
Now, let's write the current date and time:
let d = new Date(); // creates a variable which will contain the current date document.write("Today is: " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear()); document.write("<br />"); document.write("Time: " + d.getHours() + ":" + (d.getMinutes()));
The result:
The date and time are taken from the user's computer (JavaScript runs on the client side), so if you change the time locally, it'd change on the website as well In the next lesson, Basic data types in JavaScript and its functions, we'll look at data types in more detail. All 3 source codes are available for download below in case you made a mistake (this will be the case for every one of the articles).
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 20x (2.42 kB)
Application includes source codes in language JavaScript