Explain JavaScript functions
JavaScript functions are blocks of code designed to perform particular tasks. A function is executed when something invokes it (calls it).
Syntax
function functionName(parameters) {
// code to be executed
}
Example 1: Basic Function
function sayHello() {
console.log("Hello, World!");
}
sayHello();
Output:
Hello, World!
Example 2: Function with Parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
Output:
Hello, Alice!
Example 3: Function with Return Value
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);
Output:
8
Example 4: Anonymous Function
let multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 7));
Output:
28
Example 5: Arrow Function
const divide = (a, b) => {
return a / b;
};
console.log(divide(10, 2));
Output:
5
Example 6: Function with Default Parameters
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet();
greet("Bob");
Output:
Hello, Guest!
Hello, Bob!
Example 7: Immediately Invoked Function Expression (IIFE)
(function() {
console.log("This function runs immediately!");
})();
Output:
This function runs immediately!
Example 8: Function as a Parameter
function repeat(operation, num) {
for (let i = 0; i < num; i++) {
operation();
}
}
function sayHi() {
console.log("Hi!");
}
repeat(sayHi, 3);
Output:
Hi!
Hi!
Hi!
These examples demonstrate different ways to define and use functions in JavaScript. Functions are fundamental to JavaScript programming, allowing for code reuse, modularity, and abstraction.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.