Dev.to WebDev πŸ›  Dev πŸ‘ 1 πŸ“– 1 min read

Functions in JavaScript

Functions are one of the most fundamental building blocks in JavaScript. They let you package up a piece of logic, give it a name, and reuse it wherever you need it. If you're learning JavaScript, getting comfortable wit

Functions are one of the most fundamental building blocks in JavaScript. They let you package up a piece of logic, give it a name, and reuse it wherever you need it. If you're learning JavaScript, getting comfortable with functions early will save you a lot of headaches later on.

What Is a Function?

At its core, a function is a reusable block of code designed to perform a specific task. Instead of writing the same logic over and over, you write it once inside a function and simply "call" that function whenever you need it.

function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Ragul")); // Hello, Ragul!

Here, greet takes an input (called a parameter), does something with it, and returns an output.

Ways to Write Functions

JavaScript gives you several ways to define a function, and each has its own use cases.

1. Function Declarations

This is the classic style, and it's "hoisted" β€” meaning you can call it before it appears in your code.

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

2. Function Expressions

Here, a function is assigned to a variable. Unlike declarations, these are not hoisted in the same way, so they must be defined before use.

const multiply = function (a, b) {
  return a * b;
};

3. Arrow Functions

Introduced in ES6, arrow functions offer a shorter syntax and behave differently with this (more on that below).

const subtract = (a, b) => a - b;

For a single expression, you can even skip the curly braces and the return keyword β€” the result is returned automatically.

Parameters and Default Values

Functions can take any number of parameters, and you can assign them default values in case no argument is passed.

function greet(name = "friend") {
  return `Hey there, ${name}!`;
}

console.log(greet()); // Hey there, friend!

You can also accept an unlimited number of arguments using the rest parameter:

function sumAll(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sumAll(1, 2, 3, 4)); // 10
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.