Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs.
function sum(a, b) {
return a + b;
}
console.log(sum(6, 9)); // output: 15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or function statement. Below are the rules for creating a function in JavaScript:
- Begin with the keyword function Keyword
- A user-defined function name (In the above example, the name is sum)
- A list of parameters enclosed within parentheses and separated by commas (In the above example, parameters are x and y)
- A list of statements composing the body of the function enclosed within curly braces {} (In the above example, the statement is "return x + y").
Return Statement
A function can return a result using the return keyword. This is optional but useful when you want to send data back from the function.
Function Parameters
Parameters are input passed to a function. In the above example, sum(x , y) takes two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the function. We can call a function by using the function name separated by the value of parameters enclosed between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome");
}
let nameVal = "user";
// calling the function
console.log(welcomeMsg(nameVal));
output
Hello User welcome
Function Expression
It is similar to a function declaration without the function name. Function expressions can be stored in a variable assignment.
const mul = function (x, y) {
return x * y;
};
console.log(mul(4, 5));
Output
20
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do not bind their own this context.
const sum = (num1,num2) => {
return num1 + num2;
}
let result = sum(5,5)
console.log(result);
output
10
Top comments (0)