Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Function Declarations Expressions
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Function Declarations and Expressions

Creating reusable blocks of code

Functions are one of the fundamental building blocks in JavaScript. They allow you to write code once and reuse it many times, making your programs more organized, maintainable, and efficient. There are two main ways to create functions: function declarations and function expressions. Let's master both and understand when to use each!

What Are Functions?

A function is a reusable block of code designed to perform a particular task. Think of it as a recipe or instruction set that you can use whenever needed.

Real-world analogy:

A function is like a vending machine. You put in inputs (money + selection), it processes them, and gives you an output (snack). Same machine, reusable for different inputs!

Why Use Functions?

  • Reusability: Write once, use many times
  • Organization: Break complex problems into smaller pieces
  • Maintainability: Update code in one place
  • Readability: Give meaningful names to operations
  • Testing: Test individual pieces of functionality
JAVASCRIPT
// Without functions (repetitive)
console.log("Hello, Alice!");
console.log("Hello, Bob!");
console.log("Hello, Charlie!");

// With function (reusable)
function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Alice");
greet("Bob");
greet("Charlie");
// Much cleaner and reusable!

Function Declarations

A function declaration defines a named function using the function keyword.

Syntax

JAVASCRIPT
function functionName(parameters) {
  // Code to execute
  return value;  // Optional
}

// Example
function sayHello() {
  console.log("Hello, World!");
}

sayHello();  // Call the function
// Output: "Hello, World!"

Function Declaration Components

  1. function keyword: Declares a function
  2. Function name: Identifier to call the function
  3. Parameters: (Optional) Input values in parentheses
  4. Function body: Code block in curly braces
  5. return statement: (Optional) Value to return

Basic Function Declarations

JAVASCRIPT
// Function with no parameters
function greet() {
  console.log("Hello!");
}

greet();  // "Hello!"

// Function with one parameter
function greetPerson(name) {
  console.log(`Hello, ${name}!`);
}

greetPerson("Alice");  // "Hello, Alice!"

// Function with multiple parameters
function add(a, b) {
  return a + b;
}

let sum = add(5, 3);
console.log(sum);  // 8

// Function with calculation
function calculateArea(width, height) {
  let area = width * height;
  return area;
}

console.log(calculateArea(5, 10));  // 50

// Function with conditional logic
function isEven(number) {
  if (number % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

console.log(isEven(4));  // true
console.log(isEven(7));  // false

Naming Functions

JAVASCRIPT
// Good function names (descriptive, verb-based)
function calculateTotal() { }
function getUserName() { }
function isValidEmail() { }
function sendEmail() { }
function formatDate() { }

// Bad function names (vague, unclear)
function doStuff() { }
function process() { }
function handle() { }
function temp() { }
function x() { }

// Naming conventions
function getUser() { }        // get - retrieve data
function setTheme() { }       // set - assign value
function calculatePrice() { } // calculate - compute
function validateForm() { }   // validate - check validity
function formatCurrency() { } // format - transform data
function isActive() { }       // is/has - boolean check
function hasPermission() { }  // is/has - boolean check

Best Practice: Use descriptive names that explain what the function does. Start with a verb (action word) like get, set, calculate, validate, etc.

Function Expressions

A function expression defines a function as part of an expression, typically by assigning it to a variable.

Syntax

JAVASCRIPT
// Anonymous function expression
const functionName = function(parameters) {
  // Code to execute
  return value;
};

// Example
const sayHello = function() {
  console.log("Hello, World!");
};

sayHello();  // "Hello, World!"

// Named function expression (less common)
const greet = function greetUser(name) {
  console.log(`Hello, ${name}!`);
};

greet("Alice");  // "Hello, Alice!"

Function Expression Examples

JAVASCRIPT
// Simple function expression
const greet = function(name) {
  return `Hello, ${name}!`;
};

console.log(greet("Bob"));  // "Hello, Bob!"

// Function expression with multiple parameters
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(4, 5));  // 20

// Function expression assigned to object property
const calculator = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  }
};

console.log(calculator.add(10, 5));       // 15
console.log(calculator.subtract(10, 5));  // 5

// Function expression as callback
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(function(num) {
  return num * 2;
});

console.log(doubled);  // [2, 4, 6, 8, 10]

Note: Function expressions must end with a semicolon because they're part of a variable assignment statement. Function declarations don't need semicolons.

Function Declarations vs Expressions

Two ways to create functions

Function Declaration

// Function Declaration
function add(a, b) {
  return a + b;
}

// Can be called before declaration
console.log(multiply(3, 4));  // 12

function multiply(a, b) {
  return a * b;
}

// Characteristics:
// - Hoisted (can call before defined)
// - Must have a name
// - Can't be used as expressions
Output:
Not run yet...

Function Expression

// Function Expression
const add = function(a, b) {
  return a + b;
};

// Cannot be called before definition
// console.log(multiply(3, 4));  // Error!

const multiply = function(a, b) {
  return a * b;
};

// Characteristics:
// - Not hoisted (can't call before)
// - Can be anonymous
// - Can be used in expressions
Output:
Not run yet...

Key Differences

FeatureDeclarationExpression
Hoisting✓ Fully hoisted✗ Not hoisted
Name Required✓ Must have name✗ Can be anonymous
Call Before Define✓ Yes✗ No
Semicolon✗ Not needed✓ Required
Use in Expression✗ No✓ Yes

Understanding Hoisting

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation.

Function Declaration Hoisting

JAVASCRIPT
// This works! Declaration is hoisted
console.log(greet("Alice"));  // "Hello, Alice!"

function greet(name) {
  return `Hello, ${name}!`;
}

// What JavaScript does behind the scenes:
// 1. Moves function declaration to top
// 2. Then executes code in order

// Effectively becomes:
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Alice"));  // "Hello, Alice!"

Function Expression Hoisting

JAVASCRIPT
// This doesn't work! Expression is NOT hoisted
// console.log(greet("Alice"));  // Error: Cannot access before initialization

const greet = function(name) {
  return `Hello, ${name}!`;
};

// Variable is hoisted but not initialized
// Effectively becomes:
let greet;  // Hoisted declaration (undefined)

// console.log(greet("Alice"));  // Error: greet is not a function

greet = function(name) {  // Assignment happens here
  return `Hello, ${name}!`;
};

console.log(greet("Alice"));  // Now it works!

Hoisting with var, let, and const

JAVASCRIPT
// var: hoisted and initialized as undefined
console.log(typeof funcVar);  // "undefined"
var funcVar = function() {
  return "Hello";
};
console.log(funcVar());  // "Hello"

// let/const: hoisted but in "temporal dead zone"
// console.log(typeof funcLet);  // ReferenceError!
let funcLet = function() {
  return "Hello";
};

// console.log(typeof funcConst);  // ReferenceError!
const funcConst = function() {
  return "Hello";
};

Important: While function declarations are fully hoisted, function expressions are not. Always define function expressions before using them to avoid errors.

When to Use Each Type

Use Function Declarations when:

  • You want the function available throughout its scope
  • Creating utility functions used across your code
  • You prefer traditional, clear syntax
  • Hoisting behavior is desired
  • Creating top-level functions in modules

Use Function Expressions when:

  • Assigning functions to variables or object properties
  • Passing functions as arguments (callbacks)
  • Creating functions conditionally
  • You want to control when function is defined
  • Following modern JavaScript patterns
JAVASCRIPT
// Good use of declaration
function calculateTotal(price, tax) {
  return price + (price * tax);
}

// Can use it anywhere in the scope
let total1 = calculateTotal(100, 0.08);
let total2 = calculateTotal(200, 0.08);

// Good use of expression - callback
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
  return num * 2;
});

// Good use of expression - object method
const calculator = {
  add: function(a, b) {
    return a + b;
  },
  subtract: function(a, b) {
    return a - b;
  }
};

// Good use of expression - conditional function
let greetFunc;

if (isMorning) {
  greetFunc = function() {
    return "Good morning!";
  };
} else {
  greetFunc = function() {
    return "Good evening!";
  };
}

Practical Examples

Example 1: Utility Functions

JAVASCRIPT
// Declarations for utility functions
function formatCurrency(amount) {
  return `$${amount.toFixed(2)}`;
}

function validateEmail(email) {
  return email.includes("@") && email.includes(".");
}

function capitalize(text) {
  return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Using the utilities
console.log(formatCurrency(19.99));        // "$19.99"
console.log(validateEmail("test@ex.com")); // true
console.log(capitalize("hello"));          // "Hello"
console.log(getRandomInt(1, 10));          // Random 1-10

Example 2: Object with Methods

JAVASCRIPT
// Expressions for object methods
const user = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  
  getFullName: function() {
    return `${this.firstName} ${this.lastName}`;
  },
  
  isAdult: function() {
    return this.age >= 18;
  },
  
  greet: function() {
    return `Hello, I'm ${this.getFullName()}`;
  },
  
  haveBirthday: function() {
    this.age++;
    return `Happy birthday! Now ${this.age} years old.`;
  }
};

console.log(user.getFullName());  // "John Doe"
console.log(user.isAdult());      // true
console.log(user.greet());        // "Hello, I'm John Doe"
console.log(user.haveBirthday()); // "Happy birthday! Now 31 years old."

Example 3: Calculator Application

JAVASCRIPT
// Mix of declarations and expressions
function createCalculator() {
  // Private state
  let result = 0;
  
  // Return object with methods (expressions)
  return {
    add: function(num) {
      result += num;
      return this;  // For chaining
    },
    
    subtract: function(num) {
      result -= num;
      return this;
    },
    
    multiply: function(num) {
      result *= num;
      return this;
    },
    
    divide: function(num) {
      if (num === 0) {
        console.log("Cannot divide by zero");
        return this;
      }
      result /= num;
      return this;
    },
    
    getResult: function() {
      return result;
    },
    
    clear: function() {
      result = 0;
      return this;
    }
  };
}

// Using the calculator
const calc = createCalculator();

calc.add(10).multiply(2).subtract(5).divide(3);
console.log(calc.getResult());  // 5

calc.clear().add(100).subtract(50);
console.log(calc.getResult());  // 50

Function Declarations and Expressions

Experiment with different function types

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • Functions are reusable blocks of code that perform specific tasks
  • Function declarations: function name() {}
  • Function expressions: const name = function() {};
  • Declarations are hoisted; expressions are not
  • Use descriptive names starting with verbs
  • Declarations are good for utility functions
  • Expressions are good for callbacks and object methods
  • Both types can accept parameters and return values
  • Function expressions require semicolons; declarations don't
  • Choose based on your needs and coding style

What's Next?

You now understand how to create functions using both declarations and expressions! Functions are essential to writing clean, reusable code.

In the next lesson, we'll explore Arrow Functions—a modern, concise syntax for writing functions introduced in ES6. Arrow functions are incredibly popular and make your code shorter and more readable!

💪 Practice Challenge:

Before moving on, try creating:

  1. A function that checks if a number is prime
  2. A function that reverses a string
  3. An object with methods for a simple bank account (deposit, withdraw, getBalance)
  4. A function that finds the longest word in an array
  5. A function that converts a sentence to title case

Test Your Understanding

Question 1 / 4

What is a function in JavaScript?

Score: 0 / 0

Learning JavaScript functions! 🔧

Previous
Break and Continue Statements
Next
Arrow Functions

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript functions. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo