Understanding Functions in JavaScript
Source: Dev.to
What is a Function?
A function is a block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can write it once inside a function and reuse it whenever needed.
Why Use Functions?
- Reduce code repetition
- Make code easier to understand
- Help in organizing large programs
- Allow reuse of logic
How to Create a Function
In JavaScript, you can create a function using the function keyword.
function greet() {
console.log("Hello, welcome to JavaScript!");
}How to Call a Function
To execute (run) a function, simply call it by its name:
greet();Output
Hello, welcome to JavaScript!Functions with Parameters
Functions can take inputs called parameters.
function greetUser(name) {
console.log("Hello " + name);
}
greetUser("Athithya");Output
Hello AthithyaFunctions with Return Value
A function can return a value using the return keyword.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);Output
8