Functions are one of the most used language features, not just in JavaScript function in almost all the languages. Functions are used when we want to repeat a particular action for many number times ie: reusable code.
Writing a function in JavaScript is very simple. You can either use the function declaration syntax using the function keyword or a function expression syntax that returns a new function.
Syntax:
function funcName() { code };
Example:
function sayHi(name){
console.log(name);
}
sayHi("Kaarthik"); // logs kaarthik in to console
Every function will gives us a value in back we can either log that in console or we can use the value using return keyword.
return result;
In the below function, we are just adding the two values a
& b
and capturing the value into new variable result
via return
statement.
function sum(a, b) {
return a + b;
}
// We're saving the value into new variable
const result = sum(1,2);
// logging the value
console.log(result);