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
Top comments (4)
Function expression and assigning a function to a variable are two different things. You haven't explained what function expression is.
You're right, thank you for clarifying Function Expression
No, they are the same. Here, a function expression is assigned to a variable not a function. If we use the variable to store a function, that function was said to be function expression.
Function expression occurs when the
functionkeyword is used in an expression context (i.e. when using it at a point the code where a statement would be invalid). Using it in this manner creates a function 'in place' without storing it (kind of a function literal). THIS is function expression.Functions created in this manner are often stored in variables (as in your example) - but the action of storing it in a variable has no bearing on the fact that function expression was used, it is unrelated.
developer.mozilla.org/en-US/docs/W...