Introduction to JavaScript Functions
20 January, 2023
15
15
0
Contributors
Introduction to JavaScript functions
In JavaScript, a function is a block of code that performs a specific task. It can take zero or more input parameters, return a value, or perform some action. Functions can be defined and invoked (called) multiple times in a script. They help organize and reuse code.
Here is an example of a simple JavaScript function that takes two input parameters and returns their sum:
function add(a, b) {
return a + b;
}
To call this function, you would use the following syntax:
let result = add(1, 2); // result will be 3
Functions can also be defined using the function expression syntax, which is often used when defining anonymous functions:
let add = function(a, b) {
return a + b;
}
In this case, the function is assigned to the add
variable and can be called using the same syntax as before:
let result = add(1, 2); // result will be 3
Function Hoisting
In JavaScript, hoisting
refers to how declarations are treated in the code. When a variable or function is declared, it is automatically moved (or "hoisted") to the top of its scope. However, only the declaration is hoisted, not the assignment or initialization of the variable.
For example, consider the following code:
console.log(num); // Output: undefined
var num;
num = 10;
Even though the variable num
is declared and initialized at the bottom of the code, it is still accessible at the top because of hoisting. When the code is executed, the declaration of num
is automatically moved to the top, so the output is undefined
rather than a reference error.
Function declarations are also hoisted in JavaScript. This means you can call a function before it is defined in the code. For example:
add(2, 3); // Output: 5
function add(a, b) {
return a + b;
}
In this case, the function declaration for add
is hoisted to the top of the code, so it is available for use before it is defined.
It's important to note that function expressions
are not hoisted similarly. If you try to call a function that is defined using a function expression before it is defined, you will get a reference error. For example:
add(2, 3); // Uncaught ReferenceError: add is not defined
let add = function(a, b) {
return a + b;
};
In this case, the function expression is assigned to the add
variable, but the variable is not hoisted to the top like a function declaration. Therefore, you cannot call the add
function before it is defined.
Function Parameters
In JavaScript, function parameters are the values that are passed to a function when it is called. These values are used inside the function to perform some action or to calculate a result.
Function parameters are specified in the function definition as a list of names separated by commas. For example:
function greet(name) {
console.log('Hello, ' + name);
}
In this example, the greet
function has one parameter called name
. When the function is called, the value of the name
parameter is used inside the function to greet the user.
Here is an example of calling the greet
function with a parameter:
greet('John'); // Output: "Hello, John"
A function can have any number of parameters or none at all. For example:
function add(a, b) {
return a + b;
}
let result = add(1, 2); // result will be 3
In this case, the add
function has two parameters, a
and b
, and they are used to calculate the sum of their values.
When a function is called with fewer arguments than the number of parameters, the missing arguments are assigned the value undefined
. For example:
function greet(name, greeting) {
console.log(greeting + ', ' + name);
}
greet('John'); // Output: "undefined, John"
It is also possible to specify default values for function parameters if they are not provided when the function is called. For example:
function greet(name, greeting = 'Hello') {
console.log(greeting + ', ' + name);
}
greet('John'); // Output: "Hello, John"
In this case, the greeting
parameter has a default value of 'Hello'
, so if it is not provided when the function is called, that default value will be used.
Function Arguments
In JavaScript, the arguments
object is an array-like
object that contains the values of the arguments passed to a function. It is available inside the body of every function and provides a way to access the arguments passed to the function from within the function.
The arguments
object has the following properties:
arguments.length
: The number of arguments passed to the function.arguments[i]
: The value of the i-th argument passed to the function, wherei
is the index of the argument.
Here is an example of using the arguments
object to access the arguments passed to a function:
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
let result = sum(1, 2, 3, 4, 5); // result will be 15
In this example, the sum
function takes an arbitrary number of arguments and calculates their sum. The arguments
object is used to loop over the arguments and add them up.
It's important to note that the arguments
object is not an array but behaves like one in many ways. It does not have all of the methods of a true array, such as map
or forEach
. However, it can be converted to a true array using the Array.from
function or the spread operator (...
).
For example:
let args = Array.from(arguments);
let args = [...arguments];
These techniques will create a true array from the arguments
object, which can then be used with all array methods.
Nested Functions
In JavaScript, a function can be defined inside another function, creating a nested function. A nested function has access to the variables and parameters of the outer function and can be used as a closure.
Here is an example of a nested function in JavaScript:
function outer(x) {
function inner(y) {
return x + y;
}
return inner;
}
let add5 = outer(5);
console.log(add5(3)); // Output: 8
In this example, the outer
function defines a nested function called inner
, which takes a single parameter y
and returns the sum of x
and y
. The outer
function then returns the inner
function.
The add5
variable is assigned the result of calling outer
with argument 5
. This means that add5
references the inner
function, with x
set to 5
. When add5
is called with argument 3
, it returns the sum of 5
and 3
, which is 8
.
Nested functions can be useful for organizing code and creating reusable functions. They can also be used to create private variables and methods that are not accessible from outside the outer function.
It's important to note that the variables and parameters of the outer function are closed over by the inner function, meaning they are kept in scope even after the outer function has returned. This allows the inner function to access and use them even after the outer function has finished executing.