diff options
Diffstat (limited to 'files/tr/web/javascript/guide/functions/index.html')
-rw-r--r-- | files/tr/web/javascript/guide/functions/index.html | 663 |
1 files changed, 663 insertions, 0 deletions
diff --git a/files/tr/web/javascript/guide/functions/index.html b/files/tr/web/javascript/guide/functions/index.html new file mode 100644 index 0000000000..ff7638ebb5 --- /dev/null +++ b/files/tr/web/javascript/guide/functions/index.html @@ -0,0 +1,663 @@ +--- +title: Fonksiyonlar +slug: Web/JavaScript/Guide/Functions +tags: + - Başlangıç seviyesi + - Fonksiyonlar + - Rehber +translation_of: Web/JavaScript/Guide/Functions +original_slug: Web/JavaScript/Guide/Fonksiyonlar +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</div> + +<p class="summary">Foksiyonlar, JavaScript'in en temel yapıtaşlarından biridir. Her bir fonksiyon, bir JavaScript işlemidir—herhangi bir görevi yerine getiren veya değer hesaplayan bir ifade kümesini içerirler. Bir fonksiyonu kullanmak için, fonksiyonu çağıracağınız kısmın faaliyet gösterdiği alanda fonksiyonu tanımlıyor olmanız gerekmektedir.</p> + +<p>Daha fazla bilgi için <a href="/en-US/docs/Web/JavaScript/Reference/Functions">JavaScript fonksiyonları ile ilgili buradaki detaylı kaynağı</a> inceleyebilirsiniz.</p> + +<h2 id="Fonksiyonların_tanımlanması">Fonksiyonların tanımlanması</h2> + +<h3 id="Fonksiyon_tanımlamaları">Fonksiyon tanımlamaları</h3> + +<p>Bir <strong>fonksiyon tanımı</strong> (<strong>fonksiyon betimlemesi</strong>, veya <strong>fonksiyon ifadesi</strong> de denir) <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function" title="function"><code>function</code></a> anahtar kelimesinden sonra aşağıdaki kısımları içerir:</p> + +<ul> + <li>Fonksiyonun adı.</li> + <li>Fonksiyonun aldığı parametreler (parantezler ile çevrili ve virgüller ile birbirinden ayrılmış olmalıdırlar).</li> + <li>Çalıştırılacak JavaScript ifadeleri (süslü parantezler ile çevrilmelidir<font face="Consolas, Liberation Mono, Courier, monospace">)</font>.</li> +</ul> + +<p>Örneğin aşağıdaki kodda <code>karesiniAl</code> isimli basit bir fonksiyon tanımlanmıştır:</p> + +<pre class="brush: js">function <code>karesiniAl</code>(sayı) { + return sayı * sayı; +} +</pre> + +<p><code>karesiniAl</code> fonksiyonu, <code>sayı</code> isminde tek bir parametre içerir. Tek bir ifade içeren fonksiyonda, <code>sayı</code> parametresinin kendisi ile çarpılıp geri döndürülmesi işlemi yapılmıştır. <a href="/en-US/docs/Web/JavaScript/Reference/Statements/return" title="return"><code>return</code></a> ifadesi, fonksiyon tarafından döndürülen değeri belirler.</p> + +<pre class="brush: js">return sayı * sayı; +</pre> + +<p>Sayı türünde olduğu gibi ilkel parametreler fonksiyonlara <strong>değer ile geçilirler</strong>; ilgili değer, fonksiyona parametre olarak geçildiğinde parametre değerinin fonksiyonda ayrı bir kopyası alınır, eğer fonksiyon içerisinde parametre değerinde değişik yapılırsa, bu değişiklik sadece kopyalanan değer üzerinde gerçekleşmiştir, fonksiyona geçilen asıl değer değişmez.</p> + +<p>Eğer bir nesneyi ({{jsxref("Array")}} veya bir kullanıcı tanımlı nesne gibi ilkel olmayan değer) fonksiyona parametre olarak geçerseniz, nesne fonksiyon içerisinde kopyalanmadığı için nesne üzerinde yapılan değişiklikler fonksiyon dışında da korunur. Aşağıdaki örneği inceleyelim:</p> + +<pre class="brush: js">function arabamıDeğiştir(araba) { + araba.markası = "Toyota"; +} + +var arabam = {markası: "Honda", modeli: "Accord", yılı: 1998}; +var x, y; + +x = arabam.markası ; // "Honda" değerini getirir + +arabamıDeğiştir(arabam); +y = arabam.markası; // "Toyota" değeri döndürülür + // (markası özelliği fonksiyon tarafından değiştirilmiştir) +</pre> + +<h3 id="Fonksiyon_ifadeleri">Fonksiyon ifadeleri</h3> + +<p>Yukarıdaki fonksiyon tanımlaması sözdizimsel olarak bir ifade olmasına rağmen, fonksiyonlar ayrıca bir f<strong>onksiyon ifadesi </strong>ile de oluşturulabilirler. Böyle bir fonksiyon <strong>anonim</strong> olabilir; bir isme sahip olmak zorunda değildir. Örnek olarak, matematikteki kare alma fonksiyonu aşağıdaki şekilde tanımlanabilir:</p> + +<pre class="brush: js">var karesiniAl = function(sayı) { return sayı * sayı }; +var x = karesiniAl(4) // x'in değeri 16 olur.</pre> + +<p>Fonksiyon ifadesi ile belirtilen fonksiyon adı, fonksiyonun içerisinde kendisini çağıracak şekilde kullanılabilir:</p> + +<pre class="brush: js">var faktoriyel = function fa(n) { return n < 2 ? 1 : n * fa(n-1) }; + +console.log(faktoriyel(3)); +</pre> + +<p>Fonksiyon ifadeleri, bir fonksiyon diğer fonksiyona parametre olarak geçilirken oldukça elverişlidir. Aşağıdaki örnekte <code>map</code> fonksiyonu tanımlanmış ve ilk parametresinde başka bir fonksiyonu parametre olarak almıştır:</p> + +<pre class="brush: js">function map(f,d) { + var sonuç = [], // Yeni bir dizi + i; + for (i = 0; i != d.length; i++) + sonuç[i] = f(d[i]); + return sonuç; +} +</pre> + +<p>Aşağıdaki kodda kullanımı mevcuttur:</p> + +<pre class="brush: js">var çarpım = function(x) {return x * x * x}; // Fonksiyon ifadesi. +map(çarpım, [0, 1, 2, 5, 10]); +</pre> + +<p>[0, 1, 8, 125, 1000] dizisini döndürür.</p> + +<p>JavaScript'te bir fonksiyon, herhangi bir duruma bağlı olarak oluşturulabilir.Örneğin aşağıdaki fonksiyonda <code>benimFonk</code> fonksiyonu, <code>sayı</code> değeri sadece 0'a eşit olursa tanımlanır:</p> + +<pre class="brush: js">var <code>benimFonk</code>; +if (sayı === 0){ + <code>benimFonk </code>= function(araba) { + araba.marka = "Toyota" + } +}</pre> + +<p>Burada tanımlanan fonksiyonlara ek olarak {{jsxref("Function")}} yapıcısını kullanarak da çalışma zamanında fonksiyon oluşmasını sağlanabilir. Örneğin {{jsxref("eval", "eval()")}} ifadesi gibi.</p> + +<p>Bir nesnenin özelliği olan fonksiyona <strong>metot</strong> adı verilir. Nesneler ve metotlar hakkında daha fazla bilgi için bkz: <a href="/tr/docs/Web/JavaScript/Guide/Working_with_Objects" title="en-US/docs/JavaScript/Guide/Working with Objects">Nesneler ile çalışma</a>.</p> + +<h2 id="Fonksiyonları_çağırma">Fonksiyonları çağırma</h2> + +<p>Bir fonksiyonu tanımlamakla o fonksiyon çalışmaz. Fonksiyonu tanımlamak kısaca, o fonksiyona bir isim vermek ve o fonkisyon çağırıldığında bizim için hangi eylemleri yapması gerektiğini belirtmektir. Fonksiyonu <strong>çağırmak</strong>, bu belirlenmiş eylemleri bizim o fonksiyona verdiğimiz parametrelerin de kullanılmasıyla gerçekleştirir. Örneğin, <code>karesiniAl </code>diye bir fonksiyon tanımladığınızda, o fonksiyonu aşağıdaki gibi çağırabilirsiniz:</p> + +<pre class="brush: js"><code>karesiniAl</code>(5); +</pre> + +<p>Bu ifade, fonksiyona parametre olarak 5 sayısını yollayarak çağırır. Fonksiyon, tanımlanırken belirttiğimiz eylemleri yapar ve bize 25 değerini döndürür.</p> + +<p>Fonksiyonlar çağrıldıklarında bir alanda olmalıdılar, fakat fonksiyon bildirimi kaldırılabilir, örnekteki gibi:</p> + +<pre class="brush: js">console.log(square(5)); +/* ... */ +function square(n) { return n * n } +</pre> + +<p>Bir fonksiyonun alanı, bildirilen işlevdir, veya tüm program üst seviyede bildirilmişse.</p> + +<div class="note"> +<p><strong>Not:</strong> Bu, yalnızca yukarıdaki sözdizimini (i.e. <code>function benimFonk(){}</code>) işlevini kullanarak işlevi tanımlarken çalışır. Aşağıdaki kod çalışmayacak. Yani, işlev kaldırma sadece işlev bildirimi ile çalışır ve işlev ifadesiyle çalışamaz.</p> +</div> + +<pre class="brush: js example-bad">console.log(square); // square is hoisted with an initial value undefined. +console.log(square(5)); // TypeError: square is not a function +var square = function (n) { + return n * n; +} +</pre> + +<p>Bir fonksiyonun argümanları karakter dizileri ve sayılarla sınırlı değildir. Tüm nesneleri bir fonksiyona aktarabilirsiniz. <code>show_props()</code> fonksiyonu (<a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_Properties" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties">Working with objects</a> bölümünde tanımlanmıştır.) nesneyi argüman olarak alan bir fonksiyon örneğidir.</p> + +<p>Bir fonksiyon kendini çağırabilir. Örneğin, burada faktöriyelleri yinelemeli olarak hesaplayan bir fonksiyon var.</p> + +<pre class="brush: js">function factorial(n){ + if ((n === 0) || (n === 1)) + return 1; + else + return (n * factorial(n - 1)); +} +</pre> + +<p>Daha sonra bir ile beş arasındaki faktöriyelleri şu şekilde hesaplayabilirsiniz:</p> + +<pre class="brush: js">var a, b, c, d, e; +a = factorial(1); // a gets the value 1 +b = factorial(2); // b gets the value 2 +c = factorial(3); // c gets the value 6 +d = factorial(4); // d gets the value 24 +e = factorial(5); // e gets the value 120 +</pre> + +<p>Fonksiyonları çağırmanın başka yolları da var. Bir fonksiyonun dinamik olarak çağrılması gerektiği veya bir fonksiyonun argümanlarının sayısının değişebileceği veya fonksiyon çağrısının içeriğinin çalışma zamanında belirlenen belirli bir nesneye ayarlanması gerektiği durumlar vardır. Fonksiyonların kendileri nesneler olduğu ve bu nesnelerin sırasıyla yöntemleri olduğu anlaşılıyor (bkz. {{Jsxref ("Function")}} nesnesi). Bunlardan biri, {{jsxref ("Function.apply", "application ()")}} yöntemi, bu amaca ulaşmak için kullanılabilir.</p> + +<h2 class="deki-transform" id="Fonksiyon_Kapsamı">Fonksiyon Kapsamı</h2> + +<p class="tw-data-text tw-ta tw-text-small" dir="ltr" id="tw-target-text" style="text-align: left; height: 408px;"><span lang="tr">Bir fonksiyon içinde tanımlanmış değişkenlere, fonksiyonun dışındaki herhangi bir yerden erişilemez, çünkü değişken sadece fonksiyon kapsamında tanımlanır. Bununla birlikte, bir fonksiyon tanımlandığı kapsamda tanımlanan tüm değişkenlere ve fonksiyonlara erişebilir. Başka bir deyişle, global kapsamda tanımlanan bir fonksiyon, global kapsamda tanımlanan tüm değişkenlere erişebilir. Başka bir fonksiyonun içinde tanımlanmış bir fonksiyon, ana fonksiyonunda tanımlanan tüm değişkenlere ve ana fonksiyonun erişebildiği herhangi bir değişkene de erişebilir.</span></p> + +<pre class="brush: js">// The following variables are defined in the global scope +var num1 = 20, + num2 = 3, + name = "Chamahk"; + +// This function is defined in the global scope +function multiply() { + return num1 * num2; +} + +multiply(); // Returns 60 + +// A nested function example +function getScore () { + var num1 = 2, + num2 = 3; + + function add() { + return name + " scored " + (num1 + num2); + } + + return add(); +} + +getScore(); // Returns "Chamahk scored 5"</pre> + +<h2 id="Kapsam_ve_fonksiyon_yığını">Kapsam ve fonksiyon yığını</h2> + +<h3 id="Yineleme">Yineleme</h3> + +<p class="tw-data-text tw-ta tw-text-small" id="tw-target-text" style="text-align: left; height: 96px;"><span lang="tr">Bir fonksiyon kendisine başvurabilir ve kendisini arayabilir. Bir işlevin kendisine başvurması için üç yol vardır:</span></p> + +<p> </p> + +<ol> + <li>fonksiyonun adı</li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee">arguments.callee</a></code></li> + <li> + <p class="tw-data-text tw-ta tw-text-medium" dir="ltr" id="tw-target-text" style="text-align: left; height: 72px;"><span lang="tr">fonksiyona başvuran bir kapsam içi değişken</span> </p> + </li> +</ol> + +<div class="oSioSc"> +<div id="tw-target"> +<div class="gsrt tw-ta-container tw-nfl" id="tw-target-text-container"> +<p class="tw-data-text tw-ta tw-text-small" dir="ltr" id="tw-target-text" style="text-align: left; height: 48px;"><span lang="tr">Örneğin, aşağıdaki işlev tanımını göz önünde bulundurun:</span></p> +</div> +</div> +</div> + +<p> </p> + +<pre class="brush: js">var foo = function bar() { + // statements go here +}; +</pre> + +<p>Fonksiyon gövdesinde aşağıdakilerden hepsi eşdeğerdir.</p> + +<ol> + <li><code>bar()</code></li> + <li><code>arguments.callee()</code></li> + <li><code>foo()</code></li> +</ol> + +<p class="tw-data-text tw-ta tw-text-small" dir="ltr" id="tw-target-text" style="text-align: left; height: 216px;"><span lang="tr">Kendisini çağıran fonksiyona özyinelemeli fonksiyon denir. Bazı açılardan, özyineleme bir döngüye benzer. Her ikisi de aynı kodu birkaç kez uygular ve her ikisi de bir koşul gerektirir (bu, sonsuz bir döngüden kaçınmak veya daha doğrusu bu durumda sonsuz özyinelemeden kaçınmak için). Örneğin, aşağıdaki döngü:</span></p> + +<pre class="brush: js">var x = 0; +while (x < 10) { // "x < 10" is the loop condition + // do stuff + x++; +} +</pre> + +<p><span lang="tr">özyinelemeli bir fonksiyona ve bu fonksiyonun çağrısına dönüştürülebilir:</span></p> + +<pre class="brush: js">function loop(x) { + if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)") + return; + // do stuff + loop(x + 1); // the recursive call +} +loop(0); +</pre> + +<p><span lang="tr">Ancak, bazı algoritmalar basit yinelemeli döngüler olamaz. Örneğin, bir ağaç yapısının tüm düğümlerinin </span>(örneğin <a href="/en-US/docs/DOM">DOM</a>) <span lang="tr">alınması özyineleme kullanılarak daha kolay yapılır:</span></p> + +<pre class="brush: js">function walkTree(node) { + if (node == null) // + return; + // do something with node + for (var i = 0; i < node.childNodes.length; i++) { + walkTree(node.childNodes[i]); + } +} +</pre> + +<p><span lang="tr">Fonksiyon </span><code>döngüsü</code><span lang="tr"> ile karşılaştırıldığında, her özyinelemeli çağrının kendisi burada birçok özyinelemeli çağrı yapar.</span></p> + +<p><span lang="tr">Herhangi bir özyinelemeli algoritmayı özyinelemeli olmayan bir algoritmaya dönüştürmek mümkündür, ancak çoğu zaman mantık çok daha karmaşıktır ve bunu yapmak bir yığının kullanılmasını gerektirir. Aslında, özyinelemenin kendisi bir yığın kullanır: Fonksiyon yığını.</span></p> + +<p><span lang="tr">Yığın benzeri davranış aşağıdaki örnekte görülebilir:</span></p> + +<pre class="brush: js">function foo(i) { + if (i < 0) + return; + console.log('begin:' + i); + foo(i - 1); + console.log('end:' + i); +} +foo(3); + +// Output: + +// begin:3 +// begin:2 +// begin:1 +// begin:0 +// end:0 +// end:1 +// end:2 +// end:3</pre> + +<h3 id="Nested_functions_and_closures">Nested functions and closures</h3> + +<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a <em>closure</em>. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).</p> + +<p>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.</p> + +<p>To summarize:</p> + +<ul> + <li>The inner function can be accessed only from statements in the outer function.</li> +</ul> + +<ul> + <li>The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.</li> +</ul> + +<p>The following example shows nested functions:</p> + +<pre class="brush: js">function addSquares(a,b) { + function square(x) { + return x * x; + } + return square(a) + square(b); +} +a = addSquares(2,3); // returns 13 +b = addSquares(3,4); // returns 25 +c = addSquares(4,5); // returns 41 +</pre> + +<p>Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:</p> + +<pre class="brush: js">function outside(x) { + function inside(y) { + return x + y; + } + return inside; +} +fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it +result = fn_inside(5); // returns 8 + +result1 = outside(3)(5); // returns 8 +</pre> + +<h3 id="Preservation_of_variables">Preservation of variables</h3> + +<p>Notice how <code>x</code> is preserved when <code>inside</code> 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 outside. The memory can be freed only when the returned <code>inside</code> is no longer accessible.</p> + +<p>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.</p> + +<h3 id="Multiply-nested_functions">Multiply-nested functions</h3> + +<p>Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called <em>scope chaining</em>. (Why it is called "chaining" will be explained later.)</p> + +<p>Consider the following example:</p> + +<pre class="brush: js">function A(x) { + function B(y) { + function C(z) { + console.log(x + y + z); + } + C(3); + } + B(2); +} +A(1); // logs 6 (1 + 2 + 3) +</pre> + +<p>In this example, <code>C</code> accesses <code>B</code>'s <code>y</code> and <code>A</code>'s <code>x</code>. This can be done because:</p> + +<ol> + <li><code>B</code> forms a closure including <code>A</code>, i.e. <code>B</code> can access <code>A</code>'s arguments and variables.</li> + <li><code>C</code> forms a closure including <code>B</code>.</li> + <li>Because <code>B</code>'s closure includes <code>A</code>, <code>C</code>'s closure includes <code>A</code>, <code>C</code> can access both <code>B</code> <em>and</em> <code>A</code>'s arguments and variables. In other words, <code>C</code> <em>chains</em> the scopes of <code>B</code> and <code>A</code> in that order.</li> +</ol> + +<p>The reverse, however, is not true. <code>A</code> cannot access <code>C</code>, because <code>A</code> cannot access any argument or variable of <code>B</code>, which <code>C</code> is a variable of. Thus, <code>C</code> remains private to only <code>B</code>.</p> + +<h3 id="Name_conflicts">Name conflicts</h3> + +<p>When two arguments or variables in the scopes of a closure have the same name, there is a <em>name conflict</em>. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:</p> + +<pre class="brush: js">function outside() { + var x = 10; + function inside(x) { + return x; + } + return inside; +} +result = outside()(20); // returns 20 instead of 10 +</pre> + +<p>The name conflict happens at the statement <code>return x</code> and is between <code>inside</code>'s parameter <code>x</code> and <code>outside</code>'s variable <code>x</code>. The scope chain here is {<code>inside</code>, <code>outside</code>, global object}. Therefore <code>inside</code>'s <code>x</code> takes precedences over <code>outside</code>'s <code>x</code>, and 20 (<code>inside</code>'s <code>x</code>) is returned instead of 10 (<code>outside</code>'s <code>x</code>).</p> + +<h2 id="Closures">Closures</h2> + +<p>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 security 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 outer function itself, 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.</p> + +<pre class="brush: js">var pet = function(name) { // The outer function defines a variable called "name" + var getName = function() { + return name; // The inner function has access to the "name" variable of the outer function + } + return getName; // Return the inner function, thereby exposing it to outer scopes +} +myPet = pet("Vivie"); + +myPet(); // Returns "Vivie" +</pre> + +<p>It 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.</p> + +<pre class="brush: js">var createPet = function(name) { + var sex; + + return { + setName: function(newName) { + name = newName; + }, + + getName: function() { + return name; + }, + + getSex: function() { + return sex; + }, + + setSex: function(newSex) { + if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) { + sex = newSex; + } + } + } +} + +var pet = createPet("Vivie"); +pet.getName(); // Vivie + +pet.setName("Oliver"); +pet.setSex("male"); +pet.getSex(); // male +pet.getName(); // Oliver +</pre> + +<p>In the code above, the <code>name</code> 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", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.</p> + +<pre class="brush: js">var getCode = (function(){ + var secureCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... + + return function () { + return secureCode; + }; +})(); + +getCode(); // Returns the secureCode +</pre> + +<p>There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.</p> + +<pre class="brush: js">var createPet = function(name) { // Outer function defines a variable called "name" + return { + setName: function(name) { // Enclosed function also defines a variable called "name" + name = name; // ??? How do we access the "name" defined by the outer function ??? + } + } +} +</pre> + +<p>The magical <code>this</code> variable is very tricky in closures. They have to be used carefully, as what <code>this</code> refers to depends completely on where the function was called, rather than where it was defined.</p> + +<h2 id="Using_the_arguments_object">Using the arguments object</h2> + +<p>The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:</p> + +<pre class="brush: js">arguments[i] +</pre> + +<p>where <code>i</code> is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be <code>arguments[0]</code>. The total number of arguments is indicated by <code>arguments.length</code>.</p> + +<p>Using the <code>arguments</code> 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 <code>arguments.length</code> to determine the number of arguments actually passed to the function, and then access each argument using the <code>arguments</code> object.</p> + +<p>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:</p> + +<pre class="brush: js">function myConcat(separator) { + var result = ""; // initialize list + var i; + // iterate through arguments + for (i = 1; i < arguments.length; i++) { + result += arguments[i] + separator; + } + return result; +} +</pre> + +<p>You can pass any number of arguments to this function, and it concatenates each argument into a string "list":</p> + +<pre class="brush: js">// returns "red, orange, blue, " +myConcat(", ", "red", "orange", "blue"); + +// returns "elephant; giraffe; lion; cheetah; " +myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); + +// returns "sage. basil. oregano. pepper. parsley. " +myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); +</pre> + +<div class="note"> +<p><strong>Note:</strong> The <code>arguments</code> variable is "array-like", but not an array. It is array-like in that is has a numbered index and a <code>length</code> property. However, it does not possess all of the array-manipulation methods.</p> +</div> + +<p>See the {{jsxref("Function")}} object in the JavaScript reference for more information.</p> + +<h2 id="Function_parameters">Function parameters</h2> + +<p>Starting with ECMAScript 6, there are two new kinds of parameters: default parameters and rest parameters.</p> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>In JavaScript, parameters of functions default to <code>undefined</code>. However, in some situations it might be useful to set a different default value. This is where default parameters can help.</p> + +<p>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 <code>undefined</code>. If in the following example, no value is provided for <code>b</code> in the call, its value would be <code>undefined</code> when evaluating <code>a*b</code> and the call to <code>multiply</code> would have returned <code>NaN</code>. However, this is caught with the second line in this example:</p> + +<pre class="brush: js">function multiply(a, b) { + b = typeof b !== 'undefined' ? b : 1; + + return a*b; +} + +multiply(5); // 5 +</pre> + +<p>With default parameters, the check in the function body is no longer necessary. Now, you can simply put <code>1</code> as the default value for <code>b</code> in the function head:</p> + +<pre class="brush: js">function multiply(a, b = 1) { + return a*b; +} + +multiply(5); // 5</pre> + +<p>Fore more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> in the reference.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameter</a> syntax allows us to represent an indefinite number of arguments as an array. In the example, we use the rest parameters to collect arguments from the second one to the end. We then multiply them by the first one. This example is using an arrow function, which is introduced in the next section.</p> + +<pre class="brush: js">function multiply(multiplier, ...theArgs) { + return theArgs.map(x => multiplier * x); +} + +var arr = multiply(2, 1, 2, 3); +console.log(arr); // [2, 4, 6]</pre> + +<h2 id="Arrow_functions">Arrow functions</h2> + +<p>An <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> (also known as <strong>fat arrow function</strong>) has a shorter syntax compared to function expressions and lexically binds the <code>this</code> value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "<a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">ES6 In Depth: Arrow functions</a>".</p> + +<p>Two factors influenced the introduction of arrow functions: shorter functions and lexical <code>this</code>.</p> + +<h3 id="Shorter_functions">Shorter functions</h3> + +<p>In some functional patterns, shorter functions are welcome. Compare:</p> + +<pre class="brush: js">var a = [ + "Hydrogen", + "Helium", + "Lithium", + "Beryllium" +]; + +var a2 = a.map(function(s){ return s.length }); + +console.log(a2); // logs [ 8, 6, 7, 9 ] + +var a3 = a.map( s => s.length ); + +console.log(a3); // logs [ 8, 6, 7, 9 ] +</pre> + +<h3 id="Lexical_this">Lexical <code>this</code></h3> + +<p>Until arrow functions, every new function defined its own <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a> value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.</p> + +<pre class="brush: js">function Person() { + // The Person() constructor defines `this` as itself. + this.age = 0; + + setInterval(function growUp() { + // In nonstrict mode, the growUp() function defines `this` + // as the global object, which is different from the `this` + // defined by the Person() constructor. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>In ECMAScript 3/5, this issue was fixed by assigning the value in <code>this</code> to a variable that could be closed over.</p> + +<pre class="brush: js">function Person() { + var self = this; // Some choose `that` instead of `self`. + // Choose one and be consistent. + self.age = 0; + + setInterval(function growUp() { + // The callback refers to the `self` variable of which + // the value is the expected object. + self.age++; + }, 1000); +}</pre> + +<p>Alternatively, a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> could be created so that the proper <code>this</code> value would be passed to the <code>growUp()</code> function.</p> + +<p>Arrow functions capture the <code>this</code> value of the enclosing context, so the following code works as expected.</p> + +<pre class="brush: js">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| properly refers to the person object + }, 1000); +} + +var p = new Person();</pre> + +<h2 id="Predefined_functions">Predefined functions</h2> + +<p>JavaScript has several top-level, built-in functions:</p> + +<dl> + <dt>{{jsxref("Global_Objects/eval", "eval()")}}</dt> + <dd> + <p>The <code><strong>eval()</strong></code> method evaluates JavaScript code represented as a string.</p> + </dd> + <dt>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}</dt> + <dd> + <p>The <code><strong>uneval()</strong></code> method creates a string representation of the source code of an {{jsxref("Object")}}.</p> + </dd> + <dt>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</dt> + <dd> + <p>The global <code><strong>isFinite()</strong></code> function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.</p> + </dd> + <dt>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</dt> + <dd> + <p>The <code><strong>isNaN()</strong></code> function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the <code>isNaN</code> function has <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#Description">interesting</a> rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> to determine if the value is Not-A-Number.</p> + </dd> + <dt>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</dt> + <dd> + <p>The <code><strong>parseFloat()</strong></code> function parses a string argument and returns a floating point number.</p> + </dd> + <dt>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</dt> + <dd> + <p>The <code><strong>parseInt()</strong></code> function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</dt> + <dd> + <p>The <code><strong>decodeURI()</strong></code> function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.</p> + </dd> + <dt>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</dt> + <dd> + <p>The <code><strong>decodeURIComponent()</strong></code> method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</dt> + <dd> + <p>The <code><strong>encodeURI()</strong></code> 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).</p> + </dd> + <dt>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</dt> + <dd> + <p>The <code><strong>encodeURIComponent()</strong></code> 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).</p> + </dd> + <dt>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}</dt> + <dd> + <p>The deprecated <code><strong>escape()</strong></code> method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.</p> + </dd> + <dt>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}</dt> + <dd> + <p>The deprecated <code><strong>unescape()</strong></code> 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 {{jsxref("Global_Objects/escape", "escape")}}. Because <code>unescape()</code> is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.</p> + </dd> +</dl> + +<p>{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</p> |