JavaScript Function Definitions
14 April 2025 | Category: JavaScript
In JavaScript, a function is a reusable block of code designed to perform a specific task. Defining a function means creating a set of instructions that can be called (or invoked) whenever needed.
There are multiple ways to define functions in JavaScript, each with its own syntax and behavior.
đ§± 1. Function Declaration (Named Function)
This is the most traditional way to define a function using the function
keyword.
â Syntax:
function greet(name) {
return `Hello, ${name}!`;
}
â Example:
console.log(greet("Alice")); // Hello, Alice!
â Key Features:
- Hoisted (you can call the function before its declaration in the code)
- Useful for defining reusable logic
đ§ 2. Function Expression
A function can also be defined and stored in a variable.
â Syntax:
const greet = function(name) {
return `Hi, ${name}!`;
};
â Example:
console.log(greet("Bob")); // Hi, Bob!
â ïž Note:
- Not hoisted (you must define before using)
- Can be anonymous (no name required inside
function
)
⥠3. Arrow Function (ES6+)
A cleaner and shorter syntax introduced in ES6, often used for callbacks and concise operations.
â Syntax:
const greet = (name) => `Hey, ${name}!`;
â Example:
console.log(greet("Charlie")); // Hey, Charlie!
đ Key Features:
- Shorter syntax
- No
this
,arguments
, orsuper
bindings (lexicalthis
) - Great for functional programming, but not suited for methods in objects or constructors
đ§ 4. Function Constructor (Less Common)
You can also define a function using the Function
constructor.
â Syntax:
const sum = new Function('a', 'b', 'return a + b');
â ïž Not Recommended:
- Slower
- Less readable
- Used in dynamic or advanced meta-programming
đ 5. Immediately Invoked Function Expression (IIFE)
Used to define and run a function immediately, without calling it later.
â Syntax:
(function() {
console.log("This runs instantly!");
})();
â Useful for:
- Creating private scopes
- Avoiding global variable pollution
đ§Ș Bonus: Method Definitions in Objects
You can define functions inside objects, known as methods.
const user = {
name: "Devin",
greet() {
return `Hi, I'm ${this.name}`;
}
};
đ Function Hoisting Difference
greet(); // â
Works
function greet() {
console.log("Hello!");
}
greetAgain(); // â Error
const greetAgain = function () {
console.log("Hi!");
};
â Summary Table
Method | Syntax Format | Hoisted | Uses this | Arrow Syntax |
---|---|---|---|---|
Function Declared | function name() {} | â | Yes | â |
Function Expression | const fn = function(){} | â | Yes | â |
Arrow Function | const fn = () => {} | â | No (lexical) | â |
IIFE | (function() {})() | â | Yes | â |