Why use functions?
Reusability: Write code once and use it multiple times.
Modularity: Break down complex problems into smaller, manageable pieces.
Readability: Makes your code easier to understand and maintain.
Avoid Repetition: Prevents writing the same code over and over.
Ways to Define Functions in JavaScript
There are several ways to define functions in JavaScript, each with its own nuances:
Function Declarations
Function Expressions
Arrow Functions
Immediately Invoked Function Expressions
1. Arrow Function
const add = (a, b) => a + b;
2. Anonymous Function
const greet = function(name) {
return "Hello, " + name;
};
๐งช Example: Add Two Numbers
function add(a, b) {
return a + b;
}
Usage:
console.log(add(5, 3)); // Output: 8
โจ๏ธ Form and Input Handling
const form = document.forms[0];
input.value
const name = document.getElementById("username").value;
Top comments (0)