Function is a block of code designed to perform a specific task. We can reuse it whenever needed.
notes: function() first need to know return type
1.Function declaration
function greet() { console.log("hello world"); } greet(); // hello world 2.Function with parameters/arguments
parameter - name/ input value , argument - value
Parameters receive values when the function is called.
function add(a, b){ console.log(a +b); } add(10, 20); //30 a and b are parameters. 10 and 20 arguments.
3.Function with return
return sends a value back to the caller(the value goes back to who calls).
reuse the result of another calculation.
function add(a, b){ return a + b; } let result = add(10,20); console.log(result); // 30 4.Default parameter
function without values are default parameter.
function greet(name = "world"){ console.log("hello" + name); } greet(); greet("sam"); output : hello world hello sam 5.Function expression
A function can stored in a variable.
let greet = function(){ console.log("hello"); }; greet(); //hello 6.Arrow function
A shorter way to write a function.
let add = (a, b) => { return a + b; }; console.log(add(5,3)); //8 //shorter version let add = (a, b) => a + b; console.log(add(5,3)); //8 7.Callback function
A callback is a function passed as an argument to another function.
function display(result){ console.log(result); } function add(a, b, callback){ callback(a + b); } add(10, 20, display); // 30 notes:
normal function : perform a task and return the result.
callback function : passes a function to another function so it can decide when to call it. (used in button click, arrays, timers)
8.Function returning a value
function square(n){ return n * n; } console.log(square(5)); //25 