Open In App

Explain the Different Function States in JavaScript

Last Updated : 30 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Javascript, we can create functions in many different ways according to the need for the specific operation. For example, sometimes we need asynchronous functions or synchronous functions.  In this article, we will discuss the difference between the function Person( ) { }, let person = Person ( ), and let person = new Person ( ). 

Function Declaration: The given below syntax is a declaration of the function. The code declares a function statement but does not execute until we don’t call them. Here Person is the name of the function. Functions in the javascript are declared using this method.

function Person (){}

Example of Function Declaration: In this example, we will create a function named Person and perform some tasks as shown below. 

Javascript




function Person() {
    name = "Vikash";
    age = "22";
}


Function Expression: In this code, a variable person is defined using the var keyword. We can also use const and let keywords. The person variable contains all the value references of the Person function. In javascript, every expression returns a value. The value may be undefined if the function doesn’t return and the value or the value will be the return type of the function. This function could be an anonymous function if the name is not assigned and wrapped in parenthesis interpreted as an expression. 

let person = Person ()

Example of Function Expression: This example shows the function expression

Javascript




// Function declaration
function person() { }
let person = person()
 
// Printing the return value
// of the person() function
console.log(person)
 
function person1(name) {
    return name;
}
 
let person1 = person1("Aayush")
 
// Printing the value of person1
console.log(person1)


Output:

undefined
Aayush

An undefined will print because the function doesn’t return any value whereas the second function returns the name value that’s why the name is printed in the second line.

Function Constructor: In this code, we are creating an instance using the new keyword. Here the person is the instance (object) of the Person. A function declaration is a regular function unless we create an instance of the function. The main advantage of the function constructor is to initialize the member values of the javascript functions.

Once the instance is created, we can use the function by creating a variable as shown below example. 

let person = new Person()

Example: This example shows the use of a function constructor in Javascript.

Javascript




// Creating the function
function Person(name, age) {
    this.name = name;
    this.age = age;
}
 
// Calling the function
let person = new Person("Vikah", 22);
 
console.log(person.name);
console.log(person.age);


Output:

Vikah
22


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads