JavaScript Function Statements
Functions in JavaScript are essential elements that act as the foundation for your projects. They enable the aggregation of related statements, loops, variable declarations, and other code into a reusable unit. The main goals of building your own functions are to isolate code, simplify larger systems, reduce code repetition (by following the “don’t repeat yourself” or DRY principle), and link names to particular subprograms.
“Defining a function” or “function declaration” refers to the act of constructing a function. In essence, defining a function is creating the blueprint for a block of code that will eventually be run. It just makes this code ready for usage; it doesn’t run right away when you define it.
You use the function keyword to define a function. Following this keyword are the function’s name, a string of parentheses (), and a block of code encapsulated in curly brackets. The function body is the code enclosed in curly brackets.
Here is the basic template syntax for writing a function:
function nameOfTheFunction() {
// This is the function body – the code that runs when the function is called
}
Any valid variable name can be used for a function, and it’s generally accepted that it’s best to choose names that convey the function’s intent. The code is more self-descriptive when function names are verbs or begin with prefixes like create…, show…, get…, or check…
Invoking/calling functions
The body of a JavaScript function is executed when called. Parentheses () at the end of functions’ names identify them. These brackets surround the function name in an invocation expression to invoke it.
Arguments are values passed inside brackets when calling a function. The function’s arguments affect its performance. Function calls are expressions that return values. Functions can be called as independent functions, object methods, built-in methods like call() or apply(), or browser event handlers. Using and invoking functions reduces code repetition.
For instance, here’s how you might write a simple function that displays a greeting:
function sayHello() {
let you = prompt(“What’s your name? “); // Get user input
console.log(“Hello”, you + “!”); // Display a greeting
}
The code inside your script won’t execute unless you invoke or call it, but defining this sayHello function makes it available.
Passing Parameters to Functions
Functions frequently require input values to increase their versatility. The variables defined inside the brackets () during the function definition are called parameters, and they are used to handle these inputs. In the body of the function, parameters function as local variables.
At least one parameter can be used to define a function. The brackets remain unfilled in the absence of any parameters. Commas are used to separate parameters if there are several.
Here is an example of a function defined with two parameters, x and y:
function addTwoNumbers(x, y) { // x and y are parameters
console.log(x + y);
}
The real values, referred to as arguments, are supplied inside parenthesis when you call a function that requires parameters. Your supplied arguments are provided into the function, replacing the respective parameters, and can then be utilised within the body of the function.
Calling addTwoNumbers with arguments looks like this:
addTwoNumbers(5, 10); // Here, 5 and 10 are arguments
addTwoNumbers(12, -90); // Using different arguments
Functions are flexible because, as you can see, their results can vary based on the arguments they receive.
Returning values from Functions
It is also possible for functions to generate an output value that is returned to the code that invoked them. To do this, use the return keyword. The function call expression’s evaluation value is specified by the return statement, which also instantly ends the function’s execution.
function add(x, y) {
return x + y; // This function returns the sum of x and y
}
A function’s return value can be recorded and utilised in the caller code, for instance, by allocating it to a variable:
let result = add(3, 4); // The value 7 is returned by add(3, 4)
console.log(result);
// Outputs: 7
A function without a return statement or value returns undefined.
Functions can help you write well structured, reusable, and low maintenance applications, but they need a new approach to code organisation. Learning to define and use functions requires practice. Your code becomes more modular and intelligible when you create your own functions and language of program activities.