JavaScript Functions
A JavaScript function is a block of code designed to perform a specific task. Functions are executed when they are called (invoked).
Functions help make code reusable, organized, and easier to manage.
Basic Function Example
A function is defined using the function keyword, followed by a name and parentheses.
Example
<!DOCTYPE html>
<html>
<body>
<p id="func1"></p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction() {
document.getElementById("func1").innerHTML = "Hello from Function!";
}
</script>
</body>
</html>
Try this code
Function with Parameters
Functions can take parameters (inputs) to work with different values.
Example
<!DOCTYPE html>
<html>
<body>
<p id="func2"></p>
<button onclick="showName('John')">Click Me</button>
<script>
function showName(name) {
document.getElementById("func2").innerHTML = "Hello " + name;
}
</script>
</body>
</html>
Try this code
Function with Return Value
A function can return a value using the return keyword.
Example
<!DOCTYPE html>
<html>
<body>
<p id="func3"></p>
<button onclick="showResult()">Click Me</button>
<script>
function add(a, b) {
return a + b;
}
function showResult() {
document.getElementById("func3").innerHTML = add(5, 3);
}
</script>
</body>
</html>
Try this code
Why Use Functions?
- They reduce code repetition
- They make code easier to read
- They help organize programs
- They allow reuse of logic
Function Naming Rules
- Use meaningful names (e.g., calculateSum)
- Names can contain letters, numbers, _ and $
- Names should not start with numbers
- Use camelCase for better readability
Calling a Function
A function runs when it is called. You can call it by writing its name followed by parentheses.
Example
<!DOCTYPE html>
<html>
<body>
<p id="func4"></p>
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
document.getElementById("func4").innerHTML = "Function Called!";
}
</script>
</body>
</html>
Try this code