How to Use JavaScript Arrow Functions with No Parameters
In this task, we will learn about JavaScript arrow functions with no parameters in a simple and easy way. Arrow functions were introduced in ES6 to make JavaScript code shorter, cleaner, and more readable.
These functions are commonly used when :
- No input values are required
- The function performs a small task
Standard Function vs Arrow Function
Traditional Function
To a traditional function, we also call a standard function. Before the introduction of ES6, JavaSccript function were written using the function keyword. This is the classic and most basic way to define a function in JavaScript.
Syntax :
function functionName() {
//function body
}The above is the syntax of the standard function.
Example :
function sayhello() {
console.log("Hello, sir!");
}In this example, the function keyword is used to create the function. The function name is sayhello, and the code inside {} runs when the function is called using sayhello().
Output :
Hello, sir!
Arrow Function with No Parameters
Arrow functions were introduced in ES6 to provide a shorter and more modern way to write functions in JavaScript. When an arrow function does not take any parameters, it follows a specific syntax that must be written correctly.
Syntax :
const functionName = () => {
// function body
};The above is the syntax of the Arrow function with no Parameters.
Example :
const sayhelloArrow = () => {
console.log("Hello, Sir!");
};In this example, const is used to store the function in a variable. The function name is sayhelloArrow. The empty parentheses () show that the function takes no parameters, and the => symbol is used instead of the function keyword. The code inside {} runs when the function is called.
The function is called using :
sayhelloArrow();
OutPut :
Hello, Sir!
When an arrow function does not accept any arguments, empty parentheses () are mandatory.
() => {
// function body
}This rule is important because, unlike a one-parameter arrow function, a zero-parameter arrow function always requires ().
Example 1: Basic console Logging
This example demonstrates a simple arrow function that prints a message to the console.
const showMessage = () => {
console.log("Welcome to JavaScript Arrow Functions!");
};
showMessage();OutPut :
Welcome to JavaScript Arrow Functions!
This type of function is useful when we want to display a message or run a small block of code without taking any input.
Example 2: Implicit Return (One-Liner Function)
If an arrow function contains only one statement and that statement returns a value, then you can remove the curly braces {} and the return keyword.
const getGreetingShort = () => "Hello, sir!"; console.log(getGreetingShort());
OutPut :
Hello, sir!
This one-line syntax makes the code shorter and is widely used in modern JavaScript
Leave a Reply