Computer >> Computer tutorials >  >> Programming >> Javascript

How to define a JavaScript function using the expression?


To understand the concept of a JavaScript function using the expression, let us see the difference between Function Declaration and Function expression.

Function Declaration

The “function” keyword declares a function in JavaScript. To define a function in JavaScript use the “function” keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces.

Here’s an example

function sayHello(name, age)
{
   document.write (name + " is " + age + " years old.");
}

Function Expression

Function Expression should not start with the keyword “function”. Functions defined can be named or anonymous.
Here are the examples

//anonymous function expression
var a = function() {
   return 5;
}

Or

//named function expression
var a = function bar() {
   return 5;
}