JavaScript Introduction

Separation of Concerns

So far we’ve looked at how to create content with HTML and style it with CSS. Now, we’ll learn how to transform and manipulate our content dynamically using JavaScript.
HTML
CSS
JavaScript
Content
Style
Behavior
What it says
What it looks like
What it does

Writing JavaScript in your browser

Chrome’s Web Inspector has a powerful JavaScript console built into it. You can access the console by going to View > Developer > JavaScript Console, or by selecting the Console tab when Dev Tools is open.
With the console open, you can execute JavaScript directly in your browser and see the updates live.

Adding JavaScript to your website

Adding JavaScript to your website can be done either directly inline in your HTML document, in between <script></script> tags, or preferably in an external JavaScript file, similar to how you link an external CSS file.

<script src="main.js"></script>

The JavaScript file can be linked from anywhere in the <head> or <body> element, but usually you will add it in the <head>, right after your CSS file, or at the very end of your document, before the closing </body> tag. It’s a good practice to add it to the end of your document so that downloading the script doesn’t block the rendering of your HTML page.

<!DOCTYPE html>
<html>
<head>
  <title>Document</title>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- Your HTML goes here. At the very end of the document, right before the closing </body> tag, include your javascript. -->
  <script src="/js/main.js"></script>
</body>
</html>

Data Types

A data type in programming languages is an important concept as it means that a particular piece of data can be acted upon with a particular set of actions. For example, adding two numbers together will lead to obvious results, but adding two strings together lead to a different results.

1 + 1         // 2
'cat' + 'dog' // 'catdog'
'1' + '1'     // '11'

Some common data types that we will be using are strings numbers booleans and arrays.
'core interaction'         // String
16                         // Number
true                       // Boolean
false                      // Boolean
[1, 2, 'three', 'four', 5] // Array
{                          // Object
  key1: 'item 1',
  key2: 'item 2'