Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Different ways to create a function in javascript

In this chapter, you will learn about different ways to create a function in javascript. This chapter helps you to understand how many ways we can create a function in Javascript. We can create the function in Javascript in different ways. Let’s look at the below examples

Different ways to create a function in javascript

Different ways to create a function in Javascript:
Function declaration:

The function declaration approach created a regular function, the function starts with the keyword function followed by function name.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// function declaration
function fullNameByDec(firstName, lastName) {
return firstName + ' '+ lastName;
}
console.log(fullNameByDec('John','Mickel'));
// output
// John Mickel
// function declaration function fullNameByDec(firstName, lastName) { return firstName + ' '+ lastName; } console.log(fullNameByDec('John','Mickel')); // output // John Mickel
// function declaration
function fullNameByDec(firstName, lastName) {
    return firstName + ' '+ lastName;
}
console.log(fullNameByDec('John','Mickel'));

// output
// John Mickel

Function expression:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// function expression
const fullNameByExp = function(firstName, lastName) {
return firstName + ' '+ lastName;
}
console.log(fullNameByExp('John','Mickel'));
// output
// John Mickel
// function expression const fullNameByExp = function(firstName, lastName) { return firstName + ' '+ lastName; } console.log(fullNameByExp('John','Mickel')); // output // John Mickel
// function expression
const fullNameByExp = function(firstName, lastName) {
    return firstName + ' '+ lastName;
}
console.log(fullNameByExp('John','Mickel'));

// output
// John Mickel

Arrow function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// function
const fullNameByArrow = (firstName, lastName) => {
return firstName + ' '+ lastName;
}
console.log(fullNameByArrow('John','Mickel'));
// output
// John Mickel
// function const fullNameByArrow = (firstName, lastName) => { return firstName + ' '+ lastName; } console.log(fullNameByArrow('John','Mickel')); // output // John Mickel
// function
const fullNameByArrow = (firstName, lastName) => {
    return firstName + ' '+ lastName;
}
console.log(fullNameByArrow('John','Mickel'));

// output
// John Mickel

 

One thought on “Different ways to create a function in javascript

Comments are closed.