Day 11

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

FUNCTION

AND METHODS
IN JAVASCRIPT
1
• Types of functions in JS
• How JS treat function (first-class-citizens)
• What are callbacks ?
AGENDA • What are higher-order functions
Types Of Functions ?

There are 3 popular types of functions we can develop in JavaScript :

1. Named Function

2. Anonymous Function

3. Arrow Function
Named Function
Steps Needed For Function ?

In JavaScript the function based programming approach requires 2 steps:

1. Defining/Creating the function

2. Calling/Using the function


Syntax Of Named Function Defining

function function_Name( arg 1,arg 2. . .)


{
// some code
}

Syntax Of Calling A Function

Function_Name(arg 1,arg 2. . .);


Named Function Example:-

function greet(name) {
return "Hello, " + name + "!";
}

var userName = "Alice";


var greeting = greet(userName);

console.log(greeting); // Outputs: Hello, Alice!


Points To Remember

* A function with no parameters must include a parenthesis after it’s


name

* The word “function” must be written in lowercase.


Anonymous Function
A Very Important Point !!

In JavaScript functions are first-class citizens.

This means that we can:


a. JS can store functions in variables
b. In JS we can pass them as argument to other functions
c. return them from other functions

In simple words, in JavaScript, functions are treated as values


just like any other values such as 23, "andy", and so on.
Anonymous Functions Defining
A function definition can be directly assigned to a variable .
This variable is like any other variable except that it’s value is a function
definition and can be used as a reference to that function.
Syntax:
var variablename = function(Argument List)
{
//Function Body
};

Calling Anonymous Functions


We can call an anonymous function using it’s variable name
Syntax:
variableName(arguments);
Anonymous Function Example : -

var add = function(a, b) {


return a + b;
};

const result = add(5, 3);

console.log(result); // Outputs: 8
Arrow Function
The Arrow Function

Arrow functions were introduced with ES6 as a new syntax for writing
JavaScript functions

They provide us with an alternative way to write a shorter syntax as


compared to the regular function.

Thus we can say that Arrow Functions save a developer’s time and
simplify code development
General Syntax

The General Syntax of Arrow Functions is :

(argument1, argument2, ... argumentN) => {


// function body
}

Points to understand:
1. No function keyword
2. No function name
3. A list of arguments within parenthesis, followed by a
'fat arrow' (=>), followed by a function body.
Example

To understand Arrow Function , consider the following example try


defining a function which adds two numbers passed as argument and
returns their sum:

let add = function(x,y) {


return x + y;
}

console.log(add(10,20)); // will display 30

The same can be done in a more concise way using an Arrow Function
Let’s see how…
Example

The Arrow Function version of the previous code will be:

let add = (x,y)=> {


return x + y;
};

console.log(add(10,20)); // will display 30


More Variations

If the Arrow Function has only one statement, and the statement
returns a value, we can remove the braces as well as the
return keyword:

For example:

let add = (x,y)=> x + y;


console.log(add(10,20)); // will display 30
More Variations

If the Arrow Function has only one parameter, then we can skip the
parentheses as well:

For example:

let square = n => n*n;


console.log(square(10)); // will display 100
CALLBACKS
DOES JS TREAD FUNCTION AS OBJECTS TOO ?
Yes, in JavaScript, functions are considered first-class objects. This means
that functions in JavaScript are a special type of object. Here are some
key points about functions being treated as objects in JavaScript:

Functions are Objects: In JavaScript, functions are actually objects of


type "Function." This means you can treat them like any other object,
which includes assigning them to variables, passing them as arguments
to other functions, and storing them in data structures like arrays or
objects.

Properties and Methods: Since functions are objects, they can have
properties and methods just like any other object. For example,
functions have a length property that indicates the number of named
arguments they expect, and they also have methods like bind, call, and
apply.
Example:-

function add(a, b) {
return a + b;
}

console.log("Number of Arguments Expected:", add.length);


NOTE
add.length and
var args = [2, 3]; add.apply
var sum = add.apply(null, args); Only possible
because
function
console.log("Sum:", sum); are objects

Output:-

Number of Arguments Expected: 2


Sum: 5
Callback Functions

In JavaScript, all functions are objects, just like Array , Math, Date etc

Thus they have all the features of an object like:

1. They can be stored in a variable

2. Like variables they can be passed as arguments to other functions.

3. Like variables , they can be returned from a function also


Callback Functions

Now, when we apply 2nd point in our code,


i.e. when we pass a function as argument to another function ,
then it is called a CALLBACK FUNCTION
GENERAL SYNTAX OF CALL BACK FUNCTION

<function_1>(<some_arg>,<function_2>);

In the above syntax , we are calling function_1() with some data and the
name of another function called function_2 as argument.

Then in function_1() , we might do some initial processing and


after that we can call function_2() to run.

function function_1(arg,function_2){
// initial code
function_2();
}
Example

To understand callbacks , let us start with a normal JS function

A regular JS Function:
function multiply(a, b) {
var result = a * b;
console.log("multiply Function Result:",result);
}

multiply(2, 4);

Here we have a simple function which multiplies 2 numbers. We are


then calling the function with inputs 2 and 4.
Example

Now imagine if we had to run another operation immediately


after multiply computes the result.

This is where we use a callback…


Example

function multiply(a, b, callback) {


var result = a * b;
console.log("multiply Function Result:",result);
callback(result);
}
function checkOddEven(result){
if(result%2==0){
console.log('checkOddEven Function:',result,' is Even');
}
else {
console.log('checkOddEven Function:',result,' is Odd');
}
}
multiply(7, 9, checkOddEven);
Example

Here in the multiply() function, we accept a callback as well as the input.

When we call the multiply() function we pass callback as checkOddEven.

So basically a callback is nothing but a function.

checkOddEven is a function which checks whether a number is odd or


even.
Example

In the multiply() function, at the end, we have callback(result).

This is where we ask the callback function to execute.

So in the above code, the sequence is as follows


1. First we call the multiply() function and pass checkOddEven as the callback
2. The multiply() function executes and computes the multiplication result
3. Once the result is calculated, multiply() function asks the callback to execute.
4. In this case, the callback is checkOddEven function.
5. So checkOddEven function will execute.
Anonymous Functions As Callbacks

Another way of passing a callback is by using anonymous functions as shown below:


Example:

function multiply(a, b, callback) {


var result = a * b;
console.log("multiply Function Result:", result);
callback(result);
}
multiply(-7, 9, function(result) {
if (result > 0) {
console.log('checkPosNeg Function:', result, ' is Positive');
}
else {
console.log('checkPosNeg Function:', result, ' is Negative');
}
});
Arrow Functions As Callbacks
If we prefer, then we can also write the same callback function as an ES6 Arrow Function
Example:
function multiply(a, b, callback) {
var result = a * b;
console.log("multiply Function Result:", result);
callback(result);
}
multiply(-7, 9, (result)=> {
if (result > 0) {
console.log('checkPosNeg Function:', result, ' is Positive');
}
else {
console.log('checkPosNeg Function:', result, ' is Negative');
}
});
Why We Need Callback ?

JavaScript runs code sequentially in top-down order.

However, there are some cases that a piece of code must run after
something else happens and also not sequentially.

This is called Asynchronous Programming. That we will cover while covering later
in the course.

Callbacks make sure that a function is not going to run before a task is
completed but will run right after the task has completed.

It helps us develop asynchronous JavaScript code and keeps us safe from


problems and errors.
HIGH ORDER FUNCTION
(HOD)
A higher order function is a function that takes one or more functions as
arguments that it…

so all parent function that take callback function as an argument are higher
order function (HOD).

In JS Higher-order methods, often referred to as higher-order functions


which associated with an object, like arrays…

Here's a list of some common higher-order methods:-

• forEach()
• map()
• filter()
• etc.…
foreach()
foreach()

So, what is forEach? At its core, forEach is a method available for arrays in
JavaScript.

It's designed to iterate over each element in an array and apply a provided
function (often referred to as a "callback") to each of those elements.

This means we can customize what happens to each item in the array without
writing a traditional for loop.
forEach syntax

The syntax for forEach is straightforward:

array.forEach(callback(currentValue, index, array), thisArg);

•array: This is the array you want to iterate over.


•callback: This is the heart of forEach. It's a function that you define. It takes three arguments:
•currentValue: This is the value of the current element being processed.
•index: This is the index of the current element.
•array: This is the array that forEach is being applied to.
•thisArg (Optional): You can provide an optional this context for the callback function.
foreach() Callbacks Rule
The real power of forEach lies in the callback. You can do just about
anything you want with each element. For instance, you can modify
the original array, create a new one, or perform complex
calculations.
Example:-
var numbers = [1, 2, 3, 4, 5];
var doubled = [];

numbers.forEach(function(currentValue) {
doubled.push(currentValue * 2);
});

console.log(doubled); // [2, 4, 6, 8, 10]


map()
map()

map's a built-in method for arrays in JavaScript.

It's a higher-order function designed to create a new array by


applying a custom function (a "callback") to each element in
an existing array.
map syntax

The syntax for map is straightforward and same as foreach:

const newArray = originalArray.map(callback(currentValue, index, array), thisArg);

•array: This is the array you want to iterate over.


•callback: This is the heart of forEach. It's a function that you define. It takes three arguments:
•currentValue: This is the value of the current element being processed.
•index: This is the index of the current element.
•array: This is the array that forEach is being applied to.
•thisArg (Optional): You can provide an optional this context for the callback function.
Transformation, Not Mutation
Here’s is the best part about map(), it doesn't mutate the original
array. Instead, it creates a fresh, shiny new array with transformed
values, leaving the original array untouched.

Example:-
var numbers = [1, 2, 3, 4, 5];

var doubledNumbers = numbers.map(function(currentValue) {


return currentValue * 2;
});

// doubledNumbers is now [2, 4, 6, 8, 10]


filter()
filter()

Filter is a higher-order function allows us to create a new


array by selecting elements from an existing array that meet
specific criteria.
filter syntax

The syntax for filter is straightforward and same as foreach and map:

const newArray = originalArray. filter(callback(currentValue, index, array), thisArg);

•array: This is the array you want to iterate over.


•callback: This is the heart of forEach. It's a function that you define. It takes three arguments:
•currentValue: This is the value of the current element being processed.
•index: This is the index of the current element.
•array: This is the array that forEach is being applied to.
•thisArg (Optional): You can provide an optional this context for the callback function.
The Power of Selection by filter()
With filter(), you have the power to select and extract elements
that match your criteria. Whether you're looking for numbers within
a certain range, specific words in a text, or objects with particular
properties, filter() is your trusted assistant.
Example:-
// Original array of numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Using `filter()` to create a new array of even numbers


const evenNumbers = numbers.filter(function(element) {
return element % 2 === 0;
});

// `evenNumbers` now contains [2, 4, 6, 8, 10]


Functions with the Rest Operator
Functions with the Rest Operator

So, what is the rest operator in JavaScript functions? At its core,


it's a mechanism that enables us to capture an Infinite number
of arguments as an array. This array can then be manipulated,
processed, and used within our functions. Think of it as a magic
container that can hold as many items as we throw into it.
The Rest Operator Syntax

function functionName(param1, param2, ...restParams) {


// Function logic here
}

1. functionName: This is the name of your function.


2. param1, param2: These are regular function parameters.
3. ...restParams: This is the rest parameter, marked by .... It collects all remaining arguments as
an array called restParams.

4. One important rule to remember: the rest parameter always comes at the end in the
function syntax. This means that you define regular parameters first, and then the rest
parameter, which collects all remaining arguments. This order is crucial for JavaScript to
correctly interpret the function's behavior.
Unleashing the Power of Flexibility
The beauty of the rest operator lies in its ability to handle an arbitrary
number of arguments gracefully. Consider a scenario where you want
to create a function that calculates the sum of any number of values:

Example:-
function calculateSum(...numbers) {
return numbers.reduce((acc, current) => acc + current, 0);
}

const result = calculateSum(1, 2, 3, 4, 5);

console.log(result); // Outputs: 15

You might also like