Lecture-5 Notes - Functions in JS-3302
Lecture-5 Notes - Functions in JS-3302
Function Declaration:
Function Expression
● A function expression involves assigning a function to a variable or a property
of an object.
● Function expressions are not hoisted and must be defined before they are
called.
● They can be anonymous (without a name) or named.
● Function expressions are often used to create functions on the fly, as
arguments to other functions, or to encapsulate code within a specific scope.
● Examples of function expressions include anonymous functions, arrow
functions, and immediately invoked function expressions (IIFE).
Anonymous Function:
● An anonymous function, also known as a nameless function or function
expression, is a function that is defined without a specified name. Instead, it is
assigned to a variable or used as an argument directly within the code.
● Anonymous functions are useful when you need to define a small function for
a specific task without the need for a named function declaration.
Example:
};
console.log(square(5)); // Output: 25
(function() {
// Function body
})();
Example:
(function() {
function displayMessage() {
console.log(message);
displayMessage();
})();
Arrow Function:
● An arrow function is a concise syntax introduced in ES6 for defining functions.
It offers a more compact and expressive way to write functions, particularly for
one-liners.
● It's important to note that arrow functions have a lexically bound "this"
context, which differs from regular functions. However, since we haven't
covered "this" in the earlier lectures, we will explore it in detail shortly.
Here are some important points to understand about arrow functions:
Arrow functions are defined using the => (fat arrow) notation, followed by the
function body enclosed in curly braces {}.
2. Implicit return: Arrow functions have an implicit return feature. The return
statement is not required if the function body consists of a single expression.
The result of the expression is automatically returned. For example:
console.log(double(5)); // Output: 10
Callback Function
In JavaScript, a callback function is a function that is passed as an argument to
another function and is executed later in response to an event or an asynchronous
operation. Callback functions provide a way to ensure that certain code is executed
only when a specific task is completed or an event occurs.
Example:
callback(message);
function displayMessage(message) {
console.log(message);
In this example, the greet function takes a name and a callback function
callback as arguments. It constructs a greeting message using the name
parameter and then invokes the callback function with the message.
Impure Function
● A pure function is a function that always produces the same output for the
same inputs and does not cause any side effects.
● It relies only on its arguments and does not modify any external state. Pure
functions are predictable, easier to test, and promote code reusability.
● Pure functions are a fundamental concept in functional programming and play
a crucial role in building reliable and maintainable code. By following the
principles of pure functions, you can minimize side effects, improve code
predictability, and make your programs easier to understand and reason
about.
Example:
Impure Function
● An impure function is a function that can produce different outputs for the
same inputs or cause side effects by modifying external state.
● It may rely on variables outside its scope or perform actions like modifying
global variables or making network requests. Impure functions can be harder
to reason about and test.
Example:
function incrementCounter() {
counter++;
console.log("Counter incremented.");
}
incrementCounter(); // Output: Counter incremented.
console.log(counter); // Output: 1
Higher-Order Function
In JavaScript, a higher-order function is a function that can accept other functions as
arguments or return a function as its result. Higher-order functions provide a
powerful and flexible way to work with functions and enable functional programming
paradigms.
1. map():
● The map() method is a higher-order function that operates on arrays in
JavaScript. It creates a new array by applying a provided callback function to
each original array element.
● The callback function is executed for every element, and the return value of
each function call is added to the new array.
● The resulting array has the same length as the original array, with each
element transformed based on the logic defined in the callback function.
Example:
return name.length;
});
2. filter():
● The filter() method is another higher-order function that works with arrays.
It creates a new array containing elements from the original array that satisfy
a specified condition.
● The callback function provided to filter() is executed for each element, and
if the return value is true, the element is included in the resulting array. If the
return value is false, the element is excluded.
Example:
});
3. reduce():
● The reduce() method is a higher-order function that allows for the
accumulation of a single value by iterating over the elements of an array.
● It executes a reducer function on each element and maintains an
accumulator that stores the accumulated value.
● The reducer function takes two arguments: the accumulator and the current
element. The accumulator is updated based on the logic defined in the
reducer function, and the final accumulated value is returned.
Example:
}, 1);
In this example, the reduce() function is used to calculate the product of all the
numbers in the numbers array.
find():
● The find() method returns the first element in an array that satisfies the
provided testing function.
● It executes the callback function once for each element in the array until it
finds a match, and then stops the iteration.
● If a matching element is found, it is returned; otherwise, undefined is
returned.
Example:
});
console.log(foundNumber); // Output: 4
In this example, the find() method is used to search for the first element in
the numbers array that is greater than 3. The callback function takes a number
as an argument and returns true if the condition is satisfied. The find()
method stops iterating as soon as it finds the first match, and returns that
element (4 in this case).
findIndex():
● The findIndex() method returns the index of the first element in an array
that satisfies the provided testing function.
● It executes the callback function once for each element in the array until it
finds a match, and then stops the iteration.
● If a matching element is found, its index is returned; otherwise, `-1` is
returned.
Example:
});
console.log(index); // Output: 2
In this example, the findIndex() method is used to search for the index of the first
occurrence of the string "grape" in the fruits array. The callback function takes a
fruit as an argument and returns true if the condition is satisfied. The
findIndex() method stops iterating as soon as it finds the first match, and returns
the index of that element (`2` in this case).
Other functions in JavaScript
● There are various functions in-built functions in JavaScript that make it easy to
use.
● The array functions given below are powerful tools in JavaScript for
manipulating and working with arrays. They provide convenient ways to
iterate, search, and modify arrays based on specific conditions or operations.
1. every:
The every function tests whether all elements in an array pass a specific condition
defined by a provided function. It returns a boolean value indicating if all elements
satisfy the condition.
Example:
});
2. fill:
The fill function changes all elements in an array with a static value, starting from
a specified start index and ending at a specified end index.
Example:
numbers.fill(0, 2, 4);
3. findLast:
The findLast function returns the last element in an array that satisfies a given
condition defined by a provided function. It searches the array from right to left.
Example:
});
console.log(foundNumber); // Outputs: 40
4. findLastIndex:
The findLastIndex function returns the index of the last element in an array that
satisfies a given condition defined by a provided function. It searches the array from
right to left.
Example:
});
console.log(foundIndex); // Outputs: 3
5. forEach:
The forEach function executes a provided function once for each element in an
array. It is commonly used to perform an operation on each item of the array without
returning a new array.
Example:
const numbers = [1, 2, 3];
numbers.forEach(function(number) {
console.log(number * 2);
});
Function currying
● Function currying is a technique in JavaScript that involves transforming a
function with multiple arguments into a sequence of functions, each taking a
single argument.
● It allows you to create new functions by partially applying the original function
with some arguments, resulting in a more specialized and reusable function.
● Function currying is a powerful technique in JavaScript that enables code
reuse, modularity, and composability. It helps create more flexible and
specialized functions by partially applying arguments, leading to cleaner and
more expressive code.
function multiply(a, b) {
return a * b;
function curriedMultiply(a) {
}
const multiplyByTwo = curriedMultiply(2);
console.log(multiplyByTwo(5)); // Output: 10
console.log(multiplyByThree(5)); // Output: 15
this keyword
The this keyword in JavaScript refers to the object that is currently executing the
code or the object that a function is a method of. It is a special identifier that allows
you to access properties and methods within the context of the object.Some of its
usage are mentioned below:
1. Implicit Binding:
● In most cases, the this keyword is implicitly bound to the object that is left of
the dot when invoking a method.
● The value of this is determined dynamically at runtime based on how a
function is called.
● It allows methods to access the properties and other methods of the object
they belong to.
Example:
const person = {
name: "John",
age: 25,
greet: function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age}
years old.`);
}
};
person.greet(); // Output: Hello, my name is John and I'm 25 years
old.
In this example, the greet() method of the person object uses the this keyword to
access the name and age properties of the same object. The this keyword is
implicitly bound to person since person is left of the dot when invoking the greet()
method.
2. Explicit Binding:
3. Global Context:
● In the global scope or when this is not inside any object or function, it refers to
the global object (window in browsers, global in Node.js).
● However, in strict mode ("use strict"), the value of this is undefined in the
global context.
Example:
console.log(this); // Output: Window (in browsers) or Global
The behavior of the this keyword can vary depending on how a function is called or
the context in which it is used. Understanding the different binding mechanisms of
this is essential for properly accessing and manipulating object properties and
methods in JavaScript.
Summarizing it
In this set of notes, we covered various concepts related to functions in JavaScript.
References
● this keyword in JavaScript: Link
Iife function
(function (){
console.log("Hello Raj");
})();