- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Calling the Function: Syntax, Usage, and Examples
In JavaScript, calling a function means executing the code inside the function body. You do this by writing the function's name followed by parentheses.
How to Call a Function in JavaScript
The syntax for calling a function is simple:
functionName();
If the function expects arguments, you can pass them inside the parentheses:
greetUser("Anna");
This executes the code defined in the function with the provided arguments. Calling the function is what actually runs the logic, it won't do anything until it's called.
Here’s a full example:
function greetUser() {
console.log("Good morning Anna");
console.log("Welcome back");
}
greetUser(); // Calls the function
The function greetUser
runs only when you call it with greetUser();
.
When to Use Function Calls in JavaScript
You call functions whenever you want to execute a block of reusable code. Here are common scenarios where calling a function is helpful:
1. Responding to User Actions
You can call a function when a user clicks a button, types in a form, or scrolls down a page.
function showAlert() {
alert("Thanks for clicking!");
}
document.getElementById("myButton").addEventListener("click", showAlert);
In this case, showAlert
is called when the user clicks the button.
2. Organizing Reusable Code
Instead of repeating code, you can put it inside a function and call it whenever needed.
function calculateTax(price) {
return price * 0.1;
}
let tax1 = calculateTax(100);
let tax2 = calculateTax(250);
This makes your code cleaner and easier to maintain.
3. Running Code on Page Load
You might call a function when the page loads to initialize settings, fetch data, or set up UI elements.
function initializeApp() {
console.log("App initialized");
}
initializeApp(); // Call function immediately after declaring
Calling the function at the end runs your setup logic as soon as the script runs.
Examples of Calling Functions in JavaScript
Here are a few examples of calling the function in JavaScript, from simple use cases to slightly more involved ones.
Example 1: Calling a Function with No Arguments
function sayHello() {
console.log("Hello!");
}
sayHello();
This function simply prints a greeting to the console when called.
Example 2: Calling a Function with Arguments
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Kai"); // Output: Hello, Kai!
greetUser("Sasha"); // Output: Hello, Sasha!
You're passing different values into the function. Each time, it personalizes the message.
Example 3: Calling a Function That Returns a Value
function add(a, b) {
return a + b;
}
let result = add(4, 7); // result = 11
console.log(result);
Calling add(4, 7)
runs the code and returns a value you can store or use directly.
Example 4: Calling a Function Conditionally
You can use function calls inside conditionals.
function isEven(number) {
return number % 2 === 0;
}
let userInput = 6;
if (isEven(userInput)) {
console.log("Even number!");
} else {
console.log("Odd number!");
}
The result of calling isEven
helps determine which block of code to run.
Learn More About Calling Functions in JavaScript
Function Expressions and Arrow Functions
Besides declaring functions with the function
keyword, you can also create function expressions:
const sayHi = function() {
console.log("Hi there!");
};
sayHi(); // Call the function
Or use arrow functions for shorter syntax:
const multiply = (a, b) => a * b;
console.log(multiply(3, 5)); // Output: 15
You call these the same way, with parentheses and any needed arguments.
Function Calls Inside Other Functions
You can call one function from inside another. This helps break your code into small, manageable pieces.
function calculateDiscount(price) {
return price * 0.2;
}
function printDiscountedPrice(originalPrice) {
let discount = calculateDiscount(originalPrice);
console.log("Discounted amount: $" + discount);
}
printDiscountedPrice(50); // Output: Discounted amount: $10
Calling Functions Recursively
Functions can even call themselves, which is called recursion.
function countdown(n) {
if (n <= 0) {
console.log("Done!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);
In this example, the function continues calling itself with smaller values until the base case is met.
Calling Anonymous Functions Immediately
JavaScript also allows you to call a function as soon as you define it using an Immediately Invoked Function Expression (IIFE):
(function () {
console.log("Running right away!");
})();
This is useful for running code without polluting the global scope.
Calling Methods on Objects
When you define functions inside objects, they’re called methods. You call them using dot notation:
const user = {
name: "Alex",
greet: function() {
console.log("Hi, " + this.name);
}
};
user.greet(); // Output: Hi, Alex
You’re calling a function, but in the context of an object.
In JavaScript, calling the function means executing the code wrapped inside that function. From simple function names with parentheses to more complex nested or recursive calls, learning how and when to use them helps you write more readable and efficient code.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.