Functions

Function is a code block that executes certain task.

Syntax

Void Example

A void function doesn't return any value.

Example:

Output:

Returning Result

Via the return keyword a result can be returned.

Let's have an example in which rectangle's area is calculated by passing arguments about it's sides.

Example:

Output:

There are couple of things to mark:

  • A functions is defined at lines 4 - 6. It accepts two arguments - widthArg and heightArg.
  • The function calcRectangleArea returns a result.
  • calcRectangleArea is called at line 1.
  • It's returned value is set in the variable area.

Not passing argument

If arguments is not passed it's value is considered undefined.

Output:

The function printArgs expects 3 arguments but the last one (c) is not passed. For that reason c has undefined value.

Default Value

Default value may be specified for function parameters.

Let's look at the following:

Output:

At line 2 the function argument is not passed thus it takes the default value - 3 specified at line 4.