# function Define methods
// function without arguments
function sum() {
// code
}
const sum = () => {
// code
}
const sum = _ => {
// code multi line
}
const sum = _ => { /* single line */}
const sum = _ => console.log("single")
// function with arguments
function sum(a, b) {
return a + b;
}
const sum = (a, b) => {
return a + b;
}
const sum = (a, b) => a + b;
// function arguments with default Value, ES6
const sum = (a, b = 10) => a + b;
sum(10, 20) // 30
sum(20) // 30
// void function | non return
function print() {
console.log("print");
}
print()
// return function
function print() {
return "My console";
}
console.log(print());
function sum(a, b) {
// code
// code
// code
return a + b; // Number final result
return "stringsdf" // string
return true|false // Boolean
return [1,2 3,] // array
return {
// object
}
}
sum(5, 5) // 10;
// Object function
const Car = {
color: "blue",
move: function() {
}
}
// object function shorthand
const Car = {
color: "blue",
move() {
}
}
// closure function
function increment() {
let start = 0;
return function() {
return start++;
}
}
const store = increment();
store() // 0
store() // 1
// recursion
// !5 => 5+4+3+2+1
// !10=> 10+9+.....+1
function Factorial(n) {
if (n === 0) {
return 1;
}
return n * Factorial( n - 1 );
}
function sum(a){
return function(b) {
return function(c) {
return a + b + c;
}
}
}
sum(10)(20)(30) // 60
sum(10)
=> function(b) {
return function(c) {
return a + b + c;
}
}
sum(10)(20)
=> function(c) {
return a + b + c;
}
sum(10)(20)(30)
=> a + b + c = 60
map, filter, reduce
map=
callback(element, index, array)
const num = [1, 2, 3, 4];
// Array = [1, 2, 3, 4];
// Element 1, 2, 3, 4
// Index 0, 1, 2, 3
const num2 = num.map((item) => {
return item * 2
})
const num2 = num.map(item => item * 2)
// [2, 4, 6, 8];
function map(array, callback) {
const newArray = [];
for (let i = 0; i < array.length; i++) {
newArray = callback(array[i])
}
return newArray;
}