By the end of this lesson, learners will be able to:
Declaring a function means creating it — giving it a name and defining what it should do.
function functionName() {
// code to run when the function is called
}
Part | Example | Description |
---|---|---|
function | keyword | Tells JavaScript you’re creating a function |
functionName | sayHello | The name of your function |
() | empty for now | Can hold parameters (explained in next lesson) |
{ ... } | code block | The statements that run when the function is called |
Calling a function means telling JavaScript to run the code inside the function.
functionName();
You must include the ()
even if the function doesn’t take any parameters.
function sayHello() {
console.log("Hello!");
}
sayHello(); // Output: Hello!
sayHello();
sayHello();
sayHello();
Output:
Hello!
Hello!
Hello!
✅ This demonstrates the reusability of functions.
Function names should be:
Good Names | Bad Names |
---|---|
calculateTotal | doThing |
printMessage | x |
getUserName | function1 |
function showWelcomeMessage() {
console.log("Welcome to Codevisionz!");
}
showWelcomeMessage();
You could use this on multiple screens or after login, without rewriting the message.
Just because a function is declared doesn’t mean it will run automatically.
function greet() {
console.log("Hi!");
}
This won’t do anything until you write:
greet(); // Output: Hi!
Define a function called sayGoodbye
that prints "Goodbye!"
, and then call it twice.
✅ Solution:
function sayGoodbye() {
console.log("Goodbye!");
}
sayGoodbye();
sayGoodbye();
🧠 Output:
Goodbye!
Goodbye!