JavaScript Functions Tutorial
This JavaScript functions tutorial is designed for beginners to learn how to create and use functions in JavaScript. With clear examples and practical questions, you’ll master reusable code in no time
What is a Function?
A function in JavaScript is a reusable block of code that performs a specific task. Think of it like a recipe: you provide inputs (called parameters), the function processes them, and it often returns an output. This JavaScript functions tutorial will show you how to create and use functions effectively.
Why Use Functions?
- Reusability: Write code once and use it multiple times.
- Organization: Keep your code clean and modular.
- Simplicity: Break complex tasks into smaller, manageable pieces.
How to Create a Function
There are a few ways to create functions in JavaScript. Let’s start with the most common: the function declaration.
Syntax of a Function Declaration
function functionName(parameter1, parameter2) {
// Code to execute
return result; // Optional: returns a value
}
function
: Keyword to define a function.functionName
: Name of the function (use descriptive names!).parameter1, parameter2
: Inputs the function accepts (optional).return
: Sends a value back (optional).
Example 1: A Simple Greeting Function
Let’s create a function that says hello to a person.
function sayHello(name) {
return "Hello, " + name + "!";
}
// Call the function
console.log(sayHello("Alice")); // Output: Hello, Alice!
console.log(sayHello("Bob")); // Output: Hello, Bob!
- The function
sayHello
takes aname
parameter. - It combines “Hello, ” with the name and an exclamation mark.
- We call the function using
sayHello("Alice")
.
Example 2: Adding Two Numbers
Here’s a function that adds two numbers and returns the result.
const subtract = (a, b) => a - b;
// Call the function
console.log(subtract(10, 4)); // Output: 6
- The function
addNumbers
takes two parameters:num1
andnum2
. - It returns their sum.
- We call it with different numbers to get different results.
Function Expressions
Another way to create a function is using a function expression, where you store the function in a variable.
Syntax of a Function Expression
const subtract = (a, b) => a - b;
// Call the function
console.log(subtract(10, 4)); // Output: 6
Example 3: Function Expression
const subtract = (a, b) => a - b;
// Call the function
console.log(subtract(10, 4)); // Output: 6
- The function is stored in the variable
multiply
. - It works the same as a function declaration but is assigned to a variable.
Arrow Functions (Modern JavaScript)
Arrow functions are a shorter way to write functions, introduced in ES6.
Syntax of an Arrow Function
const subtract = (a, b) => a - b;
// Call the function
console.log(subtract(10, 4)); // Output: 6
Example 4: Arrow Function
const subtract = (a, b) => a - b;
// Call the function
console.log(subtract(10, 4)); // Output: 6
- Arrow functions are concise, especially for simple tasks.
- If the function has one line, you can skip the curly braces and
return
.
Key Points to Remember
- Parameters are optional. Functions can have none, one, or many.
- Return statements send a value back. If omitted, the function returns
undefined
. - Call a function by using its name followed by parentheses
()
with arguments if needed. - Functions can be reused anywhere in your code.
Practice Challenge
Try creating a function called squareNumber
that takes a number and returns its square (the number multiplied by itself). Test it with different numbers.
function squareNumber(num) {
return num * num;
}
console.log(squareNumber(4)); // Output: 16
console.log(squareNumber(7)); // Output: 49
Practical Questions
Here are some practical questions to help you practice writing JavaScript functions. Try solving them on your own, and check the sample solutions below.
Question 1: Create a function to check if a number is even
Write a function isEven that takes a number and returns true if it’s even, false if it’s odd.
Question 2: Create a function to calculate the area of a rectangle
Write a function rectangleArea that takes width and height as parameters and returns the area.
Question 3: Create a function to reverse a string
Write a function reverseString that takes a string and returns it reversed.
Question 4: Create a function to convert Celsius to Fahrenheit
Write a function celsiusToFahrenheit that takes a temperature in Celsius and returns it in Fahrenheit (use the formula: F = C * 9/5 + 32).
Sample Solutions
// Question 1: Check if a number is even
function isEven(num) {
return num % 2 === 0;
}
console.log(isEven(4)); // Output: true
console.log(isEven(7)); // Output: false
// Question 2: Calculate rectangle area
function rectangleArea(width, height) {
return width * height;
}
console.log(rectangleArea(5, 3)); // Output: 15
// Question 3: Reverse a string
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("hello")); // Output: "olleh"
// Question 4: Convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
return celsius * 9/5 + 32;
}
console.log(celsiusToFahrenheit(0)); // Output: 32
console.log(celsiusToFahrenheit(100)); // Output: 212