Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output. To use a function, you must define it somewhere in the scope from which you wish to call it. Show See also the exhaustive reference chapter about JavaScript functions to get to know the details. A function definition (also called a function declaration, or function statement) consists of the 9 keyword, followed by:
For example, the following code defines a simple function named 1:
The function 1 takes one parameter, called 3. The function consists of one statement that says to return the parameter of the function (that is, 3) multiplied by itself. The statement 5 specifies the value returned by the function:
Parameters are essentially passed to functions by value — so if the code within the body of a function assigns a completely new value to a parameter that was passed to the function, the change is not reflected globally or in the code which called that function. When you pass an object as a parameter, if the function changes the object's properties, that change is visible outside the function, as shown in the following example:
When you pass an array as a parameter, if the function changes any of the array's values, that change is visible outside the function, as shown in the following example:
While the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a function can be anonymous; it does not have to have a name. For example, the function 1 could have been defined as:
However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces:
Function expressions are convenient when passing a function as an argument to another function. The following example shows a 7 function that should receive a function as first argument and an array as second argument:
In the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument:
Function returns: 8.In JavaScript, a function can be defined based on a condition. For example, the following function definition defines 9 only if 0 equals 1:
In addition to defining functions as described here, you can also use the 2 constructor to create functions from a string at runtime, much like 3.A method is a function that is a property of an object. Read more about objects and methods in Working with objects. Defining a function does not execute it. Defining it names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function 1, you could call it as follows:
The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 6.Functions must be in scope when they are called, but the function declaration can be (appear below the call in the code). The scope of a function declaration is the function in which it is declared (or the entire program, if it is declared at the top level). The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The 7 function (defined in ) is an example of a function that takes an object as an argument.A function can call itself. For example, here is a function that computes factorials recursively: 0You could then compute the factorials of 8 through 5 as follows: 1There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are themselves objects — and in turn, these objects have methods. (See the 2 object.) The 1 and 2 methods can be used to achieve this goal.Consider the example below: 2This code runs without any error, despite the 3 function being called before it's declared. This is because the JavaScript interpreter hoists the entire function declaration to the top of the current scope, so the code above is equivalent to: 3Function hoisting only works with function declarations — not with function expressions. The code below will not work. 4Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function, and any other variables to which the parent function has access. 5A function can refer to and call itself. There are three ways for a function to refer to itself:
For example, consider the following function definition: 6Within the function body, the following are all equivalent:
A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, consider the following loop: 7It can be converted into a recursive function declaration, followed by a call to that function: 8However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (such as the DOM) is easier via recursion: 9Compared to the function 8, each recursive call itself makes many recursive calls here.It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the following example: 0You may nest a function within another function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (most commonly, a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function. To summarize:
The following example shows nested functions: 1Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function: 2Notice how 9 is preserved when 0 is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to 1. The memory can be freed only when the returned 0 is no longer accessible.This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them. Functions can be multiply-nested. For example:
Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (The reason it is called "chaining" is explained later.) Consider the following example: 3In this example, 5 accesses 4's 9 and 3's 9.This can be done because:
The reverse, however, is not true. 3 cannot access 5, because 3 cannot access any argument or variable of 4, which 5 is a variable of. Thus, 5 remains private to only 4.When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More nested scopes take precedence. So, the innermost scope takes the highest precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the chain is the innermost scope, and the last is the outermost scope. Consider the following: 4The name conflict happens at the statement 17 and is between 0's parameter 9 and 1's variable 9. The scope chain here is { 0, 1, global object}. Therefore, 0's 9 takes precedences over 1's 9, and 28 ( 0's 9) is returned instead of 31 ( 1's 9).Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function. 5It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned. 6In the code above, the 34 variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name. 7Note: There are a number of pitfalls to watch out for when using closures! If an enclosed function defines a variable with the same name as a variable in the outer scope, then there is no way to refer to the variable in the outer scope again. (The inner scope variable "overrides" the outer one, until the program exits the inner scope. It can be thought of as a .) 8The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows: 9where 35 is the ordinal number of the argument, starting at 1. So, the first argument passed to a function would be 37. The total number of arguments is indicated by 38.Using the 39 object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use 38 to determine the number of arguments actually passed to the function, and then access each argument using the 39 object.For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows: 0You can pass any number of arguments to this function, and it concatenates each argument into a string "list": 1Note: The 39 variable is "array-like", but not an array. It is array-like in that it has a numbered index and a 43 property. However, it does not possess all of the array-manipulation methods.See the 2 object in the JavaScript reference for more information.There are two special kinds of parameter syntax: default parameters and rest parameters. In JavaScript, parameters of functions default to 45. However, in some situations it might be useful to set a different default value. This is exactly what default parameters do.In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are 45.In the following example, if no value is provided for 47, its value would be 45 when evaluating 49, and a call to 50 would normally have returned 51. However, this is prevented by the second line in this example: 2With default parameters, a manual check in the function body is no longer necessary. You can put 8 as the default value for 47 in the function head: 3For more details, see default parameters in the reference. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the following example, the function 50 uses rest parameters to collect arguments from the second one to the end. The function then multiplies these by the first argument. 4An arrow function expression (also called a fat arrow to distinguish from a hypothetical 55 syntax in future JavaScript) has a shorter syntax compared to function expressions and does not have its own 56, 39, 58, or 59. Arrow functions are always anonymous.Two factors influenced the introduction of arrow functions: shorter functions and non-binding of 56.In some functional patterns, shorter functions are welcome. Compare: 5Until arrow functions, every new function defined its own 56 value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming. 6In ECMAScript 3/5, this issue was fixed by assigning the value in 56 to a variable that could be closed over. 7Alternatively, a bound function could be created so that the proper 56 value would be passed to the 64 function.An arrow function does not have its own 56; the 56 value of the enclosing execution context is used. Thus, in the following code, the 56 within the function that is passed to 68 has the same value as 56 in the enclosing function: 8JavaScript has several top-level, built-in functions: 3The 3 method evaluates JavaScript code represented as a string. 72The global 72 function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number. 74The 74 function determines whether a value is 51 or not. Note: coercion inside the 77 function has rules; you may alternatively want to use 78 to determine if the value is Not-A-Number. 79The 79 function parses a string argument and returns a floating point number. 81The 81 function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). 83The 83 function decodes a Uniform Resource Identifier (URI) previously created by 85 or by a similar routine. 86The 86 method decodes a Uniform Resource Identifier (URI) component previously created by 88 or by a similar routine. 89The 89 method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). 91The 91 method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters). 93The deprecated 93 method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use 85 or 88 instead. 97The deprecated 97 method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like 99. Because 97 is deprecated, use 83 or 02 instead.
Apa itu function JavaScript?Fungsi Javascript kira-kira meliputi pembuatan aplikasi mobile, desktop, web, game, sampai membuat slide presentasi. Meskipun fungsi Javascript cukup banyak, biasanya bahasa pemrograman ini digunakan untuk aplikasi web. Hal ini karena website bisa terlihat lebih menarik dengan Javascript.
Apa fungsi this pada JavaScript?this digunakan di dalam sebuah fungsi dan mengandung nilai dari objek yang memanggil fungsi tersebut. Kita perlu menggunakan this untuk mengakses metode dan properti dari objek yang memanggil fungsi tersebut, terlebih lagi jika kita tidak selalu tahu nama yang digunakan oleh objek tersebut.
Apa itu parameter di JavaScript?Parameter adalah data-data yang sifatnya tidak tetap (bisa berubah-ubah) yang dimasukkan dan diolah dalam sebuah fungsi Javascript.
Aturan apa saja dalam pembuatan function?Aturan-aturan dalam pembuatan function adalah : 1. Aturan penamaan function mirip dengan penamaan variable. Terdiri dari huruf, angka dan underscore ( _ ). Nama function hanya boleh dimulai dengan huruf atau dengan underscore. 2. Parameter sifatnya tambahan.
|