4th notes
4th notes
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)
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).
//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};
IIFE's are very useful because they dont pollute the global object,
================================================
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.
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
function square(x){
return x*x;
var demo = 4;
============================================================================
==================
using default function parameters, you can initialize formal parameters with default values, if you
es6:
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())
====================================================================
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.
function hoisted(){
console.log("this function has been hoisted");
=====================================================
9.Clouser in function:
function within a function is called function clouser.
function show() {
console.log ( innerBlock);
function innerBlock(){
show();
A closure is an inner function that has access to the outer (enclosing) function variable.
- global scope.
10. Fat arrow
[=>]
normal function is having Argument object es6 doent have argument object.
return aruguments;
};
return arguments;
};
console.log(usernamewithEs6("shashi"));
Arrow function were introduced with ES6 as a new syntax for writing java script FUNCTIONs
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,
//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.
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:
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:
pop, shift, unshift, push, splice, slice, tostring,sort, filter, foreach, map, indexof, join etc..
pop:
removes the last index element of the array and presents it.
languages.pop();
shift:
language.shift();
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:
(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,
has 3 arguments.
2. how many values u want to delete or you can delete particular value also.
forEach:
it is a array method.
we have to use this with the callback function if we want to use it in the function.
it has 3 arguments:
forEach(callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any): void
{ The forEach() executes a provided function once for each array element.
syntax:
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.
1. go to getbootstrap.com
employees.forEach(function(empData){
console.log(empData);
employees.forEach(empData => {
emp.push(` `)
})
employees.forEach(function(empData){
- console.log(test);
});
employees.forEach(empData => {
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
/twitter-bootstrap/4.3.1/css/bootstrap.css">
<title>Document</title>
<style>
body{
.card{
width : 24%;
float: left;
margin : 5px;
height : 100vh;
</style>
</head>
<body id="body">
<div class="container">
<div id="templete">
</div>
</div>
</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_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_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_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_location : "blore",
emp_education :"BE"
];
employees.forEach(function(empData){
<div class="card-body">
<h5 class="card-title">${empData.emp_name}</h5>
<hr class="hr">
<br><br>
</div>
</div>`);
});
document.getElementById('templete').innerHTML=emp;
-----------------------------------------------------------------------------
reverse()
console.log(test);
-----------------------------------------------------------------------------
concat()
console.log(myChildren);
console.log(myGirls);
console.log(myBoys);*/
//concat 3 array:
console.log(mychildren);
------------------------------------------------------------------------
slice()
slice()
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
Returns the elements of an array that meet the condition specified in a callback function.
console.log(result);
function myFunction(value, index, array) {
console.log(over25);
/remove duplictaiom
//});
//console.log(duplicatUsers);
//es6
/// if(users.indexOf(users[i])==-1)
//duplicates.push(users[i]);
//}
//console.log(duplicates);
//console.log(es6waytoRemoveDuplicates);
//------------------------------------------------------
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().
(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T
A function that accepts up to four arguments. The reduce method calls the callbackfn function one
Calls the specified callback function for all the elements in an array. The return value of the callback function is
accumulated result,
without callbackfn:
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().
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.
console.log(sum);
----------------------------------------------------------------------------
every()
The every() method check if all array values pass a test.
The every method calls the callbackfn function for each element in array1 until the
Determines whether all the members of an array satisfy the specified test.
function myFunction(value) {
-----------------------------------------------------------------------------
some()
(callbackfn: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean
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.
console.log(someOver18);
-----------------------------------------------------------------------------
indexOf()
The indexOf() method searches an array for an element value and returns its position.
//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.
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
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
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.
console.log(first);
-----------------------------------------------------------------------------
Fill()
the fill() method fills(modifies) all the elements of an array from a start index(default zero) to
console.log(test);
console.log(lang);
keys():
creates iterable array objects.
//keys()
var lang=["java","c","python","react","angular"];
console.log(key);
console.log(value);
}*/
-----------------------------------------------------------------------------
for ofloop
forEach is nly for array for objects after Es6 we use "for of loop"
//console.log(x)
for(let x of user){
console.log(user)
};
syntax:
for(varible of itrable){
statement;
-----------------------------------------------------------------------------
include()
it determines whether an array includes certain element
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);
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.
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:
}[,thisArg])
the biggest difference is that foreach() allows the mutation f the original array,
map() is also faster. but it is entierly up to you to decide which one works better for you.
//map()
return value * 2;
console.log(numbers2);*/