Javascript Functions
Javascript functions are codes that execute to perform some specific task. It is an essential topic for beginners in javascript. In this article, we will be discussing javascript functions with examples.
What is Javascript Function?
A javascript function is a block of code designed to perform some specific task. It is only executed when something invokes the function or triggers it.
Function Syntax
A JavaScript function is built with the function keyword, followed by the function name and parenthesis().
Like variables, a function in javascript contains letters, digits, underscores, and dollar signs.
We also can include parameters inside the parenthesis separated by commas.
function FunctionName(parameter1, parameter2, parameter3) {
//code to be executed
}
Why use Function?
We use a function instead of writing a similar code again and again. So we can define a code once and use the same code multiple times.
We also can execute the same code with different arguments to get a different output result.
Function Invocation
As we told that the code inside a function will execute when something invokes or calls the function.
- When an event occurs, ( when we click on a button).
- When the function will be called.
- Automatically
Invoking a Function as a Function
function FuncName(per) {
return per;
}
FuncName(value);
Invoking a Function as a Method
var ThisObj = {
num: value,
myfunc: function () {
return this.num;
}
};
ThisObj.myfunc();
Here Myfunc method is a function and this function is belonging to the object ThisObj
. At last, we call the function myfunc()
.
Function Return
When we use a return statement in a function, the execution of the function is stopped and returns a value from where it was called.
var x = productOf(4, 3);
function productOf(a, b) {
return a * b;
}
// x = 12
Function hoisting
A function can be declared first and then defined later thus the concept of closure and hoisting is introduced. Similar to variable Hoisting, Function hoisting is a JavaScript technique that moves function declarations to the top of their scope before code execution begins.
showCode(); // a hoisting example
function showCode() {
console.log("a hoisting example");
}
function showCode() {
console.log("a hoisting example");
}
showCode(); // a hoisting example
It can be seen from the code above, that the showCode()
function is called before it is declared. In this scenario, the JavaScript engine physically moves the showCode()
function declaration to the top of the code before executing them.
This was a short tutorial on the Javascript functions, and we hope it helps you. The next tutorials will contain topics like Arrow functions which were introduced in the newer ECMAScript, so stay tuned for the updates. If you’re willing to dive deeper and learn more about Javascript functions you may refer to this tutorial on MDN (opens in a new tab).