1.6. Usage of JavaScript Functions
1.6. Usage of JavaScript Functions
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.
Example: Using the Math.random () function to generate a random number between 0 (inclusive)
and 1 (exclusive).
String: https://www.w3schools.com/jsref/jsref_obj_string.asp
Array: https://www.w3schools.com/jsref/jsref_obj_array.asp
1 function add(a, b) {
return a + b;
}
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
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);
}
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!"
const person = {
name: 'Alice',
greet() {
return `Hello, ${this.name}!`;
},
};
11
const anotherPerson = {
name: 'Bob',
};
console.log(factorial); // 120
const person = {
name: 'Alice',
greet: () => {
13 return `Hello, ${this.name}!`; // 'this' refers to the global object
(window in browsers)
},
};
15
function greet() {
return `Hello, ${this.name}!`;
}
const person = {
name: 'Alice',
};
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)
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();
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));
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'));
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'));
// 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]
2. findIndex: Returns the index of the first element in the array that
satisfies the provided testing function.
// 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.
// 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
28 function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
sayHello();
32