JavaScript Functions
A Javascript function is 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.
Function Declarations
Javascript function can be declared using function keyword followed by the function name, then parentheses (), and then code written inside curly brackets {}.
General Syntax
function function_name(){
//function statement
}Function Expression
General Syntax
var addNumber=function(){
// code inside
};Calling a function
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.
General Syntax
functionName(); //calling function
function functionName() {}
functionName(); //calling functionAnonymous Expression
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.
Get Diwakar Chauhan’s stories in your inbox
Join Medium for free to get updates from this writer.
A javascript function expression is only invoked after the function. If function expression is called before the function then it generates an error.
General Syntax
jsFunction();
var jsFunction = function () {};
jsFunction();Function Return Value
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.
Function returns undefined
function sayHello() {
var x = "Hello ,i am learning javascript.";
}
sayHello(); // return undefinedFunction returns string
function sayHello() {
return "I am learning js .";
}
sayHello(); // return "hello"Function Returns Number
General Syntax
function functionName(a, b) {
return a + b;
}
functionName(x, y);Function returns function
The function can also return a function. Both Functions return a function and callback.
General Syntax
function functionName() {
return function () {
return "something";
};
}
functionName();
functionName()();To read more about Javascript function, click here.




