Introduction to JavaScript Functions (With Arrow Functions)
Source: Dev.to
Function in JavaScript
A function is a reusable block of code that performs a specific task and runs only when it is called (invoked). Functions help us:
- Avoid repeating code
- Organize programs
- Make code easier to understand and maintain
Syntax
function functionName(parameters) {
// code to be executed
}
Example
function greet() {
console.log("Hello, Welcome!");
}
greet(); // Function call
Function with Parameters
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8
Frequently Asked Questions
What is a function in JavaScript?
A function is a reusable block of code that performs a specific task and runs when called.
Why do we use functions?
- Reduce code repetition
- Improve readability
- Organize code
- Make debugging easier
What are parameters and arguments?
- Parameters are variables listed in the function definition.
- Arguments are values passed to the function when calling it.
function show(name) { // name → parameter
console.log(name);
}
show("Vinayagam"); // "Vinayagam" → argument
What is the difference between return and console.log()?
returnsends a value back to the function caller.console.log()prints the output to the console.
What are the types of functions in JavaScript?
- Named Function
- Anonymous Function
- Arrow Function
- Function Expression
- Callback Function
Arrow Function in JavaScript
An arrow function provides a compact syntax for writing function expressions using the => (arrow) operator. Introduced in ES6, arrow functions make code cleaner and more readable.
Syntax
const functionName = (parameters) => {
// code
};
Normal Function Example
function add(a, b) {
return a + b;
}
console.log(add(5, 3));
Arrow Function Example
const add = (a, b) => {
return a + b;
};
console.log(add(5, 3));
Frequently Asked Questions
Why were arrow functions introduced in JavaScript?
- Reduce code length
- Improve readability
- Handle the
thiskeyword more effectively - Simplify callback functions
What are the main features of arrow functions?
- Shorter syntax
- Implicit return (no need for
returnin single‑expression functions) - No own
thisbinding (lexicalthis) - Cannot be used as constructors
- No
argumentsobject
What is implicit return in arrow functions?
Implicit return means returning a value without using the return keyword. It works when the function has only one expression.
const add = (a, b) => a + b;
How does this behave in arrow functions?
Arrow functions do not have their own this. They inherit this from the surrounding (parent) scope, a behavior known as lexical scoping of this.