Real-Life Example of a Function
Imagine a coffee machine. When you press a button, it performs a series of steps to brew coffee, such as grinding beans, heating water, and pouring coffee into a cup. These steps are predefined and executed in order whenever the button is pressed.
Similarly, a JavaScript function is like that coffee machine: you define the steps (logic) inside the function, and every time you "press the button" (call the function), it performs the same steps to produce the desired result.
What is a Function in JavaScript?
A function in JavaScript is a reusable block of code designed to perform a particular task. You can define a function once and use it multiple times in your program, which helps keep your code organized and avoid duplication.
How to Declare and Call a Function
Functions can be declared using the function keyword and name. Here's a basic example:
// Declaring the function with the 'function' keyword and name (greet)
function greet(name) {
// The function takes one parameter 'name' and logs a greeting message
console.log('Hello, ' ,name);
}
// Calling the function with the argument 'Prakash'
greet('Prakash'); // Output: Hello, Prakash!Real-life Example: Calculate the Area of a Rectangle
In this example, we'll declare a function that calculates the area of a rectangle.
function calculateArea(length, width) {
const area = length * width;
console.log('The area of the rectangle is: ' + area + ' square units.');
}
// Calling the function with real-life values:
calculateArea(5, 3); // Output: The area of the rectangle is: 15 square units.
calculateArea(7, 2); // Output: The area of the rectangle is: 14 square units.A Function is a Value
In JavaScript, functions are treated as first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and even returned from other functions. Essentially, a function is just another type of value, similar to numbers, strings, or objects.
This flexibility allows functions to be used dynamically in various ways, making JavaScript a highly versatile language. Here are some key points and examples to illustrate this concept:
function sayHmm(){
console.log("hmm")
}
console.log(sayHmm)
// output : ƒ sayHmm(){
// console.log("hmm")
// } (whole function as a value)
// Assigning a function to a variable
const greet = function () {
console.log("Welcome")
};
let copyGreet=greet
console.log(greet) // output : whole function
console.log(copyGreet) // output : while function (greet)
greet() // welcome
copyGreet() // welcome
Key Takeaways:
- Functions can be assigned to variables just like any other value.
- They can be passed as arguments to other functions, enabling dynamic and reusable code (e.g., callbacks).
- A function can return another function, creating powerful constructs like closures.
- This characteristic of functions being values is central to JavaScript's functional programming capabilities.
Different types of Functions in JavaScript
Function Declarations (Also Known as Regular Functions)
A function declaration defines a named function that can be invoked later in the code. The return keyword is used in a function to send a value back to the place where the function was called. When return is used, the function stops executing further code. If no return is specified, the function will return undefined by default. Function Declarations are hoisted, which means you can call them before they are defined in the code.
// Function declaration: 'add' is the function name
function add(a, b) {
// 'a' and 'b' are parameters. The function returns the sum of 'a' and 'b'
return a + b; // The 'return' keyword sends the result back to the caller
}
// Example usage: Calling the 'add' function with arguments 3 and 5
console.log(add(3, 5)); // Output: 8
// If no 'return' statement is used, the function will return 'undefined' by default
function greet() {
console.log('Hello!');
}
console.log(greet()); // Output: undefinedReturning a Value from a Function and Storing It in a VariableWhen a function returns a value, you can store that value in a variable. Here's an example:
// Function that returns a value
function add(a, b) {
return a + b; // Returning the sum of a and b
}
// Storing the returned value in a variable
const result = add(3, 5); // The function add returns 8
console.log(result); // Output: 8Function declarations can also include default parameters. Default parameters allow you to set default values for function arguments, which are used when the function is called without passing those specific arguments. Here's an example:
// Function with default parameters
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
// Example usage
console.log(greet('Prakash')); // Output: Hello, Prakash!
console.log(greet()); // Output: Hello, Guest!Key Characteristics of Function Declarations:
- Readable Syntax: Function declarations are easy to read and understand, making them a good choice for defining reusable blocks of code.
- Supports Default Parameters: Default parameters provide fallback values, reducing the need for additional checks inside the function.
- Reusable and Named: The function is named, making it reusable throughout its scope.
Default Parameters in Detail:
- Default parameters are evaluated at the time the function is called, not at the time of function definition.
- They are particularly useful for functions that may be called with missing or undefined arguments.
- You can combine default parameters with regular ones. Example:
function multiply(a, b = 1) { return a * b; } console.log(multiply(5, 3)); // Output: 15 console.log(multiply(5)); // Output: 5 (b defaults to 1)
Function declarations are one of the most common ways to define reusable functionality in JavaScript, and default parameters further enhance their flexibility by making them more robust and versatile.
Anonymous FunctionsThese are functions without a name, often used as arguments to other functions.
setTimeout(function() {
console.log('This runs after 2 seconds');
}, 2000);
// Output : This runs after 2 seconds
As you can see we are passing a function which has no name as an argument in setTimeout function.
Function ExpressionsA Function Expression defines a function as part of a larger expression, such as assigning it to a variable. Unlike function declarations, function expressions are not hoisted, which means you cannot call them before they are defined in the code. Function expressions can be named or anonymous, and they are often used in situations where you need a function as a value (e.g., callbacks).
// Anonymous Function Expression
const multiply = function (x, y) {
return x * y;
};
console.log(multiply(4, 5)); // Output: 20
// Named Function Expression
const divide = function divideNumbers(a, b) {
return a / b;
};
console.log(divide(10, 2)); // Output: 5Key Points:
- Function expressions are not hoisted, so they must be defined before use.
- They can be used as callbacks or passed as arguments to other functions.
- Named function expressions help in debugging, as their names will appear in stack traces.
Introduced in ES6, arrow functions are also a form of function expression, but with a shorter syntax. Arrow functions provide a concise syntax for writing functions. They are particularly useful for inline and callback functions. Making them useful in specific scenarios like handling event listeners or working with promises. Here's an example:
// Arrow function syntax:
const divide = (a, b) => a / b;
// Example usage:
console.log(divide(10, 2)); // Output: 5
// Without braces for a single return expression:
const square = x => x * x;
console.log(square(4)); // Output: 16
// With braces and explicit return for multi-line functions:
const multiplyAndLog = (a, b) => {
console.log('Multiplying:', a, b);
return a * b;
};
console.log(multiplyAndLog(3, 5)); // Output: 15Key characteristics of arrow functions:
- **Implicit Returns**: When the function body contains a single expression, you can omit braces and the
returnkeyword, making the code shorter and cleaner.
Arrow functions are a powerful tool in modern JavaScript development, particularly in React, where they are often used for defining functional components or passing callback functions.
Note : Both Function expression and arrow function supports default parameter.
An Immediately Invoked Function Expression (IIFE) is a JavaScript function that executes immediately after being defined. It is written using the syntax (function() { ... })();, where the function is defined and invoked in the same expression. IIFEs help avoid polluting the global scope by keeping variables and logic encapsulated within their own scope.
Common Use in the DOM: IIFEs are widely used in **DOM manipulation** to execute scripts immediately after the page loads. This ensures that elements are ready for interaction, preventing variable conflicts and unexpected behavior.
var iAmIIFE = function (){
return 'I execute immediately !';
}();
console.log(iAmIIFE); // 'I execute immediately !'
You can see that the iAmIIFE function is executed immediately because we invoked it using () right after its definition.
Note :iAmIIFE will be part of the global scope if it is declared in the global because it is assigned to a variable.
Example of IIFE that will not be part of the global scope(function (){
console.log('I execute immediately !');
})();
// output : I execute immediately !
The statement before an IIFE should always end with a semicolon (;), or it may throw an error.
var name = "Prakash" //missing semicolon, will throw error
(function(name){
return name;
})(name); //Uncaught TypeError: Prakash is not a function
Difference Between Regular Function and Arrow Function
| Feature | Regular Function | Arrow Function |
|---|---|---|
| Syntax | function funcName() { ... } | const funcName = () => { ... } |
| Hoisting | Hoisted (can be called before its declaration) | Not hoisted (cannot be called before assignment) |
Context of this | Own this context, based on how it's called | Lexically bound this (inherits from surrounding context) |
| Arguments Object | Has access to arguments object | No arguments object, uses rest parameters instead |
| Can Be Used as Constructor | Yes (can be used with new) | No (cannot be used with new) |
| Return Value | Explicitly returns a value with return | Implicit return (if expression is on a single line, no need for return) |
Note : Above you might have found new words like Hoisting this argument Constructor right ? Don't worry we will see all these later in details. Because i don't want to confuse you.
Difference between Regular and IIFE function
| Feature | Regular Function | IIFE (Immediately Invoked Function Expression) |
|---|---|---|
| Invocation | Needs to be called explicitly (e.g., myFunction()). | Executes immediately after definition. |
| Scope | Variables are local, but the function name remains in scope. | Variables are local, and the function name is not stored in scope. |
| Global Pollution | Function declaration stays in memory until garbage collection. | Function executes and disappears immediately. |
| Use Case | Used for reusable logic throughout the script. | Best for one-time execution, encapsulation, and avoiding conflicts. |
Summary
- Functions are reusable blocks of code.
- You can define them with different syntaxes, such as declarations, expressions, or arrow functions.
- Functions help keep your code organized and maintainable.