Functions

Functions are reusable blocks of code designed to perform a specific task. They help organize code, avoid repetition, and improve readability.

Basic Syntax

A function is defined using the function keyword, followed by a name, parentheses for parameters, and a block of code:

📌 Deep Dive: Defining and Calling a Function

JAVASCRIPT
function greet() {
  console.log("Hello, world!");
}
greet();
Output
Hello, world!

Function Parameters and Arguments

Functions can accept inputs called parameters. When you call the function, you provide arguments to fill those parameters.

📌 Deep Dive: Parameters and Arguments

JAVASCRIPT
function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Alice");
greet("Bob");
Output
Hello, Alice!
Hello, Bob!

Return Values

Functions can return a value using the return statement. This allows the function to output a result that can be stored or used elsewhere.

📌 Deep Dive: Returning a Value

JAVASCRIPT
function add(a, b) {
  return a + b;
}
const sum = add(5, 3);
console.log(sum);
Output
8

Function Expressions

Functions can also be stored in variables. These are called function expressions.

📌 Deep Dive: Function Expression

JAVASCRIPT
const multiply = function(x, y) {
  return x * y;
};
console.log(multiply(4, 6));
Output
24

Arrow Functions (ES6+)

A concise syntax for function expressions, especially useful for simple functions.

📌 Deep Dive: Arrow Function Syntax

JAVASCRIPT
const square = n => n * n;
console.log(square(5));
Output
25
Illustration of functions
Illustration of functions

💡 Important:

Functions without a return statement return undefined by default.

Function Types Comparison
TypeDescription
Function DeclarationHoisted, named function usable before declaration.
Function ExpressionStored in variables, not hoisted.
Arrow FunctionShort syntax, no own this, good for callbacks.

⚠️ Note on Hoisting

Function declarations are hoisted, so you can call them before their definition. Function expressions and arrow functions are not hoisted.