Javascript
JavaScript Fundamentals -- Functions in JavaScript
  •  

Named Functions

PRO

Named functions in JavaScript is just a fancy way to refer to a function that uses the function keyword and then a name you can use as a reference to that function. Here's an example:

function myFunction(someParameter) {
    // Do something
}

A named function has 4 basic parts: the function keyword, the name you give it and use to refer to it, the parameter list, and the body of the function.

Named functions can also be assigned to attributes on objects, and then you can call the function on the object:

function sayHi() {
    console.log (`Hi my name is ${this.name}.`);
}
const person = {
    name: 'Preston Lamb',
    sayHi
}
person.sayHi();

Named functions are one of the most common ways that functions are called in JavaScript. You'll come across them frequently.

One other thing that is important to mention here is how to return a value from a function using the return keyword. Now, this is not unique to named functions. You'll do this the same way in all functions. Here's an example:

function subtract(num1, num2) {
  return num1 - num2;
}

In this example, the function takes two parameters, num1 and num2, and returns the value of num1 minus num2. That returned value can be assigned to a variable, or logged to the console, or passed as the parameter to another function. If you don't return anything from a function, but assigned the function call to a variable, you'd get undefined as the result.

You can learn more about named functions in this blog post.