JavaScript

Submitted by coleen.yan@edd… on Wed, 02/08/2023 - 16:34
Sub Topics

A website is like a house: HTML is the frame (it organises and presents elements of a webpage); CSS is the look (how the house is decorated and styled); and JavaScript is the moving pieces (what you interact with—electricity, water and gas). When you switch the light switch, the lights turn on. JavaScript handles the interactions and provides rules and logic to determine what happens next.

JavaScript (JS) is one of the most-used programming language in the world. JS is one of the 3 core languages of web development. What are the other 2?

The 3 core languages:

  • HTML (Content)

    Nouns
    <p></p> means 'paragraph'.

    The HTML5 logo
  • CSS (Presentation)

    Adjectives
    p { color: red; } means 'the paragraph text is red'.

    The CSS3 logo
  • JS (Dynamic effects/programming)

    Verbs
    p.hide(); means 'hide the paragraph'. 

    The JavaScript logo

To help understand how HTML, CSS and JS all work together, take a look at the following video.

JavaScript (JS) is a lightweight, cross-platform, object-oriented computer programming language.

  • Lightweight: not using much memory, simple syntax.
  • Cross-platform: language can be used on many devices and systems.

There are many JavaScript libraries and frameworks (such as jQuery or AngularJS) that help developers build complex apps more easily. All are based on JS.

JS is what makes modern web development possible through:

  • dynamic effects
  • interactions and logic.

Anatomy

A diagram depicting the anatomy of JavaScript
  1. Object (where)
  2. Method
  3. Action
  4. Paramater (which/content)

JavaScript (JS) example

<script type="text/javascript">
  console.log("Hello, world!");
  alert("Hello, world!");
</script>

JavaScript syntax/tags

JavaScript can be implemented using JavaScript statements that are placed within <script></script> tags in a webpage.

You can place the <script></script> tags, containing your JavaScript, anywhere within your webpage, but it is normally recommended that you should link it to an external JS sheet in the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear as follows:

<script type="text/javascript">
  Your JavaScript goes here...
</script>

'Data types' are used to classify one particular type of data in programming languages. For instance, a number and a string of characters are different types of data that will be treated differently by JS.

This is important because the specific data type you use will determine what values you can assign to it and what you can do to it. This is to say, to be able to do operations with variables in JS, it is important to understand the data type of any given variable.

The following are the basic types of data used in JS.

Strings

A 'string' is a sequence of one or more characters (letters, numbers, symbols). Strings are useful in that they represent textual data.

In JS, strings exist within either single quotes ' or double quotes ", so to create a string, enclose a sequence of characters in quotes:

var singleQuotes = 'This is a string in single quotes.';
var doubleQuotes = "This is a string in double quotes.";

You can choose to use either single quotes or double quotes, but whichever you decide on, you should remain consistent within a program.

The program Hello, World! demonstrates how a string can be used in computer programming, as the characters that make up the phrase 'Hello, World!' in the alert() below are a string:

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    function greet() {
      alert("Hello, world!");
    };
  </script>
</head>

<body>
  <button onclick="greet()">Click me</button>
</body>

</html>

As with other data types, we can store strings in variables:

var hw = "Hello, world!";

And display the string in the alert() by calling the variable:

<!DOCTYPE html>
<html>

<head>
  <script type="text/javascript">
    var hw = "Hello, world!";

    function greet() {
      alert(hw);
    };
  </script>
</head>

<body>
  <button onclick="greet()">Click me</button>
</body>

</html>

Strings are important for communicating information to the user, and for the user to communicate information back to the program.

Booleans

The Boolean data type can be one of two values—either true or false. Booleans are used to represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science.

Many operations in maths give us answers that evaluate to either true or false:

  • greater than:
    400 > 200; // => true 
    1 > 4; // => false
  • less than:
    200 < 300; // => true 
    4 < 3; // => false
  • equal to:
    4 == 4; // => true 
    600 == 400; // => false

As with other data types, we can store a Boolean value in a variable:

var myBoolean = 5 > 7; // => false

Since 5 is not greater than 7, the variable myBoolean has the value of false.

As you write more programs in JS, you will become more familiar with how Booleans work and how different functions and operations evaluating to either true or false can change the course of the program.

Arrays

An 'array' can hold multiple values within a single variable. This means that you can contain a list of values within an array and iterate through them.

Each item or value that is inside an array is called an element. You can refer to the elements of an array by using an index number.

Just as strings are defined as characters between quotes, arrays are defined by having values between square brackets ([]).

An array of strings, for example, looks like this:

var seaAnimals = ["shark", "cuttlefish", "clownfish", "eel"];

If we call the variable sea animal, we’ll receive the following output:

["shark", "cuttlefish", "clownfish", "eel"];

Arrays are a very flexible data type as they are mutable in that they can have element values added, removed and changed.

Objects

The JS 'object' data type can contain many values as key: value; pairs. These pairs provide a useful way to store and access data. The object literal syntax is made up of key: value; pairs separated by colons with curly braces on either side ({}).

Typically used to hold data that are related, such as the information contained in an ID, a JS 'object literal' looks like this, with whitespaces between properties:

var jessica = { firstName: "jessica", lastName: "smith", color: "red", location: "sand" };

Alternatively, and especially for object literals with a high number of key: value; pairs, we can write this data type on multiple lines, with a whitespace after each colon:

var jessica = {
  firstName: "jessica",
  lastName: "smith",
  color: "red",
  location: "sand"
};

The object variable 'jessica' in each of the examples above has 4 properties: firstName, lastName, color, and location. These are each passed values separated by colons.

Enhance a basic webpage using CSS and JavaScript

Instructions:
Using the basic HTML page you have created in the previous topic, enhance the experience by adding a few of the following:

  • background color
  • background image
  • pop-up message
  • or other functionalities using CSS and JavaScript.

Share a screen capture of your enhanced webpage in the forum.

The Document Object Model (DOM), represents a web page and the element that make up its content as objects.

A diagram depicting an example of DOM Nodes
Adapted from DOM Nodes, © Refsnes Data

The DOM provides a set of functions we can use in JavaScript, to create select and manipulate elements on a webpage.

For example, the following line of JavaScript will select the body element with the document and add the background style of "blue".

// Change the background color to blue.
document.body.style.background = "blue";

This video covers, querying the DOM using the getElementById() method.

Have a look at the following example that applies styles and innerHTML to the boxes when the change button is pressed.

One common use of JavaScript is to validate form data before it is passed to a server.

In JavaScript, we can use the getElementById() method to select unique elements and test their values against certain criteria.

The example below uses the getElementById() method to store the objects "drink" and "name". It then tests the value attribute stored in "drink" to see if it matches "fruit juice". If there is a match the first alert message is displayed. If there is no match the second alert message is displayed.

We use the double equals (==) to test if two values are the same. We can test if values are not equal using !=, or we can use > or < for greater than or less than.

To test if a person is over the age of 21, you could use an if statement like the following:

if (age >= 21)

In this topic, we provided an introduction to JavaScript. JavaScript (JS) is one of the most-used programming language in the world. It is what makes modern web development possible through:

  • dynamic effects
  • interactions and logic.

JavaScript is made up of an object (where), method, action, and parameter (which/content). It is implemented using JavaScript within <script></script> tags in a webpage.

We covered different JS data types including strings, booleans, arrays, and objects.

We introduced the concept of DOM manipulation. The DOM represents a web page and the element that make up its content as objects. It provides a set of functions we can use in Javascript, to create select and manipulate elements on a webpage.

JavaScript can be used to validate data before it is passed to a server. This makes it helpful when creating forms.

Knowledge check

Module Linking
Main Topic Image
Lines of JavaScript displayed in a text editor on a laptop
Is Study Guide?
Off
Is Assessment Consultation?
Off