Functions in JavaScript.
In JavaScript, we write code to perform a specific task or to achieve something. In Javascript, we have functions to perform a specific task. function is nothing but a block of code that performs a particular task. A function is executed when something calls it and a function is composed of statements called function body.
Syntax
function sum () {
//function body
}
A Javascript function is defined with a function keyword, followed by a name, and followed by a parenthesis (). Function names can contain digits, letters, signs, etc., and parenthesis contains parameter names separated by commas.
we have declared a function named message(). To use a function, we have to call it.
Example
function add () {
let x = 12;
let y = 12;
let z = x + y;
console.log(z);
}
add();
Parameters and Arguments
The value which we pass inside a function is known as an argument and a parameter is a value that is passed when declaring a function.
Example
function add (x, y) {
let z = x + y;
console.log(z);
}
add(12, 12);
Ways to write the function
function user () {
let first_Name = 'vikas';
console.log(first_Name);
}
user();
var user = function () {
let first_Name = "vikas";
console.log(first_Name);
}
user();
var user = () => {
let name = "vikas";
}
user();
Function statement/Declaration
function call () {
console.log("ineuron");
}
Function expression
let call = function () {
console.log("ineuron");
}
here storing function into call and function can also be defined as expressions
Function with return
The return statement can be used to return the value to a function call. It denotes that the function has ended. Any code after the return is not executed and nothing is returned the function returned an undefined value.
Example
function sum (math, physics, chemistry) {
var result = math + physics + chemistry;
return result;
}
let total = sum (74, 84, 92);
console.log(total);