Search This Blog

2024/03/26

Javascript : Lambda Function

A JavaScript Lambda Function is an anonymous function
written without a name or a function definition.
These functions are often referred to as "arrow functions"
because they use the "fat arrow" (=>) syntax to define the function.

Lambda functions are a concise and convenient way to write small functions
for a specific purpose, such as transforming an array of data or filtering
a list of items.

Code:
const square = (x) => x * x

Explanation:
In this example, the function takes a single argument, x, and returns
the result of x * x. The => syntax is used to define the function, and
the entire function is written on a single line, making it concise and
easy to read.

Lambda functions can also be written with multiple arguments and a block of
code:

Code:
const multiply = (x, y) => {
return x * y;
};

Explanation:
In this example, the function takes two arguments, x and y, and returns
the result of x * y. The function is written with a block of code
enclosed in curly braces with mandatory return statement, allowing
for more complex operations.
Lambda function written with a block of code enclosed in curly braces but
without return statement.
Code:
const multiply = (x, y) => {
x * y;
};
console.log(multiply(2,3))
Output:
undefined

Explanation:
If return statement is not there in lambda function with a block of
code enclosed in curly braces then output is undefined.

Using variable defined in outer scope of lambda function:
Code:
let ext = 45
let sum = (a, b) => {
console.log(ext)
return a+b;
};
console.log(sum(5,7))
Output:
45
12
Bounded Context:
Bounded context represents a specific area or segment of a larger business
domain where the terminology, concepts, rules, and boundaries are
well-defined and consistent.

Example of Bounded Context:

Let's consider an example of a bounded context within the context of an
e-commerce platform. In this scenario, we'll focus on two bounded contexts:
"Order Management" and "Inventory Management."

1) Order Management Bounded Context:

a) Purpose: Handles the processing and management of orders placed by
customers.

b) Key Concepts and Models:
1) Order: Represents an order placed by a customer, including details
such as order ID, customer ID, items ordered, total price, shipping
address, etc.
2) OrderStatus: Tracks the status of an order (e.g., pending,
confirmed, shipped,delivered, canceled, etc.).
3) Payment: Handles payment-related information and transactions
associated with orders.

c) Ubiquitous Language:
1) Terms such as "order," "order status," "payment," "cart," "checkout
," etc., are part of the ubiquitous language within the Order
Management context.

d) Functionality:
1) Processes orders, validates payments, updates order status, sends
notifications, handles cancellations, generates invoices, etc.

2) Inventory Management Bounded Context:
a) Purpose: Manages product inventory, stock levels, and availability for
fulfilling orders.

b) Key Concepts and Models:
1) Product: Represents a product available for sale, including attributes
like product ID, name, description, price, quantity in stock, etc.

2) Inventory: Tracks inventory levels, stock movements (e.g., additions,
removals), and availability of products.
3) StockKeepingUnit (SKU): Identifies specific variants or versions of
products with unique attributes (e.g., size, color, model).

c) Ubiquitous Language:
1) Terms such as "product," "inventory," "stock," "SKU," "availability,"
etc., are part of the ubiquitous language within the Inventory Management
context.

d) Functionality:
1)Manages product catalog, updates stock levels, handles inventory
adjustments (e.g., restocking, returns, damaged items), checks product
availability, notifies Order Management about stock changes, etc.

In this example:

The "Order Management" bounded context focuses on handling customer orders,
payments, and order status tracking.The "Inventory Management" bounded context
focuses on managing product inventory, stock levels, and availability for
fulfilling orders.

Each bounded context has its own set of domain models, terminology, rules,
and functionality. The boundaries between these contexts help maintain
clarity, consistency, and separation of concerns within the e-commerce
platform. Communication and integration between these bounded
contexts can be achieved through context mapping techniques, ensuring that
Order Management and Inventory Management work together seamlessly while
maintaining autonomy and clarity within their respective domains.

Benefits of using JavaScript Lambda Functions:

1)Conciseness: Lambda functions allow you to write shorter and more compact
code compared to traditional function expressions. They eliminate the need
for the function keyword and provide a more streamlined syntax for defining
functions.

Code:
// Traditional function expression
const add = function(a, b) {
return a + b;
};

// Lambda function (arrow function)
const add = (a, b) => a + b;

2)Implicit Return: Arrow functions have implicit return behavior when the
function body consists of a single expression. This means you can omit the
return keyword, making the code even more concise.

Code:
// Traditional function expression
const multiply = function(a, b) {
return a * b;
};

// Lambda function with implicit return
const multiply = (a, b) => a * b;
3)Lexical this Binding: One of the significant advantages of arrow functions
is that they inherit the this value from the surrounding lexical context
(the context in which they are defined), rather than creating their own this
context. This behavior can help avoid confusion and errors related to this
scoping.

Code:
function Counter() {
this.count = 0;

// Using traditional function expression
setInterval(function() {
/* 'this' refers to the global object
(or undefined in strict mode),
not Counter instance*/
this.count++;
console.log(this.count);
}, 1000);

// Using arrow function
setInterval(() => {
this.count++; // 'this' refers to the Counter instance
console.log(this.count);
}, 1000);
}

const counter = new Counter();

Output:
NaN
1
NaN
2
Nan
3
.
.
.

Explanation:
Inside first setInterval using traditional function expression initial
value of this.count is undefined.Inside second setInterval using arrow
function initial value of this.count is 0 inherited from Counter()
function .

4) No Binding of arguments: Arrow functions do not have their own arguments
object. Instead, they inherit the arguments object from the enclosing function
or scope. This can lead to more predictable behavior, especially in nested
functions or callback scenarios.

Code:
function regularFunction() {
const innerFunction = () => {
// Inherits 'arguments' from regularFunction
console.log(arguments);
};
innerFunction();
}
regularFunction(1, 2, 3);
Output:
[Arguments] { '0': 1, '1': 2, '2': 3 }

Explanation:
Arrow functions do not have their own arguments object. Instead, they inherit
the arguments object from the enclosing non-arrow function (if any) or the
global scope. In other words, arrow functions do not create their own
arguments binding; they rely on the lexical scope for arguments.



Using normal function instead of arrow function in above code.

Code:
function regularFunction() {
const innerFunction = function() {
console.log(arguments);
};
innerFunction();
}

regularFunction(1, 2, 3);
Output:
[Arguments] {}

Using rest operator to capture argument:

Code:
const arrowFunction = (...args) => {
console.log(args); // Rest parameter captures function arguments
};

arrowFunction(1, 2, 3);

Output:
[ 1, 2, 3 ]



5) Ease of Use in Functional Programming: Lambda functions align well with
functional programming principles and are commonly used with higher-order
functions like map, filter, reduce, etc., to write expressive and
functional-style code.

6) Implicitly Bound Context: Arrow functions maintain the context
(this, arguments, super, and new.target) of their enclosing scope,
making them suitable for callback functions and event handlers
where maintaining the correct context is crucial.

7) Performance Considerations: While not a direct benefit of lambda functions
per se, their concise syntax and reduced overhead can contribute to improved
performance in certain scenarios, especially when working with large-scale
applications or performance-sensitive code.

No comments:

Post a Comment