[go: up one dir, main page]

0% found this document useful (0 votes)
7 views28 pages

4th notes

The document provides an overview of JavaScript functions, including their types such as anonymous functions, named functions, function expressions, and immediately invoked function expressions (IIFE). It also covers function arguments, return values, hoisting, closures, arrow functions, and the rest parameter syntax, along with a detailed explanation of array methods and their usage in JavaScript. Additionally, it includes practical examples and code snippets to demonstrate the concepts discussed.

Uploaded by

sssss170520
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views28 pages

4th notes

The document provides an overview of JavaScript functions, including their types such as anonymous functions, named functions, function expressions, and immediately invoked function expressions (IIFE). It also covers function arguments, return values, hoisting, closures, arrow functions, and the rest parameter syntax, along with a detailed explanation of array methods and their usage in JavaScript. Additionally, it includes practical examples and code snippets to demonstrate the concepts discussed.

Uploaded by

sssss170520
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

FUNCTIONs:

A function is a JavaScript procedure a set of statements that performs a task or calculates a value.

to use a function you Must define it somewhere in the scope from which you wish to call it.

syntax: function(){

//block of code.

Types of function:
1. Anonymous function:
An anonymous function is a function that was declared with out named identifier to refr to it.

As such, an anonymous function is usually not accessible after its initial creation.

CAn give self invocation by writing the complete function in () which is called IIFE(immediate invoke
function expression)

IIFE is used for data hiding.

2. NAMING FUNCTION:
A JavaScript function is defined by the function() keyword, followed by the name and followed by ().

Function names can contain letters, digits, underscores, and dollar signs( same rules as variables).

the parenthesis may include parameters names separated by commas:{parameter1, parameter2}.

Function<name of the function>({

//block of code.

})

3. FUNCTION EXPRESSION:
A javascript function can also be defined by using the expression.
a function expression can be stored in a variable ;

var x= function(a,b)

{ return a*b};

after a function expression has been stored in a variable,

the variable can be used as a function.

4. Immediate invoke function:


An immediately invoked function expression is a way to execute function immediately, as soon as they are
created.

IIFE's are very useful because they dont pollute the global object,

and they are simple way to isolate variables declaration.

IIFE is used for data hiding.

()() IIFE in ECMAscprit

{} IIFE i ES6(ECMA script 6).

================================================

5. FUNCTION with arguments:


Arguments are passed by the value the parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value. The function only gets to know the value, not the arguments’
location.
If a function changes an argument’s value, it does not change the parameter's original value.

6. Function with return:


The return statements end function execution and specifies a value to be returned to the function caller.

When a return statement is used i a function body, the execution of the function is stopped.

If specified, a given value is returned to the function caller. for example, the following function returns the
square

of its argument, x, where x is the number.

function square(x){

return x*x;

var demo = 4;

============================================================================
==================

7. Functions parameter and default value.


es5:

A javascript function can have default parameter values.

using default function parameters, you can initialize formal parameters with default values, if you

dont initialize the parameters with some value.

es6:

the default value of the parameter is undefined,

ECMAscprit 6 introduced default parameters for athe function.

using the default parameters features of ECMA 2015, you no longer have to check for an undefined
parameter
function test(username="jspiders"){

return username;

console.log(test())

====================================================================

do not use javascript reserved keywords as a function name.

ex: function for(); ==> wrong.

8. Function with aurgument object:


The arguments object is a special construct available inside all function calls,

it represents the list of arguments that were passed in when invoking the function. since JavaScript
allows FUNCTIONs to be called with any number args, we need a way to dynamically discover and access
them.

========================================================================

FUNCTION HOISTING:

Hoisting JavaScript mechanism where variables and functions declarations are moved to the top of their
scope before code execution. inevitably, this means that no matter where the functions and variables are
declared, they are moved to the top of their scope regardless of whether their scope is global or local

FUNCTION declaration:

These are of the following form and are hoisted completely to the top.

Now, we can understand why JavaScript enables us to invoke a function seemingly before
declaring it.

hoisted(); //output: function has been hoisted.

function hoisted(){
console.log("this function has been hoisted");

=====================================================

9.Clouser in function:
function within a function is called function clouser.

var x="hello x";

function show() {

var outerblock =" hello inner block";

console.log ( innerBlock);

function innerBlock(){

var innerText=" hello inner text";

show();

A closure is a function having access to the present scope.

It preserves the data from outside.

A closure is an inner function that has access to the outer (enclosing) function variable.

For every closure we have three scopes:

-local scope (own scope)

-outer function scope

- global scope.
10. Fat arrow
[=>]

using fat arrow you can avoid many lines of code.

normal function is having Argument object es6 doent have argument object.

var username= function() {

return aruguments;

};

console.log( username ("manu"));

//normal function calling

//es6 arrow function

var usernamewithEs6=() => {

return arguments;

};

console.log(usernamewithEs6("shashi"));

Arrow function were introduced with ES6 as a new syntax for writing java script FUNCTIONs

they save developers time and simplify function scope.

Arrow functions (often referred to as arrow functions or lambda functions) are a concise way of

Writing functions that do not rebind context (this) within other functions.
Their short syntax id future enhanced by their ability to return values implicitly in one line,

Simple return function

11. Rest parameter.


The rest parameter syntax allows us to represent an indefinite number of arguments as an
array.

function f(a ,b , ...the Args){

//code

A function's last parameter can be prefixed with ...which will cause all remaining aruguments to
be placed in order.

Arrays
The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.

Syntax
Use the following syntax to create an Array Object.

var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single
numeric parameter with the Array constructor, you specify the initial length of
the array. The maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows:

var array=["java","python", "nodejs"];

var[ java, python,nodejs]=array;

ARRAY METHODS:
NOTE: The syntaxs as per the traditional methods are given in all the methods and the easy way of executing the methods
is given in the codes.
In java it refers to collections:

Built in array methods:

pop, shift, unshift, push, splice, slice, tostring,sort, filter, foreach, map, indexof, join etc..

var lang = ["java", "phyton", "nodes"];

pop:

removes the last index element of the array and presents it.

languages.pop();

shift:

language.shift();

deletes the first index element and presents the array.

push:

language.push();

adds new element to the last index of an array and returns the new length of the array.

unshift:

language.unshift();

Elements to insert at the start of the Array.Inserts new elements at the start of an array.

splice:

syntax: splice(start: number, deleteCount?: number): string[]


?: says it is optional

when we want to add

(1,0, "c++")

The zero-based location in the array from which to start removing elements.

Removes elements from an array and, if necessary, inserts new elements in their place,

returning the deleted elements.

we can add and delete at the same time:

has 3 arguments.

1. position where you want to start.

2. how many values u want to delete or you can delete particular value also.

3. the content you want to add.

forEach:

it is a array method.

to iterate each and every array values.

we have to use this with the callback function if we want to use it in the function.

Always should be used with the anonymous function.

it has 3 arguments:

forEach(callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any): void

callbackfn: it should be anonymous

value: checks for the values.

index: checks with the index.

array: checks the complete array

{ The forEach() executes a provided function once for each array element.
syntax:

arr.forEach(callbackfn(currentValue [, index[, array]])[, thisArg]);

forEach() calls a provided callback function once for each element in an array in ascending order. it is
invoked for index properties that have been deleted or are uninitialized.

callback is invoked with three arguments:

the value of the element.

the index of the element.

the array object being traversed.

create an array and add 5 objects with an image.

after the creation on object

1. go to getbootstrap.com

2. go to documentation search cards

3.go to js file call employees.forEach

4. and call a callbackfn and check with console.

employees.forEach(function(empData){

console.log(empData);

can olso use fatarrow

employees.forEach(empData => {

emp.push(` `)
})

5.now create a var outside the function.

var emp = [];

6.now delete the console and push s data.

and push data and retrive the data

var emp = [];

employees.forEach(function(empData){

var test = emp.push(`<h1>${empData.emp_age}</h1>`);

- console.log(test);

});

7.Delete the opertaion and paste the bootstrap card

employees.forEach(empData => {

emp.push(`add bootstrap copied `)

})

8. chage photo and the name

photo i the src and name in h1 in cARD

9. LINK IT WITH HTML BY document.getelementby id("templete name').innerhtml=emp;

call all the remaining things.

Program as per the above steps:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs

/twitter-bootstrap/4.3.1/css/bootstrap.css">

<title>Document</title>

<style>

body{

background: linear-gradient(to right, green, red);

.card{

width : 24%;

float: left;

margin : 5px;

height : 100vh;

</style>

</head>

<body id="body">

<div class="container">

<div id="templete">

</div>

</div>

<script src=”name of jsfile.js”></script>

</body>

</html>
JSprogram:
//useage of foreach:

var employees = [

emp_id : "j123",

emp_name : "manu",

emp_age : 20,

emp_gender : "male",

emp_photo : "https://cdn.pixabay.com/photo/2018/01/15/07/51/woman-3083383__340.jpg",

emp_company : "jspiders",

emp_salary : "30000",

emp_designation: "web trainer",

emp_doj : new Date('2015/12/25'),

emp_location : "mandya",

emp_education :"BE"

},

emp_id : "j202",

emp_name : "raja",

emp_age : 21,

emp_gender : "male",

emp_photo : "https://cdn.pixabay.com/photo/2016/04/21/01/31/

handsome-1342457__340.jpg",

emp_company : "jspiders",

emp_salary : "45000",
emp_designation: "java trainer",

emp_doj : new Date('2017/2/22'),

emp_location : "gadag",

emp_education :"BE"

},

emp_id : "j100",

emp_name : "rani",

emp_age : 22,

emp_gender : "female",

emp_photo : "https://cdn.pixabay.com/photo/2018/01/15/07/51/

woman-3083376__340.jpg",

emp_company : "jspiders",

emp_salary : "40000",

emp_designation: "phythhon trainer",

emp_doj : new Date('2018/1/25'),

emp_location : "raichur",

emp_education :"BE"

},

emp_id : "j456",

emp_name : "anu",

emp_age : 25,

emp_gender : "female",

emp_photo : "https://cdn.pixabay.com/photo/2014/04/03/10/32/user-310807__340.png",

emp_company : "jspiders",
emp_salary : "38000",

emp_designation: "c++ trainer",

emp_doj : new Date('2019/12/25'),

emp_location : "blore",

emp_education :"BE"

];

var emp = [];

employees.forEach(function(empData){

var test = emp.push(`<div class="card" >

<img src="${empData.emp_photo}" class="card-img-top" alt="..." >

<div class="card-body">

<h5 class="card-title">${empData.emp_name}</h5>

<span class="badge badge-success float-right">${empData.emp_id}</span>

<hr class="hr">

<span class="badge badge-success float-right">${empData.emp_designation}</span>

<br><br>

<li class = "list-group-item"> Salary: ${empData.emp_salary}</li>

<li class = "list-group-item"> Location : ${empData.emp_location}</li>

<li class = "list-group-item"> age : ${empData.emp_age}</li>

<li class = "list-group-item">gender : ${empData.emp_gender}</li>

<li class = "list-group-item"> education : ${empData.emp_education}</li>

<li class = "list-group-item"> doj : ${empData.emp_doj.toString()}</li>

<li class = "list-group-item">company : ${empData.emp_company}</li>

<a href="#" class="btn btn-primary">Go somewhere</a>

</div>
</div>`);

});

document.getElementById('templete').innerHTML=emp;

-----------------------------------------------------------------------------

reverse()

only array is having the reverse method.

var names =[ "manu", "anu", "shashi", "tarun"];

var test = names.sort();

var test = names.reverse();

console.log(test);

-----------------------------------------------------------------------------

concat()

(...strings: string[]): string

The strings to append to the end of the string.

Returns a string that contains the concatenation of two or more strings.

var myGirls = ["Cecilie", "Lone"];

var myBoys = ["Emil", "Tobias", "Linus"];

var myChildren = myGirls.concat(myBoys);

console.log(myChildren);

console.log(myGirls);

console.log(myBoys);*/

//concat 3 array:

/*var arr1 = ["Cecilie", "Lone"];

var arr2 = ["Emil", "Tobias", "Linus"];


var arr3 = ["Robin", "Morgan"];

var myChildren = arr1.concat(arr2, arr3);

console.log(mychildren);

------------------------------------------------------------------------

slice()

(start?: number, end?: number): string

The index to the beginning of the specified portion of stringObj.

Returns a section of a string.

slice()

/*var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(0, 1); // Removes the first element of fruits

console.log(fruits);*

------------------------------------------------------------------------

filter()

filter(callbackfn: (value: number, index: number, array: number[]) => value is number, thisArg?: any): number[]

A function that accepts up to three arguments. The filter method calls the callbackfn

function one time for each element in the array.

Returns the elements of an array that meet the condition specified in a callback function.

NOTE: DOesnot change the original array.

var numbers = [45, 4, 9, 16, 25];

var over25 = numbers.filter(myFunction);

var result = numbers.filter(x=> x>25)

console.log(result);
function myFunction(value, index, array) {

return value > 25;

console.log(over25);

/remove duplictaiom

//var users= ["anu","manu","anu","shashi","shahsi","shahsi"];

//var duplicatUsers =users.filter((value, index, array)=>{

// return array.indexOf(value)=== index;

//});

//console.log(duplicatUsers);

//es6

//var [...es6waytoRemoveDuplicates] = new Set(users);

//var duplicates = [];

//for(var i= 0;i< users.length;i++){

/// if(users.indexOf(users[i])==-1)

//duplicates.push(users[i]);

//}

//console.log(duplicates);

//console.log(es6waytoRemoveDuplicates);

//------------------------------------------------------

SET is not a method but it is a data method

set object lets you stre unique values of any type, whether primitive value or object refernces
syntax

new Set([iterable]);

reduce()
The reduce() method runs a function on each array element to produce (reduce it to) a single value.

The reduce() method works from left-to-right in the array. See also reduceRight().

The reduce() method does not reduce the original array.

(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T

The total (the initial value / previously returned value)

The item value

The item index

The array itself

A function that accepts up to four arguments. The reduce method calls the callbackfn function one

time for each element in the array.

Calls the specified callback function for all the elements in an array. The return value of the callback function is
accumulated result,

and is provided as an argument in the next call to the callback function.

without callbackfn:

Es6 - Array method reduce()

reduce() method applies a function simultaneously against 2 values of the array

(from left to right) as to reduce it to single value.


const array1=[1,2,3,4];

const reducer =(accumulator , currentValue)=>

accumulator + currentValue;

console.log(array1.reduce(reducer));

console.log(array1.reduce(reducer,5));//adds 5

reduceRight()
The reduceRight() method runs a function on each array element to produce (reduce it to) a single value.

The reduceRight() works from right-to-left in the array. See also reduce().

The reduceRight() method does not reduce the original array.

(callbackfn: (previousValue, currentValue, Index, array T[]) => T): T

The total (the initial value / previously returned value)

The item value

The item index

The array itself

A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time
each element in the array.

Calls the specified callback function for all the elements in an array, in descending order.

The return value of the callback function is the accumulated result,

and is provided as an argument in the next call to the callback function.

var numbers1 = [45, 4, 9, 16, 25];

var sum = numbers1.reduceRight(myFunction);

function myFunction(total, value, index, array) {


return total + value;

console.log(sum);

----------------------------------------------------------------------------

every()
The every() method check if all array values pass a test.

(callbackfn: (value, index, array) => unknown, thisArg?: any): boolean

The item value

The item index

The array itself

A function that accepts up to three arguments.

The every method calls the callbackfn function for each element in array1 until the

callbackfn returns false, or until the end of the array.

Determines whether all the members of an array satisfy the specified test.

every() returns true or flase

/*var numbers = [45, 4, 9, 16, 25];

var allOver18 = numbers.every(myFunction);

function myFunction(value) {

return value > 18;

console.log(allOver18);//return true or false.*/

-----------------------------------------------------------------------------

some()
(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean

The item value

The item index

The array itself

A function that accepts up to three arguments. The some method calls the callbackfn function

for each element in array1 until the callbackfn returns true, or until the end of the array.

Determines whether the specified callback function returns true for any element of an array.

var numbers = [45, 4, 9, 16, 25];

var someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {

return value > 18;

console.log(someOver18);

-----------------------------------------------------------------------------

indexOf()
The indexOf() method searches an array for an element value and returns its position.

(searchString: string, position?: number): number

The substring to search for in the string.

Returns the position of the first occurrence of a substring.

//indexOf()
/*var fruits = ["Apple", "Orange", "Apple", "Mango"];

var a = fruits.indexOf("Apple");

console.log(a);*/

---------------------------------------------------------------------------

find()
The find() method returns the value of the first array element that passes a test function.

(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number

find calls predicate once for each element of the array, in ascending order,

until it finds one where predicate returns true. If such an element is found, find immediately returns that elem
value.

Otherwise, find returns undefined.

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

the function takes 3 arguments:

The item value

The item index

The array itself

/*var numbers = [4, 9, 16, 25, 29];

var first = numbers.find(myFunction);

//var find = number.find(element => element 12);// in single line

function myFunction(value, index, array) {

return value > 18;

console.log(first);

*/
-----------------------------------------------------------------------------

findIndexOf()

The findIndex() method returns the index of the first array element that passes a test function.

(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number

find calls predicate once for each element of the array, in ascending order, until it

finds one where predicate returns true. If such an element is found,

findIndex immediately returns that element index. Otherwise, findIndex returns -1.

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

var numbers = [4, 9, 16, 25, 29];

var first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {

return value > 18;

console.log(first);

-----------------------------------------------------------------------------

Fill()
the fill() method fills(modifies) all the elements of an array from a start index(default zero) to

an end index (default array length) with a static value.

It returns the modified array.

fill() overwrites the existing values

/*var numbers = [4, 9, 16, 25, 29];


var lang=["java","sql","C","C++"];

var test= lang.fill("Angular");

console.log(test);

console.log(lang);

keys():
creates iterable array objects.

used in maps and used in looping function.

an iterate string olso.

//keys()

var numbers = [4, 9, 16, 25, 29];

var lang=["java","c","python","react","angular"];

var keys = lang.keys();

var values = lang.values();

for(let key of keys){

console.log(key);

for(let value of values){

console.log(value);

}*/

-----------------------------------------------------------------------------

for ofloop
forEach is nly for array for objects after Es6 we use "for of loop"

syntax: for(let x of array){

//console.log(x)

example: var user=["anu","manu","hitarth","yuvaan"];

for(let x of user){

console.log(user)

};

the for...of statement creates a loop iterating over iterable objects,

including : builtin String ,array, array-like objects(e.g., arguments or nodelist),

typed array, map, set, and user-dfined iterables.

It invokes a custom iteration hook with statements to be executed

for value of each distinct property of the object.

syntax:

for(varible of itrable){

statement;

-----------------------------------------------------------------------------

include()
it determines whether an array includes certain element

the value returned will br in true or false.

/*var numbers = [4, 9, 16, 25, 29];

var lang=["java","c","python","react","angular"];

if (lang.includes('angular')){
alert('angualar exists');

else{

alert('angular doesnot')

var forEach=lang.forEach(x=>x);

console.log(forEach);

var map= lang.map(y=> y);

console.log(map);

map()
map:

map(callbackfn: (value: number, index: number, array: number[]) => any, thisArg?: any): any[]

A function that accepts up to three arguments. The map method calls the callbackfn function one time for e
element in the array.

Calls a defined callback function on each element of an array, and returns an array that contains the results.

both forEach and map are used for iterating purpose.

does not override the existing values it just clones.

ANOTHER METHOD

forEach does not create a new array , map creates a new array.

the map() method creates a new array with the results of calling a provided function on every element

in calling array.

syntax:

var new_array= arr.map(function callback(currentValue[,index[,array]]){


/return element for new_array

}[,thisArg])

Map and forEach:


you can use both map() and foreach() interchangeably.

the biggest difference is that foreach() allows the mutation f the original array,

while map() returns new array of the same size.

map() is also faster. but it is entierly up to you to decide which one works better for you.

//map()

/*var numbers1 = [45, 4, 9, 16, 25];

var numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {

return value * 2;

console.log(numbers2);*/

You might also like