4. JavaScript
Let’s dive in to JavaScript now! The JavaScript code that we will be writing during this semester will be run via the browser. As described in the last part on CSS, you can open the developer tools of your browser. There you’ll also find the console. You can type any JavaScript command you like into the console, run it, and the browser will interpret the code for you.
JavaScript is a programming language commonly used in web development to add interactivity and dynamic behavior to web pages. It allows developers to create responsive user interfaces, manipulate HTML and CSS, and perform asynchronous data requests to web servers. JavaScript is a client-side language, meaning it runs in the user's web browser rather than on the web server, and is widely supported by modern web browsers.
Let’s go over the most important concepts:
1. How to connect your Java Script Code with your HTML?
To connect your JavaScript script with your HTML document, you need to link the JavaScript file to your HTML file using the <script>
tag. Insert the name of your JavaScript file in quotation marks using the src attribute. Here's how you can do it:
In your HTML file, add a <script>
tag inside the <head>
or <body>
section. Specify the source file using the src
attribute and set it to the path of your JavaScript file. You can also add your JavaScript code directly inside the <script>
tag using the script
element
HTML file:
// Exemplarary HTML file
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<button onclick="showMessage()">Click me!</button>
</body>
</html>
// Exemplary java_script.js file
function showMessage() {
alert("Hello, World!");
}
2. What Console Log is and why is it really convenient?
console.log
is a built-in JavaScript function that allows you to output text or other data to the browser console. The console is a debugging tool that allows you to see the output of your code and any errors that might occur.
console.log
is useful for beginners because it allows you to see what your code is doing and to debug any issues that might arise. For example, you can use console.log
to output the value of a variable, to see if a certain block of code is being executed, or to check the results of a function.
let x = 5;
console.log(x); // Output: 5
3. Variables in JavaScript
In JavaScript, variables are used to store values for later use. There are three ways to create a variable in JavaScript: var
, let
, and const
. var
is used for variables that should be globally or locally available. let
and const
are used for variables that should only be available within a block or function.
// Example of a variable created with var
var x = 5;
console.log(x); // Output: 5
// Example of a variable created with let
let y = "Hello, world!";
console.log(y); // Output: Hello, world!
// Example of a variable created with const
const z = true;
console.log(z); // Output: true
The difference between let
and const
is that let
is used for variables that can change their value, while const
is used for variables whose value should not change.
4. Data Types in JavaScript
JavaScript supports different data types, including strings, numbers, booleans, arrays, and objects. There are also special values such as null
and undefined
.
Arrays are an important data type for coding!
// javascript file
Example of a string
let name = "John Doe";
console.log(name); // Output: John Doe
// Example of a number
let age = 30;
console.log(age); // Output: 30
// Example of a boolean
let isStudent = true;
console.log(isStudent); // Output: true
// Example of an array and access of the first element in the array
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // Output: apple
// Example of an object
let person = { name: "John", age: 30 };
console.log(person.name); // Output: John
5. Functions in JavaScript
Functions are blocks of code that can be reused. They can accept parameters and return values. We will definitely need them for our project!
// javascript file
// Example of a function that adds two numbers
function addNumbers(num1, num2) {
return num1 + num2;
}
let sum = addNumbers(5, 10); // Calling the function with arguments and assigning the return value to a variable
console.log(sum); // Output: 15
6. Arrow Functions in JavaScript
JavaScript arrow functions are a shorthand syntax for creating functions in JavaScript. They provide a more concise way of writing function expressions, especially when using them as arguments to other functions.
Here's an example of how to write a traditional function
// javascript file
function add(a, b) {
return a + b;
}
And here's how you can write the same function using an arrow function:
// javascript file
const add = (a, b) => a + b;
As you can see, the arrow function syntax is more concise, with less boilerplate code.
There are a few key features of arrow functions:
Arrow functions use a
=>
operator to separate the parameter list from the function body.If the function has only one parameter, you can omit the parentheses around the parameter list.
If the function body contains only one expression, you can omit the curly braces and the
return
keyword.
Here's an example of an arrow function that uses all of these features:
// javascript file
const double = x => x * 2;
In this example, the arrow function has one parameter x
, and it returns the result of x * 2
without using the return
keyword.
Overall, arrow functions are a useful tool for writing more concise and readable code in JavaScript. They are especially useful when working with functional programming concepts like higher-order functions and callbacks.
7. Conditional Statements aka if-Statement:
Conditional statements allow a program to make decisions based on certain conditions.
It must be defined what happens if the condition defined in the round brackets is true as well as in the case when the condition is not met.
// Some code
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
If the value of the variable age is higher then 18 in the console the String "You are an adult." will be outputted.
If it is not true the code in the else case will be run.
8. Loops: For & While Loops
Loops are used to execute code repeatedly until a certain condition is met. It saves you lots of time because you can run one line of code repeatedly.
// javascript file
// Example of a for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Example of a while loop
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
9. Scopes (block, lexical)
In JavaScript, a scope determines the visibility and accessibility of variables and functions within your code. There are two types of scopes in JavaScript: block scope and lexical scope.
Block scope: A block is any section of code within curly braces
{}
. Variables and functions declared within a block are only accessible within that block and any nested blocks. This is known as block scope.
Here's an example of a variable declared within a block scope:
// Some code
function foo() {
if (true) {
let x = 10;
console.log(x); // Output: 10
}
console.log(x); // ReferenceError: x is not defined
}
In this example, x
is declared within the if statement block, so it's only accessible within that block. If we try to access x
outside of the block, we'll get a ReferenceError.
Lexical scope: Lexical scope refers to the way JavaScript variables are resolved based on their location within nested functions. A function can access variables defined within its own scope, as well as any variables defined within its parent scope.
Here's an example of a variable declared within a lexical scope:
// Some code
function outer() {
let x = 10;
function inner() {
console.log(x); // Output: 10
}
inner();
}
outer();
In this example, inner()
is nested inside outer()
, so it has access to the x
variable defined in outer()
.
Overall, understanding scopes is important for writing efficient and organized code in JavaScript. By limiting the scope of your variables and functions, you can reduce the risk of naming collisions and improve the readability of your code.
10. Try and Catch
In JavaScript, try...catch
is a feature used for handling errors in your code.
When you write code, errors can occur for a variety of reasons, such as incorrect user input, unexpected data or network errors. These errors can cause the execution of your program to stop, making it difficult to understand and debug the problem.
The try...catch
statement provides a way to catch and handle these errors. The try
block contains the code that you want to execute, while the catch
block contains the code that will be executed if an error occurs.
Here is an example:
// Some code
try {
// The code you want to execute goes here
const userInput = prompt("Enter a number");
const num = parseInt(userInput);
if (isNaN(num)) {
throw new Error("Invalid input");
}
console.log("Your number is: ", num);
} catch (error) {
// The code that will be executed if an error occurs goes here
console.error("An error occurred: ", error.message);
}
In this example, we have a try
block that prompts the user to enter a number, converts the user input to a number using parseInt()
, and then logs the number to the console. If the user enters an invalid input (such as a string that cannot be converted to a number), the isNaN()
function will return true
, and we will throw an error using the throw
keyword. The error message will be passed to the catch
block, which will log it to the console using console.error()
.
The try...catch
statement can help make your code more robust by handling errors gracefully and providing a more user-friendly experience. It is a useful tool for both beginners and experienced developers alike.
11. The Dom
Now I bet you’re asking how does this all link up to HTML and CSS? The DOM, or document object, is where it all comes together. The DOM is the most important object in JavaScript - it’s the JavaScript representation of the structure of our HTML and is present in the variable document, when we load the page. Through the dom we can search through the document object,
// Some code
const header = document.getElementById("header");
add event listeners, that specify an action everytime the element is clicked on
// Some code
const button = document.getElementById("login-button");
button.addEventListener("click", () => {
/* check if the user's credentials were valid */
})
and even change the style of the elements dynamically!
// Some code
const button = document.getElementById("login-button");
button.style.color = "red";
12. LocalStorage
LocalStorage is a feature of modern web browsers that allows websites to store data on a user's computer. This data is stored in a key-value format and can be accessed later even if the user closes and reopens the website.
Here's an example of how to use LocalStorage in JavaScript:
// Set a value in LocalStorage
localStorage.setItem('username', 'john');
// Get a value from LocalStorage
const username = localStorage.getItem('username');
console.log(username); // Output: "john"
// Remove a value from LocalStorage
localStorage.removeItem('username');
In this example, we first set a value for the key "username" using localStorage.setItem()
. We then retrieve the value using localStorage.getItem()
and store it in the username
variable. Finally, we remove the value using localStorage.removeItem()
.
Local storage is useful for applications that want to store user preferences or data that will be used across different pages of the website. However, it's important to note that LocalStorage has a limited capacity, and storing too much data can slow down the website or cause errors.
You will save your favourite shows/movies inside localStorage under a key like favorites. You can inspect your localStorage by pressing F12 inside your browser and switching to the the tab App.

The code for that might look like this
// Create an array of objects with music data
const showData = [
{ id: 1, name: 'Top Boy', type:'Scripted...'},
{ id: 2, name: 'Naruto: Shippuuden', type:'Animation' },
{ id: 3, name: 'Naruto', type:'Animation'}
];
// Convert the array to a JSON string
const musicDataJson = JSON.stringify(showData);
// Save the JSON string to LocalStorage
localStorage.setItem('showData', showDataJson);
You can read more about localStorage on the following sites: