In this blog, we are going to speak about the functions.
What are functions
Simply put, a function is a piece of code that you can reuse repeatedly rather than having to write it out several times. Programmers can divide a problem into smaller, more manageable parts, each of which can carry out a specific task, using functions.
How to declare a function in JS
The function keyword is used to define a JavaScript function, which is then followed by the function's name and parentheses ().
Function names may also include underscores, dollar signs, and other characters (same rules as variables).
Names of parameters may be enclosed in parentheses and separated by commas: (parameter1, parameter2, ...)
Curly brackets enclose the code that the function will execute: {}
For example:
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
For example:
function sum(x, y){
console.log(sum);
}
However, when we write this function it doesn't print anything in the console. To make our function work we should first call our function. To do this, we need to write the function's name, add the symbol (), and, if the function asks for it, write the values we want to pass it inside ().
For example:
function sum(x, y){
console.log(sum);
}
sum(4,5)//this will print 4+5 which is equal to 9
Return statement
The return statement ends the function execution and specifies a value to be returned to the function caller.
For example, the following function returns the square of its argument, x, where x is a number.
function square(x) {
return x * x;
}
const demo = square(3);
// demo will equal 9
Top comments (0)