Introducción a JavaScript
¿Por qué aprender JavaScript?
¡Hola Mundo! en Mac
¡Hola Mundo! en Windows
Anatomía de una variable
Tipos de datos en JavaScript
Creación de strings
Operadores aritméticos
Conversión de tipos: Type Casting y Coerción
Conversión de tipos explícita e implícita
Estructuras de Control y Lógica
Operadores de comparación
Operadores lógicos
Ejecución condicional: if
Ejercicio: Adivina el número
Ejecución condicional: switch
Loop: for
Loop: for of
Loop: for in
Loop: while
Loop: do while
Funciones y This
Anatomía de una función
Funciones vs Métodos
Funciones puras e impuras
Arrow function y enlace léxico
Contextos de ejecución y scope chain
¿Qué es Closure?
Preguntas a Desarrolladores Senior: ¿Por qué aprender Desarrollo Web?
Manipulación de Arrays
Introducción a Arrays
Mutabilidad e inmutabilidad de Arrays
Modificación básica del final con push( ), pop( )
Iteración con map( ) y forEach( )
Filtrado y reducción con filter( ) y reduce( )
Búsqueda de elementos con find( ) y findIndex( )
Crear copias con slice( )
Spread operator: casos de uso
Programación Orientada a Objetos
Anatomía de un Objeto
Trabajando con objetos en JavaScript
Función constructora
¿Qué es una clase?
Prototipos y herencias
Herencia en la práctica
Prototipos en la práctica
this en JavaScript
Proyecto: Crea una red social
Proyecto: Crea una red social parte 2
Asincronía en JavaScript
¿Cómo funciona el JavaScript Engine?
Promesas en JavaScript
Usando Async y await en JavaScript
For await of
¿Cómo funciona la web?
¿Cómo funciona HTTP?
Método GET en JavaScript
Método POST en JavaScript
Método DELETE en JavaScript
Importancia del id en el método DELETE
ECMAScript 6 y tus siguientes pasos
You don't have access to this class
Keep learning! Join and start boosting your career
Functions in JavaScript are reusable blocks of code that allow you to perform specific tasks over and over again. Think of them like Lego pieces: you can use them to create multiple objects with the same pieces. They are a powerful tool that, once defined, can be used repeatedly with different data sets, just as you would use a calculation over and over again during a Black Friday event to automatically apply discounts to clothing prices. Thanks to functions, we avoid duplicating code, save time and minimize errors.
A function in JavaScript has a clear structure, known as its "anatomy". Each part plays a crucial role in its operation:
Function definition:
function
keyword.Parameters:
Function body:
{}
.return
to return a value at the end of execution, although this is also optional.Function call:
Let's see the step-by-step creation of a function that calculates the price after applying a discount, something useful for events like Black Friday.
function calculateDiscountedPrice(price, discountPercentage) { const discount = (price * discountPercentage) / 100; const priceWithDiscount = price - discount; return priceWithDiscount;}
Define Variables:
const originalPrice = 100; // Price of the garmentconst discountPercentage = 20; // Discount of 20%.
Calculate the Final Price:
const finalPrice = calculateDiscountedPrice(originalPrice, discountPercentage);
Result Output:
console.log
to display the results in console.console.log("Original Price: " + originalPrice);console.log("Discount: " + discountPercentage + "%");console.log("Discounted Price: " + finalPrice);
When you run this program, you will see in the console how much you should pay based on the specified discount. And best of all: you can change the input values and calculate prices for different items in a matter of milliseconds.
Creating functions like calculateDiscountedPrice
allows you to have clear, understandable, and flexible code that adapts to different situations with ease. This technique is especially valuable in software development, where code efficiency and reusability are essential. In addition, by generating more generic code, such as discount pricing, you can customize the same function for multiple needs with simple parameter changes.
So keep practicing and experimenting with functions! Over time, you will create more sophisticated and reliable applications - the sky's the limit!
Contributions 40
Questions 1
Want to see more contributions, questions and answers from the community?