JavaScript Functions

In this article, we're going to explore functions in JavaScript, how to create and use one.

So, what is a JavaScript function? A function is a group of instructions that together perform a task; it is defined once and can be used (i.e. called) as many times as needed.

Defining a function

A function is defined via the `function` keyword:

function sayHello(name) {
  return "Hello " + name;
}

Using a function

Here is how to call our `sayHello` function, using "Paul" as value for the `name` parameter:

sayHello("Paul"); // "Hello Paul"

Returned value

A function always returns a value; if nothing is specified, `undefined` is returned. In the example below, we're printing "Hello Paul" to the console but not return a value. The second `console.log` will show `undefined` as the result of calling `sayHello("Paul")`

function sayHello(name) {
  console.log("Hello " + name);
}
console.log(sayHello("Paul")); // undefined

Default arguments

Let's see what happens if we "forget" to send an argument to the function:

function sayHello(name) {
  return "Hello " + name;
}
console.log(sayHello()); // "Hello undefined"

Notice that `undefined` is appended to the "Hello " string before being returned.

We can, however, specify a default value to be used for a parameter:

function sayHello(name = "World") {
  return "Hello " + name;
}
console.log(sayHello()); // "Hello World"

Next Steps