A Javascript functions are a group of statements that performs specific tasks. It is mainly used due to avoid code repetition and It is reused again and again as per requirement.
Javascript function can be declared using function
keyword followed by the function name, then parentheses (), and then code written inside curly brackets {}
.
Source Code
function addNumber(){
// code inside
}
Source Code
var addNumber=function(a,b){
return (a+b);
};
Javascript function can be called by function name followed by parenthesis, i.e ()
.
If a function name is addNumber, then use addNumber()
to call the function.
functionName(); //calling function
function functionName() {}
functionName(); //calling function
Source Code
addNumber();
function addNumber() {}
addNumber();
There is another way to create a function using function expression. In this, a variable is declared and then assigned an anonymous to that variable. Since this function does not have a name so it is also known as an anonymous function.
A javascript function expression is only invoked after the function. If function expression is called before the function then it generates an error.
Source Code
greetMessage();
var greetMessage = function () {
alert("Hello,i have learnt function.");
};
greetMessage();
Javascript each function returns a value. Function default return value is undefined for all functions that do not contain a return statement. The function return value might be a string, number, function, array, or object.
Source Code
function sayHello() {
var x = "Hello ,i am learning javascript.";
}
sayHello(); // return undefined
Source Code
function sayHello() {
return "I am learning js .";
}
sayHello(); // return "hello"
Source Code
function addNumber() {
return 10 + 50;
}
addNumber(); // return 60
The function can also return a function. Both Functions return a function and callback.
function functionName() {
return function () {
return "something";
};
}
functionName();
functionName()();
Source Code
function sayHello() {
return function () {
return "hello,javascript";
};
}
sayHello(); // return function
sayHello()(); // return "hello,javascript"