Top image

WEB design and programming - HTML | CSS | Java Script | PHP

Basic JavaScript

JavaScript: Functions

What are functions?

WHAT IS A FUNCTION?

Function is a block for a set of commands or instructions.

A function is a reusable block of code that groups together a sequence of statements to perform a specific task its inside, in order to make a program easier. With this, you won’t have to write a same code every single time.
Here’s what a function look like:

// Declare a variable
let js = "JavaScript"; 
//Define a function
function firstFunction() {
 alert(js);
}
// Call the function
firstFunction();

You will be able to see a result of code above by clicking the button below.

NOTICE:

JavaScript offer us a tons of original functions such as alert function above, and console.log. It may be recommended to look up if there is a similar function before you want to create your own new function.

DEFINE A FUNCTION

We are going to learn how function defined in this section.
For instanse, if there is the function that calculate numbers like this;

function multiple(x, y) {
    x += 1;
    return x * y;
}
multiple(3, 6);
console.log(multiple);

In this case, a result of multiple function will be 24. This is because the function adds +1 to the value of the parameter x and multiplies it by y. The result value will be changed when you alter the either or both number:

Let’s see an anatomy how this function works, step by step.

①Declare the function

First of all step is how declare the function. In JavaScript, one way to create a function is by using a function declaration, which has been used since old time.

// An actual code
function multiple(x, y) {
    x += 1;
    return x * y;
}

// An anatomy of the code
function functionName(Parameter1, Parameter2) {
    ・・・ // Body of Function 
    return // Returned value of Function ;
}
BREAK DOWN

function – Function keyword to start a syntax
functionName – You can define any name based on a variable naming convention
Parameter – A variable as a placeholder for a value that will be passed to the function when it is invoked
Body of Function – A place wrapped by {} to write an actual processing
Return – Return keyword followed by the value that we wish to return. CHECK!

notice

> The syntax that start by function keyword is called the “Function declaration”.
> Function declaration is following by a function name.
> Can not redefine a name originally defined by JavaScript (such as alert()).
> Will be more able to find parameters out at a section of an argument below.

Return keyword

return keyword is very important since we can only receive the value handled when the return statement is exist, even if the function worked fine. Without this, JavaScript will return undefined as a default value instead.

We use the return keyword followed by the value that we wish to return. Like we have seen above as the calculated function example:

return x * y;

In this case, we’ll be able to get the result of x * y.

However, if we wrote a code like this below, we wouldn’t catch the return value but got the undefined instead since we omitted the return value!

function multiple(x, y) {
    return;
}
console.log(multiple()); // => undefined
Does return should type on the end of code?

As a return statement is executed, no further processing is performed in its function. For instance, If you write the code like this:

function multiple(x, y) {
    return x * y; 
    // The function will no longer execute until here
    x += 1; // This line will be ignored
}
multiple(3, 6);

In this code example above, the result will be 18. Since the return keyword has already run, the under line from the return statement won’t execute.

notice

> If the function does not need to return a value, the return value can be intentionally omitted, or the return statement itself, too.

②Calling the function

It can be invoked the function with following ( ) to the function name created,

// An actual code
multiple(3, 6);
// An anatomy of the code
functionName(argument1, argument2);

When calling a function together with its arguments, use the functionName (argument1, argument2);. Separate them with commas if there are two more arguments.

notice

> Be sure to put a semicolon at the end of the sentence.

Argument

An argument can be passed into the functions by adding a value within the parentheses ( ).

const greeting = "Hello!";
console.log(greeting);

In this case, console.log(greeting), the inside of parentheses, greeting, will be an argument of its function.

Deference of a parameter and an argument

What a deference of a parameter and an argument is a just simple that the parameter is in where a function defined, and the argument is in where a function called.

image

The Parameter will be assigned variables.
The argument will be assigned actual values.

notice

> As there are parameters but no arguments, undefined is assigned into the remaining parameters (When Parameters > Arguments)
> As there are arguments but no parameters, an surplus of argument will be ignored.(When Parameters < Arguments)

[ES2015] Default Parameters

Default parameters allow to have a predetermined value in case there is no argument passed into the function or if the argument is undefined when called.

function echo(x = "default value") {
    return x;
}
console.log(echo(1)); // => 1
console.log(echo(1, 6)); // => 1
console.log(echo()); // => "default value"

Thus if a default value is specified for the parameter, it can have a value in advance even if no argument is passed.

[ES2015] ARROW FUNCTION

[ES2015] introduced arrow function syntax, a shorter way to write functions by using “arrow notation”, ()=>.

How to write an arrow function

The arrow function is made up of the syntax below.

const js = "JavaScript"; 
const firstFunction = () => {
 alert(js);
}
firstFunction();

Here is a comparison of the function declaration.

const js = "JavaScript"; 
function firstFunction() {
 alert(js);
}
firstFunction();
BREAK DOWN

– Removed the need to type out the keyword function
– Instead, Use the either keyword const or let to declare the arrow function followed by Function name you want
– First include the parameters inside the ( )
– Add an arrow => following the parentheses, that points to the function body surrounded in { }

:concise body

In addition, [ES2015] allows to write a concise code in the syntax of the arrow function. Like this:

// A regular way to write the arrow function
const multiple = (num) => {
 return num * num;
}

// A concise way to write the arrow function
const multiple = num => num * num;
BREAK DOWN

– The parentheses, ( ), around num have been removed
– The curly braces { } have been removed
– The return keyword has been removed

WHY?

– This is because it is possible to omit the ( ), only when you have a single parameter
– Also you can omit those { } and return keyword, only when the function consists of a single-line block.

notice

> JavaScript has up to three types of syntax for declaring functions, which are Function Declaration, Arrow Function, and Function Expression. >>About Function Expression
> It will be helpful to be familiar with the multiple ways of those syntax.

REVIEW A FUNCTION

> Function is a reusable block of codes.

> Functions can store themselves in variables.

> There are three way to declare the function.

> Arrow function is newer type of declaration in JavaScript [ES2015].

> Return keyword is requirement when you need to receive the value from its function.

> Argument is the actual values passing into the parameters of function.

We are going to learn Functions & Scope in the next chapter.