JavaScript Functions

Photo by Sigmund on Unsplash

JavaScript Functions

All types Of Functions

Table of contents

No heading

No headings in the article.

Javascript functions are blocks of code that can be executed whenever they are called. They are used to organize and reuse code, and to create modular and maintainable programs.

There are several types of functions in Javascript, including:

  1. Function Declaration: A function declaration is a function that is defined using the "function" keyword, followed by the function name, and a set of parentheses that may include parameters. For example:
function sayHello(name) {
  console.log("Hello, " + name);
}
sayHello("John"); // output: "Hello, John"
  1. Function Expression: A function expression is a function that is defined as a variable assignment. They can be named or anonymous. For example:
let sayHello = function(name) {
  console.log("Hello, " + name);
}
sayHello("John"); // output: "Hello, John"
  1. Arrow Function: Arrow functions were introduced in ECMAScript 6 and provide a shorthand for defining function expressions. They use the "=>" operator to separate the function arguments from the function body. For example:
let sayHello = (name) => {
  console.log("Hello, " + name);
}
sayHello("John"); // output: "Hello, John"
  1. Constructor Functions: A constructor function is a special type of function that is used to create and initialize objects. The name of a constructor function should start with an uppercase letter. For example:
function Person(name, age) {
  this.name = name;
  this.age = age;
}
let john = new Person("John", 25);
console.log(john.name); // output: "John"
  1. Immediately Invoked Function Expression (IIFE): An IIFE is a function that is immediately invoked after it is defined. It is a way to create a scope for variables that should not be accessible from the outside. For example:
(function() {
  let message = "Hello, World!";
  console.log(message);
})(); // output: "Hello, World!"

These are the main types of functions in Javascript and can be used in different situations depending on the requirements of the program.

Happy Learning😊