Control Instructions in JavaScript: A Guide with Examples and Exercises

Master control statements in JavaScript. Learn conditionals, loops, and more with clear examples and exercises to program from scratch.
What are control statements in JavaScript?
Control statements in JavaScript are structures that allow you to direct the flow of code execution based on certain conditions or repetitions. These statements are fundamental for creating dynamic and adaptive programs.
Importance of control structures in programming
Control structures are essential in programming because they allow you to:
-
Make decisions based on specific conditions.
-
Repeat blocks of code to perform multiple tasks.
-
Improve code readability and maintainability.
Types of control statements in JavaScript
Conditional statements
Conditional statements allow you to execute different blocks of code depending on whether a condition is true or false.
####if and else
The basic structure of a sentenceif is:
if (condición) {
// Código a ejecutar si la condición es verdadera
} else {
// Código a ejecutar si la condición es falsa
}
Example:
let edad = 18;
if (edad >= 18) {
console.log("Eres mayor de edad.");
} else {
console.log("Eres menor de edad.");
}
####else if
You can chain multiple conditions usingelse if
if (condición1) {
// Código si condición1 es verdadera
} else if (condición2) {
// Código si condición2 es verdadera
} else {
// Código si ninguna condición es verdadera
}
Example:
let nota = 85;
if (nota >= 90) {
console.log("Sobresaliente");
} else if (nota >= 75) {
console.log("Aprobado");
} else {
console.log("Reprobado");
}
####switch
The sentenceswitchIt is useful for comparing a variable with multiple possible values:
switch (expresión) {
case valor1:
// Código si expresión === valor1
break;
case valor2:
// Código si expresión === valor2
break;
default:
// Código si ningún caso coincide
}
Example:
let dia = 3;
switch (dia) {
case 1:
console.log("Lunes");
break;
case 2:
console.log("Martes");
break;
case 3:
console.log("Miércoles");
break;
default:
console.log("Otro día");
}
Ternary Operator? :in JavaScript
The ternary operator is a concise way to write a statementif...elseThe syntax is:
condición ? expresiónSiVerdadero : expresiónSiFalso;
Example:
let edad = 20;
let mensaje = edad >= 18 ? "Eres mayor de edad." : "Eres menor de edad.";
console.log(mensaje); // Imprime: Eres mayor de edad.
Loops
Loops allow you to repeat a block of code multiple times until a specific condition is met.
####for
The loopforThis is used when you know how many times you want to repeat a block of code:
for (inicialización; condición; incremento) {
// Código a ejecutar en cada iteración
}
Example:
for (let i = 0; i < 5; i++) {
console.log("Número: " + i);
}
####while
The loopwhileRepeat a block of code while a condition is true:
while (condición) {
// Código a ejecutar mientras la condición sea verdadera
}
Example:
let contador = 0;
while (contador < 5) {
console.log("Contador: " + contador);
contador++;
}
####do...while
The loopdo...whileExecute the code block at least once, and then repeat as long as the condition is true:
do {
// Código a ejecutar
} while (condición);
Example:
let numero = 0;
do {
console.log("Número: " + numero);
numero++;
} while (numero < 5);
Loop for...into iterate through objects
The loopfor...inIt is used to iterate over the enumerable properties of an object:
let persona = {
nombre: "Juan",
edad: 30,
ciudad: "Madrid",
};
for (let clave in persona) {
console.log(clave + ": " + persona[clave]);
}
Loop for...ofto iterate through objects
The loopfor...ofIt is used to iterate over iterable objects such as arrays, strings, maps, sets, and others:
let frutas = ["Manzana", "Banana", "Cereza"];
for (let fruta of frutas) {
console.log(fruta);
}
Differences betweenfor...in and for...of
-for...inIt iterates over the enumerable properties of an object, including inherited properties. It is ideal for objects.
-for...ofIterates over the values of iterable objects such as arrays, strings, maps, and sets. It does not work with regular objects.
Additional control instructions
####break
The instructionbreakIt is used to exit a loop or a statementswitchbefore its normal execution is complete.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Sale del bucle cuando i es 5
}
console.log(i);
}
####continue
The instructioncontinueIt is used to jump to the next iteration of a loop, skipping the remaining code in the current iteration.
Example:
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Salta los números pares
}
console.log(i); // Imprime solo números impares
}
Nested Control Statements
Control statements can be nested within other statements to create more complex structures.
Example:
let edad = 20;
if (edad >= 18) {
console.log("Eres mayor de edad.");
for (let i = 0; i < 3; i++) {
console.log("Iteración: " + i);
}
} else {
console.log("Eres menor de edad.");
}
Error Handling withtry...catch
The structuretry...catchIt is used to handle errors in the code. The blocktryIt contains the code that can generate an error, and the blockcatchIt contains the code that is executed if an error occurs.
try {
// Código que puede causar un error
let resultado = 10 / 0;
console.log(resultado);
} catch (error) {
// Código para manejar el error
console.log("Ocurrió un error: " + error.message);
}
Use ofthrowto throw exceptions
The instructionthrowIt is used to throw a custom exception. You can throw any type of value, but error objects are commonly thrown.
function dividir(a, b) {
if (b === 0) {
throw new Error("No se puede dividir por cero.");
}
return a / b;
}
try {
let resultado = dividir(10, 0);
console.log(resultado);
} catch (error) {
console.log("Ocurrió un error: " + error.message);
}
Practical Examples oftry...catch...finally
The blockfinallyIt always runs, regardless of whether an exception was thrown or not. It is useful for performing cleanup tasks.
try {
let resultado = dividir(10, 0);
console.log(resultado);
} catch (error) {
console.log("Ocurrió un error: " + error.message);
} finally {
console.log("Ejecución finalizada.");
}
Case studies and best practices
Practical example: Form validation
function validarFormulario(nombre, edad) {
if (nombre === "") {
console.log("El nombre es obligatorio.");
return;
}
if (edad < 0 || edad > 120) {
console.log("La edad no es válida.");
return;
}
console.log("Formulario válido.");
}
validarFormulario("Ana", 25); // Formulario válido.
validarFormulario("", 25); // El nombre es obligatorio.
validarFormulario("Ana", 130); // La edad no es válida.
Traversing arrays with loops
let numeros = [1, 2, 3, 4, 5];
for (let i = 0; i < numeros.length; i++) {
console.log("Número: " + numeros[i]);
}
// Usando for...of
for (let numero of numeros) {
console.log("Número: " + numero);
}
// Usando forEach
numeros.forEach(function (numero) {
console.log("Número: " + numero);
});
// Usando map para crear un nuevo array
let cuadrados = numeros.map(function (numero) {
return numero * numero;
});
console.log(cuadrados); // [1, 4, 9, 16, 25]
Best Practices for Writing Control Statements in JavaScript
-
Keep your code clean and readable by using proper indentation and spacing.
-
Avoid nesting too many control statements to improve readability.
-
Use comments to explain complex blocks of code.
-
Prefer clear structures such as
switchwhen you have multiple conditions based on the same value.
Summary
Control statements in JavaScript are fundamental for directing the flow of code execution. Conditional statements (if,else,switch) allow making decisions based on conditions, while loops (for,while,do...while) facilitate the repetition of code blocks. Furthermore, instructions such asbreak,continueand error handling withtry...catchThey are essential for writing robust and efficient code. By following best practices, you can improve the readability and maintainability of your code.
-
Objects in JavaScript:Objects in JavaScript: A Beginner's Guide with Examples
-
Array methods in JavaScript:Array methods in JavaScript: A guide with examples and exercises
-
More on control instructions:mdn - Sentencias.
💻Try these basic exercises on control statements in JavaScript:
-
Age Rating with JavaScript
-
Simple calculator with if/else
-
Options Menu with switch in JavaScript
-
Vowel Identification with switch
-
Even number counter with while loop
-
Generate multiplication table with while loop
-
Add even numbers in a range using JavaScript
-
Counting vowels in a string with JavaScript
-
Count the Length of Each Word with forEach()
-
Get values using Object.values() and forEach()