Lesson 2: Declaring and Calling Functions

Learning Objectives

By the end of this lesson, learners will be able to:

  • Understand how to declare (define) a function in JavaScript
  • Understand how to call (execute) a function
  • Learn function naming conventions
  • Identify the difference between declaration and execution
  • Practice defining and calling their own functions

What Does “Declaring a Function” Mean?

Declaring a function means creating it — giving it a name and defining what it should do.

Syntax of a Function Declaration

function functionName() {
  // code to run when the function is called
}

Parts of the function:

PartExampleDescription
functionkeywordTells JavaScript you’re creating a function
functionNamesayHelloThe name of your function
()empty for nowCan hold parameters (explained in next lesson)
{ ... }code blockThe statements that run when the function is called

What Does “Calling a Function” Mean?

Calling a function means telling JavaScript to run the code inside the function.

Syntax to call a function:

functionName();

You must include the () even if the function doesn’t take any parameters.


Example: Say Hello

Step 1: Declare the function

function sayHello() {
  console.log("Hello!");
}

Step 2: Call the function

sayHello(); // Output: Hello!

You Can Call a Function As Many Times As You Want

sayHello();
sayHello();
sayHello();

Output:

Hello!
Hello!
Hello!

✅ This demonstrates the reusability of functions.


Naming Functions: Best Practices

Function names should be:

  • Descriptive and meaningful
  • Written in camelCase
  • Typically use verbs (functions do something)

Examples:

Good NamesBad Names
calculateTotaldoThing
printMessagex
getUserNamefunction1

Real-Life Use Case: Reusable UI Message

function showWelcomeMessage() {
  console.log("Welcome to Codevisionz!");
}

showWelcomeMessage();

You could use this on multiple screens or after login, without rewriting the message.


Important: Declaring ≠ Calling

Just because a function is declared doesn’t mean it will run automatically.

Example:

function greet() {
  console.log("Hi!");
}

This won’t do anything until you write:

greet(); // Output: Hi!

Practice: Create Your Own Function

Task:

Define a function called sayGoodbye that prints "Goodbye!", and then call it twice.

✅ Solution:

function sayGoodbye() {
  console.log("Goodbye!");
}

sayGoodbye();
sayGoodbye();

🧠 Output:

Goodbye!
Goodbye!