Ir al contenido

PREVIOUS READING

Block 02. Frontend with HTML, CSS, and JavaScript

0views

Block 02. Frontend with HTML, CSS, and JavaScript

Introduction

In this block, we learn how to combine the 3 basic frontend technologies.

HTML: The markup language that defines the structure and semantics of the content (the website's skeleton).

CSS: The CSS styling language that defines the visual style of the content (the website's design).

JavaScript: The programming language that allows for dynamic content modification and user interaction (the website's brain).

We will focus on discovering the potential of modern JavaScript (ES6+) to create interactive web applications. JavaScript is the language that brings the frontend to life, allowing you to:

  • Capture events and respond to user actions
  • Manipulate content dynamically and in real time.
  • Communicate with the backend using forms or APIs.

We will review fundamental programming concepts and conclude with the creation of a small web-based video game. We will work on key concepts such as DOM manipulation, event handling, object-oriented programming, JSON processing, and API consumption.

Basic JavaScript Concepts (Review)

Variables and Constants

JavaScript uses the reserved words let and const to declare variables and constants.

Ventana de terminal
// Constants (el seu contingut no es podrà modificar)
const MAX_VIDES = 3;
const NOM_JOC = "Shooter 2D";
const NUM_ENEMICS = 5;
// Variables (els seus valors assignats i tipus poden canviar durant l'execució)
let punts = 0;
let nivell = 1;
let vides = MAX_VIDES;
punts = 50;

Data Types

JavaScript is dynamic; it automatically determines the data type based on the value assigned to constants or variables. These can be:

  • Primitive Data Types: String, Number, Boolean, Null, Undefined
  • Composite Data Types: Arrays, Functions, Dates, etc.
// Tipus Primitius
let nom = "Jugador"; // String
let punts = 50; // Number
let estaDisparant = false; // Boolean
let nickname = null; // Null
let velocitat; // Undefined
// Vectors (Arrays)
const enemics = ["TieFighter", "StarDestroyer", "DeathStar"];
const puntuacions = [50, 100, 300];
// Objecte literal (Objectes simples creats pel desenvolupador)
const jugador = {
nom: "X-Wing",
vides: 3,
punts: 0,
energia: 100,
posicio: { x: 250, y: 450 }, // "posició" seria un altre objecte
armes: ["laser", "metralleta"]
};

Arithmetic, Relational, and Logical Operators

Arithmetic Operators: Allow performing mathematical operations with numeric values, constants, and variables.

  • + (Addition): Adds two values.
  • - (Subtraction): Subtracts two values.
  • * (Multiplication): Multiplies two values.
  • / (Division): Divides two values.
  • % (Modulo): Returns the remainder of the division between two values.
  • ** (Exponent): Raises a value to a power.
  • ++ (Increment): Increases the value of a variable by 1.
  • -- (Decrement): Decreases the value of a variable by 1.
  • + (String Concatenation): Legacy method for concatenating strings.

Relational Operators: Allow comparing values. Determines if the result of the operation is true or false.

  • == (Equal to): Checks if two values are equal (only considers the value).
  • === (Strictly equal to): Checks if two values are exactly equal (both value and type).
  • != (Not equal to): Checks if two values are not equal (only considers the value).
  • !== (Strictly not equal to): Checks if two values are not equal (both value and type).
  • > (Greater than): Checks if the first value is greater than the second value.
  • < (Less than): Checks if the first value is smaller than the second value.
  • >= (Greater than or equal to): Checks if the first value is greater than or equal to the second value.
  • <= (Less than or equal to): Checks if the first value is less than or equal to the second value.

Logical Operators: Allow combining conditions and determining their final result (true or false).

  • && (AND): Verifies if conditions are true. Returns true or false otherwise.
  • || (OR): Verifies if at least one condition is true. Returns true or false otherwise.
  • ! (NOT): Inverts the value of a condition. Returns true if the condition is false and vice versa.
Ventana de terminal
// Aritmètics
let puntsTotal = punts + (bonus * nivell);
let videsTotals = vides - errades;
const statusJugador = "Pepet: " + puntsTotal;
// Relacionals
let haGuanyat = punts >= puntsPerfecte;
let finalJoc = nivell === MAX_NIVELLS;
// Lògics
let potAtacar = vides >= 0 && municio > 0;
let negacio = !estaViu;
let continuaJoc = punts >= 0 || estaViu;

Conditional Control Structures

JavaScript can make decisions about which code block to execute based on the result of arithmetic, relational, and logical operations.

// (if) Executa el bloc de codi si es compleix la condició
// (else) Executa el bloc de codi si no es compleix la condició
if (vides > 0 && punts >= 50) {
vides--;
punts -= 50;
} else {
//Comanda que mostra informació i dades de l'aplicació a la consola del desenvolupador
console.log(`Game Over! T'has quedat amb ${vides} vides.`);
}
// (switch) Estructura condicional de casos
// Executa el bloc de codi segons el valor assignat a la variable
switch (nivell) {
case 1:
numEnemics = 5;
maxPunts = 100;
break;
case 2:
numEnemics = 10;
maxPunts = 200;
break;
default:
numEnemics = 3;
maxPunts = 50;
}
// (Operador ternari) - Assigna un valor si es compleix la condició sinó assigna un altre valor.
const missatge = (vides > 0) ? "Estàs viu" : "Has mort";
const nomUsuari = (usuari === null) ? "Jugador1" : usuari;

Iterative Control Structures

JavaScript can repeat the execution of a code block until a condition is met or a specific number of iterations is performed (also known as loops).

// (while) Executa un bloc de codi repetidament fins que es compleixi una condició
let estaViu = true;
let numEnemics = 3;
let vides = 5;
while (estaViu && numEnemics > 0) {
numEnemics--;
vides--;
if (vides === 0) {
estaViu = false;
}
}
// (for) Executa un bloc de codi repetidament un número determinat de vegades
let posicioEnemic = 0;
for (let i = 0; i < 10; i++) {
posicioEnemic += 5;
}
// (forEach) Executa un bloc de codi per a cada element d'un vector
const enemics = ["TieFighter", "StarDestroyer", "DeathStar"];
enemics.forEach((enemic) => {
console.log(`Enemic: ${enemic}`);
});
// (for .. in) Executa un bloc de codi per a cada clau d'un objecte (simula un array associatiu)
const puntuacions = { "facil": 100, "normal": 200, "dificil": 500 };
for (const dificultat in puntuacions) {
console.log(dificultat, puntuacions[dificultat]);
}

Functions and Procedures

Functions are blocks of code that perform a specific task; they can receive input parameters and return a result. They are independent of the program and we can “call” them at any point in the code.

We will execute the functions in the following manner:

// Función tradicional
function calcularPuntuacion(puntos, tiempos, nivel) {
let puntosTotales = Math.floor((puntos - tiempos) * nivel);
return puntosTotales;
}
// Función flecha
const calcularPuntuacion = (puntos, tiempos, nivel) => Math.floor((puntos - tiempos) * nivel);
// Tipus Primitius
let nom = "Jugador"; // String
let punts = 50; // Number
let estaDisparant = false; // Boolean
let nickname = null; // Null
let velocitat; // Undefined
// Vectors (Arrays)
const enemics = ["TieFighter", "StarDestroyer", "DeathStar"];
const puntuacions = [50, 100, 300];
// Objecte literal (Objectes simples creats pel desenvolupador)
const jugador = {
nom: "X-Wing",
vides: 3,
punts: 0,
energia: 100,
posicio: { x: 250, y: 450 }, // "posició" seria un altre objecte
armes: ["laser", "metralleta"]
};

We must understand that functions are fundamental in programming and allow us to reuse code. We can pass parameters to functions and obtain results. Functions can also be anonymous or arrow functions, as shown in the previous example.

We will see more examples of how we will use functions in our programs.