Generally, in JavaScript, the function keyword is used to declare a variable. But, there are some more ways available in JavaScript that can be used to declare functions as explained below:
- Using function keyword: This is the most common way to declare functions in JavaScript by using the function keyword before the name of the function.
- Declaring anonymous functions: In this syntax the declared function has no name as it is assigned to a variable.
- Using arrow function: It is the shorter way of declaring a function in JavaScript using an arrow(=>) introduced in ES6.
- Using Function constructor: JavaScript provides us with a Function() constructor to declare functions.
Example: The below code declares functions in JavaScript using the above-discussed approaches.
Javascript
// Using function keyword function GFG(){console.log( "GeeksforGeeks" );}
GFG(); // Anonymous function const anonyFunc = function (){console.log( "GFG" );}
anonyFunc(); // Arrow function const arrowFunc = () => {console.log( "JavaScript" );}
arrowFunc(); // Function constructor const product = Function( 'num1' , 'num2' , 'return num1*num2' );
console.log(product(3, 2)); |
Output
GeeksforGeeks GFG JavaScript 6