JavaScript functions are blocks of code designed to perform specific tasks.
They allow you to group a series of statements together and run them whenever needed, without rewriting the code.
Functions are essential for organizing and reusing code, making programs more efficient and easier to manage.
To create a function, you start with the function
keyword, followed by a name, parentheses ()
, and curly braces {}
.
Inside the parentheses, you can define parameters, which are inputs the function can use. The code inside the curly braces is what the function executes.
You call or "invoke" a function by writing its name followed by parentheses.
If the function requires inputs (arguments), you place them inside the parentheses during the call.
Functions can return values using the return
keyword, allowing the function to give back a result when it's called.
This is useful for calculations or processing data.
Functions can also be anonymous, meaning they have no name and are often used as arguments in other functions.
10 Examples of JavaScript Functions
Simple Function
function sayHello() { console.log("Hello, World!"); } sayHello();
Function with Parameters
function greet(name) { console.log("Hello, " + name + "!"); } greet("Alice");
Function Returning a Value
function add(a, b) { return a + b; } console.log(add(5, 3));
Anonymous Function
const multiply = function(x, y) { return x * y; }; console.log(multiply(4, 2));
Arrow Function
const subtract = (a, b) => a - b; console.log(subtract(10, 4));
Function with Default Parameters
function greet(name = "stranger") { console.log("Hello, " + name + "!"); } greet();
Immediately Invoked Function Expression (IIFE)
(function() { console.log("This is an IIFE!"); })();
Function as a Parameter
function callFunction(func) { func(); } callFunction(() => console.log("Called from another function"));
Recursive Function
function countdown(number) { if (number > 0) { console.log(number); countdown(number - 1); } } countdown(5);
Higher-Order Function
function applyOperation(a, b, operation) { return operation(a, b); } console.log(applyOperation(5, 3, (x, y) => x + y));
These examples illustrate how versatile and powerful JavaScript functions are in programming.