0% found this document useful (0 votes)
5 views38 pages

51-54 - Javascript Functions and Arrays

Uploaded by

Divyansh chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
5 views38 pages

51-54 - Javascript Functions and Arrays

Uploaded by

Divyansh chauhan
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 38

FRONT-END ENGINEERING

Function JavaScript: functions and


Arrays

Dr. Aman Kumar &


Dr. Bharathiraja Nagu

Department of Computer Science and Engineering


Chitkara University, Punjab
FEE-I 1
What is function?

• A function is a block of JavaScript code that is defined once but may be


executed, or invoked, any number of times.
• A function can be used to return a value, construct an object, or as a
mechanism to simply run code.
• JavaScript functions are defined with the function keyword.
• Either function declaration or a function expression can be used.
• Functions are one of the fundamental building blocks in JavaScript. A
function in JavaScript is similar to a procedure—a set of statements that
performs a task or calculates a value, but for a procedure to qualify as a
function, it should take some input and return an output where there is
some obvious relationship between the input and the output. To use a
function, you must define it somewhere in the scope from which you
wish to call it.

FEE-1 Dr. Aman Kumar


Function Declaration
• A function definition (also called a function declaration,
or function statement) consists of the function keyword,
followed by:
• The name of the function.
• A list of parameters to the function, enclosed in
parentheses and separated by commas.
• The JavaScript statements that define the function,
enclosed in curly braces, { /* … */ }.

function functionName(parameters) {
// code to be executed
}

FEE-1 Dr. Aman Kumar


Variable Length Arguments

• In JavaScript, a function with variable-length arguments is a


function that can accept any number of arguments, including zero.
This means that the function can handle a varying number of inputs,
making it more flexible and reusable.
• Functions with variable-length arguments are useful when you don't
know how many inputs will be provided, want to write a function
that can handle optional inputs, or need to manage a varying number
of inputs efficiently.
• In JavaScript, you can create functions with variable-length
arguments using:
i) The arguments object
ii) Function Rest parameter (...args)

FEE-1 Dr. Aman Kumar 4


i) Using the arguments object
The arguments object is an array-like object that contains all the
arguments passed to a function. It's not an actual array, but it can be
converted into one.
Example:
function sum()
{
var total = 0;
for (var i = 0; i < arguments.length; i++)
{
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4)); // Output: 10
FEE-I Dr. Aman Kumar 5
ii) Using Function Rest Parameters

The rest parameter syntax allows you to represent an indefinite number


of arguments as an array. This is a more modern and readable way to
handle variable-length arguments.
Example:
function sum(...numbers)
{
return numbers.reduce((total, num) => total + num, 0);
}

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

FEE-I Dr. Aman Kumar 6


Function hoisting
• Hoisting is JavaScript's default behavior of moving
declarations to the top of the current scope. Hoisting
applies to variable declarations and to function
declarations.
• Function hoisting occurs when a function declaration is
moved to the top of the scope by the JavaScript engine.
• Function hoisting only works with
function declarations — not with function expressions.

FEE-1 Dr. Aman Kumar


Function hoisting Example

helloWorld(); function
helloWorld()
{ console.log("Hello,
world!"); }

In the example above, we are calling the helloWorld function before it has been
declared. However, because of function hoisting, the function declaration is
moved to the top of the scope, and the code runs without throwing any errors.

FEE-1 Dr. Aman Kumar


Function Scope
A function defined in the global scope can
access all variables defined in the global
scope. A function defined inside another
function can also access all variables
defined in its parent function, and any
other variables to which the parent
function has access.
Example
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";
// This function is defined in the global scope
function multiply() {
return num1 * num2;
}
console.log(multiply()); // 60
// A nested function example
function getScore() {
const num1 = 2;
const num2 = 3;
function add() {
return `${name} scored ${num1 + num2}`;
}
return add();
}
console.log(getScore()); // "Chamakh scored 5"
Function within function
• We may nest a function within another function. The nested (inner) function is
private to its containing (outer) function.
• It also forms a closure. A closure is an expression (most commonly, a function)
that can have free variables together with an environment that binds those
variables (that "closes" the expression).
• Since a nested function is a closure, this means that a nested function can
"inherit" the arguments and variables of its containing function. In other words,
the inner function contains the scope of the outer function.
• To summarize:
• The inner function can be accessed only from statements in the outer function.
• The inner function forms a closure: the inner function can use the arguments
and variables of the outer function, while the outer function cannot use the
arguments and variables of the inner function.

FEE-1 Dr. Aman Kumar


Example
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}

console.log(addSquares(2, 3)); // 13
console.log(addSquares(3, 4)); // 25
console.log(addSquares(4, 5)); // 41
Function declaration vs
Expression
• Function Declaration
A function declaration also known as a function statement declares a function with a function
keyword. The function declaration must have a function name.
Function declaration does not require a variable assignment as they are standalone constructs and
they cannot be nested inside a functional block.
These are executed before any other code.
The function in the function declaration can be accessed before and after the function definition.
Syntax:
function f1(paramA, paramB) {
// Set of statements
}
// Function Declaration
function f1(paramA, paramB) {
return paramA + paramB;
}

let result = f1(5, 5);


console.log('Sum=', result);

FEE-1 Dr. Aman Kumar


Function Expression
• A function Expression is similar to a function declaration without the function name.
• Function expressions can be stored in a variable assignment.
• Function expressions load and execute only when the program interpreter reaches the line
of code.
• The function in the function expression can be accessed only after the function definition.
Syntax:
let f1= function(paramA, paramB) { // Set of statements}
Eg
let f1 = function (paramA, paramB) {
return paramA + paramB;
}

let result = f1(5, 5);


console.log("Sum: ",result);

FEE-1 Dr. Aman Kumar


Function Declaration Function Expression
A function expression is similar to a
A function declaration must have a
function declaration without the
function name.
function name.
Function declaration does not require a Function expressions can be stored
variable assignment. in a variable assignment .

Function expressions load and


These are executed before any other
execute only when the program
code.
interpreter reaches the line of code .

The function in function declaration can The function in function expression


be accessed before and after the can be accessed only after the
function definition. function definition.
Function expressions are not
Function declarations are hoisted
hoisted

Syntax: function f1(paramA, paramB) { Syntax: var f1= function(paramA,


// Set of statements } paramB) { // Set of statements }
JavaScript- Function Definitions

Function Definitions:
Syntax
function functionName(parameters)
{
// code to be executed
}

FEE Dr. Bharathiraja Nagu 16


Function Definition Example
Example:
<!DOCTYPE html>
output :
<html>
Function Definition
<body>
Example
<h1>Function Definition Example</h1>
30 is the output
<p id="demo">is the output</p>
<script>
let x = myFunction(5, 6);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b)
{ return a * b;
}
</script></body> </html>

FEE Dr. Bharathiraja Nagu 17


Function Expressions
• A JavaScript function can also be defined using an expression.
• A function expression can be stored in a variable
Example:
<html>
<body>
Output:
<p id="demo"></p> 15
<script>
const x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML = x(5, 3);
</script> </body> </html>
❑ The function above is actually an anonymous function (a function without a
name).
❑ Functions stored in variables do not need function names. They are always
invoked (called) using the variable name.

FEE Dr. Bharathiraja Nagu 18


Java Script Array Functions
• JavaScript Array length
Returns the number of elements in an array
length Syntax
The syntax to access the length property is:
arr.length
Here, arr is an array.
Example:
let city = ["California", "Barcelona", "Paris", "Kathmandu"];
// find the length of the city array
let len = city.length;
console.log(len);
// Output: 4

FEE Dr. Bharathiraja Nagu 19


Example 1: Finding Number of Elements in an
Array
var companyList = ["Apple", "Google", "Facebook", "Amazon"];
console.log(companyList.length); // Output: 4

var randomList = ["JavaScript", 44];


console.log(randomList.length); // Output: 2

var emptyArray = [];


console.log(emptyArray.length); // Output: 0

FEE Dr. Bharathiraja Nagu 20


Example 2: Using Array length in for loop

var languages = ["JavaScript", "Python", "C++", "Java", "Lua"];

// languages.length can be used to find out


// the number of times to loop over an array
for (i = 0; i < languages.length; i++){ Output:
console.log(languages[i]); JavaScript
} Python
C++
Java
Lua

FEE Dr. Bharathiraja Nagu 21


Example 3: Changing length property of Array

var languages = ["JavaScript", "Python", "C++", "Java", "Lua"];

// truncate the Array to 3 elements


languages.length = 3

// Output: [ 'JavaScript', 'Python', 'C++' ]


console.log(languages)

// extend the Array to length 6


languages.length = 6

// Output: [ 'JavaScript', 'Python', 'C++', <3 empty items> ]


console.log(languages)

FEE Dr. Bharathiraja Nagu 22


JavaScript Array reverse()

• Returns the array in reverse order

Example:
let array = [1, 2, 3, 4, 5];
array.reverse(); Output
console.log(array); let array = [1, 2, 3, 4, 5]; [ 5, 4, 3, 2, 1 ]
array.reverse();
console.log(array);

FEE Dr. Bharathiraja Nagu 23


JavaScript Array values() method

The values() method returns a new Array Iterator object that contains the values
for each index in the array.
Syntax:
Array.values()
Example:
const fruits = ["Apple", "Banana", "Cherry"];
// Get the iterator object Output:
Apple
const iterator = fruits.values(); Banana
Cherry
// Iterate over the values using the iterator
for (const value of iterator) {
console.log(value);
}

FEE Dr. Bharathiraja Nagu 24


JavaScript Array toString() Method
The toString() method converts the given value into the string.
Syntax:
arr.toString()

Example:
// Original Array
let courses = ["HTML", "CSS", "JavaScript", "React"];
// Converting array ot String
let str = courses.toString();
console.log(str); Output
HTML,CSS,JavaScript,Rea
ct

FEE Dr. Bharathiraja Nagu 25


JavaScript Array join() Method
▪ This join() method creates and returns a new string by concatenating all
elements of an array.
▪ It uses a specified separator between each element in the resulting string.
Syntax
array.join(separator)
Example:
// Original Array
let courses = ["HTML", "CSS", "JavaScript", "React"];
// Joining the array elements
console.log(courses.join('|'));
Output
HTML|CSS|JavaScript|React

FEE Dr. Bharathiraja Nagu 26


JavaScript Array delete Operator

The delete operator is used to delete the given value which can be an object,
array, or anything.
Syntax:
delete object // or delete object.property // or delete object['property']
Example:
Deleting the given object’s property by using the delete operator.
let emp = {
firstName: "Raj",
lastName: "Kumar",
Output
salary: 40000 true
} { firstName: 'Raj', lastName:
'Kumar' }
console.log(delete emp.salary);
console.log(emp);

FEE Dr. Bharathiraja Nagu 27


JavaScript Array concat() Method
The concat() method is used to concatenate two or more arrays and it gives the
merged array.
Syntax:
let newArray = arr.concat() // or
let newArray = arr1.concat(arr2) // or
let newArray = arr1.concat(arr2, arr3, ...) // or
let newArray = arr1.concat(value0, value1)
Example: Output
[
// Declare three arrays 11, 12, 13, 14, 15,
let arr1 = [11, 12, 13]; 16, 17, 18, 19
let arr2 = [14, 15, 16]; ]

let arr3 = [17, 18, 19];


let newArr = arr1.concat(arr2, arr3);
console.log(newArr);
FEE Dr. Bharathiraja Nagu 28
JavaScript Array flat() Method

The flat() method is used to flatten the array i.e. it merges all the given array
and reduces all the nesting present in it.
Syntax:
arr.flat([depth])
Example:
// Creating multilevel array
const arr = [['1', '2'], ['3', '4', '5',['6'], '7']];
Output
// Flat the multilevel array [ '1', '2', '3', '4', '5', '6', '7']
const flatArr= arr.flat(Infinity);
console.log(flatArr);

FEE Dr. Bharathiraja Nagu 29


JavaScript Array.push() Method

The push() method is used to add an element at the end of an Array.


Syntax:
Array.push(item1, item2 …)
Example:
// Declaring and initializing arrays Output
let numArr = [10, 20, 30, 40, 50]; [ 10, 20, 30, 40, 50, 60, 70, 80, 90 ]
[ 'piyush', 'gourav', 'smruti', 'ritu', sumit',
// Adding elements at the end of an array 'amit' ]
numArr.push(60);
numArr.push(70, 80, 90);
console.log(numArr);
let strArr = ["piyush", "gourav", "smruti", "ritu"];
strArr.push("sumit", "amit");
console.log(strArr);

FEE Dr. Bharathiraja Nagu 30


JavaScript Array.unshift() Method
• The unshift() method is used to add elements to the front of an Array.
Syntax:
Array.unshift(item1, item2 …)
Example:
let numArr = [20, 30, 40];
numArr.unshift(10, 20);
Output
console.log(numArr); [ 10, 20, 20, 30, 40 ]
let strArr = ["amit", "sumit"]; [ 'sunil', 'anil', 'amit', 'sumit' ]

strArr.unshift("sunil", "anil");
console.log(strArr);

FEE Dr. Bharathiraja Nagu 31


JavaScript Array.pop() Method
• The pop() method is used to remove elements from the end of an array.

Syntax:
Array.pop()

Example:
Output
let numArr = [20, 30, 40, 50]; [ 20, 30, 40 ]
numArr.pop(); [ 'amit', 'sumit' ]

console.log(numArr);
let strArr = ["amit", "sumit", "anil"];
strArr.pop();
console.log(strArr);

FEE Dr. Bharathiraja Nagu 32


Array Iteration Methods

• Iterating over an array means accessing each element of array one


by one.
Example:
Array map()
Array filter()
Array reduce()

FEE Dr. Bharathiraja Nagu 33


JavaScript Array map() Method
• The map() method creates an array by calling a specific function on each
element present in the parent array. It is a non-mutating method.
• This method iterates over an array and calls the function on every element of
an array.
Syntax:
array.map(callback(currentValue, index, array), thisArg);
Example:
let arr = [4, 9, 16, 25];
let sub = arr.map(fun);
Output
function fun() { [ [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4,
return arr.map(Math.sqrt); 5]]
}
console.log(sub);

FEE Dr. Bharathiraja Nagu 34


JavaScript Array reduce() Method
• The reduce() method is used to reduce the array to a single value and
executes a provided function for each value of the array (from left to right)
and the return value of the function is stored in an accumulator.
Syntax:
array.reduce(callback(accumulator, currentValue, index, array), initialValue);
Example:
let arr = [88, 50, 25, 10];
let sub = arr.reduce(fun);
function fun(total, num) {
return total - num;
}

console.log(sub); Output: 3

FEE Dr. Bharathiraja Nagu 35


JavaScript Array filter()
• The filter() method creates a new array with array elements that pass a test.
Example:
creates a new array from elements with a value larger than 10:
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {


return value > 10; Output:
45,16,25
}

FEE Dr. Bharathiraja Nagu 36


Array Splice() Function
JavaScript Array splice()
• The splice() method adds and/or removes array elements.
• The splice() method overwrites the original array.

Example:
// Create an Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];

// At position 2, add "Lemon" and "Kiwi":


fruits.splice(2, 0, "Lemon", "Kiwi");

FEE Dr. Bharathiraja Nagu 37


Array splice() -Example
<html>
<body>
<h1>JavaScript Arrays-Splice Function</h1>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
Output:
</html>
JavaScript Arrays-Splice Function
Banana,Orange,Lemon,Kiwi,Apple,Mang
o

FEE Dr. Bharathiraja Nagu 38

You might also like