A function is a block of JavaScript code that is defined once, but can be called repeatedly from many places in your program. Functions are the cornerstone of reusability in JavaScript programs.

Functions are defined via the function keyword and may be parameterized by invoking the function with arguments that specify the data on which to operate.</>

function add(x, y) {
    return x + y

The "x" and "y" parameters are the formal arguments for the function. The body of the function is all the code between the curly braces {}.

When invoking the function, you provide the actual parameters.

add(10, 5)

Function Literals

Unlike many other languages, JavaScript functions are values like any other JavaScript type and they can be assigned and stored in variables. Function literals are just like normal function declarations except they can optionally omit the function name and the function reference can be assigned to a variable.

var subtract = function (x, y) {
    return x - y
subtract(10, 2)
var subtractByAnotherName = add
subtractByAnotherName(7, 3)

The above function expression creates a function and assigns it to a variable named subtract. Invoking function expressions is indistinguishable from invoking regular functions. And so, you can use either form for declaring function expressions. It is your choice.

Return Statement

The return statement instructs the function to cease executing the function and return immediately to its caller. The return may take an optional result expression.

Local Variables

Variables declared inside functions are visible only within the function and are called local variables. You can declare variables using either the var or let keywords. Declarations made with var, will take effect from the start of the function and be visible in all blocks. Declarations made with let take effect only within the block containing the let declaration.

function fun() {
    var color = "red"
        let color = "blue"
        print("Inner: " + color)
    print("Outer: " + color)
/* Emits */

Inner: blue
Outer: red

Nested Functions

Function declarations nest inside other functions. When the inner function executes, it has access to all the variables defined in the outer blocks.

function fun() {
    var color = "red"
    function inner() {

Ejscript Enhancements

Ejscript adds several enhancements to standard JavaScript functions.

Ejscript also fixes some problematic issues in standard JavaScript.

© Embedthis Software, 2003-2015. All rights reserved.