DEV Community

Megalraja
Megalraja

Posted on

JavaScript Functions Explained: The Basics I Finally Understood

While learning JavaScript, I recently started understanding functions.

A function is a reusable block of code that performs a specific task.

Basic Function

function greet() {
    console.log("Hello John!");
}

greet();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello John!
Enter fullscreen mode Exit fullscreen mode

We can also pass values using parameters:

function greet(name) {
    console.log("Hello " + name);
}

greet("John");
Enter fullscreen mode Exit fullscreen mode

Here, name is the parameter, and "John" is the argument.

Returning a Value

Functions can return a value using return:

function add(a, b) {
    return a + b;
}

let result = add(10, 20);

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Arrow Function

JavaScript also provides a shorter syntax:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

The main thing I learned:

Functions help us write reusable, organized, and less repetitive code.

I'm continuing my JavaScript fundamentals step by step.

Top comments (0)