# User-defined functions

# Functions without parameters

  • A user-defined function (e.g. function writeMessage()) starts with the keyword function, followed by ( )
  • The function code should be placed between { }
function writeMessage() {
    console.log('We hope you like this JavaScript course!');
}

writeMessage();
1
2
3
4
5

# Functions with parameters

  • Put the parameters of a function between the round brackets, as in function writePersonalMessage(name)
  • When a function with parameters is called (e.g. writePersonalMessage('John');), we need to supply arguments (John) to pass to the parameters (name)
  • These parameters can be used inside your function in the same way as variables
function writePersonalMessage(name) {
    console.log(`Dear ${name}, we hope you like this JavaScript course!`);
}

writePersonalMessage('John');
1
2
3
4
5

# Default values for parameters

  • You can set a parameter to have a default value if no argument is passed to the function, as in function writePersonalMessageWithDefault(name = 'Mr./Mrs.')
function writePersonalMessageWithDefault(name = 'Mr./Mrs.') {
    console.log(`Dear ${name}, we hope you like this JavaScript course!`);
}

// use the default value 'Mr./Mrs.'
writePersonalMessageWithDefault();
// use 'Jane' as the value
writePersonalMessageWithDefault('Jane');
1
2
3
4
5
6
7
8

# Functions with return value

  • A function can return a value using the return statement, as illustrated in function average(number1, number2)
function average(number1, number2) {
    return (number1 + number2) / 2;
}

const av = average(5, 10);
console.log(av); // => 7.5
1
2
3
4
5
6

# Function declaration vs expression

  • There are two different flavors of writing a named function in JavaScript
    • A function declaration always starts with the function keyword, followed by the name of the function
    • In a function expression, the function has no name (anonymous function) and is stored in a variable (which will/can be used to call the function later on)
// function declaration
function sum1(number1, number2) {
    return number1 + number2;
}

// function expression
const sum2 = function (number1, number2) {
    return number1 + number2;
};

console.log(sum1(5, 8));  // => 13
console.log(sum2(5, 8));  // => 13
1
2
3
4
5
6
7
8
9
10
11
12

REMARKS: Semicolon?

  • Because a function declaration is not an executable statement, it doesn't need to end with a semicolon
  • Function expressions are like variable declarations and need to end with a semicolon
  • Both flavors give you exactly the same result, but:
    • Function declarations load before any code is executed, so it is possible to call the function before the declaration itself
     






    console.log(sum1(5, 8)); // => 13
    
    // function declaration
    function sum1(number1, number2) {
        return number1 + number2;
    }
    
    1
    2
    3
    4
    5
    6
    • Function expressions load when the interpreter reaches the specific line of code, so it's NOT possible to call the function before the expression itself
     






    console.log(sum2(5, 8)); // => error: Uncaught ReferenceError: Cannot access 'sum2' before initialization
    
    // function expression
    const sum2 = function (number1, number2) {
        return number1 + number2;
    };
    
    1
    2
    3
    4
    5
    6

# Self-invoking functions

  • A self-invoking function is invoked (started) automatically, without being called
  • Self-invoking functions are wrapped inside () and always end with ();
  • It's not possible to call/re-use this function later on


 



(function hello() {
    console.log('I start myself...');
})();

hello(); // => error: Uncaught ReferenceError: hello is not defined
1
2
3
4
5

# Callback functions

  • A callback function (e.g. cb) is a function passed into another function as an argument
  • We have already used callback functions several times:
    • inside an event listener: window.addEventListener('keydown', cb)
    • inside the timing functions: setTimeout(cb, 1000), setInterval(cb, 1000)
  • When you "externalize" the callback function (versions 2 and 3 below), you have to pass the function WITHOUT ()!

REMARK: countSeconds() vs countSeconds

  • countSeconds() means: execute the function
  • countSeconds doesn't execute the function but is just a reference to the code of the function countSeconds()
Last Updated: 4/22/2021, 1:32:46 PM