11. JavaScript
In this lesson, we are going to learn about computer programming and the JavaScript programming language. But, of course, you're not going to be able to learn computer programming from a single lesson. We're just going to get acquainted with the very basics.
If you decide to continue learning about web development after completing this course, I would highly recommend completing a course about JavaScript.
Java and JavaScript are not the same thing. Java is an entirely different programming language.
Java was all the rage back in the day. And somehow another language ended up having a very similar name. JavaScript and Java are completely separate and different programming languages.
In a somewhat similar vein, when I tell people that my hometown is Kansas City, they often assume that I am from Kansas City, Kansas.
Nope. I'm from Kansas City, Missouri, which was founded prior to the existence of the state of Kansas. It's about as confusing as the relationship between JavaScript and Java :)
Client-side and server-side
In a previous lesson, you were introduced to the concept of server-side and client-side programming languages.
With server-side programming languages, such as PHP, the interpreter program runs on the web server.
With client-side programming languages, the interpreter runs on the user's computer. The interpreter is also sometimes referred to as the "engine".
So, a server-side programming language sends instructions to the server. And a client-side programming language sends instructions to the user's computer.
When you view the source code of a web page, you will never see any server-side programming code. But you can see all of the client-side code.
For example, when you view the source of a page, you will never see any PHP code. But you can see all of the HTML, CSS, and JavaScript code that is being used.
Although JavaScript is now being used by many on the server side, JavaScript has primarily been used on the client side since its inception.
For our purposes, we will be focusing on the use of JavaScript on the client side.
Client-side programming languages run on the user's computer.
Browsers, such as Chrome and Firefox, have a built-in JavaScript engine that processes the scripts. Much of the real-time, interactive content you find on modern websites is powered by JavaScript.
Implementing JavaScript
In-page
JavaScript code can be used in the head or body of your HTML. And your code must be enclosed within an HTML <script>
element.
Here is a very basic example of declaring a function
in the head that will be executed when a button is clicked:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Odd Website</title>
<script>
function makeSandwich() {
alert("Sorry. JavaScript can't do that!");
}
</script>
</head>
<body>
<button onclick="makeSandwich()">Make Sandwich</button>
</body>
</html>
You can also place your <script>
element that contains Javascript code right before the </body>
tag, like I have done in the Practice 11 example.
There are performance advantages to this approach. But it's not that important while learning. You'll learn about this if you decide to learn more about JavaScript after completing this course.
External reference
Optionally, you can place your JavaScript code in a separate file.
In order to use an external JavaScript file, you use the <script>
element—with a value for src
that provides the path to the JavaScript file. JavaScript files are named with a .js
extension.
<script src="js/make-sandwich.js"></script>
The URL provided by the src
attribute above says that there is a folder named js
. And inside that, there is a file named make-sandwich.js
.
This is the contents of the make-sandwich.js
file:
function makeSandwich() {
alert("Sorry. JavaScript can't do that!");
}
I have also created a practice 11 example that uses an external JavaScript file. Right-click on the page and select "View page source" to see the code.
Programming basics
These are some basic concepts that you will find in most programming languages. The syntax will vary from language to language. But the underlying concepts remain the same.
Variables
A variable stands in place of some value.
For example, in this case I am creating a variable named fruit
and making it equal to "banana":
let fruit = "banana";
So, if I then used this JavaScript code...
window.onload = function() {
alert(fruit);
}
...when the page finishes loading, an alert window would pop up containing the word "banana".
Data types
Strings
A string is a sequence of characters. For example, "banana" is a string. And when using strings, they are enclosed in quotes.
let truth = "Cats like strings.";
Numbers
Quotes are not used for numbers.
let myNumber = 12;
Booleans
"Boolean" means that only two values are possible: true
or false
let raymondHungry = true;
Arrays
An array is a group of things stored together.
let groceries = ['pie','beer','chicken'];
If I used groceries[0]
in my code, it would refer to pie
.
The numbering begins with zero.
And groceries[1]
would refer to beer
.
And groceries[2]
is chicken
.
forEach
In JavaScript, forEach
allows you to go through the values in a list of things and do something with each one.
For example, if I wanted to output my groceries
array as an HTML list, this might be a portion of the code used:
groceries.forEach(function(item) {
htmlCode += '<li>' + item + '</li>';
});
This is saying that for each item
in the groceries
array, place the value inside of an HTML list item element (<li>
).
You can see an example of using foreach
here.
Functions
A function is some code that does something. And that code can be referred to by a single name:
function nameOfTheFunction() {
/* CODE TO DO STUFF HERE */
}
Optionally, you can put variables (called arguments) in the parentheses. Then the function can use that when calculating the result.
function addThree(myNumber) {
result = myNumber + 3;
document.write(result);
}
Then if you "call" the function:
<script>addThree(17);</script>
20
would be printed on the page.
You can see an example with an addThree()
function here.
There are some issues involved with using document.write()
. But it's fine to use while learning.
if/else statements
An if
statement checks to see if something is true. If it is true, the code between the curly brackets will be executed.
And you can use else
to provide some alternative code to use if it is not true:
if (myNumber > 9) {
message = "This number is greater than 9!";
}
else {
message = "This number is NOT greater than 9!";
}
Operators
I'm not going to discuss every operator here. So, feel free to check out this resource on JavaScript operators.
But, I will address one common area of confusion: equals signs
Assignment operators
When one equals sign is used, it is an assignment operator.
So, when I used this:
let myNumber = 12;
I was using an assignment operator. I used one equals sign to make myNumber
equal to 12.
Comparison operators
When two equals signs are used, it is a comparison operator.
If I wanted to compare two values, I would use two equals signs:
if (myNumber == 12) {
response = "This number is equal to 12!";
}
In this case, I am using a comparison operator. I used two equals signs to check if myNumber
is equal to 12.
Strict comparison operators
You can also use 3 equals signs as a comparison operator, such as:
if (MyNumber === 12) {
response = "This number is equal to 12!";
}
When three equals signs are used, both the values and the types are compared. This is referred to as a strict comparison.
In this example, the type is number
—since the value is a number that is not contained within quotes.
So, if myNumber
was a string, such as in this example...
let myNumber = "12";
A comparison with three equals signs would return false
. Although both values are "12", they have different types.
One is an number
and the other is a string
.
Events
You can instruct a JavaScript function to run when some event has occurred.
HTML event attributes
In this example...
<button onclick="makeSandwich()">Make Sandwich</button>
We have used the HTML onclick event attribute to make the makeSandwich()
function run when the button is clicked.
Another very commonly-used event is onload. This allows you to execute a function after the page has finished loading.
You can see a full list of HTML event attributes here.
JavaScript events
You can also make JavaScript functions run without using HTML attributes.
This would make the code between the curly brackets run when the page has finished loading:
window.onload = function() {
}
Let's say that the HTML for my page contains a div
element with an ID named "monkey".
<div id="monkey"></div>
In my JavaScript code, I could select that element using getElementById()
:
let monkey = document.getElementById('monkey');
I've created a variable named "monkey". And that variable name can now be used to represent that div.
And I can use innerHTML
to insert anything I would like into that div:
window.onload = function() {
let monkey = document.getElementById('monkey');
monkey.innerHTML = "MONKEY!";
}
Once the page loads, the text "MONKEY!" will be inserted into that div.
You can see an example of using window.onload
here.
It is common practice to use "camel case" when naming variables and functions in JavaScript.
The name begins with lowercase letters, then the first letter of subsequent words are capitalized, such as: camelCase
Students sometimes have problems when using getElementById
. The "E", "B", and "I" must be capitalized and all other letters must be lowercase. This is case-sensitive.
Also note that innerHTML
is different, since each letter in "HTML" must be capitalized.
JavaScript objects
If I was to explain this to you like you are five, I would say "The objects are the things before the dots":
window.onload = function() {
let monkey = document.getElementById('monkey');
monkey.innerHTML = "MONKEY!";
}
window
, document
, and monkey
are objects.
An object is a collection of information and/or functionality that can be referenced by a single name.
Objects are made up of methods and properties.
Methods are simply functions that are part of an object. They do things. And you can tell they are methods by the parentheses after the name, such as getElementById()
.
And properties are variables that are part of an object. They contain information. For example, innerHTML
is a property.
Selecting and styling
You can select elements in the page with JavaScript, just like we have done with CSS.
In the previous example, we used the getElementById()
method. There are many properties and methods like this available in JavaScript for selecting and altering elements in the page.
The querySelector() method allows you to use selectors like you would use in CSS:
let menuLink = document.querySelector('.primary-menu a');
However, that will only return the first element that matches that selector. If you wanted to select multiple elements, you could use querySelectorAll()
:
let menuLinks = document.querySelectorAll(".primary-menu a");
menuLinks.forEach(function(menuLink) {
menuLink.style.backgroundColor = "white";
});
This would select all <a>
elements inside the element with the class "primary-menu" and give them a white background color.
I haven't specified an event here. So, it would need to be wrapped within a function that is triggered upon some event.
You can see an example of selecting and styling elements here.