Leila McGlew's site by Dow-Smith Studio
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.)
JavaScript can manipulate websites, respond to user interactions, and send and receive additional information from the server.
On the web, JavaScript can:
Here are some things that JavaScript can't do on the web:
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.
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.
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>
.
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.
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.
Here are some data your variables can hold:
let pi = 3.14;
let message = 'Hello, World!';
let isLoaded = true;
Strings have three types of valid enclosing quotes:
"Hello"
'Hello'
`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.
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
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.
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)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.
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.
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.
Remix Sean Catangui's typography Glitch to make a new typographic effect.
Sign up for an account on the code sharing service Glitch, understand the existing source code, and make a variation.
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.