JavaScript Functions
Learn how to declare and use functions in JavaScript.
Introduction to Functions
Functions are blocks of code designed to perform a particular task. They are executed when called They are essential for organizing and reusing logic.
Function Declaration
A basic function is declared using the function keyword:
function greet() {
alert("Hello, world!");
}
greet(); // Call the function
Parameters and Arguments
You can pass values into functions using parameters:
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice");
Return Values
Functions can return values using the return keyword:
function add(a, b) {
return a + b;
}
let result = add(5, 3); // 8
console.log(result);
Function Expressions
Functions can also be assigned to variables:
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // 20
Arrow Functions (ES6)
Arrow functions offer a shorter syntax for writing functions:
const subtract = (a, b) => {
return a - b;
};
console.log(subtract(10, 4)); // 6
Best Practices
- Use descriptive function names
- Keep functions short and focused on a single task
- Use arrow functions for concise logic (especially in callbacks)
Practice Task
Create a function that takes two numbers and returns their average:
function average(a, b) {
return (a + b) / 2;
}
console.log("Average:", average(10, 20));