A function contains blocks of code that need to be executed repeatedly or based on certain events.
Why do we need Function?
Function is reusable set of statements and expressions. In the example below, the same set of actions is repeated and again. To avoid repetitive blocks of code. Functions provide a way to organize and reuse code, making your programs modular and more manageable
Example
let a = 10;
let b = 20;
c = a + b;
console.log("sum = " + c);
a = 100;
b = 200;
c = a + b;
console.log("sum = " + c);
Output
The above set of statements are replaced by function as shown below:
The function declaration includes two variables d and f which serve as input parameters to the functions. The input to a function is passed through function call. The function can be called as many times as needed. The main advantage is that do not need to repeat the same blocks of code again and again.
Example
let a = 10;
let b = 20;
function sum(d, f) {
let e = d + f;
console.log("sum = " + e);
}
sum(a, b);
a = 100;
b = 200;
sum(a, b);
Output
Function can be,
- a variable with a value,
- assigned as a value to the other function,
- anonymous
- used as argument to call to other function.
Function definition
To define a function is by using the function keyword followed by function name, a set of parentheses for parameters (optional) and curly braces ‘{ }’ to enclose the function body
Syntax
}
Example
function greet(name) {
console.log('Hello, ' + name + '!');
}
In the example above, a function named “greet” is defined as a parameter ‘name’. The function body logs a greeting message to the console using the provided name.
Function Invocation
To execute a function, one needs to invoke or call it by using the function name followed by parentheses. Arguments can be passed into the function within the parentheses. Functions in JavaScript can also have return statements to send back a value as the result of function. Parameters allows to pass data into the function, and the function body can contain any valid JavaScript code.
Syntax
Example
greet(“John”);
Function Expression
Function can also be defined using function expressions. In this case, the function is assigned to a variable property.
const square = function(num)
{
return num *num;
}
A function expression is defined and assigned to the square variable. The function takes a parameter ‘num’ and returns the square of the provided number.
Arrow functions
Arrow functions provide a concise syntax for writing functions, especially for simple, one line functions. They use => arrow syntax
const multiply = (a,b) => a*b;
In this example, an arrow function named ‘multiply’ takes two parameters and return their product.
Function Declaration vs. Function Expression
In JavaScript one can use either function declaration or function expression. Function Expression are always anonymous.
Properties | Function Declaration | Function Expression |
Has name | Yes | No |
Can be used standalone | Yes | NO |
Can be assigned to the variable | Yes | Yes |
Can be passed as argument in the call to the other function | Yes | Yes |
//Function Declaration
function myFn(a,b)
{
let c;
a = a+1;
c = a +b;
return c;
}
// Function Expression
function(a,b)
{
let c;
a = a + 1;
c = a+ b;
return c;
}
Function Declaration
Function declarations are hoisted to the top of their scope, which means you can call the function before its actual declaration in the code.Function declarations are block-scoped to the nearest enclosing block. However, since they are hoisted, they can be called from anywhere within the current scope.
Syntax
{
}
Example
greet(); // Output: "Hello!"
function greet() {
console.log("Hello!");
The function greet() is hoisted, so it can be called before its actual declaration in the code.
Function Expression
Function expressions are not hoisted like function declarations. You need to declare the function expression before calling it. The scope of a function expression depends on how and where it is assigned
Syntax
// Function body
};
Example
greet(); // Error: greet is not a function
var greet = function() {
console.log("Hello!");
};
In this example, the variable greet is hoisted, but since it’s assigned a function expression, the assignment itself is not hoisted. As a result, greet is undefined when the function is called, causing an error.
Function expression can be passed as an argument in function call. For example: consider the setTimeout(), a built in function in JavaScript which is used to schedule the execution of a function or an expression after a specified delay (in milli seconds). The function lets to introduce time intervals and delays in the code, making it useful for various asynchronous operations, animations and event handling scenarios.
Syntax
- function’: the function or code snipped to be executed after the specified ‘delay’
- ‘delay’: the time in milliseconds to wait before executing the function
- ‘arg1, arg2,…’: Optional argument list that needs to pass the function when it is called.
setTimeout() is asynchronous. It means that it schedules the function to be executed in the future and continues executing the rest of the code without waiting for the delay to finish. This behavior is what allows non-blocking operations in JavaScript. If you need to cancel the execution of a scheduled function before it runs, you can use the value returned by setTimeout():
Code
Demonstration of setTimeout using,
Function Declaration
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
setTimeout(sayHello, 3000, "Raji");
Output
Function Expression
setTimeout(function ()
{
console.log("Delayed Message");
}, 2000);
Output
A callback function is a function that is passed as an argument to another function and is intended to be executed later, often after some asynchronous operation or event has bee n completed. Callback functions are commonly used in scenarios where we want to ensure that certain code runs only after a particular task has finished or a specific event has occurred. When you encounter the term “callback,” it typically refers to the function that you pass to another function as an argument, which will be called later when some specific condition is met or when an asynchronous task is completed. The name “callback” is not a keyword in the language; it’s just a naming convention to describe the function’s purpose.
Code
function greeting(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
function warmwish() {
console.log("welcome!");
}
greeting("Raji", warmwish);
Output
Views: 14