JavaScript Fundamentals: Functions
What is a function?
Functions are a fundamental part of JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
How to define a function in JavaScript
A function is a set of instructions that can be used over and over again. Functions are written in a specific format:
function name(parameters) {
// code to be executed
}
The function
keyword is used to create a function. Functions are often written with a name so that they can be reused. The name is followed by parentheses, which can contain parameters. These are values that are passed into the function so that the function can use them.
The code to be executed by the function is written inside of curly braces
. Functions can be called by using their name followed by parentheses. The parentheses can contain arguments, which are values that are passed to the function.{}
For example:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
sayHello("John"); // prints "Hello, John!"
sayHello("Mary"); // prints "Hello, Mary!"
Using parameters in JavaScript functions
Functions are defined with the function keyword and can optionally take parameters. Function parameters are named variables that are passed into the function when it is invoked. The function can access and use the parameter values.
For example:
function myFunction(x) {
console.log(x);
}
myFunction("Hello world!");
Using functions as variables in JavaScript
JavaScript functions can be defined and then invoked.
Function parameters are variables that are available to the function when it is invoked.
Functions can return values to the caller using the return keyword. In JavaScript, functions are first-class objects, which means that they can be stored in variables, passed as arguments to other functions, and returned from functions.
For example:
var square = function(x) {
return x * x;
};
console.log(square(5)); // 25
Nesting functions within other functions in JavaScript
In JavaScript, functions can be nested within other functions. This is often done to create private functions that are only accessible from within the outer function. For example:
function outerFunction() {
function innerFunction() {
// code here is only accessible from within outerFunction
}
}
In this example, the innerFunction
is only accessible from within outerFunction
. This can be useful for creating helper functions that are only intended to be used by the outer function.
Nested functions have access to the parent function's scope. This means that they can access variables and functions declared in the parent function. This can be useful for organizing code and keeping related code together.
Global and local scopes
JavaScript has two types of scope: global and local. Global scope is the default scope. Variables declared outside of any function are global and can be accessed from anywhere in your code. Local scope is created when you declare a variable inside of a function. Variables declared inside of a function can only be accessed from within that function.
Here is an example of global and local scope in action:
/ This is a global variable
var globalVariable = "I can be accessed anywhere!";
function myFunction() {
// This is a local variable
var localVariable = "I can only be accessed inside this function";
}
console.log(globalVariable); // "I can be accessed anywhere!"
console.log(localVariable); // ReferenceError: localVariable is not defined
Functions as a global scope
One advantage of this is that you can use functions to modularize your code. For example, if you have a lot of code that uses a certain set of functions, you can put all of those functions in one file and include that file in your code. This way, you can keep your code organized and easy to read.
Another advantage of this is that you can reuse functions across your code. If you have a function that you use in multiple places, you can just write it once and then call it from wherever you need it. This saves you time and makes your code more efficient.
There are some disadvantages to this as well. One is that it can be difficult to debug your code if you have multiple files that include functions. Another is that it can be easy to accidentally overwrite a function that you didn't mean to.
Local scope function in JavaScript
FA function defined within another function has a local scope. This means that it can only be accessed from within the outer function. It cannot be accessed from outside the outer function.
Here is an example:
function outerFunction() {
function innerFunction() {
// code here can only be accessed from within the outerFunction
}
}
Anonymous functions in JavaScript
Functions can be anonymous. This means they don't have a name. Anonymous functions are often used as arguments to other functions.
For example, the sort()
method in JavaScript accepts a function as an argument. The function is used to compare two values. The following code sorts an array of numbers in ascending order:
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
Another example of using an anonymous function is the setTimeout()
method.
The following code prints "Hello!" after 1000 milliseconds (1 second):
setTimeout(function() {
console.log("Hello!");
}, 1000);
Immediately invoked functions
An immediately invoked function is a function that is executed as soon as it is declared.
This type of function is often used to create closures. A closure is a function that has access to the variables in the outer scope, even after the outer function has returned.
Here is an example of an immediately invoked function:
(function() {
var message = "Hello!";
console.log(message);
})();
// Output:
// "Hello!"
In the example above, the function is declared and then immediately invoked. The function will print "Hello!" to the console.
This pattern is often used when we want to create a new scope. By creating a new function, we can avoid polluting the global scope with our variables.
Functions used as values
A function is a JavaScript object that represents a piece of code. Functions can be used as values. This means that they can be assigned to variables and passed as arguments to other functions. For example, the following code assigns the function sayHello
to the variable myFunc
:
function sayHello() {
console.log("Hello!");
}
var myFunc = sayHello;
myFunc(); // prints "Hello!"
The code above defines a function ayHello
and assigns it to the variable myFunc
. The function can then be invoked by calling myFunc()
.
Functions can also be passed as arguments to other functions. For example, the following code defines a function called doSomething
that takes a function as an argument and invokes it:
function doSomething(func) {
func();
}
doSomething(sayHello); // prints "Hello!"
In the code above, the function sayHello
is passed as an argument to the function doSomething
. When doSomething
is invoked, it calls the function that was passed to it (sayHello)
which prints "Hello!"
.