Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to call a function in JavaScript?
JavaScript allows us to write our own functions as well. To invoke a function somewhere later in the script, you would simply need to write the name of that function.
Function Declaration
Before calling a function, you need to declare it. Here's the basic syntax:
function functionName() {
// Code to execute
}
Calling a Function
Once declared, you can call a function by writing its name followed by parentheses:
<html>
<head>
<script>
function sayHello() {
document.write("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Different Ways to Call Functions
Functions can be called in multiple ways depending on the context:
Direct Function Call
<script>
function greetUser() {
document.write("Welcome to our website!");
}
// Call the function directly
greetUser();
</script>
Event-Driven Function Call
<button onclick="greetUser()">Click Me</button>
<script>
function greetUser() {
alert("Button clicked!");
}
</script>
Functions with Parameters
Functions can also accept parameters when called:
<script>
function greetWithName(name) {
document.write("Hello, " + name + "!");
}
// Call function with argument
greetWithName("John");
</script>
Common Methods
| Method | When to Use | Example |
|---|---|---|
| Direct Call | Execute immediately | myFunction() |
| Event Handler | User interaction | onclick="myFunction()" |
| With Parameters | Pass data to function | myFunction(value) |
Conclusion
Calling JavaScript functions is straightforward - just use the function name followed by parentheses. Functions can be called directly, through events, or with parameters to make them more flexible and reusable.
Advertisements
