DEV Community

Cover image for FUNCTION EXPRESSION
Vinoth Kumar
Vinoth Kumar

Posted on

FUNCTION EXPRESSION

FUNCTION EXPRESSIONS IN PROGRAMMING: A way to define a function by assigning it to a variable or using it within an expression, allowing the function to be stored, passed as an argument, or executed immediately.

  • Function expressions can be named or anonymous.
  • They are not hoisted, meaning they are accessible only after their definition.
  • Frequently used in callbacks, closures, and dynamic function creation.
  • Enable encapsulation of functionality within a limited scope.

SYNTAX:
const fName = function(params) {};

EXAMPLE:

const greet = function(name) {
    return `Hello, ${name}!`;
};
console.log(greet("VINOTH"));
Enter fullscreen mode Exit fullscreen mode

ANONYMOUS FUNCTION: A function defined without an explicit name. It is commonly used as a callback or assigned to a variable.

EXAMPLE:

const greet = function() {
  return "Hi";
};
console.log(greet());
Enter fullscreen mode Exit fullscreen mode

ARROW FUNCTION: A new way to write functions using the => syntax. They are shorter and do not have their own this binding, which makes them useful in some cases.

EXAMPLE:

const square = n => n * n;
console.log(square(4));
Enter fullscreen mode Exit fullscreen mode

CALLBACK FUNCTION: An argument to another function and is executed after the completion of that function.

function num(n, callback) {
    return callback(n);
}

const double = (n) => n * 2;

console.log(num(5, double));
Enter fullscreen mode Exit fullscreen mode

CONSTRUCTOR FUNCTION: A type of function used to create multiple objects with the same structure. It’s called with the new keyword.

EXAMPLE:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const user = new Person("VINOTH", 23);
console.log(user.name);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)