2. to 1. How 3. Code

2. to 1. How 3. Code

An opinionated approach to making websites.

Home

2. to 1. How 3. Code

3. Script I

Leila McGlew's site by Dow-Smith Studio

What is JavaScript?

JavaScript was created to make webpages come alive.

It was initially called LiveScript, but it was renamed JavaScript to cash in on the popularity of the Java programming language. JavaScript is not based on Java. (CoolScript was also briefly considered.)

What is JavaScript used for?

JavaScript can manipulate websites, respond to user interactions, and send and receive additional information from the server.

On the web, JavaScript can:

  • Add new HTML to the page and change the CSS of elements.
  • Respond to the user's mouse clicks to create a slideshow.
  • Upload files and validate the data submitted in a form.
  • Draw dynamic 3D graphics and create sounds.

Here are some things that JavaScript can't do on the web:

  • Access other tabs/windows in your web browser
  • Access files on your computer (unless you explicitly upload a file)

Programming language vs. API vs. Platform

These words may seem arcane, but they convey important distinctions between parts of code.

JavaScript is a programming language, which means it defines a syntax with certain semantics or building blocks for code. This is JavaScript:

let i = 1;
i = i + 3
// 4 (this is a comment, which means JavaScript ignores it)

An application programming interface or API is a means of accessing capabilities on a certain platform, like Google Chrome. You need APIs for your code to have an effect on something concrete. Here are the APIs (Document.getElementById() and Element.classList) to add a class to an element:

let el = document.getElementById('item');
el.classList.add('myclass');

A platform or runtime is the combination of an environment (the browser), a programming language (JavaScript), and the capabilities the environment exposes (APIs).

The browser is the platform on which your web page is running. Node.js is a platform which lets you run JavaScript programs on your computer. Both platforms expose different APIs and have different capabilities. Node.js, for example, does not expose the Document.getElementById(), for example, so the above code will not work on Node.js.

Much of the complexity of coding involves navigating particularities of different environments and APIs, not necessarily learning the programming language itself.

Hello World

Let's get started.

Add a script element somewhere on your webpage:

<script>
  console.log( 'Hello, world!' );
</script>

console.log is how you print things from your code.

This will have no effect on the website itself. You must open the Developer Console in Google Chrome to see the result.

External Scripts

If you're writing a lot of JavaScript, you should move it into an external file, similar to how you can write CSS in an external file.

Simply add this line to the head of your HTML:

<script src="/path/to/script.js"></script>.

Basic JavaScript

The best resource for learning modern JavaScript is a site called Javascript.info. MDN is still a great resource for JavaScript, although it has less of a linear curriculum. I will link to the relevant pages where you should read more detail about the following topics.

Variables

A variable is a way to store data with a name. You might use a variable to store a number, some text, or an HTML element.

Here's how to declare a variable and put some data into it via an assignment (=).

let numberOfVisitors;
numberOfVisitors = 4;

JavaScript statements are usually written on separate lines, each ending with a semicolon. We can simplify our code by declaring and assigning a variable on one line:

let numberOfVisitors = 4;

JavaScript, like any programming langauge, is very picky about the exact characters which comprise your code.

Variables must contain only letters, digits, and the symbols $ and _. Variables may not start with a number. Case matters: mydata and myData are different. The latter is usually how developers write multiple-word variables.

You may see var used instead of let in other code online. let is the more modern version and almost the same. For now you can substitue let for var.

You can update the value of a variable if the data you want to store change.

let numberOfVisitors;
numberOfVisitors = 4;
// someone leaves
numberOfVisitors = 3;

Read more about variables here.

Data Types

Here are some data your variables can hold:

  • Numbers: let pi = 3.14;
  • Text, or strings: let message = 'Hello, World!';
  • A boolean (logical type): let isLoaded = true;
  • An object (like an HTML object)

Strings

Strings have three types of valid enclosing quotes:

  • Double quotes: "Hello"
  • Single quotes: 'Hello'
  • Backticks: `Hello`

Backticks are useful because they allow data to be embedded into the string

let name = 'Max';
let message = `Hello ${name}!` // Hello Max!

Read more about data types here and see how they can be converted.

Objects

An object is a way to build up complex entities from the primitive values.

Objects have properties, or "key: value" pairs. The key is a string or a name for the property and the value is a piece of data.

Here's how to create an object that represents a person:

let user = {
  name: 'Max',
  age: 30
};

Note the comma between the properties. In the first property, the key is 'name' and the value is 'Max'.

You can later access the data in the object by typing either:

console.log(user.name); // Max
console.log(user['name']); // Max

The latter is useful if your key is stored in a variable:

let key = 'name';
console.log(user[key]); // Max

Special Objects

Two useful types of objects with special syntax are arrays and functions.

Arrays are a way to store ordered collections of data.

let fruits = ["Apple", "Orange", "Plum"];

Array elements are numbered, starting with 0. You can access array elements like this:

console.log(fruits[0]); // Apple
console.log(fruits[2]); // Plum

You can also find the length of an array like this:

console.log(fruits.length) // 3

Read more about arrays here.

Functions

Up until now, we haven't learned how to really do anything. Functions are the first way to start making your site do something!

Functions are a way to create a building block of code that can be repeated many times.

function sayHello(name) {
  console.log(`Hello ${name}!`);
}

sayHello('Max'); // Hello Max!
sayHello('Emily'); // Hello Emily!
sayHello('Andrew'); // Hello Andrew!

After the function keyword comes the name of your function, and then a list of parameters between parentheses. Inside the curly brackets live the function body or the main code for the function.

Parameters are available within the function body like variables. Variables declared within the function body are only visible within the body (however you can access variables outside the function from within).

Functions can also return a value which the calling code can access or assign.

function add(n1, n2) {
  return n1 + n2;
}

console.log(add(1, 3)) // 4
let sum = add(2, 4)
console.log(sum); // 6

Read more about functions here and make sure you understand the alternate ways to write functions here.

In addition to writing your own functions, you can call builtin APIs to accomplish certain functionality. APIs are really just builtin functions. JavaScript has some of its own and the browser exposes even more.

Here are a few useful ones:

  • let element = document.querySelector('.myclass'); (returns the first matching element from the CSS selector)
  • let elements = document.querySelectorAll('.myclass'); (returns an array of elements)
  • let rand = Math.random(); (returns a random number between 0 and 1)
  • let result = Math.sin(40); (calculates the sine of an angle in radians)

Some builtin functions are actually properties of objects returned by other functions.

These functions are called methods.

  • element.classList.add('myclass');
  • element.classList.remove('myclass');
  • element.classList.toggle('myclass');

An API doesn't just mean a builtin function. It can also refer to the other properties available on objects associated with the method:

  • console.log(element.classList); (prints an array of the element's classes)
  • console.log(element.style); (prints the inline style of an element)
  • console.log(window.pageYOffset); (prints the amount of pixels the page is currently scrolled along the verical axis)

Sometimes setting new values on these exposed properties can have effects.

  • element.style.fontSize = '14px'; (sets an element's font-size CSS property dynamically)

How to Code

You've now learned how to accomplish any single thing in code!

Making anything happen on your webpage is just a matter of finding the correct API for the job and calling a method or setting a particular property.

For example, you could Google 'how to change the title of my wepage JS' to discover the document.title property.

The MDN introduction to APIs is also very useful.

We'll talk more about browser APIs next week, but you can also read more here.

Making decisions in code

In order to write code that makes things happen conditionally, you will need to use if/else statements.

let name = prompt('What is your name?')
if (name.startsWith('A')) {
  console.log( 'Your name is at the beginning of the alphabet.' );
} else {
  console.log( 'Your name falls later in the alphabet.' ); // any other letter
}

The entire else block is optional.

Read more about conditionals here and ways to compare data here.

Repeating things in code

Often when making websites we need to repeat certain code a specific number of times. A for loop allows us to repeat something a dynamic number of times:

let elements = document.querySelectorAll('img'); // all images
for (let i = 0; i < elements.length; i++) {
  let element = elements[i];
  element.classList.add('fadein');
}

Read more about loops here.

Assignment 8: Remix a typography Glitch

Remix Sean Catangui's typography Glitch to make a new typographic effect.

Wavy Wavy Glitch

Sign up for an account on the code sharing service Glitch, understand the existing source code, and make a variation.

Assignment 9: Add JavaScript to your personal site

From here on out, your goal should be to incorporate as much of your desired functionality as you feel capable.

Each week we will learn new capabilities and functionality for you to incorporate with JavaScript.