.

Introduction to JavaScript

JavaScript and its relationship to HTML and CSS

Web development is like building a house.

The HTML language builds the house, the CSS language paints the house and the JavaScript language switches on the house.

Code house analogy

Control flow and loops, arrays and objects

Almost everything in JavaScript is an object.

JavaScript variables can contain single values. We can put the house name in a variable, which is an object.

var name ="Blue house";
 
But if we have different rooms in a house we could use an array. JavaScript arrays can contain multiple values, and each of these values can be objects, functions or also arrays.
  var houses =["Office", "Kitchen","Lounge"];
  
If we wanted to use code to switch on the w-fi for the rooms we could use a loop to apply the same switching code to each room. In the loop we could use control flow statements including if, for and while.

Functions and why they are useful

Functions are like building blocks.

They allow the code inside the function to be called many times without having to rewrite the code each time. In the house example we would only need to write the switching on code once.

The DOM and DevTools

The DOM stands for Document Object Model. It is a hierarchy structure like a tree and represents all the objects in the tree.

Let's take a look at a simple HTML DOM with HTML elements:

DOM example with HTML elements


  • Each HTML element is a node.
  • In HTML the element is created with a tag with angle brackets.
  • The tree nodes are the children that roll up to root nodes, that roll up to the document node.
  • The text within the tags is a text node. These have no children, they are called leaves.
  • All the nodes are objects and are accessible using JavaScript, starting with the document. For example, document.body is the object representing the body tag.
The rooms in the house and the function to switch on the wi-fi can be included in this DOM structure.
DOM example with wifi example

When working with websites, we can also use the developer tools ( or devtools) in the browser such as Chrome Developer Tools to explore and manipulate the associated DOM and its elements.