Defining and calling functions
Learn to define and call functions with the function keyword.
What is a function?
In JavaScript, a function is a reusable block of code. You define it once and call it as many times as you need. It starts with the function keyword, followed by a name, parentheses for parameters and a body in curly braces.
Example: function greet() { console.log("Hello"); }. Defining the function does not run it; only calling it does. The statements inside the body run at that moment.
Calling a function
To run a function you defined, you add () after its name. This is called calling the function. For example, the line greet(); runs greet and executes the code in its body.
If you forget the parentheses, the function is not called; you only reference the function object. That is the difference between greet and greet(): the first is the definition, the second is the call.
Exercise Greeting function
Define a function called greet. Its body should print a welcome message with console.log. Then call the function.
Show example solution
function greet() {
console.log("Welcome");
}
greet();
Test yourself
-
Which of these is a valid function declaration?
- greet() { console.log("Hi"); }
- function greet() { console.log("Hi"); }
- function greet() => { console.log("Hi"); }
- greet: function { console.log("Hi"); }
Show answer
function greet() { console.log("Hi"); } — Correct. The function keyword + name + () + {} form is the right declaration.
-
Call the function
function greet() { console.log("Hi"); } ____;Show answer
function greet() { console.log("Hi"); } greet(); -
Match the function parts
- function
- Keyword
- greet
- Function name
- ()
- Parameter list
- { }
- Function body