When writing programs, we often need to repeat the same logic multiple times. Instead of rewriting the same code again and again, we can place that logic inside a function.
A function is simply a reusable block of code that performs a specific task.
Think of a function like a small machine:
- You give it some inputs
- It processes them
- It gives you an output Why Functions Are Useful
Functions help us:
- Reuse code
- Organize programs into smaller pieces
- Make code easier to read
- Avoid repetition
For example, imagine we want to add two numbers many times in our program.
Without a function:
console.log(2 + 3)
console.log(10 + 5)
console.log(7 + 8)
With a function:
function add(a, b) {
return a + b
}
console.log(add(2, 3))
console.log(add(10, 5))
console.log(add(7, 8))
Function Declaration Syntax
A function declaration defines a function using the function keyword followed by a name.
function functionName(parameters) {
// code to run
}
function greet(name) {
return "Hello " + name
}
console.log(greet("Alice"))
Here:
- greet is the function name
- name is a parameter
- The function returns a greeting message
*Function Expression Syntax
*
A function expression stores a function inside a variable.
const variableName = function(parameters) {
// code
}
const greet = function(name) {
return "Hello " + name
}
console.log(greet("Alice"))
This works the same as a function declaration, but the function is assigned to a variable.
*What is Hoisting? *
Hoisting means JavaScript moves certain declarations to the top of the file before running the code.
Function Declarations Are Hoisted
sayHello()
function sayHello() {
console.log("Hello")
}
Even though the function is written after the call, JavaScript already knows about it.
Function Expressions Are NOT Hoisted
This will cause error:
sayHello()
const sayHello = function() {
console.log("Hello")
}
Because the variable sayHello does not exist yet when the function is called.
When Should You Use Each Type?
Use Function Declarations When:
- The function should be available anywhere in the file
- You want simpler syntax
- The function represents a core part of your program
function calculateTotal(price, tax) {
return price + tax
}
Use Function Expressions When:
- You want to store functions in variables
- You want more control over when functions are created
- You are writing modern JavaScript patterns
Example:
const calculateTotal = function(price, tax) {
return price + tax
}
Top comments (0)