Skip to content

M02 - JavaScript - part 1

Introduction

This material does not list all the JavaScript features like a manual. The presentation tries to be concise, taking into account that the reader has basic knowledge of HTML, CSS and the basics of programming (variables, selection and repetition structures, etc.)

Here a few good resources:

JavaScript is mostly used inside a HTML document in Web browser. JavaScript code will be executed at the same time when HTML are displayed in Web browser. Code will be executed with some JavaScript engine in a browser (for example Googlen V8, Firefox IonMonkey). JavaScript language conforms to the ECMAScript standard and are historically based/started in 1995 Netscape, name was then LiveScript.

With JavaScript developers can modify HTML document structure and content to create interactive UI'. There are also more advanced server side versions of JavaScript such as Node.js, which allow developer to add more functionality to a website than downloading files (such as realtime collaboration between multiple computers). JavaScript contains a standard library of objects, such as Array, Date and Math, and a core set of language elements such as operators, control structures, and statements.

Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.

Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.

Include JavaScript to HTML document

There are three different ways to include JavaScript to HTML document.

  • as external file <script src="skripti.js"></script> <- BEST
  • using a script element <script>alert('Haloo');</script>
  • inline with some element <body onload="alert('Haloo')">

Below example will display "Hello World" text in web browser.

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
</head>

<body>
<script>document.write('Hello World!')</script>
</body>
</html>

Debugging with console.log() command

Developer can use console.log() command to display text to web browser's console. You can open console by pressing F12. This is very handy and easy way to debug your JavaScript code.

Below example uses a few console.log() commands to display values in browser's console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
</head>

<body>
<h3>Open your Web Console to see changes</h3>
<script>
console.log('First row');
console.log('Second row');
console.log(variable);
</script>
</body>
</html>

You should see below in your HTML and Web Console.

Image 01

Note

You should see warning about using a undefined variable.

You can also use Chrome degugging tools to debug your application in web browser. Here is one good link to start with : https://developer.chrome.com/docs/devtools/

Modifying HTML content

Developer can use getElementById() command to find a specific node from the HTML document. We will heavily change the content of the HTML document later, but now this is just a small example to help start working with exercises.

Changing HTML content example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<head>
<script>
function show() {
  document.getElementById("demo").innerHTML="Hello from function!";
}
</script>
</head>

<body>
  <div id="demo"></div>
  <button type="button" onclick="show()">Click Me!</button>
</body>
</html>
  • line 12 has empty div where a new content will be added
  • show function will be called after user has clicked a button at line 13
  • show function will find a demo div location using a getElementById() command
  • a new content will be added using a innerHTML property
  • as a result line 12 will be <div id="demo">Hello from function!</div>

Playground - jsbin.com

Of course it is quite an easy to just write a HTML/CSS and JavaScript code, save file and open it to browser. But you can speed up your learning using with some playgrounds.

Open jsbin.com in your web browser and copy and paste above code in there.

Image 02

  • Developer can activate different tabs: HTML, CSS, JavaScript, Console and Output
  • Developer can write JavaScript code directly and modfied code can be run without saving any files

Variables

You can define variable using a const, var or let keywords (or nothing). You are using variables for storing your application data (storing data values).

1
2
var number = 10;
var name = "Kirsi Kernel";
1
2
let number = 10;
let name = "Kirsi Kernel"
1
2
const number = 10;
const name = "Kirsi Kernel"

or even like this

1
2
number = 10;
name = "Kirsi Kernel";

Note

  • Always declare JavaScript variables with var, let or const.
  • The var keyword is used in all JavaScript code from 1995 to 2015.
  • The let and const keywords were added to JavaScript in 2015.
  • Use let if variable value can be changed and const if not.
1
2
3
4
const price1 = 5; // value can't be changed later
const price2 = 6; // value can't be changed later

let total = price1 + price2;

All JavaScript variables must be identified with unique names. Variable can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _
  • Names are case sensitive
  • Reserved words (like JavaScript keywords) cannot be used as names

Differences between var and let:

  1. let cannot be redeclared
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var name = "Pekka";
var name = "Kirsi"
console.log(name);
// displays Kirsi

let name = "Pekka";
let name = "Kirsi"
console.log(name);

// displays "SyntaxError: Identifier 'name' has already been declared"
  1. let has block scope declaration
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  var x = 2;
}
console.log(x);
// displays 2

{
  let x = 2;
}
console.log(x);
// displays "ReferenceError: x is not defined"

Arrays

An array is a special variable, which can hold more than one value. It is a common practice to declare arrays with the const keyword. It does NOT define a constant array. It defines a constant reference to an array. Because of this, developer can still change the elements of a constant array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:
cars[0] = "Toyota";

// You can add an element:
cars.push("Audi");

// Display array length
console.log(cars.length); // 4

// Loop array
for (let car of cars) {
  console.log(cars.indexOf(car) + ':' + car);  
}

Will display as

1
2
3
4
"0:Toyota"
"1:Volvo"
"2:BMW"
"3:Audi"

Find more information from here: Arrays

Loops

You can use many traditional loops in JavaScript: while, do while, for, for in and for of.

Example: for of

1
2
3
4
5
let results  = [1,2,3];

for(let result of results) {
  console.log(result);  
}

Will display as:

1
2
3
1
2
3

Functions

Functions are very important part of JavaScript programming. Developer can define a function many different ways in a JavaScript: as a traditional named function, anonym function, array function, callback function, etc...

Example: Named function

1
2
3
4
5
6
7
8
// define function
function calculateSum(a,b) {
  return a+b;
}

// call function
let sum = calculateSum(5,6);
console.log(`Sum is ${sum}`);

Will display as:

1
Sum is 11

Find more information from here: function declaration.

Example: Arrow function

1
2
3
4
let calculateSum = (a, b) => a + b;

let sum = calculateSum(5,6);
console.log(`Sum is ${sum}`);

Note

If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword!

We will discuss other function types later in the course materials.

Reading values from HTML form elements

This small demo shows how developer can read values from HTML form elements. You can use this example later in JavaScript exercises.

Image 03

Call showName function with form data (firstname, lastname) values. Values will be shown in results div.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript and form</title>
  </head>

  <body>
    <h1>Display name</h1>
    <form id="f">
      Firstname<br>
      <input type="text" id="firstname"><br>
      Lastname<br>
      <input type="text" id="lastname"><br><br>
      <button type="button" onclick="showName(f.firstname.value, f.lastname.value)">
        Show name
      </button>
    </form>
    <div id="results"></div>
    <script>   
      function showName(a, b) {  
        let div = document.getElementById("results"); 
        div.innerHTML = "<h3>" + a + " " + b + "</h3>";
      } 
    </script>
 </body>
</html>