Supriya
A block of code which is defined once but called at a later time.
Some functions can be defined and called at the same time.
function fName( arg1, arg2, ...)
{
statement-1;
statement-2;
statement-3;
}
function greetTheUser(user)
{
if(user === undefined)
{
user = "new user";
}
return (`Hello ${user}, welcome to Target`);
}
// function call
greetTheUser();
greetTheUser("james");
let fName = function ( arg1, arg2, ...)
{
statement-1;
statement-2;
statement-3;
};
let greetTheUser = function(user)
{
if(user === undefined)
{
user = "new user";
}
return (`Hello ${user}, welcome to Target`);
};
// function call
greetTheUser();
greetTheUser("audrey");
(function (arg1, arg2, ....)
{
statement-1;
statement-2;
statement-3;
})();
(function(user)
{
if(user === undefined)
{
user = "new user";
}
return (`Hello ${user}, welcome to Target`);
})(); // function call
(param1, param2, . . . ) => {
statement-1;
statement-2;
statement-3
. . .
}
function funName (user)
{
if(user === undefined)
{
user = "new user";
}
return (`Hello ${user}, welcome to Target`);
}; // function defination
funName("bennie") // function call
const funName = (user) => {
if(user === undefined)
{
user = "new user";
}
return (`Hello ${user}, welcome to Target`);
} // function defination
funName("bennie"); // function call
let numList = [45,67,67,78,45,34,23,23,2312,7];
let sum = 0;
const cube = function(num)
{
return Math.pow(num,3);
};
const add = function(num1, num2)
{
return num1+num2;
};
let cubeNum = cube(add(34,45));
// Here comes the tough one....
numList.forEach(function(n){ return sum = sum + n ; });
(function(numAry, cube)
{
numAry.forEach(function(num, i)
{
console.log(`${num}is the current value\n`);
});
console.log(cube);
})(numList, cube);
We can put the function inside the objects
Hint: { lists and dictionaries }
Property methods
reduce() method
That previous sum of the array can be done in a single line of code, but this time using the current and the next value.
Hint: { lists }