JavaScript Functions
Functions in JavaScript let you create reusable blocks of code that can be executed whenever needed. They help you organize, reuse, and manage your code more efficiently.
Functions are a core part of JavaScript and are essential for building modular and maintainable applications.
Here are some common uses for functions:
- Reusability: Use a function multiple times with different inputs.
- Organization: Break complex logic into smaller pieces.
- Abstraction: Simplify usage by hiding implementation details.
- Modularity: Isolate functionality into standalone blocks of logic.
What You'll Learn
In this tutorial, you'll learn how to define and use functions in JavaScript. We'll cover basic functions, functions with parameters, and how to return values.
Understanding Functions in JavaScript
In JavaScript, a function is defined using the function keyword. Functions help you avoid repeating code by allowing you to write it once and reuse it as many times as needed. This makes your code cleaner, more efficient, and easier to manage.
Here’s the basic syntax:
function functionName(parameters) {
// function body
return result;
}
function functionName(parameters) {
// function body
return result;
}
- function: This keyword tells JavaScript you're creating a function.
- functionName: This is the name you choose for your function, like sayHello or calculateTotal.
- parameters: These are like variables. You can pass information into your function using them. (Optional)
- return: This sends a value back to wherever the function was called. (Also optional — not all functions need to return something.)
Example 1: Simple Function
Let's start with a basic example. This function shows a message when you run it:
function greet() {
console.log("Hello, world!");
}
greet();
function greet() {
console.log("Hello, world!");
}
greet();
What’s Happening Here:
- function greet(): This creates a function called greet.
- console.log("Hello, world!"): This tells the browser to show the message “Hello, world!” in the console.
- greet(): This calls (runs) the function and shows the message.
You can call the function as many times as you want, and it will do the same thing each time.
Output:
Hello, world!
Hello, world!
Example 2: Function with Parameters
Now let’s look at a function that takes some input and uses it to do something useful — like adding two numbers.
function addNumbers(a, b) {
const result = a + b;
console.log("The sum is:", result);
}
addNumbers(5, 3);
function addNumbers(a, b) {
const result = a + b;
console.log("The sum is:", result);
}
addNumbers(5, 3);
What’s Happening Here:
- function addNumbers(a, b): This creates a function named addNumbers. It takes two values (we call them a and b).
- const result = a + b: This adds the two values together and stores the result.
- console.log(...): This shows the result in the console.
- addNumbers(5, 3): This calls the function and gives it 5 and 3 as input. The function adds them and prints the result.
You can reuse this function with different numbers anytime you want!
Output:
The sum is: 8
The sum is: 8
Example 3: Checking if a Number is Even or Odd
This function checks whether a number is even or odd and shows the result in the console.
function checkEvenOdd(num) {
if (num % 2 === 0) {
console.log(num + " is even");
} else {
console.log(num + " is odd");
}
}
checkEvenOdd(7);
function checkEvenOdd(num) {
if (num % 2 === 0) {
console.log(num + " is even");
} else {
console.log(num + " is odd");
}
}
checkEvenOdd(7);
What’s Happening Here:
- function checkEvenOdd(num): This creates a function called checkEvenOdd that takes one input called num.
- if (num % 2 === 0): This checks if the number divides evenly by 2. If it does, it’s even.
- console.log(...): This shows whether the number is even or odd.
- checkEvenOdd(7): This calls the function and passes in the number 7. The function checks it and prints the result.
Try changing the number to see different results!
Output:
7 is odd
7 is odd
Example 4: Squaring a Number
This function takes a number and shows its square (the number multiplied by itself).
function square(num) {
const result = num * num;
console.log("The square is:", result);
}
square(6);
function square(num) {
const result = num * num;
console.log("The square is:", result);
}
square(6);
What’s Happening Here:
- function square(num): This creates a function named square that takes one number.
- num * num: This multiplies the number by itself.
- console.log(...): This shows the result in the console.
- square(6): This calls the function and gives it the number 6.
You can try calling this function with different numbers to see their squares!
Output:
The square is: 36
The square is: 36
Exercises
Try these exercises to get more practice writing and using functions. Each one does something different using basic logic and console.log().
1. Write a function that prints a welcome message.
// Exercise 1: Print a welcome message
function welcomeMessage() {
console.log("Welcome to JavaScript!");
}
welcomeMessage();
// Exercise 1: Print a welcome message
function welcomeMessage() {
console.log("Welcome to JavaScript!");
}
welcomeMessage();
2. Write a function that takes a name and prints "Hello, [name]!"
// Exercise 2: Greet someone by name
function greetByName(name) {
console.log("Hello, " + name + "!");
}
greetByName("peter");
// Exercise 2: Greet someone by name
function greetByName(name) {
console.log("Hello, " + name + "!");
}
greetByName("peter");
3. Write a function that takes a number and prints if it’s positive, negative, or zero.
// Exercise 3: Check if a number is positive, negative, or zero
function checkNumber(num) {
if (num > 0) {
console.log("The number is positive");
} else if (num < 0) {
console.log("The number is negative");
} else {
console.log("The number is zero");
}
}
checkNumber(-5);
// Exercise 3: Check if a number is positive, negative, or zero
function checkNumber(num) {
if (num > 0) {
console.log("The number is positive");
} else if (num < 0) {
console.log("The number is negative");
} else {
console.log("The number is zero");
}
}
checkNumber(-5);
4. Write a function that prints all numbers from 1 to 5.
// Exercise 4: Print numbers from 1 to 5
function printNumbers() {
for (let i = 1; i <= 5; i++) {
console.log(i);
}
}
printNumbers();
// Exercise 4: Print numbers from 1 to 5
function printNumbers() {
for (let i = 1; i <= 5; i++) {
console.log(i);
}
}
printNumbers();
5. Write a function that prints the length of a word.
// Exercise 5: Print the length of a word
function printWordLength(word) {
console.log("Length:", word.length);
}
printWordLength("JavaScript");
// Exercise 5: Print the length of a word
function printWordLength(word) {
console.log("Length:", word.length);
}
printWordLength("JavaScript");
Frequently Asked Questions
What is a function in JavaScript?
What is a function in JavaScript?
A function in JavaScript is a block of code designed to perform a specific task. Functions help organize your code, making it easier to reuse and maintain.
How do you define a function in JavaScript?
How do you define a function in JavaScript?
You define a function using the function keyword, followed by the function name and parentheses. Inside the parentheses, you can define parameters (optional), and the function body is enclosed in curly braces.
What is the purpose of the return statement in JavaScript?
What is the purpose of the return statement in JavaScript?
The return statement sends a result back from the function to the part of the program that called it. This allows the function to provide an output. If you don't use `return`, the function will return `undefined` by default.
Can a function have parameters in JavaScript?
Can a function have parameters in JavaScript?
Yes, functions in JavaScript can accept parameters, which are variables you define in the function definition. You can pass values into these parameters when you call the function.
What is the difference between parameters and arguments in JavaScript?
What is the difference between parameters and arguments in JavaScript?
Parameters are the variables defined in the function declaration. Arguments are the actual values you pass into the function when calling it.
What's Next?
Up next, you'll explore JavaScript function parameters in more detail—learning about default values, rest parameters, and how arguments are passed. This will help you write more dynamic and flexible functions.