Functions are one of the most important parts of JavaScript. They allow you to write a block of code once and reuse it many times. This makes your code cleaner, more organized, and easier to maintain.
Function Syntax
function functionName(param1, param2, ...) {
// code to execute
}
You define a function using the function
keyword, followed by the function name, and parentheses. Inside the curly braces {}
, you write the code that should run when the function is called.
Defining a Function
function greet() {
alert("Hello World!");
}
This greet
function shows a simple alert box. It does not take any parameters.
Calling a Function
greet();
When you call a function, JavaScript runs the code inside it.
Function Parameters
You can pass values to a function using parameters.
function greet(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}
greet("Steve", "Jobs");
JavaScript functions are flexible — they accept different types of parameters:
greet("Bill", "Gates"); // Hello Bill Gates
greet(100, 200); // Hello 100 200
Passing Extra or Fewer Arguments
greet("Steve", "Jobs", "Mr."); // Hello Steve Jobs
greet("Bill"); // Hello Bill undefined
greet(); // Hello undefined undefined
Extra arguments are ignored, and missing ones become undefined
.
Using arguments
Object
Inside a function, you can use the built-in arguments
object to access all passed values, even if you didn’t define parameters.
Returning a Value
You can return a result using the return
keyword.
function getNumber() {
return 10;
}
let result = getNumber();
console.log(result); // 10
Example: Return Sum
function sum(num1, num2) {
return num1 + num2;
}
let result = sum(10, 20); // 30
Returning Another Function
function multiply(x) {
function inner(y) {
return x * y;
}
return inner;
}
let triple = multiply(3);
console.log(triple(2)); // 6
console.log(triple(3)); // 9
Function Expression
You can assign a function to a variable. This is called a function expression.
let add = function(num1, num2) {
return num1 + num2;
};
console.log(add(10, 20)); // 30
Anonymous Function
An anonymous function has no name. It's often used as an argument or inside array methods like map()
.
let numbers = [10, 20, 30, 40];
let squares = numbers.map(function(number) {
return number * number;
});
console.log(squares); // [100, 400, 900, 1600]
Arrow Function
Arrow functions are shorter versions of anonymous functions. They do not have their own this
.
let square = num => num * num;
console.log(square(5)); // 25
Nested Functions
A function can be defined inside another function. Inner functions can use variables from the outer function.
function greet(firstName) {
function sayHello() {
alert("Hello " + firstName);
}
return sayHello();
}
greet("Steve");