What is a Function?
A function in JavaScript is a block of reusable code that performs a specific task. Functions help in organizing code, avoiding repetition, and making programs easier to understand and maintain.
How to Define a Function
There are multiple ways to define a function in JavaScript. The most basic one is using the function
keyword.
Example 1: Basic Function Definition and Call
function greet() {
console.log("Hello, welcome to JavaScript!");
}
greet();
Output:
Hello, welcome to JavaScript!
This is a simple function named greet
that prints a message. We call it using greet()
.
Example 2: Function with Parameters
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice");
greetUser("Bob");
Output:
Hello, Alice! Hello, Bob!
Here, name
is a parameter. When calling the function, you pass an argument like "Alice"
. The function uses it to personalize the output.
Question:
Can a function have more than one parameter?
Answer: Yes! You can pass multiple parameters separated by commas.
Example 3: Multiple Parameters
function add(a, b) {
console.log("Sum is:", a + b);
}
add(5, 7);
add(10, 15);
Output:
Sum is: 12 Sum is: 25
Returning a Value from a Function
Functions can also return a value using the return
keyword.
Example 4: Function with Return
function square(num) {
return num * num;
}
let result = square(6);
console.log("Square is:", result);
Output:
Square is: 36
This function computes the square of a number and returns the result. We can store the return value in a variable.
Function Syntax Recap
function functionName(parameters) {
// code to execute
return value; // optional
}
Best Practices
- Use meaningful function names that describe the task.
- Keep functions focused on one task only.
- Avoid using global variables inside functions unless necessary.
Question:
What happens if you define a function but never call it?
Answer: The function code won't run. Functions only execute when they are called.
Try it Yourself
Define a function that takes your name and age, and logs a greeting like: "Hi, I'm Alex and I'm 25 years old."
// Your turn to practice
function introduce(name, age) {
console.log("Hi, I'm " + name + " and I'm " + age + " years old.");
}
introduce("Alex", 25);
Output:
Hi, I'm Alex and I'm 25 years old.
Summary
- Functions encapsulate code that can be reused.
- You define them using
function
, and call them by their name followed by()
. - Functions can accept parameters and return results.