JS - 03.02 - Defining Function

There are three ways to define a function in JavaScript:
Function Expressions, Function Declarations, and Arrow Functions.


1. Function Expression

A Function Expression is when a function is defined as part of an expression.
The function itself is assigned to a variable, which can then be called later.
Since the function is part of an expression, it cannot be used before it is defined. This allows for creating a function in the middle of any expression.

As the function creation happens in the context of the assignment expression (to the right side of =), this is a Function Expression.

  • The function is created when the execution reaches it, meaning you cannot call it before it is declared.
  • Function Expressions are anonymous or named functions assigned to variables.
const square = function(x) {
  return x * x;
};

console.log(square(12)); // 144

Function for square is defined as an expression and assigned to the variable square. It can be called later after the definition.

  • A function starts with the function keyword, followed by a set of parameters inside parentheses (), and then a body inside curly braces {}.
  • Functions can have no parameters or multiple parameters.
  • The return keyword is used to return a value from the function. If no return statement is provided, the function returns undefined by default.

Example with no parameters:

const makeNoise = function() {
  console.log("Ping!");
};
makeNoise(); // Ping!

Example with multiple parameters:

const roundTo = function(n, step) {
  let remainder = n % step;
  return n - remainder + (remainder < step / 2 ? 0 : step);
};

console.log(roundTo(23, 10)); // 20

If the remainder is less than half of step, it rounds down; otherwise, it rounds up.

Python Equivalent:

def makeNoise():
    print("Ping!")

makeNoise()

def roundTo(n, step):
    remainder = n % step
    if remainder >= step / 2:
        return (n - remainder) + step
    return (n - remainder)

print(roundTo(23, 10)) # 20

Important Note:

  • A Function Expression typically ends with a semicolon (;) since it’s part of an assignment statement. But function declaration do not.

A Function Expression is created here as function(…) {…} inside the = assignment statement:  let sayHi = …;. The semicolon ; is recommended at the end of the statement, it’s not a part of the function syntax.

let sayHi = function() {
  // function body
}; // semicolon required

2. Function Declaration

A Function Declaration is the classic way to define a function in JavaScript. It starts with the function keyword, followed by the function name, parameters, and the function body enclosed in curly braces.

function functionName(parameter1, parameter2, ...parameterN) {
  // body
}
function square(x) {
  return x * x;
}
console.log(square(12)); // 144

//function expression
let square = function(x) {
	return x * x;
};
  • A Function Declaration does not require a semicolon after it, because it’s a complete statement by itself.
  • The function name must be valid (cannot start with a number, etc.).
  • The function is created when the script is loaded and is hoisted to the top of its scope. This means it can be called before its actual declaration in the code.

Hoisting Behavior:

Function Declarations are hoisted to the top of their scope, so they can be called before they are defined in the code. Function Expressions, on the other hand, are not hoisted and can only be called after they are defined.

console.log("The future says: ", future());

function future() {
  return "You will never have flying cars";
}

In this example, the function future() can be called before it’s defined because the function declaration is hoisted to the top.

  • Function Declarations are useful when you want your functions to be accessible throughout the entire scope.
  • Function Expressions are useful when you need to define functions dynamically (such as inside loops, conditionals, or callbacks).

Function Declarations and Scope

  • A Function Declaration is visible throughout the entire scope it’s defined in (whether in a block, function, or global scope).
  • If a function is declared within a block (e.g., inside if or for statements), it’s only visible inside that block, not outside of it. So calling it from outside is not possible.

So better to declare a function using function expression outside a code block first, and reassign it inside the code block. This makes the function visible from outside also.

Function Declaration Inside Code Blocks:

let age = 18;

let welcome;  // Declare the variable to hold the function

if (age < 18) {
  welcome = function() {
    alert("Hello");
  };
} else {
  welcome = function() {
    alert("Greetings");
  };
}

welcome(); // Outputs either "Hello" or "Greetings" based on the age
  • Alternative with Ternary Operator:
let age = prompt("What is your age?", 18);

let welcome = (age < 18)
  ? function() { alert("Hello"); }
  : function() { alert("Greetings"); };

welcome(); // Outputs based on age

Key Differences Between Function Expressions and Function Declarations

FeatureFunction DeclarationFunction Expression
HoistingHoisted to the top, can be called before declaration.Not hoisted, can only be called after definition.
Syntaxfunction name() {}let name = function() {}
SemicolonNo semicolon required after function body.Semicolon is required after function expression.
Use CaseIdeal for globally accessible functions.Ideal for dynamically defined functions or passing functions as arguments.

Summary

  • Function Expressions are functions assigned to variables and are only usable after their definition.
  • Function Declarations are hoisted, meaning they can be used before the declaration in the code.
  • Choose Function Declarations for global accessibility and Function Expressions for dynamic or localized functions.