Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

1.6. Usage of JavaScript Functions

The document discusses JavaScript functions including built-in and user-defined functions, function calls, exercises on functions, and function methods like call, apply and bind.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

1.6. Usage of JavaScript Functions

The document discusses JavaScript functions including built-in and user-defined functions, function calls, exercises on functions, and function methods like call, apply and bind.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Learning outcome1:

Use Fundamental Features of

Basic Features

Usage of
1. Table of Contents
1. Table of Contents ............................................................................................................................ 2
2. Usage of JavaScript Functions ......................................................................................................... 3
1.1. Introduction ............................................................................................................................ 3
1.2. Types of JavaScript Functions ................................................................................................. 3
1.2.1. Built-in functions: ................................................................................................................ 3
1.2.2. User-defined Functions ....................................................................................................... 3
1.3. Function call ............................................................................................................................ 4
1.4. Exercises on JavaScript Functions ........................................................................................... 4
Exercises .............................................................................................................................................. 4
2. Usage of JavaScript Functions
1.1. Introduction
JavaScript functions are reusable blocks of code performing specific tasks, enhancing code
organization, and promoting modularity for efficient development.

1.2. Types of JavaScript Functions


JavaScript functions can be defined and invoked to perform specific tasks. There are two main types
of functions: built-in functions (also known as standard functions or native functions) and user-
defined functions.

1.2.1. Built-in functions:


Built-in functions are part of the JavaScript language and are available for use without requiring any
additional setup.

Example: Using the Math.random () function to generate a random number between 0 (inclusive)
and 1 (exclusive).

Built-in functions cover a wide range of tasks, such as working with

 strings (toUpperCase(), slice(), indexOf(), etc.),


 arrays (push(), pop(), sort(), etc.),
 performing mathematical calculations (Math.sqrt(), Math.floor(), etc.),
 and manipulating dates (new Date(), getDate(), etc.),
 etc.
Note: For more information about string and array built-in function, visit the following link:

 String: https://www.w3schools.com/jsref/jsref_obj_string.asp
 Array: https://www.w3schools.com/jsref/jsref_obj_array.asp

1.2.2. User-defined Functions


User-defined Functions are functions created by the programmer to perform a specific task. They
can take input parameters and return a value.

Example: A simple function to calculate the area of a rectangle.


1.3. Function call
JavaScript function call is invoking a function to execute its code

1.4. Exercises on JavaScript Functions


Exercises
#
What is a Named Function?
A named function is a function with a specific name declared using the function keyword

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

What is an Anonymous Function?


An anonymous function is a function without a name.
It is often used as a callback or assigned to a variable.
2
const greet = function(name) {
return `Hello, ${name}!`;
};
What is an Arrow Function?
Arrow functions are a shorthand syntax for writing anonymous functions, with a more concise
3 syntax and a lexical ‘this’ binding.

const multiply = (a, b) => a * b;

What is an IIFE (Immediately Invoked Function Expression)?


An IIFE is a function that is executed immediately after its creation.
4
(function() {
console.log('This is an IIFE');
})();

What is a Higher-Order Function?


A higher-order function is a function that takes one or more functions as arguments (callback)
or returns a function.

// Example of a higher-order function that takes a function as an


argument

function higherOrderFunction(callbackFunction) {
// Perform some operation
const result = 10;
// Call the callback function with the result
return callbackFunction(result);
}

function callbackFunction(value) {
5 return value * 2;
}

console.log(higherOrderFunction(callbackFunction)); // Output: 20

// Example of a higher-order function that returns a function


function multiplier(factor) {
// This is a higher-order function that returns a new function
return function(x) {
return x * factor;
};
}
const double = multiplier(2); // Returns a function that doubles its
input
console.log(double(5)); // Output: 10

What is a Callback Function?


6 A callback function is a function passed as an argument to another function and executed later.
function fetchData(url, callback) {
// ... fetch data from the url ...
callback(data);
}

What is a Recursive Function?


A recursive function is a function that calls itself to solve a problem.

// Example of a recursive function to calculate factorial


function factorial(n) {
if (n === 0 || n === 1) {
7 return 1;
} else {
return n * factorial(n - 1);
}
}

What is a Rest Parameter in a Function?


The rest parameter allows a function to accept an indefinite number of arguments as an array.

// Example of a function with a rest parameter


function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

// Example with a rest parameter and many other parameters


A function definition can only have one rest parameter, and the rest
parameter must be the last parameter in the function definition.

 Wrong
8 function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}
 Correct
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");


// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

What is a Default Parameter in a Function?


Default parameters provide default values for function arguments if they are not explicitly
9 passed.

// Example of a function with default parameters


function greet(name = 'Guest') {
return `Hello, ${name}!`;
}

What are the Function Methods call, apply, and bind used for?
These methods allow you to set the context (i.e., the this value) explicitly for a function call.

const person = {
name: 'Alice',
greet() {
return `Hello, ${this.name}!`;
},
};

const anotherPerson = {
name: 'Bob',
10 };

// Using call
const greetAlice = person.greet.call(anotherPerson); // "Hello, Bob!"

// Using apply
const greetBob = person.greet.apply(anotherPerson); // "Hello, Bob!"

// Using bind
const greetJohn = person.greet.bind({ name: 'John' });
console.log(greetJohn()); // "Hello, John!"

What is the difference between bind and call in JavaScript?


bind returns a new function with the bound context (this value), while call immediately calls
the function with the provided context.

const person = {
name: 'Alice',
greet() {
return `Hello, ${this.name}!`;
},
};
11
const anotherPerson = {
name: 'Bob',
};

const boundFunction = person.greet.bind(anotherPerson);


boundFunction(); // "Hello, Bob!"

const calledFunction = person.greet.call(anotherPerson);


calledFunction; // "Hello, Bob!"
What is a Recursive IIFE?
A recursive IIFE is an IIFE that calls itself within its definition.

// Example of a recursive IIFE that calculates factorial


12 const factorial = (function(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
})(5);

console.log(factorial); // 120

Explain the concept of bind with an arrow function.


Arrow functions do not have their own this value, so using bind with an
arrow function does not have any effect on the function's this value.

const person = {
name: 'Alice',
greet: () => {
13 return `Hello, ${this.name}!`; // 'this' refers to the global object
(window in browsers)
},
};

const greetFunc = person.greet.bind({ name: 'Bob' });


console.log(greetFunc()); // "Hello, undefined!"

Explain the new keyword and how it creates objects from a


constructor function.
The new keyword is used to create objects from constructor functions. It
creates a new object, sets the constructor's this to the new object, and
implicitly returns the new object.

function Person(name, age) {


14 this.name = name;
this.age = age;
}

const john = new Person('John', 30);


console.log(john); // Person { name: 'John', age: 30 }

Explain the concept of call with a regular function.


The call method allows you to call a function with a specified this value
and individual arguments.

15
function greet() {
return `Hello, ${this.name}!`;
}

const person = {
name: 'Alice',
};

console.log(greet.call(person)); // "Hello, Alice!"

What is a Factory Function?


A factory function is a function that returns an object without using the
new keyword.

function createPerson(name, age) {


return {
16 name: name,
age: age,
};
}

const john = createPerson('John', 30);


console.log(john); // { name: 'John', age: 30 }

What are Callbacks used for in asynchronous JavaScript?


Callbacks are used to handle asynchronous operations in JavaScript, ensuring that certain code
is executed after an asynchronous operation completes.
function fetchData(url, onSuccess, onError) {
// Asynchronous operation to fetch data
fetch(url)
.then((response) => response.json())
.then((data) => onSuccess(data))
.catch((error) => onError(error));
}
17
fetchData(
'https://api.example.com/data',
(data) => {
console.log('Data received:', data);
},
(error) => {
console.error('Error occurred:', error);
}
);

Explain the concept of this in a regular function and an arrow


function.
In a regular function, this refers to the context in which the function is called (determined by
18 the calling object). In an arrow function, this lexically represents the value of this from the
enclosing scope.

const person = {
name: 'Alice',
regularFunc: function() {
console.log(this.name); // Refers to the calling object (person)
},
arrowFunc: () => {
console.log(this.name); // Refers to the 'this' of the enclosing
scope (global object)
},
};

person.regularFunc(); // "Alice"
person.arrowFunc(); // undefined (or error if 'name' is not defined in
the global object)

Explain the reduce function with an example.


The reduce function is used to accumulate a single value from an array by executing a reducer
function on each element.

19 const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((acc, num) => acc + num, 0);


console.log(sum); // 15

Explain the async and await keywords and their usage in


asynchronous JavaScript.
The async keyword is used to declare an asynchronous function that returns a promise. The
await keyword is used inside an async function to wait for the resolution of a promise before
continuing execution.

function fetchData(url) {
return fetch(url).then((response) => response.json());
}
20 async function processData() {
try {
const data = await fetchData('https://api.example.com/data');
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}

processData();

What are Promises in JavaScript and how do they handle


asynchronous operations?
21 Promises are objects representing the eventual completion (or failure) of an asynchronous
operation. They provide a clean way to handle asynchronous code and avoid the callback hell.

function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => response.json())
.then((data) => resolve(data))
.catch((error) => reject(error));
});
}

fetchData('https://api.example.com/data')
.then((data) => console.log('Data:', data))
.catch((error) => console.error('Error:', error));

What is the purpose of the finally method in a Promise?


The finally method in a Promise is used to specify a callback that will be executed regardless of
whether the Promise is resolved or rejected.

function fetchData(url) {
return fetch(url).then((response) => response.json());
22 }

fetchData('https://api.example.com/data')
.then((data) => console.log('Data:', data))
.catch((error) => console.error('Error:', error))
.finally(() => console.log('Cleanup or final actions here'));

What is the purpose of the finally method in a Promise?


The finally method in a Promise is used to specify a callback that will be executed regardless of
whether the Promise is resolved or rejected.

function fetchData(url) {
return fetch(url).then((response) => response.json());
23 }

fetchData('https://api.example.com/data')
.then((data) => console.log('Data:', data))
.catch((error) => console.error('Error:', error))
.finally(() => console.log('Cleanup or final actions here'));

What is the difference between forEach, map, and filter


functions on arrays?
1. forEach: Executes a provided function once for each array element
24 but does not create a new array. Used for side effects.

2. map: Creates a new array by applying a function to each element of


the array.
3. filter: Creates a new array containing all elements that pass the
test implemented by the provided function.

const numbers = [1, 2, 3, 4, 5];

// Using forEach
numbers.forEach((num) => console.log(num)); // 1, 2, 3, 4, 5

// Using map
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]

// Using filter
const evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // [2, 4]

Explain the find and findIndex functions on arrays with an


example.
1. find: Returns the value of the first element in the array that
satisfies the provided testing function.

2. findIndex: Returns the index of the first element in the array that
satisfies the provided testing function.

25 const numbers = [10, 20, 30, 40, 50];

// Using find
const foundNumber = numbers.find((num) => num > 30);
console.log(foundNumber); // 40

// Using findIndex
const foundIndex = numbers.findIndex((num) => num > 30);
console.log(foundIndex); // 3

What are the some and every functions on arrays used for?
1. some: Returns true if at least one element in the array satisfies the
provided testing function.

2. every: Returns true if all elements in the array satisfy the provided
26 testing function.

const numbers = [10, 20, 30, 40, 50];

// Using some
const hasEvenNumber = numbers.some((num) => num % 2 === 0);
console.log(hasEvenNumber); // true
// Using every
const allGreaterThanZero = numbers.every((num) => num > 0);
console.log(allGreaterThanZero); // true

What is a Set in JavaScript and how is it different from an


Array?
A Set is a collection of unique values in JavaScript. Unlike an Array, a Set does not allow
duplicate values.
27
const uniqueNumbers = new Set([1, 2, 2, 3, 3, 4]);
console.log(uniqueNumbers); // Set { 1, 2, 3, 4 }

Explain the concept of the rest operator (...) in a function


parameter list.
The rest operator (...) is used to represent an indefinite number of function arguments as an
array.

28 function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

What is JavaScript Function Expression?


A function expression is a way to define an anonymous function without giving it a name.

let sayHello = function(){


29
console.log('Hello Reader!');
}

sayHello();

Discus on the difference between Function Expression and Function Declaration.


30 Guide: https://www.geeksforgeeks.org/javascript-function-expression/

Explain the role of an Immediately Invoked Function Expression.


Guide: https://www.geeksforgeeks.org/immediately-invoked-function-expressions-iife-in-
31
javascript/

Discuss when to use IIFEs instead of traditional functions.


32 Guide: https://circleci.com/blog/ci-cd-for-js-iifes/

32

You might also like