From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../a_re-introduction_to_javascript/index.html | 931 --------------------- files/tr/web/javascript/data_structures/index.html | 299 ------- .../control_flow_and_error_handling/index.html | 420 ---------- .../guide/details_of_the_object_model/index.html | 758 ----------------- files/tr/web/javascript/guide/functions/index.html | 663 --------------- .../javascript/guide/grammar_and_types/index.html | 640 -------------- files/tr/web/javascript/guide/index.html | 122 --- .../web/javascript/guide/introduction/index.html | 134 --- .../guide/loops_and_iteration/index.html | 331 -------- .../guide/working_with_objects/index.html | 505 ----------- files/tr/web/javascript/index.html | 106 --- .../inheritance_and_the_prototype_chain/index.html | 561 ------------- .../web/javascript/language_resources/index.html | 157 ---- .../tr/web/javascript/memory_management/index.html | 199 ----- .../tr/web/javascript/reference/classes/index.html | 276 ------ .../javascript/reference/classes/static/index.html | 127 --- .../tr/web/javascript/reference/errors/index.html | 31 - .../missing_semicolon_before_statement/index.html | 71 -- .../reference/functions/arrow_functions/index.html | 359 -------- .../web/javascript/reference/functions/index.html | 596 ------------- .../global_objects/array/concat/index.html | 167 ---- .../global_objects/array/entries/index.html | 129 --- .../global_objects/array/every/index.html | 189 ----- .../global_objects/array/filter/index.html | 243 ------ .../reference/global_objects/array/find/index.html | 205 ----- .../global_objects/array/findindex/index.html | 177 ---- .../global_objects/array/foreach/index.html | 308 ------- .../reference/global_objects/array/from/index.html | 258 ------ .../global_objects/array/includes/index.html | 176 ---- .../reference/global_objects/array/index.html | 371 -------- .../global_objects/array/indexof/index.html | 246 ------ .../global_objects/array/isarray/index.html | 154 ---- .../reference/global_objects/array/join/index.html | 107 --- .../global_objects/array/length/index.html | 145 ---- .../reference/global_objects/array/map/index.html | 307 ------- .../reference/global_objects/array/of/index.html | 98 --- .../reference/global_objects/array/pop/index.html | 117 --- .../reference/global_objects/array/push/index.html | 152 ---- .../global_objects/array/reverse/index.html | 107 --- .../global_objects/array/shift/index.html | 112 --- .../reference/global_objects/array/sort/index.html | 251 ------ .../global_objects/array/splice/index.html | 149 ---- .../global_objects/array/unshift/index.html | 114 --- .../global_objects/array/values/index.html | 86 -- .../global_objects/arraybuffer/index.html | 222 ----- .../reference/global_objects/boolean/index.html | 159 ---- .../global_objects/boolean/tosource/index.html | 51 -- .../reference/global_objects/eval/index.html | 318 ------- .../global_objects/function/apply/index.html | 262 ------ .../reference/global_objects/function/index.html | 189 ----- .../javascript/reference/global_objects/index.html | 178 ---- .../reference/global_objects/isfinite/index.html | 138 --- .../reference/global_objects/isnan/index.html | 170 ---- .../reference/global_objects/json/index.html | 205 ----- .../global_objects/json/stringify/index.html | 313 ------- .../reference/global_objects/map/index.html | 207 ----- .../reference/global_objects/math/index.html | 191 ----- .../reference/global_objects/math/sign/index.html | 110 --- .../global_objects/object/assign/index.html | 311 ------- .../object/defineproperty/index.html | 391 --------- .../global_objects/object/entries/index.html | 141 ---- .../global_objects/object/freeze/index.html | 234 ------ .../object/getprototypeof/index.html | 134 --- .../reference/global_objects/object/index.html | 213 ----- .../global_objects/object/tostring/index.html | 161 ---- .../global_objects/object/values/index.html | 96 --- .../global_objects/promise/all/index.html | 234 ------ .../global_objects/promise/catch/index.html | 201 ----- .../reference/global_objects/promise/index.html | 317 ------- .../reference/global_objects/regexp/index.html | 606 -------------- .../reference/global_objects/string/index.html | 316 ------- .../global_objects/string/substring/index.html | 149 ---- files/tr/web/javascript/reference/index.html | 48 -- .../reference/lexical_grammar/index.html | 374 --------- .../reference/operators/function_star_/index.html | 85 -- .../web/javascript/reference/operators/index.html | 278 ------ .../reference/operators/instanceof/index.html | 208 ----- .../reference/operators/super/index.html | 166 ---- .../javascript/reference/operators/this/index.html | 348 -------- .../reference/operators/typeof/index.html | 260 ------ .../reference/statements/block/index.html | 179 ---- .../reference/statements/break/index.html | 117 --- .../reference/statements/const/index.html | 149 ---- .../reference/statements/export/index.html | 186 ---- .../web/javascript/reference/statements/index.html | 141 ---- .../reference/statements/return/index.html | 195 ----- .../reference/statements/throw/index.html | 201 ----- .../reference/statements/while/index.html | 79 -- .../javascript/reference/strict_mode/index.html | 363 -------- 89 files changed, 21248 deletions(-) delete mode 100644 files/tr/web/javascript/a_re-introduction_to_javascript/index.html delete mode 100644 files/tr/web/javascript/data_structures/index.html delete mode 100644 files/tr/web/javascript/guide/control_flow_and_error_handling/index.html delete mode 100644 files/tr/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/tr/web/javascript/guide/functions/index.html delete mode 100644 files/tr/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/tr/web/javascript/guide/index.html delete mode 100644 files/tr/web/javascript/guide/introduction/index.html delete mode 100644 files/tr/web/javascript/guide/loops_and_iteration/index.html delete mode 100644 files/tr/web/javascript/guide/working_with_objects/index.html delete mode 100644 files/tr/web/javascript/index.html delete mode 100644 files/tr/web/javascript/inheritance_and_the_prototype_chain/index.html delete mode 100644 files/tr/web/javascript/language_resources/index.html delete mode 100644 files/tr/web/javascript/memory_management/index.html delete mode 100644 files/tr/web/javascript/reference/classes/index.html delete mode 100644 files/tr/web/javascript/reference/classes/static/index.html delete mode 100644 files/tr/web/javascript/reference/errors/index.html delete mode 100644 files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/tr/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 files/tr/web/javascript/reference/functions/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/entries/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/every/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/findindex/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/indexof/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/length/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/push/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/sort/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/arraybuffer/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/boolean/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/eval/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/function/apply/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/isfinite/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/isnan/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/json/stringify/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/math/sign/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/assign/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/entries/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/freeze/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/tostring/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/object/values/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/promise/all/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/string/substring/index.html delete mode 100644 files/tr/web/javascript/reference/index.html delete mode 100644 files/tr/web/javascript/reference/lexical_grammar/index.html delete mode 100644 files/tr/web/javascript/reference/operators/function_star_/index.html delete mode 100644 files/tr/web/javascript/reference/operators/index.html delete mode 100644 files/tr/web/javascript/reference/operators/instanceof/index.html delete mode 100644 files/tr/web/javascript/reference/operators/super/index.html delete mode 100644 files/tr/web/javascript/reference/operators/this/index.html delete mode 100644 files/tr/web/javascript/reference/operators/typeof/index.html delete mode 100644 files/tr/web/javascript/reference/statements/block/index.html delete mode 100644 files/tr/web/javascript/reference/statements/break/index.html delete mode 100644 files/tr/web/javascript/reference/statements/const/index.html delete mode 100644 files/tr/web/javascript/reference/statements/export/index.html delete mode 100644 files/tr/web/javascript/reference/statements/index.html delete mode 100644 files/tr/web/javascript/reference/statements/return/index.html delete mode 100644 files/tr/web/javascript/reference/statements/throw/index.html delete mode 100644 files/tr/web/javascript/reference/statements/while/index.html delete mode 100644 files/tr/web/javascript/reference/strict_mode/index.html (limited to 'files/tr/web/javascript') diff --git a/files/tr/web/javascript/a_re-introduction_to_javascript/index.html b/files/tr/web/javascript/a_re-introduction_to_javascript/index.html deleted file mode 100644 index d6fabce7c3..0000000000 --- a/files/tr/web/javascript/a_re-introduction_to_javascript/index.html +++ /dev/null @@ -1,931 +0,0 @@ ---- -title: JavaScript ile Tekrar Tanışmak (JS Eğitimi) -slug: Web/JavaScript/A_re-introduction_to_JavaScript -tags: - - BetikKodlama - - Giriş - - JavaScript - - Orta düzey - - Rehber - - öğren -translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---- -
{{jsSidebar}}
- -

Neden yeniden tanışma? Çünkü {{Glossary("JavaScript")}}, dünyanın en yanlış anlaşılan programlama dili olma gibi bir üne sahip. Genellikle bir oyuncak olarak atfedilmesine karşın, aldatıcı sadeliğinin altında güçlü dil özellikleri barındırır. Bunlardan biri, inanılmaz sayıda yüksek profilli uygulama tarafından kullanılıyor olmasıdır. Bu da bize Javascript teknolojisine ait derin bir bilginin her web veya mobil geliştirici için önemli bir beceri olduğunu gösterir.

- -

Dilin geçmişini anlatarak başlamak faydalı olacaktır. Javascript 1995 yılında Netscape'de bir mühendis olan Brendan Eich tarafından oluşturulmuştur ve Netscape 2 ile eş zamanlı olarak 1996 yılının başlarında kullanıma açılmıştır. Başta Livescript ismi ile çıkacakken -aralarında hemen hemen hiç benzerlik olmamasına rağmen- Sun Microsystem şirketine ait Java dilinin popülerliğini arttırmak adına talihsiz bir pazarlama seçimi ile Javascript ismi ile devam edilmiştir. Bu olay o zamandan beri karışıklıklığa neden olmaktadır.

- -

Birkaç ay sonra Microsoft dilin çoğu platforma uyumlu bir versiyonu olan Jscript'i IE 3 ile çıkardı. Netscape, dili Avrupa standartlarında bir organizasyon olan Ecma International'a sundu ve bu da 1997'de {{Glossary("ECMAScript")}} standardının ilk versiyonu ile sonuçlandı. Standart 1999'da ECMAScript edition 3 olarak önemli bir güncellemeyi aldı ve o zamandan beri oldukça istikrarlı kaldı. Ancak dördüncü baskı, dil karmaşıklığı ile ilgili politik farklılıklar nedeniyle terk edildi. Dördüncü baskının pek çok bölümü, 2009 yılı Aralık ayında yayınlanan ECMAScript 5. versiyonunun  ve 2015 yılında yayınlanacak olan standartın 6. büyük versiyonunun temelini oluşturdu.

- -
-

Daha aşina olduğumuz için bu yazı boyunca ECMAScript yerine Javascript ismi ile devam edeceğiz.

-
- -

Çoğu programlama dilinin aksine, JavaScript dilinin hiçbir girdi veya çıktı kavramı yoktur. Bir ana bilgisayar ortamında bir betik dili olarak çalışacak şekilde tasarlanmıştır ve dış dünyayla iletişim kurmak için mekanizmalar sağlamak ana bilgisayar ortamına bağlıdır. En yaygın ana bilgisayar ortamı tarayıcıdır, ancak JavaScript yorumlayıcıları Adobe Acrobat, Photoshop, SVG görüntüleri, Yahoo!'nun Widget altyapısında ve node.js. gibi sunucu ortamlarında da bulunabilir. JavaScript'in kullanıldığı alanların listesi burada bitmez. Ayrıca, açık kaynaklı Apache CouchDB, gömülü bilgisayarlar veya GNOME (GNU / Linux işletim sistemleri için en popüler GUI'ler) gibi tam masaüstü ortamları gibi NoSQL veritabanlarını da içerir.

- -

Genel Bakış

- -

JavaScript türlere, operatörlere ve standart hazır nesnelere sahip nesneye yönelik, dinamik bir dildir. Sözdizim kuralları Java ve C dillerinden gelmektedir ve bu dillerden birçok yapıyı başarılı şekilde barındırır. Bu diller ile arasındaki önemli bir fark, JavaScript'in sınıflara (class) sahip olmamasıdır. JavaScript, sınıfların yaptığı işleri nesne prototiplerini (object prototype) kullanarak yapar. Bir diğer temel fark ise fonksiyonların birer nesne olmasıdır. Bu şekilde fonksiyonların da yürütülebilir kodu saklama ve diğer her nesne gibi aktarılma kapasitesi vardır.

- -

Her dilin yapıtaşı sayılabilecek olan unsuru öğrenerek başlayalım: türler (types). JavaScript programları değerleri (value) manipüle eder ve bu değerlerin hepsi bir türe aittir. JavaScript'in türleri şunlardır:

- - - -

... oh, ayrıca {{jsxref("undefined")}} ve {{jsxref("null")}}, ki ... biraz garipler. Ayrıca özel bir nesne kabul edebileceğimiz {{jsxref("Array")}}. Bir de bedava elde edebileceğiniz nesneler olan {{jsxref("Date")}} ve {{jsxref("RegExp")}}.  Teknik olarak fonksiyonlar da özel bir tür nesnedir. Bu nedenle asıl diyagramımız böyle görünmeli:

- - - -

Ayrıca bazı gömme {{jsxref("Error")}} türlerinden de söz edebiliriz. Ancak ilk diyagramla hareket etmemiz bizim işimizi kolaylaştıracaktır.

- -

Sayılar 

- -

JavaScript'teki sayılar, spesifikasyonlara göre "çift duyarlıklı 64 bit format IEEE 754 değerleri" dir. Ancak bunun bazı ilginç sonuçları var. Örneğin JavaScript'te tamsayı gibi bir şey yoktur, bu yüzden eğer C veya Java'da kullanılan matematiğe alışkınsanız, aritmetiğinize biraz dikkat etmelisiniz.

- -

Ayrıca aşağıdaki gibi olaylara dikkat edin:

- -
0.1 + 0.2 == 0.30000000000000004
-
- -

Pratikte tamsayı değerleri 32-bit int olarak sayılır (ve bazı tarayıcı uygulamalarında bu şekilde saklanır). Bu, bit-temelli eylemler gerçekleştirmek istediğinizde önemli bir ayrıntıdır.

- -

Ekleme, çıkarma, modül (veya kalan) aritmetik ve benzeri dahil olmak üzere standart aritmetik operatörler desteklenir. Daha ileri matematiksel fonksiyonlar gerçekleştirmek istiyorsanız kullanmanız gereken gömme nesne {{jsxref("Math")}}'dir:

- -
Math.sin(3.5);
-var d = Math.PI * r * r;
-
- -

{{jsxref("Global_Objects/parseInt", "parseInt()")}} gömme fonksiyonunu kullanarak bir string'i tamsayıya çevirebilirsiniz. Bu fonksiyon isteğe bağlı ikinci bir argüman olarak sayı tabanını alır:

- -
parseInt('123', 10); // 123
-parseInt('010', 10); // 10
-
- -

Eski tarayıcılarda "0" değeri ile başlayan stringler sekizli taban kabul ediliyordu. Eğer taban değerini yazmazsanız 2013 öncesi tarayıcılarda şaşırtıcı sonuçlar alabilirsiniz:

- -
parseInt("010"); // 8
-parseInt("0x10"); // 16
-
- -

Yukarıda gördüğünüz hata, {{jsxref("Global_Objects/parseInt", "parseInt()")}} fonksiyonu, yazılan string'i baştakı 0 nedeniyle sekizli taban cinsinden işlem yapması yüzünden gerçekleşti.

- -

Bir sayıyı binary'den tamsayıya dönüştürmek isterseniz tek yapmanız gereken tabanı değiştirmektir:

- -
parseInt("11", 2); // 3
-
- -

Benzer şekilde float türü sayıları ayrıştırmak için {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} gömülü fonksiyonunu kullanabilirsiniz. Bu fonksiyon, kuzeni sayabileceğimiz  {{jsxref("Global_Objects/parseInt", "parseInt()")}} fonksiyonunun aksine 10 tabanlı sistemi kullanır.

- -

Ayrıca +  operatörünü kullanarak değerleri sayıya çevirebilirsiniz:

- -
+ '42'; //42
-+ '010'; //10
-+ '0x10'; //16
-
- -

String sayısal bir değer değil ise karşınıza {{jsxref("NaN")}} (Açılımı: "Not a Number"' = sayı değil) çıkar:

- -
parseInt("hello", 10); // NaN
-
- -

NaN toksik gibidir: eğer onu bir girdi olarak herhangi bir matematiksel operasyonda kullanırsanız sonuç yine NaN olacaktır:

- -
NaN + 5; // NaN
-
- -

NaN  {{jsxref("Global_Objects/isNaN", "isNaN()")}} gömme fonksiyonu ile test edilebilir:

- -
isNaN(NaN); // true
-
- -

JavaScript ayrıca {{jsxref("Infinity")}} (sonsuz) ve-Infinity (- sonsuz) gibi özel değerlere sahiptir:

- -
1 / 0; //  Infinity
--1 / 0; // -Infinity
-
- -

 Infinity, -Infinity ve NaN değerlerini gömme fonksiyon  {{jsxref("Global_Objects/isFinite", "isFinite()")}} ile test edebilirsiniz: 

- -
isFinite(1/0); // false
-isFinite(-Infinite); //false
-isFinite(NaN); // false
-
- -
Not: {{jsxref("Global_Objects/parseInt", "parseInt()")}} ve {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} fonksiyonları, belirtilen sayı biçimi için geçerli olmayan bir karaktere ulaşıncaya kadar bir dizeyi ayrıştırır, ardından bu noktaya kadar ayrıştırılan sayıyı döndürür. Ancak "+" operatörü, içinde geçersiz bir karakter varsa dizeyi  NaN 'a dönüştürür. Bahsettiğimiz yöntemleri kullanarak"10.2abc" dizesini konsolda kendiniz ayrıştırmayı denerseniz farklarını daha iyi anlayabilirsiniz.
- -

Stringler

- -

JavaScript'teki stringler, karakter dizileridir. Daha doğrusu her karakter 16 bitlik bir sayı ile temsil edilen Unicode karakter dizisidir. Bu, uluslararasılaşma ile uğraşmak zorunda kalmış herkese iyi bir haber diyebiliriz.

- -

Tek bir karakteri temsil etmek istiyorsanız, sadece 1 uzunluğunda bir string kullanmanız yeterlidir.

- -

Bir string'in uzunluğunu bulmak istiyorsanız length özelliğini kullanabilirsiniz:

- -
"merhaba".length; // 7
-
- -

Böylelikle Javascript nesnelerine ilk adımımızı atmış olduk! Stringlerin de nesne olduğundan bahsetmiş miydik? Onların da stringleri manipüle etmek ve stringlerden bilgi almak için kullanılabilecek metodları vardır:

- -
> 'merhaba'.charAt(0); // "m"
-> 'merhaba, dünya'.replace('merhaba', 'elveda'); // "elveda, dünya"
-> 'merhaba'.toUpperCase(); // MERHABA
-
- -

Diğer Türler

- -

JavaScript, bir değer sayılmayan (ve sadece null  anahtar kelimesi ile erişilebilen) {{jsxref ("null")}} ve atanmamış değer olduğunu belirten {{jsxref ("undefined")}} arasındaki farkı ayırt edebilir. Daha sonra değişkenlerden bahsedeceğiz, ancak şimdiden belirtmeliyiz ki JavaScript'te değer atamadan da değişken tanımlamak mümkündür. Bunu yaparsanız, değişkenin türü undefined olur, bu da bize undefined türünün aslında bir sabit olduğunu gösterir.

- -

Javascript, true (doğru) ve false (yanlış) değerlerini alabilen bir boolean türüne sahiptir. Aşağıdaki kurallar dahilinde her değer boolean'e çevrilebilir:

- -
    -
  1.  false, 0, boş stringler (""), NaN, ve undefined değerlerinin tamamı false,
  2. -
  3. Kalan tüm değerler true olur.
  4. -
- -

Bu dönüşümü, Boolean() fonksiyonunu kullanarak kolayca gerçekleştirebilirsiniz:

- -
Boolean('');  // false
-Boolean(234); // true
- -

Ancak bu dönüşüm çoğu zaman gereksizdir çünkü Javascript bir boolean -bir if else ifadesi gibi (aşağıda görebilirsiniz)- beklediğinde bu dönüşümü sessizce gerçekleştirir. Bu nedenle "doğru değerler" ve "yanlış değerler"den bahsederken aslında  true ve false haline gelen değerlerden bahsediyoruz. Bu sizin true ve false değerleri yerine "truthy" ve "falsy" gibi sözcükler de kullanabileceğiniz anlamına gelir.

- -

&& (ve), || (veya), ve ! (değil) gibi mantıksal boolean işlemleri desteklenmektedir; aşağıda daha fazla bilgi bulabilirsiniz.

- -

Değişkenler

- -

Javascript'de yeni değişkenler letconst, veya var anahtar kelimeleri ile tanımlanır.

- -

let, blok-düzeyinde değişkenleri tanımlamaya yarar. Tanımlanan değişken sadece kapsadığı blok dahilinde geçerlidir.

- -
let a;
-let isim = "eren";
-
- -

Aşağıda let ile tanımlanmış bir değişken örneği görebilirsiniz:

- -
// letDegiskenim burada kullanılabilir *değil*
-
-for (let letDegiskenim = 0; letDegiskenim < 5; letDegiskenim++) {
-    // letDegiskenim sadece burada kullanılabilir
-}
-
-// letDegiskenim burada kullanılabilir *değil*
-
- -

const ile ileride değiştirme amacınız olmayan değişkenler tanımlayabilirsiniz. Değişken sadece içinde tanımlandığı blokta kullanılabilir.

- -
const Pi = 3.14;
-Pi = 1; // const değişkenlerine yeni değerler atanamayacağı için hata verecektir.
- -

var en çok kullanılan tanımlayıcı anahtar sözcüktür. let ve const'daki kısıtlamalar bu anahtar sözcükte geçerli değildir. Bunun nedeni Javascript'de geçmişten beri bir değişken tanımlamak için var kullanılmasıdır. Bu anahtar sözcükle tanımlanan değişkenler, tanımlandığı fonksiyon içerisinde kullanılabilir.

- -
var a;
-var isim = 'eren';
- -

Aşağıda var ile tanımlanmış bir değişken örneği görebilirsiniz:

- -
// varDegiskenim burada kullanılabilir
-
-for (let varDegiskenim = 0; varDegiskenim < 5; varDegiskenim++) {
-    // varDegiskenim tüm fonksiyon için kullanılabilir
-}
-
-// varDegiskenim burada kullanılabilir
- -

Eğer bir değişkeni değer atamadan tanımlarsanız, türü undefined olur.

- -

Javascript ve Java gibi diller arasındaki önemli bir fark, Javascript'de blokların değil sadece fonksiyonların kapsama alanınından bahsedebilmemizdir. Yani bileşik bir ifade (örneğin bir if kontrol yapısı gibi) içerisinde var ile tanımlanan değişken, tüm fonksiyon içerisinde kullanılabilir. Ancak, ESMAScript 2015'den beri, let ve const tanımlayıcıları size blok-düzeyinde değişkenler oluşturmanıza yarar.

- -

Operatörler

- -

Javascript'de +, -, *, / ve % gibi sayısal operatörler bulunur. (%: "kalan" operatörüdür ve modülüs ile aynı değildir.). Değerler = ile atanır, ayrıca += ve -= gibi bileşke atama ifadeleri de kullanılabilir.

- -
x += 5;
-x = x + 5;
-
- -

 ++ and -- operatörlerini sırasıyla arttırmak ve azaltmak için kullanabilirsiniz.  Bu operatörler, değerden önce veya sonra yazılabilir (++deger ve deger++ gibi).

- -

+ operatorü stringleri birbirine bağlamak için de kullanılabilir:

- -
> "merhaba" + " dünya"
-merhaba dünya
-
- -

Eğer bir sayıya (veya herhangi bir değere) string eklerseniz, her şey stringe dönüştürülür. Aşağıdaki örneğe bir göz atın:

- -
> '3' + 4 + 5 // "345"
-> 3 + 4 + '5' // "75"
-
- -

Bir değere boş string ekleyerek onu stringe dönüştürmek pratik bir yoldur.

- -

Javascript'de karşılaştırmalar <><= ve >= ile yapılır. Bu operatörleri hem string hem de sayı değerleri için kullanabilirsiniz. Eşitlik ise bundan biraz daha karmaşık bir konudur. Çift-eşitlik operatörü, aşağıda görebileceğiniz gibi farklı türleri karşılaştırdığınızda düşündüğünüzden farklı sonuçlar verebilir:

- -
123 == '123' // true
-1 == true;   // true
-
- -

Farklı türlerle çalışırken bu tarz karışıklıklarlardan kaçınmak için üçlü-eşitlik operatörünü kullanın:

- -
123 === '123'; // false
-1 === true;   // false
-
- -

Javascript'de ayrıca != ve !== operatörleri de vardır.

- -

Eğer bit-dizeyinde işlemlerle ilgileniyorsanız buraya tıklayarak referans belgelerinden daha ayrıntılı bilgi alabilirsiniz.

- -

Kontrol yapıları

- -

Javascript, C ailesine benzer nitelikte kontrol yapılarına sahiptir. Koşullu ifadeler if ve else ile desteklenir; isterseniz onları aşağıda göreceğiniz gibi birlikte kullanabilirsiniz:

- -
var isim = 'kediler';
-if (isim  == 'köpekler') {
-    isim += 'havlar';
-} else if (isim == 'kediler') {
-    isim += 'miyavlar';
-} else {
-    isim += '!';
-}
-isim == 'kediler miyavlar';
- -

JavaScript'de iki tür döngü (loop) vardır: while ve do-while . İlki basit döngüler için idealken; ikincisi, döngünün gövdesinin en az bir kez yürütüldüğünden emin olmak istediğiniz döngüler içindir:

- -
while (true) {
-  // sonsuz döngü!
-}
-
-var input;
-do {
-  input = get_input();
-} while (inputIsNotValid(input))
-
- -

JavaScript'de for döngüsü aynı C ve Java'daki gibidir, döngünün kontrol bilgisini tek bir satıra yazmanıza olanak sağlar.

- -
for (var i = 0; i < 5; i++) {
-  // 5 kez yürütülecektir
-}
-
- -

JavaScript'de ayrıca döngüler için iki önemli ifade vardır: for...of

- -
for (let value of array) {
-  // value değeri ile ilgili bir şey yap
-}
- -

ve for...in:

- -
for (let property in object) {
-  // object'e ait property değeri ile ilgili bir şey yap
-}​​​
-
- -

&& ve || kısa devre mantığı ile çalışır, ikinci işlenecek olan işlenen (operand), ilkine bağlıdır. Bu şekilde null nesnelerinin niteliklerine erişmeden önce kontrol etmek için kullanılabilir:

- -
var name = o && o.getName();
-
- -

Veya değerleri önbelleğe almak için (falsy değerleri geçersiz olduğunda):

- -
var name = cachedName || (cachedName = getName());
- -

JavaScript koşullu ifadeler için üçlü bir operatöre sahiptir:

- -
var giriş_izni = (yaş > 18) ? 'evet' : 'hayır';
- -

switch ifadesi bir sayıya veya string'e bağlı olarak birden fazla kolda kullanılabilir:

- -
switch (eylem) {
-  case 'çiz':
-    Çizim();
-    break;
-  case 'ye':
-    Yemek();
-    break;
-  default:
-    birSeyYapma();
-}
- -

break ifadesini eklemezseniz yürütme esnasında kod bir sonraki seviyeye "atlayacaktır". Bu çoğu zaman isteyeceğiniz bir durum değildir  — ancak eğer amacınız fallthrough ( açıkça yeniden yönlendirilmedikçe, yürütme işleminin bir listede sonraki duruma geçtiği durum)  yapmak ise yorum eklemeniz debug sürecini kolaylaştıracaktır:

- -
switch (a) {
-  case 1: // fallthrough
-  case 2:
-    Yemek();
-    break;
-  default:
-    birSeyYapma();
-}
- -

default maddesi tamamen isteğe bağlıdır.  İsterseniz hem switch kısmında hem de case kısmında ifade kullanabilirsiniz. 

- -
switch (1 + 3) {
-  case 2 + 2:
-    yaşasın();
-    break;
-  default:
-    aslaGerceklesmez();
-}
-
- -

Nesneler

- -

Javascript nesneleri (objects), basit isim-değer çiftleri olarak düşünülebilir. Bu açıdan diğer dillerdeki karşılıkları aşağıdaki gibidir:

- - - -

Bu veri yapısının çok yaygın kullanıldığı gerçeği, çok yönlülüğünün bir kanıtıdır. JavaScript'teki her şey bir nesneden oluştuğu için, her JavaScript programı doğal olarak çok sayıda komut çizelgesi (hash table) aramaları içerir.

- -

"İsim" kısmı bir Javascript string'i iken, değer olarak herhangi bir Javascript değeri yazabilirsiniz — diğer nesneler de dahil. Bu şekilde istediğiniz kadar komplike veri yapıları oluşturabilirsiniz.

- -

Boş nesne oluşturmanın iki temel yolu vardır:

- -
var nesne = new Object();
- -

Ve:

- -
var nesne = {};
- -

Bunlar semantik olarak eşdeğerdir; ikinci nesne örneğine değişmez sözdizimi (literal syntax) denir ve daha kullanışlıdır. Bu sözdizimi aynı zamanda JSON formatının özüdür ve her zaman tercih edilmelidir.

- -

Değişmez sözdizimi ile bir nesneyi tamamen tanımlayabilirsiniz:

- -
var nesne = {
-  isim: 'Havuç',
-  kime: 'Max',
-  detaylar: {
-    renk: 'turuncu',
-    boyut: 12
-  }
-};
- -

Özelliklere erişmek için aşağıda gördüğünüz iki yolu da kullanabilirsiniz:

- -
nesne.detaylar.renk; // turuncu
-nesne['detaylar']['boyut']; // 12
- -

Aşağıdaki örnekte bir nesne prototipi (Kişi) ve bu prototipin bir örneğini (sen) oluşturacağız:

- -
function Kişi(isim, yaş) {
-  this.isim= isim;
-  this.yaş = yaş;
-}
-
-// Bir nesne tanımlayalım
-var sen = new Kişi('Sen', 24);
-// Adı "Sen" olan 24 yaşında bir kişi yaratmış olduk.
- -

Bir kere oluşturulduktan sonra, nesnenin değerlerine erişebilmenin iki yolu vardır: 

- -
// nokta notasyonu
-nesne.isim = 'Ayşe';
-var isim = nesne.isim;
- -

Ve...

- -
// parantez notasyonu
-nesne['isim'] = 'Ayşe';
-var isim = nesne['isim'];
-// Anahtar (key) tanımlamak için değişken kullanabilirsiniz.
-var kullanıcı = prompt('Anahtar değeriniz nedir?')
-obj[kullanıcı] = prompt('Anahtarın değeri nedir?')
-
- -

Yukarıda gördüğünüz örnekler de semantik olarak eşdeğerdir. İkinci metodun avantajı, özelliğin ismi string olarak sunulduğu için, yükleme zamanı (run-time) içerisinde hesaplanmasıdır. Ancak bu yöntemin kullanılması bazı Javascript motoru ve sıkıştırma optimizasyonlarının (minifier optimizations) çalışmasına engel olabilir.  Ayrıca parantez notasyonu ile rezerve sözcükleri kullanarak özellik atama ve çağırma işlemleri yapabilirsiniz:

- -
obj.for = 'Simon'; // Sözdizimi hatası verecektir çünkü 'for' rezerve sözcüklerden
-obj['for'] = 'Simon'; // düzgün çalışır
- -
-

ECMAScript 5'den itibaren, rezerve sözcükler nesne özelliği olarak kullanılabiliyor. Daha fazla bilgi için: ES5 Spesifikasyonu

-
- -

Nesneler ve prototipleri hakkında daha fazla bilgi için Object.prototype adresini ziyaret edebilirsiniz. Nesne prototipleri  ve nesne prototip zincirleri için daha detaylı öğrenmek için: Kalıtım ve prototip zinciri.

- -
-

ECMAScript 5'den itibaren, nesne anahtarları parantez notasyonuyla oluşturulmuş değişkenler ile tanımlanabilir. Yani var telKullanıcı = {}; telKullanıcı[telNum] = 12345yerine sadece {[telNum]: 12345} ifadesini kullanmak mümkündür.

-
- -

Diziler

- -

Javascript'de diziler (arrays) aslında özel birer nesneden ibarettir. Çoğu açıdan sıradan nesneler gibi çalışırlar (sayısal özelliklere doğal olarak yalnızca [] ile erişilebilir) ancak onları nesnelerden ayıran sihirli bir özellik vardır: 'length'. Bu değer her zaman en yüksek index değerinden bir fazladır.

- -

Dizi oluşturmanın bir yolu aşağıdaki gibidir:

- -
var a = new Array();
-a[0] = 'köpek';
-a[1] = 'kedi';
-a[2] = 'tavuk';
-a.length; // 3
- -

Bir diğer yol ise değişmez dizi (literal array) oluşturmaktır:

- -
var a = ['köpek', 'kedi', 'tavuk'];
-a.length; // 3
- -

Fark edebileceğiniz gibi array.length her zaman dizideki öğe sayısı anlamına gelmez. Aşağıdaki örneğe dikkat edin:

- -
var a = ['köpek', 'kedi', 'tavuk'];
-a[100] = 'tilki';
-a.length; // 101
- -

Unutmayın — dizinin uzunluğu en yüksek index'den bir fazladır.

- -

Eğer varolmayan bir dizi index'ini sorgularsanız, undefined sonucunu alırsınız:

- -
typeof a[90]; // undefined
- -

Yukarıda gördüğünüz [] ve length unsurları ile istediğiniz her dizi üzerinden for döngüsü ile geçebilirsiniz:

- -
for (var i = 0; i < a.length; i++) {
-  //  a[i] kere ... yap
-}
- -

ES2015, diziler gibi yinelenen nesneler için daha kullanışlı bir for...of döngüsünü tanıttı:

- -
for (const currentValue of a) {
-  // currentValue kadar ... yap
-}
- -

for...in döngüsü kullanarak da bir dizi üzerinden geçebilirsiniz ancak bu işlem dizi elemanları üzerinden değil, dizi index'i üzerinden işlenir. Ayrıca Array.prototype 'a yeni özellikler eklendiği takdirde, onlar da döngüde yer alacaktır. Bu nedenle bu döngü türü diziler için önerilmez. 

- -

Bir dizi üzerinden geçmenin bir diğer yolu ECMAScript 5 ile eklenen forEach() yöntemidir:

- -
['köpek', 'kedi', 'tavuk'].forEach(function(currentValue, index, array) {
-  // currentValue veya array[index] ile ... yap
-});
- -

Bir diziye yeni bir eleman eklemek istiyorsanız aşağıdaki basit metodu uygulamanız yeterli olacaktır:

- -
a.push(item);
- -

Diziler için birçok metod mevcuttur. Tam dokümantasyon için buraya tıklayabilirsiniz.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Metod ismiAçıklama
a.toString() toString() içerisine virgülle ayırarak yazılan her öğeyi string şeklinde return eder.
a.toLocaleString() toLocaleString() içerisine virgülle ayırarak yazılan her öğeyi string şeklinde return eder.
a.concat(item1[, item2[, ...[, itemN]]])Seçilen öğeler eklenmiş bir biçimde yeni bir dizi return eder.
a.join(sep)Diziyi string'e dönüştürür. — öğeleri sep ile ayırarak
a.pop()Son öğeyi siler ve return eder.
a.push(item1, ..., itemN)Öğeleri dizinin sonuna ekler.
a.reverse()Diziyi ters çevirir.
a.shift()İlk değeri siler ve return eder
a.slice(start[, end])Bir alt dizi oluşturur.
a.sort([cmpfn])İsteğe bağlı bir karşılaştırma fonksiyonu alır.
a.splice(start, delcount[, item1[, ...[, itemN]]])Bir bölümü silerek ve yerine daha fazla öğe ile ekleyerek bir diziyi modife etmenizi sağlar.
a.unshift(item1[, item2[, ...[, itemN]]])Öğeleri dizinin başlangıcına ekler.
- -

Fonksiyonlar

- -

Nesnelerle gibi fonksiyonlar da Javascript'i anlamak için öğrenmeniz gereken ana bileşenlerden biridir. En temel fonksiyon aşağıda görebileceğiniz gibi oldukça kolaydır:

- -
function topla(x, y) {
-  var toplam = x + y;
-  return toplam;
-}
- -

Javascript fonksiyonları birden fazla adlandırılmış parametre alabileceği gibi, parametresiz de oluşturulabilir. Fonksiyon gövdesi istediğiniz kadar ifade içerebilir ve o fonksiyonda yer alan yerel değişkenler de tanımlayabilir. return ifadesi ile birlikte istediğiniz değer getirilir ve fonksiyon sonlandırılır. Eğer hiçbir return ifadesi kullanılmamışsa (veya değer girilmemiş boş bir return kullanılmışsa) Javascript undefined sonucunu verir.

- -

Adlandırılmış parametreler tam bir kılavuz niteliğindedir. Fonksiyonun beklediği parametreleri girmeden de çağırabilirsiniz, sonuç olarak karşınıza undefined çıkacaktır.

- -
topla(); // NaN
-// undefined bir değerle toplama işlemi gerçekleştiremezsiniz.
- -

Ayrıca fonksiyonun beklediğinden fazla argüman da ekleyebilirsiniz:

- -
topla(2, 3, 4); // 5
-// İlk iki değerle işlem yapıp 4'ü ihmal edecektir
- -

Biraz saçma gelebilir; ama fonksiyonlar, gövdelerinde ek bir değişken olarak bulunan argümanlara erişebilir. Argümanlar, fonksiyonlara verilen tüm değerleri kaydeden dizi-benzeri nesnelerdir. Hadi toplama fonksiyonumuzu istediğimiz kadar değer alabileceği şekilde yeniden yazalım:

- -
function topla() {
-  var toplam = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    toplam += arguments[i];
-  }
-  return toplam;
-}
-
-topla(2, 3, 4, 5); // 14
- -

Yine de bu fonksiyonu kullanmak yerine 2 + 3 + 4 + 5  yazmak daha mantıklı duruyor. O yüzden bir de ortalama alan bir fonksiyon yazalım:

- -
function ort() {
-  var toplam = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    toplam += arguments[i];
-  }
-  return toplam / arguments.length;
-}
-
-ort(2, 3, 4, 5); // 3.5
- -

Oldukça kullanışlı, ancak gereksiz ifadeler olması gerekenden fazla kullanılmış gibi. Yazdığımız kodu kısaltmak için argüman dizimizin yerine Rest parameter syntax yolunu kullanabiliriz. Bu yöntem hem istediğimiz sayıda argümanı fonksiyonumuzda kullanıp hem de kod uzunluğunu minimum seviyede tutmanıza yarar. Rest parametre operatörü şu şekilde listeleme yapar: ...değişken, ve bu değişkenle beraber, fonksiyonla beraber çağrılan tüm argümanların bir listesi. Ayrıca for döngüsü yerine for..of döngüsünü kullanmamız daha mantıklı olacaktır.

- -
function ort(...args) {
-  var toplam = 0;
-  for (let value of args) {
-    toplam += value;
-  }
-  return toplam / args.length;
-}
-
-ort(2, 3, 4, 5); // 3.5
- -
-

Yukarıdaki kodda args değişkeni, fonksiyona verilen tüm değerleri tutar.

- -

Unutmamanız gereken önemli bir ayrıntı: rest parametre operatörü nerede tanımlandıysa, tanımladığı satırdan sonraki argümanları belleğe alacaktır. Bir diğer deyişle, fonksiyona verilen ilk değer firstValue değişkeninde, kalan argümanlar ise args'da saklanacaktır. Bu yararlı bir dil özelliği olsa da bizi yeni bir sorunla başbaşa bırakıyor. avg() fonksiyonu virgülle ayrılan argüman listesini alabilir — ancak eğer dizinin ortalamasını bulmak istersek ne yapmamız gerekir? Fonksiyonu aşağıdaki gibi yazmak iyi bir çözüm olabilir:

-
- -
function avgArray(arr) {
-  var toplam = 0;
-  for (var i = 0, j = arr.length; i < j; i++) {
-    toplam += arr[i];
-  }
-  return toplam / arr.length;
-}
-
-avgArray([2, 3, 4, 5]); // 3.5
- -

Yine de önceden oluşturduğumuz fonksiyonu kullanabilmek daha iyi olurdu. Neyseki Javascript, size isteğe bağlı bir dizi argümana sahip bir fonksiyon çağırmanıza olanak sağlıyor. Bunun için tek yapmanız gereken {{jsxref("Function.apply", "apply()")}} metodunu kullanmak.

- -
avg.apply(null, [2, 3, 4, 5]); // 3.5
- -

 Bir diğer apply() yöntemi ise argüman olarak dizi kullanmaktır. Bu bilgi dahilinde, fonksiyonların da birer nesne olduğunu tekrardan hatırlamış olalım.

- -
-

Aynı sonucu spread operatörünü çağırarak da elde edebilirsiniz.

- -

Örneğin: avg(...numbers)

-
- -

JavaScript ile anonim fonksiyonlar oluşturabilirsiniz.

- -
var avg = function() {
-  var toplam = 0;
-  for (var i = 0, j = arguments.length; i < j; i++) {
-    toplam += arguments[i];
-  }
-  return toplam / arguments.length;
-};
- -

Yukarıda gördüğünüz yöntem semantik olarak function avg() ifadesine eşdeğerdir. Oldukça güçlü olan bu yöntem ile normalde ifade yazabileceğiniz her yere fonksiyon tanımı koyabilirsiniz. Bu şekilde zekice hilelere başvurabilirsiniz. Aşağıda gördüğünüz yerel değişken "saklama" yöntemi bunlardan sadece biri:

- -
var a = 1;
-var b = 2;
-
-(function() {
-  var b = 3;
-  a += b;
-})();
-
-a; // 4
-b; // 2
- -

JavaScript, fonksiyonları özyinelemeli (recursively) çağırmanıza olanak sağlar. Bu, özellikle tarayıcı DOM'larında rastlayacağınız ağaç yapıları (tree structures) ile çalışırken oldukça faydalıdır.

- -
function countChars(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += countChars(child);
-  }
-  return count;
-}
- -

Bu anonim fonksiyonlarda olası bir sorunu işaret eder. Eğer bu fonksiyonların bir adı yoksa, onları nasıl özyinelemeli çağırabiliriz? Javascript bunun için fonksiyon ifadelerini adlandırmanıza olanak sağlar. Aşağıda görebileceğiniz gibi IAIFEs (Immediately Invoked Function Expressions) özelliğini kullanabilirsiniz:

- -
var charsInBody = (function counter(elm) {
-  if (elm.nodeType == 3) { // TEXT_NODE
-    return elm.nodeValue.length;
-  }
-  var count = 0;
-  for (var i = 0, child; child = elm.childNodes[i]; i++) {
-    count += counter(child);
-  }
-  return count;
-})(document.body);
- -

Yukarıdaki fonksiyona verilen isme sadece fonksiyonun kendi kapsamında erişilebilir. Bu şekilde Javascript motorunun daha fazla optimizasyon yapmasına olanak sağlamış olursunuz, böylelikle kodunuz daha okunur hale gelir. Ayrıca, hata ayıklama yaparken zamandan tasarruf edebilirsiniz.

- -

Fark ettiyseniz Javascript'de -diğer her şey gibi- fonksiyonlar da birer nesnedir. Böylelikle daha önceki bölümlerde öğrendiğiniz nesnelerdeki gibi, özellik ekleme ve değiştirmeniz mümkündür.

- -

Özel nesneler

- -
-

JavaScript'te nesne yönelimli programlama hakkında daha ayrıntılı bilgiler için Nesne Yönelimli Javascript'e Giriş sayfasına göz atabilirsiniz.

-
- -

Nesne yönelimli programlamada; nesneler, yine aynı veriler üzerinde işlem yapan veri ve metod koleksiyonlarıdır. Javascript prototip tabanlı bir dil olduğu için, C++ ve Java'nın aksine sınıf (class) kavramına sahip değildir. Javascript'de sınıf yerine fonksiyonlar kullanılır. Ad ve soyad alanları olan bir Kişi fonksiyonu düşünelim. Tam adı görüntülemenin iki yolu olabilir: "ad, soyad" ve "soyad, ad". Fonksiyonları ve nesneleri kullanarak veriyi aşağıda göreceğiniz gibi ekrana yansıtabiliriz:

- -
function Kişi(ad, soyad) {
-  return {
-    ad: ad,
-    soyad: soyad
-  };
-}
-function tamİsim(a) {
-  return a.ad + ' ' + a.soyad;
-}
-function tamİsimTers(a) {
-  return a.soyad + ', ' + a.ad;
-}
-
-s = Kişi('Simon', 'Willison');
-tamİsim(s); // "Simon Willison"
-tamİsimTers(s); // "Willison, Simon"
-
- -

Yukarıda gördüğünüz kod çalışacaktır ama oldukça çirkin gözüküyor. Çünkü yapmak istediğiniz işlemler arttıkça global ad alanı (namespace) onlarca fonksiyon ile dolabilir. Bu nedenle yapmamız gereken şey nesnemize fonksiyon eklemek. Fonksiyonlar da birer nesne olduğu için işimiz oldukça kolay:

- -
function Kişi(ad, soyad) {
-  return {
-    ad: ad,
-    soyad: soyad,
-    tamİsim: function() {
-      return this.ad + ' ' + this.soyad;
-    },
-    tamİsimTers: function() {
-      return this.soyad + ', ' + this.ad;
-    }
-  };
-}
-
-s = Kişi('Simon', 'Willison');
-s.tamİsim(); // "Simon Willison"
-s.tamİsimTers(); // "Willison, Simon"
- -

Fark ettiyseniz burada yeni bir anahtar kelime kullandık: this. Fonksiyonun içinde kullanıldığında this, geçerli nesneyi ifade eder. Ne anlama geleceği fonksiyonu çağırma yöntemine göre belirlenir. Örneğin; bir nesne üzerinde, fonksiyonu nokta notasyonu veya parantez notasyonu ile çağırırsanız, o nesne this olur. Eğer nokta notasyonu çağrı işleminde kullanılmadıysa this global nesneyi ifade eder.

- -

this anahtar sözcüğü birçok hataya sebep olabilir. Aşağıdaki örneğe bir göz atın:

- -
s = Kişi('Simon', 'Willison');
-var tamİsim = s.tamİsim;
-fullName(); // undefined undefined 
- -

tamİsim() fonksiyonunu  s.tamİsim()'i kullanmadan tek başına çağırdığımızda, this global nesneye bağlıdır. ad ve soyad gibi global değişkenler olmadığı için ekrana her biri için undefined sonucu yansıyacaktır.

- -

Şimdi Kişi fonksiyonumuzu geliştirmek için this anahtar kelimesini kullanalım:

- -
function Kişi(ad, soyad) {
-  this.ad = ad;
-  this.soyad = soyad;
-  this.tamİsim = function() {
-    return this.ad + ' ' + this.soyad;
-  };
-  this.tamİsimTers = function() {
-    return this.soyad + ', ' + this.ad;
-  };
-}
-var s = new Kişi('Simon', 'Willison');
- -

Yeni bir anahtar kelimeden bahsetmenin vakti geldi: new. new, this ile doğrudan bağlantılıdır. Tamamen yeni bir boş nesne yaratır ve belirtilen fonksiyonu yeni nesnenin this değeriyle güncelleyerek çağırır. Fark ettiyseniz this, sadece this nesnesinde değişiklik yapar. Bir değeri return eden new anahtar kelimesidir. new tarafından çağırılacak fonksiyonlara kurucu (constructor) fonksiyon denir. Bu fonksiyonları new ile çağırmayı unutmamak için büyük harfle isimlendirmek yaygın bir yöntemdir.

- -

Geliştirdiğimiz fonksiyon hala tamİsim()'i tek başına çağırdığımızda istediğimiz sonucu vermeyecek.

- -

Kişi nesnelerimiz artık eskisinden daha iyi, ancak hala kötü tarafları mevcut. Her kişi nesnesi oluşturduğumuzda, iki yepyeni fonksiyon yaratmış oluyoruz — peki bu kod paylaşılsaydı daha iyi olmaz mıydı?

- -
function tamİsim() {
-  return this.ad + ' ' + this.soyad;
-}
-function tamİsimTers() {
-  return this.soyad + ', ' + this.ad;
-}
-function Kişi(ad, soyad) {
-  this.ad = ad;
-  this.soyad = soyad;
-  this.tamİsim= tamİsim;
-  this.tamİsimTers = tamİsimTers;
-}
- -

Çok daha iyi. Artık metod fonksyionlarını bir defa oluşturuyoruz ve referansları kurucu fonksiyonun içinde atıyoruz. Bundan daha iyisini de yapabilir miyiz? Cevap evet:

- -
function Kişi(ad, soyad) {
-  this.ad = ad;
-  this.soyad = soyad;
-}
-Kişi.prototype.tamİsim = function() {
-  return this.ad+ ' ' + this.soyad;
-};
-Kişi.prototype.tamİsimTers = function() {
-  return this.soyad + ', ' + this.ad;
-};
- -

Kişi.prototypeKişi'nin tüm özelliklerinin paylaşıldığı bir nesnedir. Bir diğer adı "prototip zinciri" olan bu nesne, bir arama zincirinin parçasını oluşturur. Kişi'ye ait ayarlanmamış bir özelliğe erişmek istediğinizde, Javascript bu özelliğin var olup olmadığını Kişi.prototype öğesinde arayacaktır. Böylelikle Kişi.prototype'a atanan her şey, this nesnesi kullanılarak kurucu fonksiyonda da geçerli hale gelecektir.

- -

Bu, oldukça güçlü bir özellik. Javascript, size istediğiniz zaman, herhangi bir şeyin prototipini modifiye etmenize olanak tanır. Bu şekilde önceden oluşturduğunuz nesnelere yeni metodlar ekleyebilirsiniz:

- -
s = new Kişi('Simon', 'Willison');
-s.isimCaps(); // 1. satırda TypeError: s.isimCaps bir fonksiyon değil
-
-Kişi.prototype.isimCaps = function() {
-  return this.first.toUpperCase();
-};
-s.isimCaps(); // "SIMON"
- -

İlginç bir şekilde gömülü Javascript nesnelerinin prototiplerine de bir şeyler ekleyebilirsiniz. Hadi String  nesnesine sözcükleri ters çevirmeye yarayan bir metod ekleyelim:

- -
var s = 'Simon';
-s.ters(); // 1. satırda TypeError: s.ters bir fonksiyon değil
-
-String.prototype.ters = function() {
-  var r = '';
-  for (var i = this.length - 1; i >= 0; i--) {
-    r += this[i];
-  }
-  return r;
-};
-
-s.ters(); // nomiS
- -

Yeni metodumuz aşağıda görebileceğiniz durumlarda bile çalışıyor:

- -
'Ters çevir'.ters(); // riveç sreT
- -

Daha önce de bahsettiğimiz gibi; prototip, zincirin bir kısmını oluşturur. Bu zincirin kökü Object.prototype, içerdiği metodlardan biri ise toString()'dir. — hatırlarsanız bu metodu bir nesneyi string'e çevirmek için çağırıyorduk. Bu yöntem Kişi nesnelerimizin hata ayıklama sürecinde yardımcı olacaktır.

- -
var s = new Kişi('Simon', 'Willison');
-s.toString(); // [object Object]
-
-Kişi.prototype.toString = function() {
-  return '<Kişi: ' + this.isim() + '>';
-}
-
-s.toString(); // "<Kişi: Simon Willison>"
- -

Hatırlarsanız avg.apply() metodu yeni bir boş argüman oluşturuyordu. Şimdi o konuya geri dönebiliriz.  apply() kullanacağımız ilk argüman, 'this' ile ele alınacak bir nesne olmalıdır. Aşağıda new anahtar kelimesinin kullanıldığı küçük bir uygulama görebilirsiniz:

- -
function Deneme(constructor, ...args) {
-  var o = {}; // Nesne yaratır
-  constructor.apply(o, args);
-  return o;
-}
- -

Bu, prototip zincirini oluşturmadığı için new ifadesinin tam anlamıyla karşılığı sayılmaz (bu durumu anlatması biraz zor) ve çok sık kullanacağınız bir şey değil, ancak yine de bilmek faydalı olacaktır. Bu örnekte ...args, "rest arguments" olarak da geçer. — adından da anlayacağınız üzere geriye kalan tüm argümanları temsil eder.

- -

Bu nedenle bu satır,

- -
var bill = Deneme(Kişi, 'William', 'Orange');
- -

hemen hemen bu satır ile aynıdır:

- -
var bill = new Kişi('William', 'Orange');
- -

apply() metodunun kardeşi sayabileceğimiz call, apply()'dan farklı olarak genişletilmiş bir argüman listesi alır.

- -
function soyadCaps() {
-  return this.last.toUpperCase();
-}
-var s = new Kişi('Simon', 'Willison');
-soyadCaps.call(s);
-// Veya aşağıdaki yöntemi kullanabilirsiniz:
-s.soyadCaps = soyadCaps;
-s.soyadCaps(); // WILLISON
- -

İç fonksiyonlar

- -

JavaScript fonksiyonların içinde başka fonksiyonlar tanımlayabilirsiniz. Bu durumu  Kişi() fonksiyonumuzun önceki versiyonlarında görmüştük. İç içe oluşturulan fonksiyonlara dair önemli bir detay, içteki fonksiyonun içinde bulunduğu "parent" fonksiyon kapsamında kullanılan değişkenlere erişebilmesidir:

- -
function parentFonk() {
-  var a = 1;
-
-  function içFonk() {
-    var b = 4; // parentFonk bunu kullanamaz.
-    return a + b;
-  }
-  return içFonk(); // 5
-}
- -

Bu, daha sürdürülebilir bir kod yazmanızda büyük yarar sağlar. Eğer bir fonksiyonunuz, başka kısımlarda işinize yaramayacak bir veya daha fazla fonksiyona bağlıysa; bu fonksiyonları başka bir yerde çağıracağınız fonksiyonun içine yazabilirsiniz. Bu şekilde global düzeyde kullanılan değişken sayısını azaltacağınız için, daha güvenli bir koda sahip olursunuz.

- -

Yazdığınız kod karmaşık bir hal aldıkça birden çok fonksiyon arasında değer paylaşmak yerine global değişkenler kullanmak daha cazip gelebilir — ki bu sebeple sürdürülmesi zor bir kod yaratmış olursunuz. İç içe fonksiyonlar dış fonksiyon ile değişken paylaşabildiği için global isim alanınızı (global namespace) kirletmeden, sadece ilgili fonksiyonları bir araya getirerek bu mekanizmayı kullanabilirsiniz.  —  bu şekilde kullanacağınız değişkenlere "yerel global" bile diyebiliriz. Ne kadar kullanışlı da olsa bu mekanizmayı dikkatli kullanmanız gerekir.

- -

Kaplamlar

- -

Sıra geldi Javascript'in en güçlü -bir yandan da en kafa karıştırıcı-  soyutlamalarından birine. Peki kaplamlar (closures) tam olarak ne yapar?

- -
function ekle(a) {
-  return function(b) {
-    return a + b;
-  };
-}
-var x = ekle(5);
-var y = ekle(20);
-x(6); // ?
-y(7); // ?
- -

ekle() fonksiyonun işlevini anlamışsınızdır; yeni bir "toplama" fonksiyonu oluşturur ve tek bir argümanla çağrıldığında, oluşturulduğu argümana o değeri ekler.

- -

Burada gördüğünüz olayın gerçekleşme şekli, daha önce bahsettiğimiz iç fonksiyonların çalışma prensibiyle hemen hemen aynı: içeride tanımlanmış fonksiyon, dış fonksiyonun değişkenlerine erişim hakkı vardır. Buradaki tek fark ise şu; dış fonksiyon return edildiğinde yerel değişkenleri artık yok olacak gibi düşünürüz, ancak hala bellektedirler — aksi takdirde fonksiyonlarımız çalışmazdı. Dahası, ekle() fonksiyonunun yerel değişkenlerinin iki farklı "kopyası" bulunuyor. — bir 5 olan a ve bir de 20 olan a. Bu yüzden yukarıdaki kodun sonucu böyle olacaktır:

- -
x(6); //  11
-y(7); //  27
- -

Şimdi arkaplanda ne olup bittiğini yazalım. Javascript ne zaman bir fonksiyonu yürütse, fonksiyon içerisindeki yerel değişkenleri tutma amaçlı bir 'kapsama alanı' oluşturur. Bu alan, fonksiyon parametresi olarak gönderilen tüm değişkenler üzerinden tanımlanır. Bahsettiğimiz durum tüm global değişken ve fonksiyonları içeren global nesneye benzese de, birkaç önemli farklılık taşır: ilk olarak, fonksiyon her yürütüldüğünde yepyeni bir kapsam nesnesi oluşturulur, ve ikinci olarak, kapsam nesneleri global nesnelerin aksine Javascript kodu üzerinden doğrudan erişilebilir değildir. Örneğin, geçerli kapsam nesnesinin özellikleri üzerinde yineleme yapmak için bir mekanizma yoktur.

- -

Özetlemek gerekirse; ekle() çağırıldığında, fonksiyona geçen argüman, yani tek bir özelliğe sahip (a) bir kapsam nesnesi oluşturulur. Ardından ekle() fonksiyonu yeni bir fonksiyon return eder. Normal koşullarda Javascript'in çöp toplayıcısının ekle() için oluşturulan bu yeni fonksiyonu temizlemesi gerekirken, return edilen fonksiyon yine de kapsam fonksiyonu için referans konumunda durur. Bu nedenle ekle()'nin oluşturduğu fonksiyon nesnesine herhangi bir referans kalmayana dek bu kapsamda hiç bir öğe silinmeyecektir.

- -

Kapsam nesneleri, JavaScript'in nesne sisteminde kullanılan prototip zincirine benzer şekilde, kapsam zinciri adı verilen bir zinciri oluşturur.

- -

Kaplam, bir fonksiyon ile, o fonksiyon beraberinde oluşturulan kapsam nesnesinin bir kombinasyonudur. Kaplamlar durum (state) kaydetmenize olanak sağlar — böylelikle nesnelerin yerine kullanılabilirler. Kaplamlar hakkında bazı muhteşem bilgiler için buraya tıklayabilirsiniz.

- -
-

Orijinal Belge Bilgileri

- - -
- -
wiki.languages({
-  "fr": "fr/Une_r\u00e9introduction_\u00e0_JavaScript",
-  "it": "it/Una_re-introduzione_a_Javascript",
-  "ja": "ja/A_re-introduction_to_JavaScript",
-  "ko": "ko/A_re-introduction_to_JavaScript",
-  "pl": "pl/JavaScript/Na_pocz\u0105tek",
-  "ru": "ru/\u041f\u043e\u0432\u0442\u043e\u0440\u043d\u043e\u0435_\u0432\u0432\u0435\u0434\u0435\u043d\u0438\u0435_\u0432_JavaScript",
-  "zh-cn": "cn/A_re-introduction_to_JavaScript",
-  "zh-tw": "zh_tw/\u91cd\u65b0\u4ecb\u7d39_JavaScript",
-  "es": "es/JavaScript/Una_nueva_introducción_a_JavaScript"});
-
diff --git a/files/tr/web/javascript/data_structures/index.html b/files/tr/web/javascript/data_structures/index.html deleted file mode 100644 index f71614add0..0000000000 --- a/files/tr/web/javascript/data_structures/index.html +++ /dev/null @@ -1,299 +0,0 @@ ---- -title: JavaScript veri tipi ve veri yapısı -slug: Web/JavaScript/Data_structures -tags: - - Başlangıç - - JavaScript - - Veri Türleri -translation_of: Web/JavaScript/Data_structures -original_slug: Web/JavaScript/Veri_Yapısı ---- -
{{jsSidebar("More")}}
- -

Programlama dilleri dil ile birlikte gelen sabit veri yapılarına sahiptir, fakat bu veri yapıları dilden dile değişiklik gösterir. Bu makale JavaScript'teki sabit veri yapılarını ve bu veri yapılarının özelliklerini listeler; böylece bu veri yapıları kullanılarak farklı veri yapıları yaratılabilir. Makale boyunca karşılaştırmanın mümkün olduğu bölümlerde, farklı dillerle kıyaslama yapılmıştır.

- -

Dinamik Veri Tipi

- -

JavaScript esnek (ya da dinamik) veri tipine sahip bir dildir. JavaScript dilinde değişkenler belirli bir veri tipi ile direkt ve sabit olarak ilişkilendirilmez ve herhangi bir değişkene herhangi bir veri tipine sahip bir değer atanabilir, bu değer daha sonra farklı bir veri tipinin değeri ile değiştirilebilir.

- -
var foo = 42;    // foo değişkeni şuan bir sayıdır
-foo     = 'bar'; // foo değişkeni şuan karakter dizisidir
-foo     = true;  // foo değişkeni şuan boolean veri türüdür
-
- -

Veri Tipleri

- -

Son ECMAScript standartları 7 veri tipi tanımlar:

- - - -

İlkel (Primitive)  değerler

- -

Nesne dışındaki bütün veri tipleri sonradan değiştirilemez değerler tanımlar. Örnek olarak C dilinin tersine karakter dizileri (String) değiştirilemez. Bu tipteki değerler ilkel değerler (primitive values) olarak tanımlanır.

- -

Boolean tipi

- -

Boolean veri tipi doğru ( true ) ve yanlış ( false ) olmak üzere iki mantıksal değerden birine sahip olan veri tiplerini temsil eder.

- -

Null tipi

- -

Boş olan değişkenlerin alabiileceği tek değer vardır: null. Daha fazla detay için buraya bakınız {{jsxref("null")}} and {{Glossary("Null")}}.

- -

Undefined tipi

- -

Herhangi bir değer atanmamış değişkenlerin değeri undefined (tanımlanmamış)dır. Daha fazla detay için buraya {{jsxref("undefined")}}  ve buraya {{Glossary("Undefined")}} bakınız.

- -

Number type

- -

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (numbers between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

- -

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

- -

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

- -
> 42 / +0
-Infinity
-> 42 / -0
--Infinity
-
- -

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

- -

String type

- -

JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

- -

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

- - - -

Beware of "stringly-typing" your code!

- -

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

- - - -

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

- -

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

- -

Symbol type

- -

Symbols are new to JavaScript in ECMAScript 2015. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

- -

Objects

- -

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

- -

Properties

- -

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

- -

There are two types of object properties which have certain attributes: The data property and the accessor property.

- -

Data property

- -

Associates a key with a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted, can't be changed to an accessor property and attributes other than [[Value]] and [[Writable]] can't be changed.false
- - - - - - - - - - - - - - - - - - - - - - - - - -
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
- -

Accessor property

- -

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get.undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set.undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
- -
-

Note: Attribute is usually used by JavaScript engine, so you can't directly access it (see more about Object.defineProperty()). That's why the attribute is put in double square brackets instead of single.

-
- -

"Normal" objects, and functions

- -

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

- -

Functions are regular objects with the additional capability of being callable.

- -

Dates

- -

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

- -

Indexed collections: Arrays and typed Arrays

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

- -

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

- -

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

- -

Determining types using the typeof operator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES2015')}}Added Symbol.
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}}
- -

See also

- - diff --git a/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html b/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html deleted file mode 100644 index ba35caf1d9..0000000000 --- a/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html +++ /dev/null @@ -1,420 +0,0 @@ ---- -title: Kontrol akışı ve hata yakalama -slug: Web/JavaScript/Guide/Control_flow_and_error_handling -tags: - - Başlangıç - - JavaScript - - Rehberi -translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling -original_slug: Web/JavaScript/Guide/Ifadeler ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
- -

JavaScript, uygulamanızın etkilişim halinde olmasını sağlayan kontrol akışı ifadeleri gibi birçok ifadeyi destekler. Bu bölümde, bu ifadeler üzerine durulacaktır.

- -

En basit olarak anlatmak gerekirse, JavaScript tarafından çalıştırılacak her komuta ifade adı verilir. Noktalı virgül (;) karakteri ise, JavaScript kodundaki ifadelerin birbirinden ayrılması için kullanılmaktadır.

- -

Blok ifadesi

- -

En temel ifade türü, ifadelerin gruplanmasını sağlayan blok ifadesidir. Blok ifadesi,  bir çift süslü parantezle sınırlandırılır:

- -
{ ifade_1; ifade_2; . . . ifade_n; }
-
- -

Örnek

- -

Blok ifadeleri genellikle kontrol akışı ifadeleri ile birlikte kullanılır (örn: if, for, while).

- -
while (x < 10) {
-  x++;
-}
-
- -

Buradaki, { x++; } bir blok ifadesidir.

- -

Önemli: ECMAScript2015'ten önceki JavaScript'te blok etki alanı bulunmamaktadır. Blok içerisinde yer alan değişkenlerin etki alanı, onları içeren fonksiyon veya .js dosyası kadar geniş bir alanı kapsar, ve bu değişkenler üzerinde yapılan değişiklikler bloğun ötesinde de kalıcılık gösterir. Başka bir deyişle blok ifadeleri, değişkenler için bir etki alanı oluşturmazlar. C ve Java dilinden aşina olduğunuz değişkenden bağımsız blok ifadeleri, JavaScript'te tamamıyla farklı bir davranış sergileyebilirler. Aşağıdaki örneği inceleyelim:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // Ekrandaki çıktı: 2
-
- -

Kodun çıktısı 2 olacaktır. Çünkü blok içerisindeki var x ifadesi  ile bloktan önce gelen var x ifadesi aynı etki alanı içerisindedir. Eğer üstteki kod C veya Java dilinde olsaydı, ekrandaki çıktı 1 olacaktı.

- -

ECMAScript 6 ile birlikte gelen let tanımıyla oluşturulan değişkenler, blok seviyesinde etki alanına sahiptir. Daha fazla bilgi için {{jsxref("Statements/let", "let")}} sayfasına bakınız.

- -

Koşullu ifadeler

- -

Belirli bir koşul sağlandığında çalışacak komutlar kümesine koşullu ifade denilir. JavaScript, iki adet koşullu ifadeyi destekler: if...else ve switch.

- -

if...else ifadesi

- -

Belirli bir mantıksal durum sağlandığında bir ifadenin çalıştırılması için if ifadesi kullanılır. Mantıksal durum sağlanmadığında çalıştırılacak komutlar için ise else kelimesi kullanıılabilir. Bir if ifadesi aşağıdaki şekilde oluşturulur:

- -
if (mantıksal_durum) {
-  ifade_1;
-} else {
-  ifade_2;
-}
- -

mantıksal_durum, true veya false değerler alabilen herhangi bir ifade olabilir. Eğer mantıksal_durum, true olursa ifade_1 çalışacak; aksi halde, ifade_2 is çalışacaktır. ifade_1 ve ifade_2 ifadeleri, çalıştırılacak herhangi bir ifade olabilir.

- -

Birçok mantıksal durumun kontrolünün bütün bir halde yapılabilmesi için aşağıdaki şekilde else if tanımlamalarını kullanabilirsiniz.

- -
if (mantıksal_durum_1) {
-  ifade_1;
-} else if (mantıksal_durum_2) {
-  ifade_2;
-} else if (mantıksal_durum_n) {
-  ifade_n;
-} else {
-  ifade_son;
-}
-
- -

Üstteki gibi çoklu mantıksal durumların olduğu ifadelerde,  yalnızca true olan ilk mantıksal durum çalıştırılır, ilişkili diğer kontrol ifadeleri çalıştırılmaz. Birçok ifadenin çalıştırılması için ifadeler, blok ifadesi ({ ... }) içerisinde gruplandırılır. Özellikle iç içe if ifadelerinin olduğu durumlar başta olmak üzere blok ifadeleri, geliştiriciler arasında yaygın olarak kullanılmaktadır:

- -
if (mantıksal_durum) {
-  eğer_durum_true_ise_çalışacak_ifade_1;
-  eğer_durum_true_ise_çalışacak_ifade_2;
-} else {
-  eğer_durum_false_ise_çalışacak_ifade_3;
-  eğer_durum_false_ise_çalışacak_ifade_4;
-}
-
- -
mantıksal_durum kısmında herhangi bir değişkene değer atamak yanlış bir kullanımdır, çünkü kodunuza sizden sonra bakan biri atama işlemini ilk bakışta eşitlik olarak görebilir. Örneğin aşağıdaki şekilde bir kullanım yanlıştır:
- -
- -
if (x = y) {
-  /* diğer ifadeler */
-}
-
- -

Eğer mantıksal_durum kısmında gerçekten atama yapmanız gerekiyorsa, bunu yapmanın en iyi yolu atama ifadesini parantezler içerisine almaktır. Örneğin:

- -
if ((x = y)) {
-  /* diğer ifadeler */
-}
-
- -

Yanlışımsı (falsy) değerler

- -

Aşağıdaki değerler JavaScript tarafından false olarak değerlendirilir ve ({{Glossary("Falsy")}} değerler olarak bilinir):

- - - -

Mantıksal durum içerisine alınan diğer bütün değerler ve nesneler, JavaScript tarafından true olarak değerlendirilir.

- -

{{jsxref("Boolean")}} nesnesindeki true ve false ile ilkel tipteki true ve false değerlerini karıştırmayınız. Örneğin:

- -
var b = new Boolean(false);
-if (b) // bu ifade true olarak değerlendirilir
-
- -

Örnek

- -

Aşağıdaki örnekte bulunan checkData fonksiyonu, HTML dokümanındaki formda yer alan ikiKarakter isimli girdi nesnesine ait değerin, karakter sayısı 2 ise true döndürülür, değilse ekrana bir uyarı metni basılır ve false döndürülür:

- -
function checkData() {
-  if (document.form1.ikiKarakter.value.length == 2) {
-    return true;
-  } else {
-    alert("Tam olarak iki karakter giriniz. " +
-    document.form1.ikiKarakter.value + " geçersizdir.");
-    return false;
-  }
-}
-
- -

switch ifadesi

- -

Bir switch ifadesine, mantıksal bir ifade verilir ve bu ifade ile eşleşen bir etiket varsa, etiketi içeren case ifadesi çalıştırılır, yoksa varsayılan ifade (default) çalıştırılır. Örnek:

- -
switch (mantıksal_ifade) {
-  case etiket_1:
-    ifadeler_1
-    [break;]
-  case etiket_2:
-    ifadeler_2
-    [break;]
-    ...
-  default:
-    varsayılan_ifadeler
-    [break;]
-}
-
- -

Üstteki kodu çalıştırırken JavaScript, mantıksal_ifade ile eşleşen etikete sahip case cümleciğini arar ve ilişkili ifadeleri çalıştırır. Eğer eşleşen hiçbir etiket bulunamadıysa, default cümleciğinin olup olmadığına bakar, varsa ve ilgili varsayılan ifadeleri çalıştırır. Eğer default cümleciği de yoksa, switch bloğundan çıkılır.  default cümleciğinin sırası önemli olmamakla birlikte, genel kullanımlarda hep en sonda yer almaktadır.

- -

Her case cümleciğinde, isteğe bağlı olarak konulan break ifadesi,  eşleşen ifadenin çalıştırılıp tamamlandıktan sonra switch bloğundan çıkmayı sağlar. Eğer break ifadesi yazılmazsa, program switch ifadesi içerisindeki bir sonraki case ifadesini çalıştırarak yoluna devam eder. 

- -

Örnek

- -

Aşağıdaki örnekte, meyve ifadesinin değeri "Muz" ise,  program "Muz" değeri ile eşleşen case "Muz" ifadesini çalıştırır. break ile karşılaşıldığında, program switch bloğundan çıkar ve switch bloğundan sonraki kodları çalıştırır. Eğer break ifadesi olmasaydı, "Muz" ile alakasız olan, case "Kiraz" ifadesi de çalıştırılacaktı.

- -
switch (meyve) {
-  case "Portakal":
-    console.log("Portakalların kilosu ₺1.99 lira.");
-    break;
-  case "Elma":
-    console.log("Elmaların kilosu ₺1.49 lira.");
-    break;
-  case "Muz":
-    console.log("Muzların kilosu ₺2.49 lira.");
-    break;
-  case "Kiraz":
-    console.log("Kirazların kilosu ₺2.19 lira.");
-    break;
-  case "Çilek":
-    console.log("Çileklerin kilosu ₺2.49 lira.");
-    break;
-  case "Avokado":
-    console.log("Avokadoların kilosu ₺5.99 lira.");
-    break;
-  default:
-   console.log("Maalesef elimizde hiç " + meyve + " kalmadı.");
-}
-console.log("Başka bir şey lazım mı?");
- -

Exception (Hata) yakalama ifadeleri

- -

throw ifadesi ile exception fırlatabilir, try...catch ifadeleri kullanarak hata yakalama işlemlerinizi yürütebilirsiniz.

- - - -

Exception türleri

- -

JavaScript'te neredeyse her nesne fırlatılabilir. Buna rağmen fırlatılacak türdeki nesnelerin hepsi aynı şekilde oluşturulmamışlardır. Sayı ve string değerlerinin hata olarak fırlatılması oldukça yaygın olmasına rağmen, bu amaç için belirli olarak  oluşturulan aşağıdaki exception türlerinden birinin kullanılması daha anlamlıdır:

- - - -

throw ifadesi

- -

Bir exception fırlatmak için throw ifadesini kullanılır. Bir exception fırlattığınız zaman, fırlatılacak ifadeyi de belirlersiniz:

- -
throw ifade;
-
- -

Herhangi bir türdeki ifadeyi exception olarak fırlatabilirsiniz. Aşağıdaki kodda çeşitli türlerdeki exception'lar fırlatılmaktadır:

- -
throw "Hata2";   // String türü
-throw 42;         // Sayı türü
-throw true;       // Boolean türü
-throw { toString: function() { return "Ben bir nesneyim."; } };
-
- -
Not: Bir exception fırlatırken ilgili exception nesnesini belirleyebilirsiniz. Daha sonra catch bloğunda hatayı yakaladığınızda ilgili exception nesnesinin özelliklerine erişebilirsiniz. Aşağıdaki ifadede, KullanıcıHatası sınıfından bir nesne oluşturulmakta, ve throw ifadesinde bu nesne fırlatılmaktadır.
- -
// KullanıcıHatası türünde nesne oluşturuluyor
-function KullanıcıHatası(mesaj){
-  this.mesaj=mesaj;
-  this.adı="KullanıcıHatası";
-}
-
-// Oluşturulan KullanıcıHatası nesnesinin konsola yazıldığında güzel bir
-// ifade yazılması için aşağıdaki şekilde toString() fonksiyonunu override ediyoruz.
-KullanıcıHatası.prototype.toString = function () {
-  return this.adı+ ': "' + this.mesaj+ '"';
-}
-
-// KullanıcıHatası nesnesi yaratılır ve exception olarak fırlatılır
-throw new KullanıcıHatası("Yanlış bir değer girdiniz.");
- -

try...catch ifadesi

- -

try...catch ifadesi, çalıştırılması istenen ifadeleri bir blokta tutar. Fırlatılacak exception için bir veya daha fazla ifade belirlenerek, oluşacak bir try...catch ifadesi tarafından yakalanması sağlanır.

- -

try...catch ifadesi, çalıştırılacak bir veya daha fazla komutun yer aldığı, ve try bloğu içerisinde hata oluştuğunda çalışacak ifadeleri içeren, 0 veya daha fazla catch ifadesinin yer aldığı bir try bloğu içerir. Bu şekilde, try içerisinde yer alan başarıyla çalışmasını istediğiniz kodlarda bir sorun oluştuğunda, catch bloğunda bu sorunun üstesinden gelecek kontrolleri yazabilirsiniz. Eğer try bloğu içerisindeki herhangi bir ifade (veya try bloğu içerisinden çağırılan fonksiyon) bir exception fırlatırsa, JavaScript anında catch bloğuna bakar. Eğer try bloğu içerisinde bir exception fırlatılmazsa, catch bloğu çalıştırılmaz ve atlanır. try ve catch bloklarından sonra, eğer varsa finally bloğu da çalıştırılır.

- -

Aşağıdaki örnekte bir try...catch ifadesi kullanılmaktadır. Fonksiyonda, parametre olarak geçilen ay sayısı değeri baz alınarak, diziden ilgili ayın adı getirilmektedir. Eğer ay sayısı değeri 1-12 arasında değilse, "Geçersiz ay sayısı." değeri exception olarak fırlatılır. catch bloğundaki ayAdı değişkeni de "bilinmeyen" olarak atanır.

- -
function getAyAdı(aySayisi) {
-  aySayisi= aySayisi-1; // Dizi indeksi için aySayisi 1 azaltılır (1=Oca, 12=Ara)
-  var aylar= ["Oca","Şub","Mar","Nis","May","Haz","Tem",
-                "Ağu","Eyl","Eki","Kas","Ara"];
-  if (aylar[aySayisi] != null) {
-    return aylar[aySayisi];
-  } else {
-    throw "Geçersiz ay sayısı."; // burada throw ifadesi kullanılıyor
-  }
-}
-
-try { // denenecek ifadeler
-  ayAdı = getAyAdı(aySayim); // function could throw exception
-}
-catch (e) {
-  ayAdı = "bilinmiyor";
-  hatalarımıKaydet(e); // hataların kaydedilmesi için exception nesnesi geçiliyor.
-}
-
- -

catch bloğu

- -

try bloğunda oluşturulan tüm exception'ların yakalanması için catch bloğunu kullanabilirsiniz.

- -
catch (exceptionDeğişkeni) {
-  ifadeler
-}
-
- -

catch bloğunda, throw ifadesi tarafından belirlenecek değerin tutulması için bir değişken tanımlanır; bu değişken kullanılarak, fırlatılan exception ile ilgili bilgiler elde edilmiş olur. catch bloğuna girildiğinde JavaScript, bu değişkenin içini doldurur; değişken değeri sadece catch bloğu süresince geçerli kalır; catch bloğu çalışmasını tamamladığında değişken artık mevcut değildir.

- -

Örneğin aşağıdaki kodda, bir exception fırlatılıyor, ve fırlatıldığı anda otomatik olarak catch bloğuna iletiliyor.

- -
try {
-  throw "hata" // bir exception oluşturur.
-}
-catch (e) {
-  // herhangi bir exception'ı yakalamak için oluşturulan ifadeler
-  hatalarımıKaydet(e) // hataların kaydedilmesi için exception nesnesi geçilir.
-}
-
- -

finally bloğu

- -

finally bloğu, try...catch ifadesinden sonra çalıştırılacak kod satırlarını içerir. finally bloğu, hata olsun veya olmasın çalışır. Eğer hata olmuşsa ve exception fırlatılmışsa, bu hatayı karşılayacak catch bloğu olmasa dahi finally bloğu çalışır. 

- -

finally bloğu, hata oluştuğunda bu hataya sebep olan değişkenin kullandığı kaynakların sisteme geri verilmesi için en iyi yerdir. Bu şekilde hata tüm ayrıntılarıyla çözülmüş olur. Aşağıdaki örnekte bir dosya açılmakta, ve sonrasında dosyaya yazma işlemleri için kullanan ifadeler çalıştırılmaktadır (Sunucu taraflı yazılmış koddur. İstemci tarafında dosyaya yazma işlemleri güvenlik açısından engellenmiştir. Eğer dosya, yazmak için açılırken bir exception fırlatılırsa, kod hata vermeden önce finally bloğu çalışır ve erişilecek dosyayı kapatır.

- -
dosyaAç();
-try {
-  dosyayaYaz(veriler); // Bu kısım hata verebilir
-} catch(e) {
-  hatayıKaydetveGöster(e); // Hata ile ilgili bilgiler kaydedilir ve kullanıcıya bir hata mesajı sunulur.
-} finally {
-  dosyayıKapat(); // Dosyayı kapatır (hata olsa da olmasa da).
-}
-
- -

Eğer finally bloğu bir değer geri döndürürse,  bu değer, try ve catch içerisindeki return ifadelerine bakmaksızın, try-catch-finally ifadesinin tamamı için geri dönüş değeri haline gelir:

- -
function f() {
-  try {
-    console.log(0);
-    throw "hata";
-  } catch(e) {
-    console.log(1);
-    return true; // Buradaki return ifadesi,
-                 // finally bloğu tamamlanana dek duraklatılır.
-    console.log(2); // Üstteki return ifadesinden dolayı çalıştırılmaz.
-  } finally {
-    console.log(3);
-    return false; // catch kısmındaki return ifadesinin üstüne yazar ve geçersiz hale getirir.
-    console.log(4); // return'den dolayı çalıştırılmaz.
-  }
-  // Şimdi "return false" ifadesi çalıştırılır ve fonksiyondan çıkılır.
-  console.log(5); // Çalıştırılmaz.
-}
-f(); // Konsola 0 1 3 yazar ve false değerini döndürür.
-
- -

finally bloğunun, geri dönüş değerlerinin üstüne yazma etkisi, aynı zamanda catch bloğu içerisindeki exception'lar için de aynı şekilde çalışır:

- -
function f() {
-  try {
-    throw "hata";
-  } catch(e) {
-    console.log('İçerideki "hata" yakalandı.');
-    throw e; // Burası finally bloğu tamamlanana dek duraklatılır.
-  } finally {
-    return false; // Önceki "throw" ifadesinin üstüne yazar ve
-                  //  throw ifadesini geçersiz hale getirir.
-  }
-  // Şimdi "return false" ifadesi çalıştırılır.
-}
-
-try {
-  f();
-} catch(e) {
-  // f() fonksiyonundaki throw ifadesi geçersiz hale geldiği için
-  //  buradaki catch bloğu çalıştırılmaz.
-  console.log('Diğer "hata" yakalandı.');
-}
-
-// Ekran çıktısı: İçerideki "hata" yakalandı.
- -

İçiçe try...catch ifadeleri

- -

Bir veya daha fazla iç içe try...catch ifadeleri tanımlayabilirsiniz. Eğer içteki try...catch ifadesinin catch bloğu yoksa, bir dıştaki try...catch ifadesinin catch bloğu kontrol edilir.

- -

Error nesnelerinin etkili kullanımı

- -

Error nesnesinin türüne bağlı olarak,  'name' ve 'message' özellikleri vasıtasıyla daha anlamlı hata mesajları tanımlayabilirsiniz. 'name' özelliği, oluşan hatayı sınıflandırır (örn, 'DOMException' veya 'Error'). 'message' ise hata nesnesinin string'e dönüştürülmesine nazaran  genellikle daha kısa bir mesaj sunulmasına olanak tanır.

- -

Eğer kendi exception nesnelerinizi fırlatıyorsanız ve bu özellikleri kullanarak hatayı anlamlı hale getirmek istiyorsanız Error sınıfının yapıcısının getirdiği avantajlardan faydalanabilirsiniz (örneğin catch bloğunuzun, kendi exception'larınız ile sistem exception'ları arasındaki farkı ayırt edemediği gibi durumlarda). Aşağıdaki örneği inceleyelim:

- -
function hatayaMeyilliFonksiyon() {
-  if (hataVerenFonksiyonumuz()) {
-    throw (new Error('Hata oluştu'));
-  } else {
-    sistemHatasıVerenFonksiyon();
-  }
-}
-
-try {
-  hatayaMeyilliFonksiyon();
-}
-catch (e) {
-  console.log(e.name); // 'Error' yazar
-  console.log(e.message); // 'Hata oluştu' veya bir JavaScript hata mesajı yazar
-}
- -

Promise nesneleri

- -

ECMAScript2015 ile birlikte JavaScript'e, asenkron ve geciktirilmiş işlemlerin akış kontrolünün sağlanması için {{jsxref("Promise")}} nesneleri gelmiştir.

- -

Bir Promise nesnesi aşağıdaki durumlardan birinde bulunur:

- - - -

- -

XHR ile resim yükleme

- -

Promise ve XMLHttpRequest kullanarak bir resmin yüklenmesi için MDN GitHub promise-test sayfasında basit bir örnek mevcuttur. Ayrıca örneği canlı olarak da görebilirsiniz. Örnekteki her aşamaya yorum satırları eklenmiştir. Bu sayede Promise ve XHR mimarisini daha yakından izleyebilirsiniz. Aşağıda Promise nesnesinin akışını gösteren örneğin belgelendirilmemiş sürümü bulunmaktadır:

- -
function resimYükle(url) {
-  return new Promise(function(başarıSonucundaFonk, hataSonucundaFonk) {
-    var istek = new XMLHttpRequest();
-    istek.open('GET', url);
-    istek.responseType = 'blob';
-    istek.onload = function() {
-      if (istek.status === 200) {
-        başarıSonucundaFonk(istek.cevabı);
-      } else {
-        hataSonucundaFonk(Error('Resim yüklenemedi; hata kodu:'
-                     + istek.hataKodu));
-      }
-    };
-    istek.onerror = function() {
-      hataSonucundaFonk(Error('Bir bağlantı hatası oluştu.'));
-    };
-    istek.send();
-  });
-}
- -

Daha fazla detaylı bilgi için {{jsxref("Promise")}} sayfasına bakınız.

- -
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git a/files/tr/web/javascript/guide/details_of_the_object_model/index.html b/files/tr/web/javascript/guide/details_of_the_object_model/index.html deleted file mode 100644 index 160959eda2..0000000000 --- a/files/tr/web/javascript/guide/details_of_the_object_model/index.html +++ /dev/null @@ -1,758 +0,0 @@ ---- -title: Details of the object model -slug: Web/JavaScript/Guide/Details_of_the_Object_Model -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
- -

JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.

- -

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.

- -

Class-based vs. prototype-based languages

- -

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

- - - -

A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

- -

Defining a class

- -

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

- -

JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

- -
-

Note that ECMAScript 2015 introduces a class declaration:

- -
-

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

-
-
- -

Subclasses and inheritance

- -

In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only the name and dept properties, and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

- -

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the EmployeeManager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, calling the Employee constructor and specifying the reports property. Finally, you assign a new object derived from Employee.prototype as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

- -

Adding and removing properties

- -

In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

- -

Summary of differences

- -

The following table gives a short summary of some of these differences. The rest of this chapter describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Comparison of class-based (Java) and prototype-based (JavaScript) object systems
CategoryClass-based (Java)Prototype-based (JavaScript)
Class vs. InstanceClass and instance are distinct entities.Tüm nesneler başka bir nesneden miras alabilir.
DefinitionDefine a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Creation of new objectnew operatörü ile tek bir nesne oluşturulur.Aynı.
Construction of object hierarchyConstruct an object hierarchy by using class definitions to define subclasses of existing classes. -

Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.

-
Inheritance modelInherit properties by following the class chain.Inherit properties by following the prototype chain.
Extension of propertiesClass definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
- -

The employee example

- -

The remainder of this chapter uses the employee hierarchy shown in the following figure.

- -
-
-

A simple object hierarchy with the following objects:

- -

-
- -
-
    -
  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • -
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • -
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • -
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • -
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".
  • -
-
-
- -

Creating the hierarchy

- -

There are several ways to define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application.

- -

This section shows how to use very simple (and comparatively inflexible) definitions to demonstrate how to get the inheritance to work. In these definitions, you cannot specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time.

- -

In a real application, you would probably define constructors that allow you to provide property values at object creation time (see More flexible constructors for information). For now, these simple definitions demonstrate how the inheritance occurs.

- -

The following Java and JavaScript Employee definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a strongly typed language while JavaScript is a weakly typed language).

- -
-

JavaScript

- -
function Employee() {
-  this.name = '';
-  this.dept = 'general';
-}
-
- -


- Java

- -
public class Employee {
-   public String name = "";
-   public String dept = "general";
-}
-
-
- -

The Manager and WorkerBee definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function, then override the prototype.constructor to the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

- -
-

JavaScript

- -
function Manager() {
-  Employee.call(this);
-  this.reports = [];
-}
-Manager.prototype = Object.create(Employee.prototype);
-Manager.prototype.constructor = Manager;
-
-function WorkerBee() {
-  Employee.call(this);
-  this.projects = [];
-}
-WorkerBee.prototype = Object.create(Employee.prototype);
-WorkerBee.prototype.constructor = WorkerBee;
-
- -


- Java

- -
public class Manager extends Employee {
-   public Employee[] reports =
-       new Employee[0];
-}
-
-
-
-public class WorkerBee extends Employee {
-   public String[] projects = new String[0];
-}
-
-
-
-
- -

 

- -

The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

- -
-

JavaScript

- -
function SalesPerson() {
-   WorkerBee.call(this);
-   this.dept = 'sales';
-   this.quota = 100;
-}
-SalesPerson.prototype = Object.create(WorkerBee.prototype);
-SalesPerson.prototype.constructor = SalesPerson;
-
-function Engineer() {
-   WorkerBee.call(this);
-   this.dept = 'engineering';
-   this.machine = '';
-}
-Engineer.prototype = Object.create(WorkerBee.prototype)
-Engineer.prototype.constructor = Engineer;
-
- -


- Java

- -
public class SalesPerson extends WorkerBee {
-   public String dept = "sales";
-   public double quota = 100.0;
-}
-
-
-public class Engineer extends WorkerBee {
-   public String dept = "engineering";
-   public String machine = "";
-}
-
-
-
- -

Using these definitions, you can create instances of these objects that get the default values for their properties. The next figure illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

- -
-

Note: The term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

-
- -

Creating objects with simple definitions

- -
-

Object hierarchy

- -

The following hierarchy is created using the code on the right side.

- -

- -

 

- -

Individual objects = Jim, Sally, Mark, Fred, Jane, etc.
- "Instances" created from constructor

- -
var jim = new Employee;
-// Parentheses can be omitted if the
-// constructor takes no arguments.
-// jim.name is ''
-// jim.dept is 'general'
-
-var sally = new Manager;
-// sally.name is ''
-// sally.dept is 'general'
-// sally.reports is []
-
-var mark = new WorkerBee;
-// mark.name is ''
-// mark.dept is 'general'
-// mark.projects is []
-
-var fred = new SalesPerson;
-// fred.name is ''
-// fred.dept is 'sales'
-// fred.projects is []
-// fred.quota is 100
-
-var jane = new Engineer;
-// jane.name is ''
-// jane.dept is 'engineering'
-// jane.projects is []
-// jane.machine is ''
-
-
- -

Object properties

- -

This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.

- -

Inheriting properties

- -

Suppose you create the mark object as a WorkerBee with the following statement:

- -
var mark = new WorkerBee;
-
- -

When JavaScript sees the new operator, it creates a new generic object and implicitly sets the value of the internal property [[Prototype]] to the value of WorkerBee.prototype and passes this new object as the value of the this keyword to the WorkerBee constructor function. The internal [[Prototype]] property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

- -

This process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the internal [[Prototype]] property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the mark object has the following properties and values:

- -
mark.name = '';
-mark.dept = 'general';
-mark.projects = [];
-
- -

The mark object is assigned local values for the name and dept properties by the Employee constructor. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

- -

Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

- -
mark.name = 'Doe, Mark';
-mark.dept = 'admin';
-mark.projects = ['navigator'];
- -

Adding properties

- -

In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:

- -
mark.bonus = 3000;
-
- -

Now, the mark object has a bonus property, but no other WorkerBee has this property.

- -

If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

- -
Employee.prototype.specialty = 'none';
-
- -

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

- -


- Adding properties

- -

More flexible constructors

- -

The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.

- -


- Specifying properties in a constructor, take 1

- -

The following table shows the Java and JavaScript definitions for these objects.

- -
-

JavaScript

- -

Java

-
- -
-
function Employee(name, dept) {
-  this.name = name || '';
-  this.dept = dept || 'general';
-}
-
- -

 

- -

 

- -

 

- -

 

- -

 

- -
public class Employee {
-   public String name;
-   public String dept;
-   public Employee () {
-      this("", "general");
-   }
-   public Employee (String name) {
-      this(name, "general");
-   }
-   public Employee (String name, String dept) {
-      this.name = name;
-      this.dept = dept;
-   }
-}
-
-
- -
-
function WorkerBee(projs) {
-
- this.projects = projs || [];
-}
-WorkerBee.prototype = new Employee;
-
- -

 

- -

 

- -

 

- -
public class WorkerBee extends Employee {
-   public String[] projects;
-   public WorkerBee () {
-      this(new String[0]);
-   }
-   public WorkerBee (String[] projs) {
-      projects = projs;
-   }
-}
-
-
- -
-
-function Engineer(mach) {
-   this.dept = 'engineering';
-   this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-
- -

 

- -

 

- -

 

- -
public class Engineer extends WorkerBee {
-   public String machine;
-   public Engineer () {
-      dept = "engineering";
-      machine = "";
-   }
-   public Engineer (String mach) {
-      dept = "engineering";
-      machine = mach;
-   }
-}
-
-
- -

These JavaScript definitions use a special idiom for setting default values:

- -
this.name = name || '';
-
- -

The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

- -
-

Note: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

-
- -

With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. You can use the following statement to create a new Engineer:

- -
var jane = new Engineer('belau');
-
- -

Jane's properties are now:

- -
jane.name == '';
-jane.dept == 'engineering';
-jane.projects == [];
-jane.machine == 'belau';
-
- -

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

- -

So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.

- -


- Specifying properties in a constructor, take 2

- -

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -

Suppose you create a new Engineer object as follows:

- -
var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-
- -

JavaScript follows these steps:

- -
    -
  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. -
  3. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  4. -
  5. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object. The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  6. -
  7. The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.
  8. -
  9. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  10. -
  11. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  12. -
  13. Upon return from the constructor, JavaScript assigns the new object to the jane variable.
  14. -
- -

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-Employee.prototype.specialty = 'none';
-
- -

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

- -
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-var jane = new Engineer('Doe, Jane', ['navigator', 'javascript'], 'belau');
-Employee.prototype.specialty = 'none';
-
- -

Now the value of the jane object's specialty property is "none".

- -

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

- -
-
function Engineer(name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
- -
function Engineer(name, projs, mach) {
-  WorkerBee.call(this, name, 'engineering', projs);
-  this.machine = mach || '';
-}
-
-
- -

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

- -

Property inheritance revisited

- -

The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.

- -

Local versus inherited values

- -

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

- -
    -
  1. Check to see if the value exists locally. If it does, return that value.
  2. -
  3. If there is not a local value, check the prototype chain (using the __proto__ property).
  4. -
  5. If an object in the prototype chain has a value for the specified property, return that value.
  6. -
  7. If no such property is found, the object does not have the property.
  8. -
- -

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

- -
function Employee() {
-  this.name = '';
-  this.dept = 'general';
-}
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
- -

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

- -
var amy = new WorkerBee;
-
- -

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so derive from the amy object's __proto__ property. Thus, amy has these property values:

- -
amy.name == '';
-amy.dept == 'general';
-amy.projects == [];
-
- -

Now suppose you change the value of the name property in the prototype associated with Employee:

- -
Employee.prototype.name = 'Unknown';
-
- -

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

- -

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look further up the chain to Employee.prototype.

- -

If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:

- -
function Employee() {
-  this.dept = 'general';    // Note that this.name (a local variable) does not appear here
-}
-Employee.prototype.name = '';    // A single copy
-
-function WorkerBee() {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-var amy = new WorkerBee;
-
-Employee.prototype.name = 'Unknown';
-
- -

In this case, the name property of amy becomes "Unknown".

- -

As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.

- -

Determining instance relationships

- -

Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property __proto__. This continues recursively; the process is called "lookup in the prototype chain".

- -

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

- -

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

- -
var f = new Foo();
-var isTrue = (f instanceof Foo);
- -

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

- -
var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji');
-
- -

With this object, the following statements are all true:

- -
chris.__proto__ == Engineer.prototype;
-chris.__proto__.__proto__ == WorkerBee.prototype;
-chris.__proto__.__proto__.__proto__ == Employee.prototype;
-chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
-chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
-
- -

Given this, you could write an instanceOf function as follows:

- -
function instanceOf(object, constructor) {
-   object = object.__proto__;
-   while (object != null) {
-      if (object == constructor.prototype)
-         return true;
-      if (typeof object == 'xml') {
-        return constructor.prototype == XML.prototype;
-      }
-      object = object.__proto__;
-   }
-   return false;
-}
-
- -
Note: The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See {{ bug(634150) }} if you want the nitty-gritty details.
- -

Using the instanceOf function defined above, these expressions are true:

- -
instanceOf(chris, Engineer)
-instanceOf(chris, WorkerBee)
-instanceOf(chris, Employee)
-instanceOf(chris, Object)
-
- -

But the following expression is false:

- -
instanceOf(chris, SalesPerson)
-
- -

Global information in constructors

- -

When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for Employee:

- -
var idCounter = 1;
-
-function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   this.id = idCounter++;
-}
-
- -

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

- -
var victoria = new Employee('Pigbert, Victoria', 'pubs');
-var harry = new Employee('Tschopik, Harry', 'sales');
-
- -

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

- -
var idCounter = 1;
-
-function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   this.id = idCounter++;
-}
-
-function Manager(name, dept, reports) {...}
-Manager.prototype = new Employee;
-
-function WorkerBee(name, dept, projs) {...}
-WorkerBee.prototype = new Employee;
-
-function Engineer(name, projs, mach) {...}
-Engineer.prototype = new WorkerBee;
-
-function SalesPerson(name, projs, quota) {...}
-SalesPerson.prototype = new WorkerBee;
-
-var mac = new Engineer('Wood, Mac');
-
- -

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

- -

Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:

- -
function Employee(name, dept) {
-   this.name = name || '';
-   this.dept = dept || 'general';
-   if (name)
-      this.id = idCounter++;
-}
-
- -

When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

- -

Alternatively, you can create a copy of Employee's prototype object to assign to WorkerBee:

- -
WorkerBee.prototype = Object.create(Employee.prototype);
-// instead of WorkerBee.prototype = new Employee
-
- -

No multiple inheritance

- -

Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

- -

Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

- -

In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

- -
function Hobbyist(hobby) {
-   this.hobby = hobby || 'scuba';
-}
-
-function Engineer(name, projs, mach, hobby) {
-   this.base1 = WorkerBee;
-   this.base1(name, 'engineering', projs);
-   this.base2 = Hobbyist;
-   this.base2(hobby);
-   this.machine = mach || '';
-}
-Engineer.prototype = new WorkerBee;
-
-var dennis = new Engineer('Doe, Dennis', ['collabra'], 'hugo');
-
- -

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

- -
dennis.name == 'Doe, Dennis';
-dennis.dept == 'engineering';
-dennis.projects == ['collabra'];
-dennis.machine == 'hugo';
-dennis.hobby == 'scuba';
-
- -

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

- -
Hobbyist.prototype.equipment = ['mask', 'fins', 'regulator', 'bcd'];
-
- -

The dennis object does not inherit this new property.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Using_promises")}}
diff --git a/files/tr/web/javascript/guide/functions/index.html b/files/tr/web/javascript/guide/functions/index.html deleted file mode 100644 index ff7638ebb5..0000000000 --- a/files/tr/web/javascript/guide/functions/index.html +++ /dev/null @@ -1,663 +0,0 @@ ---- -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 ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
- -

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.

- -

Daha fazla bilgi için JavaScript fonksiyonları ile ilgili buradaki detaylı kaynağı inceleyebilirsiniz.

- -

Fonksiyonların tanımlanması

- -

Fonksiyon tanımlamaları

- -

Bir fonksiyon tanımı (fonksiyon betimlemesi, veya fonksiyon ifadesi de denir)  function anahtar kelimesinden sonra aşağıdaki kısımları içerir:

- - - -

Örneğin aşağıdaki kodda karesiniAl isimli basit bir fonksiyon tanımlanmıştır:

- -
function karesiniAl(sayı) {
-  return sayı * sayı;
-}
-
- -

karesiniAl fonksiyonu, sayı isminde tek bir parametre içerir. Tek bir ifade içeren fonksiyonda, sayı parametresinin kendisi ile çarpılıp geri döndürülmesi işlemi yapılmıştır. return ifadesi, fonksiyon tarafından döndürülen değeri belirler.

- -
return sayı * sayı;
-
- -

Sayı türünde olduğu gibi ilkel parametreler fonksiyonlara değer ile geçilirler; 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.

- -

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:

- -
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)
-
- -

Fonksiyon ifadeleri

- -

Yukarıdaki fonksiyon tanımlaması sözdizimsel olarak bir ifade olmasına rağmen, fonksiyonlar ayrıca bir fonksiyon ifadesi ile de oluşturulabilirler. Böyle bir fonksiyon anonim olabilir; bir isme sahip olmak zorunda değildir. Örnek olarak, matematikteki kare alma fonksiyonu aşağıdaki şekilde tanımlanabilir:

- -
var karesiniAl = function(sayı) { return sayı * sayı };
-var x = karesiniAl(4) // x'in değeri 16 olur.
- -

Fonksiyon ifadesi ile belirtilen fonksiyon adı, fonksiyonun içerisinde kendisini çağıracak şekilde kullanılabilir:

- -
var faktoriyel = function fa(n) { return n < 2 ? 1 : n * fa(n-1) };
-
-console.log(faktoriyel(3));
-
- -

Fonksiyon ifadeleri, bir fonksiyon diğer fonksiyona parametre olarak geçilirken oldukça elverişlidir. Aşağıdaki örnekte map fonksiyonu tanımlanmış ve ilk parametresinde başka bir fonksiyonu parametre olarak almıştır:

- -
function map(f,d) {
-  var sonuç = [], // Yeni bir dizi
-      i;
-  for (i = 0; i != d.length; i++)
-    sonuç[i] = f(d[i]);
-  return sonuç;
-}
-
- -

Aşağıdaki kodda kullanımı mevcuttur:

- -
var çarpım = function(x) {return x * x * x}; // Fonksiyon ifadesi.
-map(çarpım, [0, 1, 2, 5, 10]);
-
- -

[0, 1, 8, 125, 1000] dizisini döndürür.

- -

JavaScript'te bir fonksiyon, herhangi bir duruma bağlı olarak oluşturulabilir.Örneğin aşağıdaki fonksiyonda benimFonk fonksiyonu, sayı değeri sadece 0'a eşit olursa tanımlanır:

- -
var benimFonk;
-if (sayı === 0){
-  benimFonk = function(araba) {
-    araba.marka = "Toyota"
-  }
-}
- -

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.

- -

Bir nesnenin özelliği olan fonksiyona metot adı verilir. Nesneler ve metotlar hakkında daha fazla bilgi için bkz: Nesneler ile çalışma.

- -

Fonksiyonları çağırma

- -

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 çağırmak, bu belirlenmiş eylemleri bizim o fonksiyona verdiğimiz parametrelerin de kullanılmasıyla gerçekleştirir.  Örneğin,  karesiniAl diye bir fonksiyon tanımladığınızda, o fonksiyonu aşağıdaki gibi çağırabilirsiniz:

- -
karesiniAl(5);
-
- -

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.

- -

Fonksiyonlar çağrıldıklarında bir alanda olmalıdılar, fakat fonksiyon bildirimi kaldırılabilir, örnekteki gibi:

- -
console.log(square(5));
-/* ... */
-function square(n) { return n * n }
-
- -

Bir fonksiyonun alanı, bildirilen işlevdir, veya tüm program üst seviyede bildirilmişse.

- -
-

Not:  Bu, yalnızca yukarıdaki sözdizimini (i.e. function benimFonk(){}) 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.

-
- -
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;
-}
-
- -

Bir fonksiyonun argümanları karakter dizileri ve sayılarla sınırlı değildir. Tüm nesneleri bir fonksiyona aktarabilirsiniz. show_props() fonksiyonu (Working with objects bölümünde tanımlanmıştır.) nesneyi argüman olarak alan bir fonksiyon örneğidir.

- -

Bir fonksiyon kendini çağırabilir. Örneğin, burada faktöriyelleri yinelemeli olarak hesaplayan bir fonksiyon var.

- -
function factorial(n){
-  if ((n === 0) || (n === 1))
-    return 1;
-  else
-    return (n * factorial(n - 1));
-}
-
- -

Daha sonra bir ile beş arasındaki faktöriyelleri şu şekilde hesaplayabilirsiniz:

- -
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
-
- -

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.

- -

Fonksiyon Kapsamı

- -

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.

- -
// 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"
- -

Kapsam ve fonksiyon yığını

- -

Yineleme

- -

Bir fonksiyon kendisine başvurabilir ve kendisini arayabilir. Bir işlevin kendisine başvurması için üç yol vardır:

- -

 

- -
    -
  1. fonksiyonun adı
  2. -
  3. arguments.callee
  4. -
  5. -

    fonksiyona başvuran bir kapsam içi değişken  

    -
  6. -
- -
-
-
-

Örneğin, aşağıdaki işlev tanımını göz önünde bulundurun:

-
-
-
- -

 

- -
var foo = function bar() {
-   // statements go here
-};
-
- -

Fonksiyon gövdesinde aşağıdakilerden hepsi eşdeğerdir.

- -
    -
  1. bar()
  2. -
  3. arguments.callee()
  4. -
  5. foo()
  6. -
- -

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ü:

- -
var x = 0;
-while (x < 10) { // "x < 10" is the loop condition
-   // do stuff
-   x++;
-}
-
- -

özyinelemeli bir fonksiyona ve bu fonksiyonun çağrısına dönüştürülebilir:

- -
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);
-
- -

Ancak, bazı algoritmalar basit yinelemeli döngüler olamaz. Örneğin, bir ağaç yapısının tüm düğümlerinin (örneğin DOM) alınması özyineleme kullanılarak daha kolay yapılır:

- -
function walkTree(node) {
-  if (node == null) //
-    return;
-  // do something with node
-  for (var i = 0; i < node.childNodes.length; i++) {
-    walkTree(node.childNodes[i]);
-  }
-}
-
- -

Fonksiyon döngüsü ile karşılaştırıldığında, her özyinelemeli çağrının kendisi burada birçok özyinelemeli çağrı yapar.

- -

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ı.

- -

Yığın benzeri davranış aşağıdaki örnekte görülebilir:

- -
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
- -

Nested functions and closures

- -

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. 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).

- -

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:

- -
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
-
- -

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

- -
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
-
- -

Preservation of variables

- -

Notice how x is preserved when inside 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 inside 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.

- -

Multiply-nested functions

- -

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 scope chaining. (Why it is called "chaining" will be explained later.)

- -

Consider the following example:

- -
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)
-
- -

In this example, C accesses B's y and A's x. This can be done because:

- -
    -
  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. -
  3. C forms a closure including B.
  4. -
  5. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.
  6. -
- -

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

- -

Name conflicts

- -

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. 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:

- -
function outside() {
-  var x = 10;
-  function inside(x) {
-    return x;
-  }
-  return inside;
-}
-result = outside()(20); // returns 20 instead of 10
-
- -

The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

- -

Closures

- -

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.

- -
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"
-
- -

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.

- -
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
-
- -

In the code above, the name 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.

- -
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
-
- -

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.

- -
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 ???
-    }
-  }
-}
-
- -

The magical this variable is very tricky in closures. They have to be used carefully, as what this refers to depends completely on where the function was called, rather than where it was defined.

- -

Using the arguments object

- -

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:

- -
arguments[i]
-
- -

where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

- -

Using the arguments 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 arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments 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:

- -
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;
-}
-
- -

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

- -
// 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");
-
- -
-

Note: The arguments variable is "array-like", but not an array. It is array-like in that is has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

-
- -

See the {{jsxref("Function")}} object in the JavaScript reference for more information.

- -

Function parameters

- -

Starting with ECMAScript 6, there are two new kinds of parameters: default parameters and rest parameters.

- -

Default parameters

- -

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

- -

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 undefined. If in the following example, no value is provided for b in the call, its value would be undefined  when evaluating a*b and the call to multiply would have returned NaN. However, this is caught with the second line in this example:

- -
function multiply(a, b) {
-  b = typeof b !== 'undefined' ?  b : 1;
-
-  return a*b;
-}
-
-multiply(5); // 5
-
- -

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

- -
function multiply(a, b = 1) {
-  return a*b;
-}
-
-multiply(5); // 5
- -

Fore more details, see default parameters in the reference.

- -

Rest parameters

- -

The rest parameter 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.

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(x => multiplier * x);
-}
-
-var arr = multiply(2, 1, 2, 3);
-console.log(arr); // [2, 4, 6]
- -

Arrow functions

- -

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "ES6 In Depth: Arrow functions".

- -

Two factors influenced the introduction of arrow functions: shorter functions and lexical this.

- -

Shorter functions

- -

In some functional patterns, shorter functions are welcome. Compare:

- -
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 ]
-
- -

Lexical this

- -

Until arrow functions, every new function defined its own this 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.

- -
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();
- -

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

- -
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);
-}
- -

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

- -

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Predefined functions

- -

JavaScript has several top-level, built-in functions:

- -
-
{{jsxref("Global_Objects/eval", "eval()")}}
-
-

The eval() method evaluates JavaScript code represented as a string.

-
-
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
-
-

The uneval() method creates a string representation of the source code of an {{jsxref("Object")}}.

-
-
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
-
-

The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.

-
-
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
-
-

The isNaN() function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.

-
-
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
-
-

The parseFloat() function parses a string argument and returns a floating point number.

-
-
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
-
-

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

-
-
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
-
-

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
-
-

The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
-
-

The encodeURI() 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).

-
-
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
-
-

The encodeURIComponent() 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).

-
-
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
-
-

The deprecated escape() 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.

-
-
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
-
-

The deprecated unescape() 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 unescape() is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.

-
-
- -

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}

diff --git a/files/tr/web/javascript/guide/grammar_and_types/index.html b/files/tr/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index a1619e77aa..0000000000 --- a/files/tr/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,640 +0,0 @@ ---- -title: Dil bilgisi ve türler -slug: Web/JavaScript/Guide/Grammar_and_types -tags: - - JavaScript - - Rehber -translation_of: Web/JavaScript/Guide/Grammar_and_types ---- -

{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

- -

Bu bölümde JavaScript'in temel dil bilgisi, değişken tanımları, veri türleri ve sabitleri üzerine değinilecektir.

- -

Temeller

- -

JavaScript çoğu söz dizimini Java'dan almıştır. Awk, Perl and Python'dan da etkilenmiştir.

- -

JavaScript büyük-küçük harfe duyarlıdır ve Unicode karakter setini kullanır.

- -

JavaScript'te, komutlara {{Glossary("Statement", "statements")}} denir ve noktalı virgül (;) ile ayrılırlar. Boşluklara, tablara ve satırbaşı karakterlerine whitespace denir. JavaScript betiklerinde, kaynak metin soldan sağa taranır ve token, kontrol karakterleri, satır sonlayıcıları, yorumlar ve whitespace gibi girdi elemanları dizisine dönüştürülür. ECMAScript, bazı kelimeleri ve sabitleri tanımlamıştır ayrıca noktalı virgül (;) karakterinin komut sonlarına otomatik olarak eklenmesi için kurallar belirlemiştir. Ancak kodda herhangi bir yan etki oluşturmaması için komut sonlarına her zaman noktalı virgül konması önerilir.  Daha fazla bilgi için JavaScript'in sözcük dil bilgisi hakkındaki başvurusuna bakınız.

- -

Yorumlar

- -

Yorumların söz dizimi C++ ve çoğu diğer dillerde olduğu şekilde aynıdır:

- -
// Tek satırlık yorum.
-
-/* *
- * Bu ise daha uzun,
- * çok satırlı yorum.
- */
-
-/* Ancak /* iç içe yorum */  konulması söz dizimi hatasına yol açar */
- -

Bildirimler

- -

JavaScript'te üç çeşit bildirim vardır:

- -

{{jsxref("Statements/var", "var")}}

- -
-
Bir değişkeni tanımlar, isteğe bağlı olarak değer ataması yapılır.
-
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
-
Etki alanı kod bloğudur, yerel değişken tanımlar, isteğe bağlı olarak değer ataması yapar.
-
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
-
Salt okunur değişken tanımlar.
-
- -

Değişkenler

- -

Uygulamalarınızda, verilerin sembolik birer gösterimi olarak değişkenleri kullanırsınız. Değişkenlerin isimine {{Glossary("Identifier", "identifiers")}} denir ve kesin kurallar çerçevesinde oluşturulurlar.

- -

JavaScript'te değişken adı; bir harfle, alt tire (_) ile veya dolar işareti ($) ile başlamalıdır; ardından rakamlar gelebilir (0-9). JavaScript'in büyük-küçük harfe duyarlı olmasından dolayı, harfler büyük harf (A'dan Z'ye) ve küçük harf (a'dan z'ye) içerebilirler. 

- -

Değişken adları için å ve ü gibi Unicode harfleri bulunan ISO 8859-1 standardındaki karakter setini kullanabilirsiniz. Ayrıca değişkenlerdeki karakterler olarak, Unicode kaçış karakterlerini kullanabilirsiniz.

- -

Bir kaç uygun örnek: Popüler_şarkılar, jamesBond007, _isim.

- -

Değişken tanımlama

- -

Bir değişkeni üç yolla tanımlayabilirsiniz:

- - - -

Değişkenlerin değerlendirilmesi

- -

var veya let komutuyla başlangıç değer ataması yapmadan tanımlanan değişkenler, {{jsxref("undefined")}} değerine sahiptirler.

- -

Değer ataması yapılmayan bir değişkene erişilmeye çalışıldığında {{jsxref("ReferenceError")}} hatası alınır:

- -
var a;
-console.log("a'nın değeri " + a); // a'nın değeri undefined
-
-var b;
-console.log("b'nın değeri " + b); // b'nin değeri undefined
-
-console.log("c'nin değeri " + c); // 
-Yakalanmamış Referans Hatası: c değeri tanımlanamadı
-
-let x;
-console.log("x'in değeri " + x); // x'in değeri undefined
-
-console.log("y'in değeri " + y); // 
-Yakalanmamış Referans Hatası: y değeri tanımlanamadı
-let y;
- -

undefined'ı, bir değişkenin herhangi bir değere sahip olup olmadığını kontrol etmek için kullanabilirsiniz.  Aşağıdaki kod parçasında girdi değişkenine değer atanmamıştır ve if ifadesi doğru olarak değerlendirileceği için bunuYap(); metodu çalıştırılmış olur. 

- -
var girdi;
-if(girdi === undefined){
-  bunuYap();
-} else {
-  sunuYap();
-}
-
- -

Eğer undefined değeri boolean bir kontrol deyiminde (if, while vb.) kullanılırsa  yanlış (false) çıktı verecek şekilde davranır . Örneğin, aşağıdaki kodda benimDizim değişkeni tanımsız olduğu için yap() fonksiyonu çalıştırılır:

- -
var benimDizim = [];
-if (!benimDizim[0]) yap();
-
- -

Eğer undefined değeri sayısal bir içerikte kullanıldığında NaN (sayı değil) değerini alır.

- -
var a;
-a + 2;  // NaN sonucunu verir
- -

{{jsxref("null")}} değişkeni sayısal bir içerikte kullanıldığında 0, boolean bir içerikte kullanıldığında ise false gibi davranır. Örneğin:

- -
var n = null;
-console.log(n * 32); // ekrana 0 yazdırır
-
- -

Değişkenin etki alanı

- -

Herhangi bir fonksiyon etki alanının dışında bir değişken tanımladığınız zaman, global değişken tanımlamış olursunuz. Bu sayede JavaScript dokümanı içerisinde herhangi bir kod parçası bu değişkene erişilebilir. Bir fonksiyon etki alanı içerisinde değişken tanımladığınızda local (yerel)  değişken tanımlamış olursunuz. Bu sayede değişkene sadece o fonksiyon içerisinden erişilebilir.

- -

ECMAScript 6'dan önceki JavaScript'te, blok seviyesinde etki alanı yoktur; bilâkis, blok içerisinde tanımlanan değişken, o bloğun bulunduğu fonksiyonda (veya global etki alanında) yerel olarak tanımlanmış olur. Örneğin aşağıdaki kod ekrana 5 değerini yazdırır. Çünkü x'in etki alanı, if bloğu içerisinde değil, x'in tanımlandığı fonksiyonda (veya globalde) yer almaktadır.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // 5
-
- -

ECMAScript 2015'te belirlenen let ifadesi ile kullanılırsa, çıktı değişkenlik gösterebilir. Çünkü let ifadesi global alanı değil if bloğunun alanını etki alanı olarak ele alır ve y değişkeni, JavaScript tarafından tanımsız olarak değerlendirileceği için hata döndürür:

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // Uncaught ReferenceError: y is not defined
-
- -

Değişkeni yukarı alma (hoisting)

- -

JavaScript'teki değişkenler hakkında bir sıradışı olay ise, tanımladığınız bir değişkene daha önceki satırda hata almadan erişebiliyor olmanızdır. Bu kavram hoisting (yukarı alma) olarak bilinir; JavaScript'te tanımlanan değişkenler bir anlamda fonksiyon veya ifadenin üzerine alınmış (hoisted) olarak ele alınır. Yukarı alınan değişkenler atandıkları değer yerine undefined değerini alırlar. Hatta bu değişkeni kullandıktan sonra tekrar tanımlarsanız, yine undefined sonucunu alırsınız.

- -
/**
- * Örnek 1
- */
-console.log(x === undefined); // "true" yazar
-var x = 3;
-
-/**
- * Örnek 2
- */
-// undefined değeri alacak
-var degiskenim = "değerim";
-
-(function() {
-  console.log(degiskenim); // undefined
-  var degiskenim = "yerel değerim";
-})();
-
- -

Üstteki örnekler bilgisayar tarafından aşağıdaki şekilde yorumlanır:

- -
/**
- * Örnek 1
- */
-var x;
-console.log(x === undefined); // "true" yazar
-x = 3;
-
-/**
- * Örnek 2
- */
-var degiskenim = "değerim";
-
-(function() {
-  var degiskenim;
-  console.log(degiskenim); // undefined yazar
-  degiskenim = "yerel değerim";
-})();
-
- -

Yukarı alma ile ilgili sorunların yaşanmaması için, fonksiyon içerisinde yer alan bütün değişken tanımları olabildiğince en üste taşınmalıdır. Değişken tanımlamanın en iyi yöntemi de zaten budur. Bu sayede kodun okunabilirliği artmış olur. 

- -

ECMAScript 2015'te, let veya const ifadesi ile tanımlanan değişken, üste alınmaz. Değişken tanımından önce o değişkenin kullanılmaya çalışılırsa {{jsxref("ReferenceError")}} hatası ile sonuçlanır. Değişken, bloğun başlangıcından itibaren tanımının yapıldığı yere kadar ölü bölgededir.

- -

Fonksiyonu yukarı alma

- -

Fonksiyonlarda, yalnızca fonksiyon tanımı yukarı alınır. Fonksiyon ifadesine erişilmeye çalışıldığında ise hata oluşur.

- -
/* fonksiyon tanımlama */
-
-foo(); // "bar"
-
-function foo() {
-  console.log('bar');
-}
-
-
-/* fonksiyon ifadesi */
-
-baz(); // TypeError: baz is not a function
-
-var baz = function() {
-  console.log('bar2');
-};
-
- -

Global değişkenler

- -

Global değişkenler aslında temel bir global nesnenin özellikleridirler. Web sayfalarında bulunan global nesnenin adı {{domxref("window")}} 'dur. Böylece global değişkenlere, window.variable söz dizimi kullanılarak erişilebilir.

- -

Sonuç olarak, herhangi bir window veya iframe'deki global değişkenlere, diğer window veya iframe üzerinden değişkenin ismi kullanılarak erişilebilir. Örneğin, eğer bir dokümanda telefonNumarası isminde bir değişken tanımlanmışsa, bu değişkene iframe içerisinden parent.telefonNumarası şeklinde erişebilirsiniz.

- -

Sabitler

- -

{{jsxref("Statements/const", "const")}} anahtar kelimesi ile sabit bir değişken oluşturabilirsiniz. Sabit değerler için söz dizimi, değişken değerleri ile aynıdır: bir harf, alt çizgi veya dolar işareti ile başlamalıdırlar, devamında ise alfabetik, sayısal veya alt çizgi gibi karakterler gelebilir.

- -
const PI = 3.14;
- -

JavaScript kodu çalışırken bir sabitin değeri, atama yapılarak değiştirilemez ve sabit tekrar tanımlanamaz. Ayrıca sabitlere başlangıçta tanımlanırken bir değer atanması zorunludur.

- -

Sabitlerin etki alanı let bloğunun etki alanındaki değişkenler ile aynıdır. Eğer const ifadesi çıkarılırsa, ifade artık değişken haline gelir.

- -

Bir etki alanında, halihazırda bir fonksiyon veya değişken varsa, aynı isimli sabit tanımlamak hataya yol açar. Örneğin:

- -
// BU HATAYA NEDEN OLUR
-function f() {};
-const f = 5;
-
-// BU DA HATAYA NEDEN OLUR
-function f() {
-  const g = 5;
-  var g;
-}
-
- -

Sabit bir nesneye atanan özellikler diğer fonksiyonların kullanımına karşı korunmamışlardır ve nesnenin kendisi sabit olmasına rağmen değişken değerler alabilirler. Bu sebeple aşağıdaki ifade sorunsuz bir şekilde çalışır.

- -
const BENIM_NESNEM = {"anahtar": "değer"};
-BENIM_NESNEM.anahtar = "diğerDeğer";
- -

Veri yapıları ve tipleri

- -

Veri tipleri

- -

Son yayınlanan ECMAScript standardı ile yedi veri tipi tanımlanabilir:

- - - -

Veri tipleri nispeten az miktarda olmalarına rağmen, uygulamalarınızla yararlı işlevler oluşturmanıza olanak sağlarlar. {{jsxref("Object", "Objects")}} (nesneler) ve {{jsxref("Function", "functions")}} (fonksiyonlar) dilin diğer temel elemanlarıdırlar. Nesneleri, değerleriniz için isimlendirilmiş kutular, fonksiyonları (functions) ise uygulamanızın gerçekleştirebileceği işlevler olarak düşünebilirsiniz.

- -

Veri tipi dönüşümü

- -

JavaScript dinamik tipli bir dildir. Bunun anlamı, bir değişken tanımlarken, veri tipini belirtme zorunluluğunuzun olmaması ve değişkenin veri tipinin çalışma esnasında ihtiyaç olunan tipe otomatik olarak dönüştürülmesidir. Örneğin sayısal bir değişken tanımlayabilirsiniz:

- -
var yanit = 42;
-
- -

Ve sonra, aynı değişkene string bir değer atayabilirsiniz:

- -
yanit = "Hoşçakal, balık için teşekkürler...";
-
- -

JavaScript dinamik tipli olduğu için, bu atama bir hata vermez.

- -

Bir string ve sayının toplama işlemine konulması ile JavaScript otomatik olarak sayısal değeri string ifadeye çevirir ve eklenecek string ile birleştirir. Örneğin aşağıdaki ifadelere bakalım:

- -
x = "Cevap " + 42 // "Cevap 42"
-y = 42 + " cevaptır." // "42 cevaptır."
-
- -

Toplama işlemi dışındaki diğer işlemlerde JavaScript otomatik olarak tür dönüşümü yapmaz. Örneğin:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

String ifadelerin sayısal değerlere dönüştürülmesi

- -

Bellekte sayısal bir ifadeyi temsil eden bir string'in olduğu durumlarda tip dönüşümü yapmak için aşağıdaki metodları kullanabilirsiniz: 

- - - -

parseInt fonksiyonu sadece tam sayı döndürür, bu yüzden ondalık sayılarla kullanıldığında ondalık kısmını atar. Buna ek olarak parseInt'in en uygun kullanımlarından biri de sayının hangi tabanda (2'lik, 10'luk, 16'lık vb.) yazılabileceğini parametre olarak fonksiyona verebilmenizdir. Taban parametresi hangi sayısal sistemin kullanılacağının belirlenmesini sağlar.

- -

String ifadelerin, sayısal ifadelere dönüştürülmesinin diğer bir yolu da, string ifadenin başına + operatörünün eklenmesidir:

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Not: parantezler gösterim kolaylığı için konulmuştur, zorunlu değildir.
- -

Değişken değerleri

- -

JavaScript'te değişkenlerin temsil edilmesi için değerler kullanırsınız. Bunlar, kodunuzda değişkenlere = operatöründen sonra atadığınız değerlerdir. Bu kısımda aşağıdaki değer tiplerini inceleyeceğiz:

- - - -

Dizi değerleri

- -

Bir dizi değeri 0 veya daha fazla ifadeden oluşan liste biçimindedir, liste başında ve sonunda listeyi açıp/kapatan köşeli parantezler [ ] bulunur. Bir dizi oluşturup bu diziye değerler atadığınızda, belirlediğiniz değerleri kendi elemanı olarak barındıran bir dizi üretilir ve dizinin uzunluğu belirlediğiniz değer sayısı kadardır.

- -

Aşağıdaki örnekte, 3 elemanı barındıran ve bu nedenle 3 uzunluğunda olan kahveler isimli bir dizi oluşturulmaktadır:

- -
var kahveler = ["Türk kahvesi", "Espresso", "Mocha"];
-
- -
-

Not : Bir dizi değeri, bir nesne başlatıcısı türündedir. Dahası için bkz: Nesne başlatıcılarının kullanımı.

-
- -

Eğer bir dizi, üst-seviye betikte sabit değer kullanarak oluşturulmuşsa JavaScript, bu diziyi içeren her ifadeyi çalıştırdığında diziyi yorumlar. Buna ek olarak, fonksiyon içerisinde tanımlanan diziler, her fonksiyon çağrımında yeni bir dizi olarak bellekte oluşturulur.

- -

Dizi değerleri ayrıca Array nesneleridirler. Detaylı bilgi için {{jsxref("Array")}} ve Index'li koleksiyonlar kısmına bakınız.

- -

Dizi değerleri arasında bulunan fazladan virgül

- -

Dizi tanımlarken her değeri belirlemek zorunda değilsiniz. Eğer iki tane virgülü art arda koyarak dizi oluşturursanız, virgüller arasında kalan tanımlanmayan her değer için undefined değeri üretilir. Aşağıdaki örnekte bir balık dizisi oluşturulmaktadır:

- -
var balik = ["Japon", , "Melek"];
-
- -

Bu dizi değerlere sahip 2 elemana ve bir tane boş elemana sahiptir (balik[0] = "Japon", balik[1]undefined, ve balik[2] = "Melek").

- -

Eğer dizideki elemanların sonuna virgül koyarsanız virgül, JavaScript tarafından görmezden gelinir. Aşağıdaki örnekte bulunan dizinin uzunluğu üçtür. dizi[3]'ü ifade eden herhangi bir eleman bulunmamaktadır. Listedeki diğer virgüller, undefined değerine sahip yeni bir elemanı ifade eder. 

- -
-

Not : Sona konan virgüller, eski versiyonlu tarayıcılarda hatalara neden olur. Yapılacak en doğru şey, dizi sonlarında kullanılan virgüllerin kaldırılmasıdır.

-
- -
var dizi = ['ev', , 'okul', ];
-
- -

Aşağıdaki örnekte oluşturulan dizinin uzunluğu, dizi[0] ve dizi[2] değerleri tanımlanmadığı halde 4'tür.

- -
var dizi = [ , 'ev', , 'okul'];
-
- -

Aşağıdaki bir diğer örnekte, dizinin uzunluğu, dizi[1] ve dizi[3] değerleri tanımlanmadığı halde yine 4'tür. Sadece son virgül görmezden gelinir.

- -
var dizi = ['ev', , 'okul', , ];
-
- -

Ekstra virgüllerin davranışlarının kavranılması, JavaScript dilinin öğrenilmesi için çok önemlidir, ancak kendi kodunuzu yazarken tanımsız elemanları undefined olarak dizi içerisinde belirlemeniz, kodunuzun okunabilirliğini ve bakım yapılabilirliğini önemli ölçüde arttıracaktır.

- -

Boolean değerleri

- -

Boolean tipinde iki çeşit değer bulunur: true (doğru) ve false (yanlış).

- -

İlkel Boolean değerleri olan true ve false ile Boolean nesnesi olan true ve false değerlerini karıştırmayınız. Boolean nesnesi, ilkel olan Boolean veri tipinin alınması ve üzerine bazı ek özellikler getirilmesi ile oluşturulmuştur. Daha fazlası için bkz: {{jsxref("Boolean")}}.

- -

Tam sayılar

- -

Tam sayılar; ikilik (binary) (2 tabanında), sekizlik (octal) (8 tabanında), onluk (decimal) (10 tabanında), ve onaltılık (hexadecimal) (16 tabanında) temsil edilebilirler.

- - - -

Bazı örnek tamsayılar:

- -
0, 117 and -345 (onluk, 10 tabanında)
-015, 0001 and -077 (sekizlik, 8 tabanında)
-0x1123, 0x00111 and -0xF1A7 (onaltılık, "hex" veya 16 tabanında)
-0b11, 0b0011 and -0b11 (ikilik, 2 tabanında)
-
- -

Daha fazlası için bkz: Sayısal değerler ve sözsel gramer başvurusu.

- -

Ondalıklı değerler

- -

Bir ondalıklı değer aşağıdaki kısımları içerebilir:

- - - -

Katsayı kısmı  bir "e" veya "E" karakteridir ve devamında işaretli olabilen bir tamsayı gelir. Ondalıklı değerin tanımlanabilmesi için en az bir rakam ve devamında ondalıklı sayı ve katsayı "e" (veya "E") içermelidir.

- -

Özetle söz dizimi aşağıdaki şekildedir:

- -
[(+|-)][rakamlar][.rakamlar][(E|e)[(+|-)]rakamlar]
-
- -

Örneğin:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Nesne değerleri

- -

Bir nesne değeri, süslü parantezlerle {} çevrili sıfır veya daha fazla özellik ismi ve bu özellikler ile ilişkili değerleri içeren bir listeden oluşur. Bir kod satırının başlangıcında değişken ismi olmadan sadece süslü parantezler ile başlayarak bir nesne oluşturmamanız gerekmektedir. Eğer oluşturursanız, JavaScript nesne başlangıcındaki { karakterini, bir kod bloğuna başlangıç yapılıyormuş gibi yorumlar ve bunun sonucunda ya bir hata mesajı alırsınız, ya da yazdığınız kod beklediğiniz şekilde çalışmaz.

- -

Aşağıda, nesne değerini içeren bir örnek bulunmaktadır. otoGaleri nesnesinin ilk elemanı, "Fiat" değerini barındıran arabam isminde bir özelliği tanımlamaktadır; ikinci elemanı arabaAl özelliğidir ve function (arabaTipleri("Honda")) fonksiyonu çalıştırıldıktan hemen sonra fonksiyonun sonucunu içerir; üçüncü eleman sporArabaAl özelliğidir, halihazırda varolan hayalimdekiAraba değişkenini kullanır.

- -
var hayalimdekiAraba = "Bugatti";
-
-function arabaTipleri(markaAdı) {
-  if (markaAdı == "Wolksvagen") {
-    return markaAdı;
-  } else {
-    return "Üzgünüz, malesef " + markaAdı + " marka araba elimizde bulunmamaktadır.";
-  }
-}
-
-var otoGaleri = {
-    arabam: "Fiat",
-    arabaAl: arabaTipleri("Wolksvagen"),
-    sporArabaAl: arabaTipleri(hayalimdekiAraba)
-};
-
-console.log(otoGaleri.arabam);   // Fiat
-console.log(otoGaleri.arabaAl);  // Wolksvagen
-console.log(otoGaleri.sporArabaAl); // Üzgünüz, malesef Bugatti marka araba elimizde bulunmamaktadır.
-
- -

Ek olarak, sayısal veya string bir değer, özellik adı veya iç içe olan diğer bir nesnenin adı yerine kullanabilir. Aşağıdaki örnekte bu seçenekleri görebiliriz:

- -
var otoGaleri = {
-    arabalar: {s: "Saab", "j": "Jeep"},
-    7: "Mazda"
-};
-
-console.log(otoGaleri.arabalar.j); // Jeep
-console.log(otoGaleri[7]); // Mazda
-
- -

Nesne özelik adları boş bir string de dahil olmak üzere herhangi bir string ifade olabilirler. Eğer özellik adı geçerli bir JavaScript {{Glossary("Identifier","identifier")}} değilse, tırnak içinde yazılması gereklidir. Buna ek olarak geçersiz olan özellik adlarına, nokta (.) ile erişim yapılamaz, bunun yerine dizi tarzında köşeli parantezler([]) kullanılır:

- -
var geçersizÖzellikAdlarıÖrnek = {
-  "": "Boş bir string",
-  "!": "Ateş!"
-}
-console.log(geçersizÖzellikAdlarıÖrnek."");   // SyntaxError: Unexpected string
-console.log(geçersizÖzellikAdlarıÖrnek[""]);  // Boş bir string
-console.log(geçersizÖzellikAdlarıÖrnek.!);    // SyntaxError: Unexpected token !
-console.log(geçersizÖzellikAdlarıÖrnek["!"]); // Ateş!
- -

Diğer örnekler:

- -
var nesne = {a: "armut", 2: "iki"};
-console.log(nesne.a);    // armut
-console.log(nesne[2]);   // iki
-//console.log(nesne.2);  // Error: missing ) after argument list
-//console.log(nesne[a]); // Error: a is not defined
-console.log(nesne["a"]); // armut
-console.log(nesne["2"]); // iki
-
- -

Düzenli İfade (RegExp) değerleri

- -

Bir düzenli ifade değeri bölü (/) karakterleri arasında ifade edilir. Aşağıda, örnek bir düzenli ifade bulunmaktadır:

- -
var re = /ab+c/;
- -

String değerleri

- -

Bir string değer çift tırnak (") veya tek tırnak (') arasında bulunan sıfır veya daha fazla karakterlerin yer almasıyla oluşur. Bir string değer aynı tip tırnak ile sonlanmalıdır; bu nedenle karakterleri kapsayan tırnaklar ya çift tırnak ya da tek tırnak ikililerinden oluşmalıdır. Aşağıdaki örnekte string değerler ifade edilmiştir:

- -
"elma"
-'armut'
-"1234"
-"bir satır \n diğer satır"
-"Zafer'in kedisi"
-
- -

String nesnesinin herhangi bir fonksiyonuna, string değerin sonuna nokta koyarak erişebilir ve çalıştırabilirsiniz—JavaScript otomatik olarak string değeri geçici bir String nesnesine dönüştürür, metodu çağırır, ve sonra oluşan geçici String nesnesini hafızadan siler. Ayrıca String.length özelliğini de string değerinin sonuna .length ekleyerek kullanablirsiniz:

- -
console.log("Zafer'in kedisi".length);
-// Boşluk da dahil olmak üzere, string içerisindeki tüm sembollerin sayısını ekrana yazar.
-// Ekrana yazılan değer: 15
-
- -

String nesnesine hususi olarak ihtiyaç duymadığınız durumlarda, string değerleri kullanmanız gerekir. String nesneler için bkz: {{jsxref("String")}}.

- -

Özel karakterlerin string değerlerde kullanımı

- -

String değerler oluştururken, her zamanki kullandığınız karakterlere ek olarak aşağıdaki şekilde özel karakterler de kullanabilirsiniz:

- -
"bir satır \n diğer satır"
-
- -

Aşağıdaki tabloda, JavaScript string değerleri içerisinde kullanabileceğiniz özel karakterler listelenmiştir: 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tablo: JavaScript özel karakterleri
KarakterAnlamı
\0Boş değer
\bGeri silme
\fForm beslemesi
\nYeni satır
\rEnter karakteri
\tTab
\vDikey tab
\'Kesme işareti veya tek tırnak
\"Çift tırnak
\\Ters bölü (\) karakteri
\XXX3 adet sekizlik rakamı barındırabilen, ve 0-377 arasındaki XXX değerlerinin Latin-1 kodlaması ile oluşturulduğu karakterdir. Örneğin, sekizlik \251 değeri telif hakkı sembolünü (©) ifade eder.
\xXX -

2 adet onaltılık karakteri barındırabilen ve 00-FF arasındaki XX değerlerinin Latin-1 kodlaması ile oluşturduğu karakterdir. Örneğin, onaltılık \xA9 değeri telif hakkı sembolünü (©) ifade eder.

-
\uXXXX -

4 adet onaltılık karakteri barındırabilen XXXX değerleri ile belirlenen Unicode karakteridir. Örneğin \u00A9 karakteri, Unicode olarak telif hakkı sembolünü (©) ifade eder. Bkz: Unicode kaçış karakterleri.

-
\u{XXXXX}Unicode kod noktası kaçış karakterlerini ifade eder. Örneğin, \u{2F804} karakteri, \uD87E\uDC04 ile aynı sembolü ifade eder.
- -

Kaçış karakterleri

- -

Üstteki tabloda yer almayan karakterlerin başına ters bölü işaretinin konulduğunda, ters bölü işareti göz ardı edilir, fakat bu tarz kullanım artık rafa kaldırılmıştır ve kullanımından kaçınılması gerekir. 

- -

Bir string değer içerisinde tırnak işaretini kullanabilmeniz için, karakterin başına ters bölü işareti eklemeniz gerekir. Bu kullanıma tırnaktan kaçış (escaping the quotation mark) denir. Örneğin:

- -
var alıntı = "Sebahattin Ali'nin \"Kürk Mantolu Madonna\" adlı kitabını okudu.";
-console.log(alıntı);
-
- -

Ekran çıktısı aşağıdaki gibi olacaktır:

- -
Sebahattin Ali'nin "Kürk Mantolu Madonna" adlı kitabını okudu.
-
- -

String değer içerisinde ters bölü işaretini kullanabilmeniz için, tekrar bir ters bölü karakteri daha eklemeniz gerekir. Örneğin c:\temp isimli dosya yolunu, bir string olarak aşağıdaki şekilde ifade edebiliriz:

- -
var geçiciDosyalarDizini = "c:\\temp";
-
- -

Uzun string değerleri satır satır yazmak için tırnak artı tırnak (" + ") işaretleri ile eklemek yerine satır sonuna sadece ters bölü işareti ekleyebilirsiniz. Ters bölü ve satır sonu karakterleri, string değerinden çıkarılmış olarak tek satır halinde döndürülür.

- -
var metin = "Bu metin \
-birçok \
-satıra ayrılarak \
-oluşturulmuştur."
-console.log(metin);  // Ekran çıktısı: Bu metin birçok satıra ayrılarak oluşturulmuştur.
-
- -

JavaScript'in paragrafları tanımlamak için bir söz dizimi bulunmamasına rağmen, her satır sonuna  \n\ karakterleri ekleyerek paragraf oluşturabilirsiniz:

- -
var şiir =
-"Sana gitme demeyeceğim \n\
-Ama gitme Lavinia \n\
-Adını gizleyeceğim \n\
-Sen de bilme Lavinia.";
-
- -

Daha fazlası

- -

Bu bölümde, tanımlamalar ve türler için temel söz dizimleri konuları üzerinde durulmuştur. JavaScript'in dil oluşturucularıyla ilgili daha fazla bilgi edinmek için bu rehberde bulunan aşağıdaki bölümleri inceleyebilirsiniz:

- - - -

Sonraki bölümde, kontrol akışının oluşturulması ve hata yakalamaya göz atacağız.

- -

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git a/files/tr/web/javascript/guide/index.html b/files/tr/web/javascript/guide/index.html deleted file mode 100644 index 5e4e177f58..0000000000 --- a/files/tr/web/javascript/guide/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: JavaScript Rehberi -slug: Web/JavaScript/Guide -tags: - - AJAX - - Intermediate - - JavaScript - - JavaScript_Guide - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Guide ---- -
{{jsSidebar("JavaScript Rehberi")}}
- -

JavaSript Rehber'i size JavaScript'i nasıl kullanacağınızı ve dil hakkında genel bir bakış açısını sunar. JS hakkında daha geniş bir bilgiye ihtiyacınız varsa, JavaScript referansına bakınız.

- - - - - - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/tr/web/javascript/guide/introduction/index.html b/files/tr/web/javascript/guide/introduction/index.html deleted file mode 100644 index 64b7180c80..0000000000 --- a/files/tr/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Introduction -slug: Web/JavaScript/Guide/Introduction -translation_of: Web/JavaScript/Guide/Introduction ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Bu bölümde JavaScript tanıtılacak ve bazı temel kavramları üzerine yoğunlaşılacaktır.

- -

Halihazırda biliyor olmanız gerekenler

- -

Bu rehber aşağıdakileri biliyor olduğunuzu varsayar:

- - - -

JavaScript hakkında nereden bilgi edinirim

- -

MDN'deki JavaScript dökümantasyonu şunları içerir:

- - - -

JavaScript'te yeniyseniz, öğrenme alanı ve JavaScript Rehberi ile başlayınız. JavaScript temellerini sağlam olarak kavradığınızda, nesneler ve ifadeler ile ilgili detaylı bilgiler için özelleşmiş olan JavaScript Referansı'nı kullanabilirsiniz.

- -

JavaScript nedir?

- -

JavaScript, çok platformlu ve nesne yönelimli bir script dilidir. Küçük ve hafif bir dildir. Bir ana bilgisayar ortamında (örneğin, bir web tarayıcısında) JavaScript, programatik olarak kontrol sağlamak için kendi ortamındaki nesnelerine bağlanabilir.

- -

Javascript, Array, Date, and Math gibi nesneleri içeren standart nesne kütüphanesini ve operatörler, kontrol yapıları ve ifadeler gibi temel dil setlerini içerir. JavaScript çekirdeği, ilave nesneler ile birlikte çeşitli amaçlar için genişletilebilir.Örneğin:

- - - -

JavaScript ve Java

- -

JavaScript ve Java bazı yönleriyle benzer olmakla birlikte temelde farklıdırlar.  JavaScript dili, Java'ya benzer fakat JavaScript'te, sabit Java tipleri ve Java'daki güçlü tip denetimi yoktur. JavaScript'in Java ile benzerlik göstermesi nedeniyle, isminin LiveScript'ten JavaScript'te değiştirilmesine neden olan Java'daki çoğu söz dizim ifadesini, isimlendirme düzenini ve basit kontrol akışını yapılarını destekler.

- -

Java'nın tanımlanarak oluşturulmuş sınıfları derle-çalıştır sisteminin aksine; Javascript, veri tiplerinin ufak bir kısmı olan sayısal, boolean ve string veri tiplerini destekleyen çalışma sistemine sahiptir. JavaScript'te, diğer dillerde yaygın olarak kullanılan sınıf temelli nesne modeli yerine prototip temelli nesne modeli vardır. Prototip-temelli model, dinamik olarak miras almayı destekler. Böylelikle miras olarak alınan verinin, nesneler tarafından çoklanarak değiştirilebilmesini sağlanır. Ayrıca JavaScript, herhangi bir özel tanımlamaya gerek kalmadan fonksiyonları da destekler. Fonskiyonlar, esnek biçimlerde çalıştırılabilen metodlar halinde bir nesnenin özellikleri olabilirler.

- -

JavaScript, Java'ya göre oldukça serbest biçimli bir dildir. Tüm değişkenleri, sınıfları ve metodları baştan tanımlamanıza gerek yoktur. Metodların public, private, veya protected olup olmadığı ile ilgili kaygılanmanıza gerek yoktur ve arayüzleri tanımlamanıza gerek yoktur. Değişkenler, parametreler ve fonksiyon dönüş türleri üstü kapalı türler değildir. (Tipine derleyici karar verir.)

- -

Java, tip güvenliği ve hızlı çalıştırma için tanımlanmış bir sınıf-tabanlı programlama dilidir. Tip güvenliği, örneğin bir Java tamsayısını bir nesne referansına çeviremeyeceğiniz ya da gizli belleğe Java bytecodlarını bozarak ulaşamayacağınız anlamına gelir. Java'nın sınıf tabanlı modeli, programların sadece sınıflardan ve onların metodlarından oluştuğu anlamına gelir. Java'nın sınıf kalıtımı ve sıkı yazılışı, genellikle sıkıca bağlanmış nesne hiyerarşileri gerektirir. Bu gereksinimler, Java programlamayı JavaScript programlamadan daha kompleks yapar.

- -

Javascript'in küçük yapısının aksine temelleri HyperTalk ve dBASE gibi dinamik tipli dillere dayanır.Bu betik dilleri; kolay söz dizimi, özelleştirilmiş tümleşik yapısı ve nesne oluşturma için minimum gereksinimlere ihtiyaç duyması sayesinde diğer dillere göre daha geniş programcı kitlesine hitap eder.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript ile Java dillerinin farkları
JavaScriptJava
Nesne temellidir. Nesnelerin türleri arasında bir ayrım söz konusu değildir. Prototype mekanizması ile oluşturulan kalıtım sayesinde, değişkenler ve metodlar herhangi bir objeye dinamik olarak eklenebilir.Nesne temellidir. Nesneler, sınıflar halinde birbirlerinden ayrılmışlardır ve örnekleri arasında oluşturulan kalıtım sınıf hiyerarşisi ile sağlanır. Sınıflar ve oluşturulan nesnelere dinamik olarak değişken ve metot eklemesi yapılamaz.
Değişkenlerin veri türlerinin tanımlanmasına gerek yoktur. İlk atama yapıldığında bir veri türüne sahip olurlar (dinamik tipleme). Örn: var degiskenAdi;Değişkenlerin veri türleri tanımlanmak zorundadır (statik tipleme). Örn: String degiskenAdi.
Otomatik olarak sabit diske yazılamazlar.Otomatik olarak sabit diske yazılabilirler.
- -

Javascript ve Java ile ilgili farklılıklar hakkında daha fazla bilgi edinmek için, Details of the object model bölümüne göz atabilirsiniz.

- -

JavaScript ve ECMAScript beyannamesi

- -

JavaScript standardı, Ecma International tarafından belirlenir. Ecma International, JavaScript temelli standartlaştırılmış uluslararası bir programlama dili (ECMAScript) sunmak için, bilgi ve iletişim sistemlerinin standartlaştırılmasını sağlayan bir Avrupa derneğidir (ECMA'nın eski açınımı: European Computer Manufacturers Association (Avrupa Bilgisayar Üreticileri Derneği)). Standartlaştırılmış JavaScript versiyonu olan ECMAScript, standardı destekleyen tüm uygulamalarda aynı şekilde çalışır. Firmalar, açık standart dili kullanarak kendi Javascript dillerini oluşturabilirler. ECMAScript standardı ECMA-262 beyannamesi altında belgelendirilmiştir. JavaScript ve ECMAScript beyannameleri hakkında detaylı bilgi edinmek için New in JavaScript bölümüne bakabilirsiniz.

- -

ECMA-262 standardı ayrıca ISO tarafından ISO-16262 olarak onaylanmıştır. Beyannameyi Ecma International'ın web sitesinde de bulabilirsiniz. ECMAScript beyannamesi, DOM (Doküman Nesnesi Modeli) hakkında bir tanımlama sunmaz. Zira DOM, World Wide Web Consortium (W3C) ve WHATWG (Web Hypertext Application Technology Working Group) tarafından standartlaştırılmıştır. DOM, HTML dokümanındaki nesnelerin, JavaScript betiğinize aktarılması için bir yol sunar. JavaScript ile programlamada kullanılan farklı teknolojiler hakkında bilgi edinmek için JavaScript technologies overview bölümüne bakabilirsiniz.

- -

JavaScript dokümantasyonu ve ECMAScript beyannamesi farkları

- -

ECMAScript beyannamesi, ECMAScript dilinin gerçekleştirilmesi için gereksinimleri belirler. Kendi ECMAScript gerçekleştiriminizi veya Firefox'taki SpiderMonkey gibi standartlara uyan bir ECMAScript motoru oluşturmanız için kullanışlıdır.

- -

ECMAScript dokümanı, programcıların betik yazması için düzenlenmemiştir; betik yazmak hakkında bilgi edinmek için için JavaScript dokümantasyonunu kullanabilirsiniz.

- -

ECMAScript beyannamesinin kullandığı terminoloji ve söz dizimine bir JavaScript programcısı alışkın olmayabilir. Dilin açıklaması ECMAScript'ten farklılık göstermesine rağmen, dilin kendisi aynı kalmıştır. Yani JavaScript, ECMAScript beyannamesinde belirlenen bütün fonksiyonelliği kapsar.

- -

JavaScript dokümantasyonu, JavaScript programcısının aşina olduğu şekilde dilin özelliklerini ele alır.

- -

JavaScript ile başlangıç

- -

JavaScript'e başlamak kolaydır: tüm ihtiyacınız modern bir web tarayıcısı. Bu rehber, sadece Firefox'un son sürümlerinin desteklediği bazı JavaScript özelliklerini içerir, bu yüzden Firefox'un son sürümlerini kullanmak önerilir.

- -

Firefox'ta çalıştırabileceğiniz iki tane kullanışlı JS aracı vardır: Web konsol ve Scratchpad.

- -

Web Konsolu

- -

Web Konsolu yüklü olan sayfanın yapısal içeriğini gösterir ve ayrıca o anda JavaScript kodlarınızı çalıştırabileceğiniz bir komut satırı da içerir.

- -

Web konsolunu açmak için (Ctrl+Shift+K) komutunu kullanabilir veya "Geliştirici" menüsünden "Tarayıcı Konsolu"'nu seçebilirsiniz. Geliştirici menüsü Firefox'unuzda sağ üst bölümde bulunan "Araçlar" kısmındadır. Tarayıcı konsolu penceresi sayfanın üstüne açılır. Konsolun en alt kısmında aşağıdaki şekilde JavaScript kodunu gireceğiniz ve çıktısını alabileceğiniz bir komut satırı bulunmaktadır:

- -

- -

Karalama defteri

- -

Web konsolu tek satırlı JavaScript kodunuzu çalıştırmak için iyi bir araçtır. Çok satırlı JavaScript kodları çalıştırmak istediginizde ise web konsolu'nun bunu yapma yetisi olsa da kullanışlı değildir ve yazdığınız kod örneklerini kaydedemez. Bu yüzden daha kompleks kod örnekleri için Karalama defteri daha iyi bir araçtır.

- -

Karalama defterini açmak için (Shift+F4) komutunu kullanabilir veya "Web geliştirici" menüsünden "Karalama defteri"'ni seçebilirsiniz. JavaScript kodu yazıp çalıştırabileceğiniz, farklı bir editör penceresi açılır. Ayrıca komutlarınızı diskinizde saklayabilir ve diskinizden yükleyebilirsiniz.

- -

- -

Merhaba Dünya

- -

JS'e başlamak için, Karalama defteri'ni açın ve ilk kodunuz olan "Merhaba Dünya"  yazın:

- -
function selamVer(adiniz) {
-  alert("Merhaba" + adiniz);
-}
-
-selamVer("Dünya");
-
- -

Yukarıda gösterildiği gibi yazdığınız kodu Karalama defteri penceresinden seçin ve çalıştırmak için Ctrl+R komutunu kullanın ve izleyin.

- -

İlerleyen sayfalar, daha kompleks uygulamar yazabileceğiniz JS syntaxlarını ve dil özelliklerini içerir.

- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/tr/web/javascript/guide/loops_and_iteration/index.html b/files/tr/web/javascript/guide/loops_and_iteration/index.html deleted file mode 100644 index 8b224ab288..0000000000 --- a/files/tr/web/javascript/guide/loops_and_iteration/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Döngüler ve yinelemeler -slug: Web/JavaScript/Guide/Loops_and_iteration -translation_of: Web/JavaScript/Guide/Loops_and_iteration ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Ifadeler", "Web/JavaScript/Guide/Functions")}}
- -

Döngüler, bir işlemin art arda yapılması için hızlı ve kolay bir yöntem sunarlar. JavaScript Rehberi'nin bu bölümünde, JavaScript içerisinde yer alan çeşitli yineleme ifadeleri anlatılacaktır.

- -

Döngüleri şu şekildeki basit bir bilgisayar oyunu olarak düşünebilirsiniz: Doğu yönünde 5 adım ilerle ve devamında batı yönünde 3 adım ilerleyerek hazineyi bul. Bu fikri basitçe kodlamak gerekirse:

- -
var adım;
-for (adım = 0; adım < 5; adım++) {
-  // 5 defa ekrana yazıyor
-  // adım 0'dan 4'e kadar değerler alıyor.
-  console.log('Doğu yönünde bir adım atılıyor.');
-}
-
- -

Birçok döngü türü vardır, fakat özünde hepsi aynı şeyi yaparlar: ardı ardına belirlenen bir işlemi gerçekleştirirler. Genelde gerçekleştirilen işlem adımı 0'dan başlar. Döngünün bitiş ve başlangıç noktalarının belirlenmesi için çeşitli döngü mekanizmaları mevcuttur. Bir döngünün diğer döngülere göre daha avantajlı olmasını sağlayan farklı durumlar vardır.

- -

JavaScript'teki döngü ifadeleri aşağıdaki şekilde listelenmiştir:

- - - -

for döngüsü

- -

Bir {{jsxref("statements/for","for")}} döngüsü, belirlenen koşul sağlandığı sürece içerdiği komutların çalıştırılmasını sağlar. JavaScript'teki for döngüsü, Java ve C dilindeki for döngüsü ile benzerdir. For döngüsünün söz dizimi aşağıdaki şekildedir:

- -
for ([başlangıçAtaması]; [koşulİfadesi]; [arttırımİfadesi])
-  ifade
-
- -

Bir for döngüsündeki algoritmanın adımları aşağıdaki şekildedir:

- -
    -
  1. Bir başlangıçAtaması ifadesi varsa çalıştırılır. Bu ifadede genellikle bir veya daha fazla döngü sayıcısına atama işlemi yapılır. Ayrıca değişken tanımı da yapılabilir.
  2. -
  3. koşulİfadesi çalıştırılır. Eğer koşulİfadesi değeri true ise, ifade çalıştırılabilir. Eğer koşulİfadesi değeri false ise, for döngüsünden çıkılır. Eğer koşulİfadesi boş geçilirse, değeri her zaman true olarak varsayılır ve sonsuz döngü oluşturulmuş olur.
  4. -
  5. ifade çalıştırılır. Birden fazla ifade çalıştırılacaksa, ifadeleri gruplamak için blok ifadesi ({ ... }) kullanılır.
  6. -
  7. arttırımİfadesi varsa çalıştırılır ve 2 numaralı adıma geri dönülür.
  8. -
- -

Örnek

- -

Aşağıdaki fonksiyon, scroll'lanabilen bir listedeki seçilen değerlerin sayısını sayan bir for ifadesi içerir (buradaki liste, çoklu seçimler yapabilmeye izin veren bir {{HTMLElement("select")}} elemanıdır) . for ifadesinde i değişkeni tanımlanır ve sıfır değeri atanır. i'nin değerinin, <select> elemanındaki {{HTMLElement("option")}} elemanlarının sayısından daha az olup olmadığı kontrol edilir, if ifadesini çalıştırılır, ve döngü her tamamlandığında i değişkeni bir arttırılır.

- -
<form name="selectForm">
-  <p>
-    <label for="müzikTürleri">Sevdiğiniz müzik türlerini seçip aşağıdaki butona basınız:</label>
-    <select id="müzikTürleri" name="müzikTürleri" multiple="multiple">
-      <option selected="selected">Pop</option>
-      <option>Rap</option>
-      <option>Rock</option>
-      <option>Arabesk</option>
-      <option>Türk Sanat Müziği</option>
-      <option>Klasik Müzik</option>
-    </select>
-  </p>
-  <p><input id="btn" type="button" value="Kaç tanesi seçildi?" /></p>
-</form>
-
-<script>
-function kaçTane(müzikTürleri) {
-  var seçilenMüzikSayısı = 0;
-  for (var i = 0; i < müzikTürleri.options.length; i++) {
-    if (müzikTürleri.options[i].selected) {
-      seçilenMüzikSayısı++;
-    }
-  }
-  return seçilenMüzikSayısı;
-}
-
-var btn = document.getElementById("btn");
-btn.addEventListener("click", function(){
-  alert('Seçilen müzik türü sayısı: ' + kaçTane(document.selectForm.müzikTürleri))
-});
-</script>
-
-
- -

do...while döngüsü

- -

{{jsxref("statements/do...while", "do...while")}} döngüsü, belirlenen bir koşul sağlandığı sürece döngünün çalıştırılmasına olanak tanır. Bir do...while döngüsü aşağıdaki gibidir:

- -
do
-  ifade
-while (koşul);
-
- -

koşul kontrol edilmeden hemen önce ifade çalıştırılır. Çoklu ifadelerin çalıştırılması için, blok ifadesi ({...}) kullanılarak ifadeler gruplandırılır. Eğer koşul sağlanırsa, ifade tekrar çalıştırılır. Çalıştırıldıktan sonra, koşul tekrar kontrol edilir. Eğer koşul sağlanmazsa, ifadenin çalıştırılması durdurulur ve do...while döngüsünden sonraki komutlar çalıştırılır. koşul kontrol edilmeden hemen önce ifade çalıştırıldığı için, koşul değeri false olsa bile blok satırınız içerisindeki kodlar 1 defa çalıştırılır.

- -

Örnek 1

- -

Aşağıdaki örnekte, do döngüsü en az bir kere çalıştırılır, ve i değişkeninin değeri 5'ten küçük olduğu sürece çalıştırma devam eder:

- -
var i = 0;
-do {
-  i += 1;
-  console.log(i);
-} while (i < 5);
-
- -

while döngüsü

- -

Bir {{jsxref("statements/while","while")}} döngüsü, belirlenen koşul sağlandığı sürece çalıştırılmaya devam eder. Örnek bir while döngüsü aşağıdaki gibidir:

- -
while (koşul)
-  ifade
-
- -

Döngü içerisindeki ifade çalıştırılmadan önce koşul kontrol edilir. Eğer koşul sağlanırsa, ifade çalıştırılır ve koşul tekrar kontrol edilir. Eğer koşul sağlanmazsa, döngü içerisindeki ifadenin çalıştırılması durdurulur ve while döngüsünden çıkılarak sonraki komutlar çalıştırılır.

- -

Çoklu ifadelerin çalıştırılması için, blok ifadesi ({...}) kullanılarak ifadeler gruplanır.

- -

Örnek 1

- -

Aşağıdaki while döngüsü, n değişkeni 3'ten küçük olduğu sürece çalıştırılır:

- -
var n = 0;
-var x = 0;
-while (n < 3) {
-  n++;
-  x += n;
-}
-
- -

Her döngüde, n değişkeninin değeri 1 arttırılır ve x'e eklenir. Bunun sonucunda x ve n değişkenleri aşağıdaki değerleri alırlar:

- - - -

3. kez döngü çalıştırılıp tamamlandığında, n < 3 koşulu artık true değerini almaz ve döngüden çıkılır.

- -

Örnek 2

- -

Sonsuz döngülerden uzak durulmalıdır. Döngü içerisindeki koşulun, eninde sonunda false değerini alacağı emin olunmalıdır; aksi taktirde, döngü sonsuza dek çalışır. Aşağıdaki while döngüsündeki ifade sonsuza dek çalışır, çünkü koşul asla false değerini alamaz:

- -
while (true) {
-  console.log("Merhaba dünya");
-}
- -

Etiketlenmiş ifadeler

- -

Bir {{jsxref("statements/label","etiketlenmiş ifadede")}} , bir anahtar kelime ve bu kelimeye bağlı çalıştırılacak bir ifade bulunur.Anahtar kelime kullanılarak, program içerisindeki herhangi bir yerde, anahtar kelime ile ilişkili ifade çalıştırılabilir. Örneğin, bir döngü, anahtar kelime ile etiketlenerek, uygulama içerisindeki herhangi bir yerden çalıştırılabilir.

- -

Etiketlenmiş bir ifade aşağıdaki şekildedir:

- -
etiket :
-   çalıştırılacak_ifade
-
- -

Etiket adı, herhangi bir değişken adının aldığı şekilde değerler alabilir. Etiket ile tanımlanan çalıştırılacak_ifade içerisinde herhangi bir komut yer alabilir.

- -

Örnek

- -

Bu örnekte, döngüyüİşaretle etiketi while döngüsünü tanımlar.

- -
döngüyüİşaretle:
-while (işaret == true) {
-   merhabaDünya();
-}
- -

break ifadesi

- -

{{jsxref("statements/break","break")}} ifadesi kullanılarak bir döngüden, switch ifadesinden veya herhangi bir etiketlenmiş ifadeden çıkılabilir.

- - - -

break ifadesinin söz dizimi aşağıdaki gibidir:

- -
break [etiket];
-
- -

Bu söz diziminin ilk ifadesi (break) ile, break'i çevreleyen en içteki döngü veya switch'ten çıkılır; ikinci ifade ([etiket]) ile belirlenen etiketten çıkılması sağlanır.

- -

Örnek 1

- -

Aşağıdaki örnekte, değer'e eşit olan dizi elemanı bulununcaya dek dizi içerisindeki elemanlar bir döngüde gezilir.

- -
for (var i = 0; i < a.length; i++) {
-  if (a[i] == değer) {
-    break;
-  }
-}
- -

Örnek 2: Bir etiketten çıkma

- -
var x = 0;
-var z = 0;
-
-döngüdenÇıkmaEtiketi: while (true) {
-  console.log("Dıştaki döngüler: " + x);
-  x += 1;
-  z = 1;
-  while (true) {
-    console.log("İçteki döngüler: " + z);
-    z += 1;
-    if (z === 10 && x === 10) {
-      break döngüdenÇıkmaEtiketi;
-    } else if (z === 10) {
-      break;
-    }
-  }
-}
-
- -

continue ifadesi

- -

{{jsxref("statements/continue","continue")}} ifadesi; while, do-while, for, veya etiketlenmiş ifadelere tekrar girilmesini sağlar.

- - - -

continue ifadesinin söz dizimi aşağıdaki gibidir:

- -
continue [etiket];
-
- -

Örnek 1

- -

Aşağıdaki örnekte yer alan while döngüsündeki continue ifadesi, i'nin değeri yalnızca 3 olduğunda çalıştırılmaktadır. Böylece n, sırasıyla şu değerleri alır: 1, 3, 7, 12.

- -
var i = 0;
-var n = 0;
-while (i < 5) {
-  i++;
-  if (i == 3) {
-    continue;
-  }
-  n += i;
-}
-
- -

Örnek 2

- -

Aşağıdaki örnekte bulunan kontrolivej etiketinde yer alan ifadede, kontrolj etiketli diğer bir ifade yer almaktadır. Eğer continue ifadesi ile karşılaşılırsa, uygulama kontrolj'nin o anki döngüsünü sonlandırır ve sonraki iterasyona geçer. Her continue ifadesi ile karşılaşıldığında, kontrolj döngüsü false değerini döndürene dek  devam eder. false döndürdüğünde, döngüden çıkılır ve döngüden sonra gelen kontrolivej ifadesinin kalan kısmı tamamlanır. kontrolivej döngüsüne tekrar girilir. i değişkeni 4'ten büyük oluncaya dek kontrolivej etiketinin çalıştırılmasına devam ettirilir.

- -

Eğer continue ifadesi, kontrolj etiketi yerine kontrolivej etiketini içerseydi, program kontrolivej ifadesinin altındaki while döngüsünden devam edecekti.

- -
kontrolivej:
-  while (i < 4) {
-    console.log(i);
-    i += 1;
-    kontrolj:
-      while (j > 4) {
-        console.log(j);
-        j -= 1;
-        if ((j % 2) == 0) {
-          continue kontrolj;
-        }
-        console.log(j + " tek sayıdır.");
-      }
-      console.log("i = " + i);
-      console.log("j = " + j);
-  }
- -

for...in ifadesi

- -

{{jsxref("statements/for...in","for...in")}} döngüsü, bir nesnenin sayılabilir (enumerable) özelliklerinin üzerinde dolaşılmasını sağlar. Her bir özellik için JavaScript, belirlenen ifadeleri çalıştırır. Bir for...in döngüsü aşağıdaki şekilde oluşturulur:

- -
for (değişken in nesne) {
-  çalıştırılacak_ifadeler
-}
-
- -

Örnek

- -

Aşağıdaki fonksiyon, bir nesne ve nesnenin adını parametre olarak alır. Sonrasında nesnenin tüm özellikleri üzerinde gezer ve nesnede bulunan özelliklerin adını ve değerini listeleyen bir string döndürür. 

- -
function özellikleriListeOlarakVer(nesne, nesnenin_adi) {
-  var sonuç = "";
-  for (var i in nesne) {
-    sonuç += nesnenin_adi + "." + i + " = " + nesne[i] + "<br>";
-  }
-  sonuç += "<hr>";
-  return sonuç;
-}
-
- -

marka ve model özelliklerini içeren bir araba nesnesi için sonuç, aşağıdaki şekilde olacaktır:

- -
araba.marka = Tesla
-araba.model = Model S
-
- -

Dizilerde kullanımı

- -

{{jsxref("Array")}} elemanlarında dolaşmak için for...in kullanımı çok cazip gözükse de for...in ifadesi, sayısal indekslere ek olarak kullanıcı tanımlı özelliklerin de isimlerini döndürür. Bu yüzden dizi üzerinde gezmek için, sayısal indeksler ile birlikte kullanılan geleneksel {{jsxref("statements/for","for")}} döngüsü daha elverişlidir. Çünkü örneğin bir Array nesnesinine özel bir değişken veya fonksiyon eklerseniz, for...in ifadesi dizi elemanlarının yanısıra eklediğiniz kullanıcı tanımlı özellikleri de getirir

- -

for...of ifadesi

- -

{{jsxref("statements/for...of","for...of")}} ifadesi bir döngü oluşturur ve gezilebilir (iterable) nesneler ({{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} nesnesi vb.) üzerinde gezer.

- -
for (değişken of nesne) {
-  çalıştırılacak_ifadeler
-}
- -

Aşağıdaki örnekte, for...of döngüsü ve {{jsxref("statements/for...in","for...in")}} döngüsü arasındaki fark gösterilmektedir. for...in döngüsü nesne değişkenlerinin isimleri üzerinde gezerken, for...of döngüsü ise değişkenlerin değerleri üzerinde gezer:

- -
let dizi = [3, 5, 7];
-dizi.selam = "merhaba";
-
-for (let i in dizi) {
-   console.log(i); // Çıktısı: "0", "1", "2", "selam"
-   console.log(typeof i); //string tipi
-}
-
-for (let i of dizi) {
-   console.log(i); // Çıktısı: 3, 5, 7
-   console.log(typeof i); //degiskenin sahip old. tip
-}
-
- -

{{PreviousNext("Web/JavaScript/Guide/Ifadeler", "Web/JavaScript/Guide/Functions")}}

diff --git a/files/tr/web/javascript/guide/working_with_objects/index.html b/files/tr/web/javascript/guide/working_with_objects/index.html deleted file mode 100644 index 7b3c555da6..0000000000 --- a/files/tr/web/javascript/guide/working_with_objects/index.html +++ /dev/null @@ -1,505 +0,0 @@ ---- -title: Nesnelerle çalışmak -slug: Web/JavaScript/Guide/Working_with_Objects -translation_of: Web/JavaScript/Guide/Working_with_Objects -original_slug: Web/JavaScript/Guide/Nesneler_ile_çalışmak ---- -
{{jsSidebar("JavaScript Rehberi")}} {{PreviousNext("Web/JavaScript/Guide/Keyed_collections", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
- -

JavaScript basit bir nesne tabanlı paradigmada tasarlanmıştır. Bir nesne bir özellikler koleksiyonudur ve bir özellik bir ad (veya anahtar) ile bir değer arasındaki ilişkidir. Bir özelliğin değeri bir fonksiyon olabilir, bu durumda özellik bir metod olarak bilinir. Tarayıcıda önceden tanımlanmış olan nesnelere ek olarak, kendi nesnelerinizi de tanımlayabilirsiniz. Bu bölümde, nesnelerin, özelliklerin, fonksiyonların ve metodların nasıl kullanıldığı ve kendi nesnelerinizin nasıl oluşturulacağı açıklanmaktadır.

- -

Nesnelere genel bakış

- -

JavaScript'teki nesneler, diğer birçok programlama dilinde olduğu gibi, gerçek hayattaki nesnelerle karşılaştırılabilir. JavaScript'teki nesneler kavramı gerçek hayattaki somut nesnelerle anlaşılabilir.

- -

JavaScript'te bir nesne, özellikleri ve tipiyle bağımsız bir varlıktır. Örneğin bir fincanla karşılaştırın. Bir fincan, özellikleri olan bir nesnedir. Bir fincan bir renge, bir tasarıma, ağırlığa, yapıldığı bir malzemeye vs. sahiptir. Aynı şekilde, JavaScript nesnelerinin de özelliklerini tanımlayan özellikleri olabilir.

- -

Nesneler ve özellikleri

- -

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:

- -
objectName.propertyName
-
- -

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named myCar and give it properties named make, model, and year as follows:

- -
var myCar = new Object();
-myCar.make = 'Ford';
-myCar.model = 'Mustang';
-myCar.year = 1969;
-
- -

Unassigned properties of an object are {{jsxref("undefined")}} (and not {{jsxref("null")}}).

- -
myCar.color; // undefined
- -

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

- -
myCar['make'] = 'Ford';
-myCar['model'] = 'Mustang';
-myCar['year'] = 1969;
-
- -

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

- -
// four variables are created and assigned in a single go,
-// separated by commas
-var myObj = new Object(),
-    str = 'myString',
-    rand = Math.random(),
-    obj = new Object();
-
-myObj.type              = 'Dot syntax';
-myObj['date created']   = 'String with space';
-myObj[str]              = 'String value';
-myObj[rand]             = 'Random Number';
-myObj[obj]              = 'Object';
-myObj['']               = 'Even an empty string';
-
-console.log(myObj);
-
- -

Please note that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). For example, in the above code, when the key obj is added to the myObj, JavaScript will call the {{jsxref("Object.toString", "obj.toString()")}} method, and use this result string as the new key.

- -

You can also access properties by using a string value that is stored in a variable:

- -
var propertyName = 'make';
-myCar[propertyName] = 'Ford';
-
-propertyName = 'model';
-myCar[propertyName] = 'Mustang';
-
- -

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

- -
function showProps(obj, objName) {
-  var result = ``;
-  for (var i in obj) {
-    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
-    if (obj.hasOwnProperty(i)) {
-      result += `${objName}.${i} = ${obj[i]}\n`;
-    }
-  }
-  return result;
-}
-
- -

So, the function call showProps(myCar, "myCar") would return the following:

- -
myCar.make = Ford
-myCar.model = Mustang
-myCar.year = 1969
- -

Enumerate the properties of an object

- -

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:

- - - -

Before ECMAScript 5, there was no native way to list all properties of an object. However, this can be achieved with the following function:

- -
function listAllProperties(o) {
-	var objectToInspect;
-	var result = [];
-
-	for(objectToInspect = o; objectToInspect !== null;
-           objectToInspect = Object.getPrototypeOf(objectToInspect)) {
-        result = result.concat(
-            Object.getOwnPropertyNames(objectToInspect)
-        );
-    }
-
-	return result;
-}
-
- -

This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

- -

Creating new objects

- -

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

- -

Using object initializers

- -

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

- -

The syntax for an object using an object initializer is:

- -
var obj = { property_1:   value_1,   // property_# may be an identifier...
-            2:            value_2,   // or a number...
-            // ...,
-            'property n': value_n }; // or a string
-
- -

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i. The obj and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

- -

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object.

- -

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:

- -
if (cond) var x = {greeting: 'hi there'};
-
- -

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

- -
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
-
- -

You can also use object initializers to create arrays. See array literals.

- -

Using a constructor function

- -

Alternatively, you can create an object with these two steps:

- -
    -
  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. -
  3. Create an instance of the object with new.
  4. -
- -

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-
- -

Notice the use of this to assign values to the object's properties based on the values passed to the function.

- -

Now you can create an object called mycar as follows:

- -
var mycar = new Car('Eagle', 'Talon TSi', 1993);
-
- -

This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

- -

You can create any number of Car objects by calls to new. For example,

- -
var kenscar = new Car('Nissan', '300ZX', 1992);
-var vpgscar = new Car('Mazda', 'Miata', 1990);
-
- -

An object can have a property that is itself another object. For example, suppose you define an object called person as follows:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
-
- -

and then instantiate two new person objects as follows:

- -
var rand = new Person('Rand McKinnon', 33, 'M');
-var ken = new Person('Ken Jones', 39, 'M');
-
- -

Then, you can rewrite the definition of Car to include an owner property that takes a person object, as follows:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-}
-
- -

To instantiate the new objects, you then use the following:

- -
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
-var car2 = new Car('Nissan', '300ZX', 1992, ken);
-
- -

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

- -
car2.owner.name
-
- -

Note that you can always add a property to a previously defined object. For example, the statement

- -
car1.color = 'black';
-
- -

adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.

- -

Using the Object.create method

- -

Objects can also be created using the {{jsxref("Object.create()")}} method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

- -
// Animal properties and method encapsulation
-var Animal = {
-  type: 'Invertebrates', // Default value of properties
-  displayType: function() {  // Method which will display type of Animal
-    console.log(this.type);
-  }
-};
-
-// Create new animal type called animal1
-var animal1 = Object.create(Animal);
-animal1.displayType(); // Output:Invertebrates
-
-// Create new animal type called Fishes
-var fish = Object.create(Animal);
-fish.type = 'Fishes';
-fish.displayType(); // Output:Fishes
- -

Inheritance

- -

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. See Inheritance and the prototype chain for more information.

- -

Indexing object properties

- -

You can refer to a property of an object either by its property name or by its ordinal index. If you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

- -

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the Car object type) and when you define individual properties explicitly (for example, myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you subsequently refer to the property only as myCar[5].

- -

The exception to this rule is array-like object reflected from HTML, such as the forms array-like object. You can always refer to objects in these array-like objects by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.forms.myForm.

- -

Defining properties for an object type

- -

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type Car, and then assigns a value to the color property of the object car1.

- -
Car.prototype.color = null;
-car1.color = 'black';
-
- -

See the prototype property of the Function object in the JavaScript reference for more information.

- -

Defining methods

- -

A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

- -
objectName.methodname = functionName;
-
-var myObj = {
-  myMethod: function(params) {
-    // ...do something
-  }
-
-  // OR THIS WORKS TOO
-
-  myOtherMethod(params) {
-    // ...do something else
-  }
-};
-
- -

where objectName is an existing object, methodname is the name you are assigning to the method, and functionName is the name of the function.

- -

You can then call the method in the context of the object as follows:

- -
object.methodname(params);
-
- -

You can define methods for an object type by including a method definition in the object constructor function. You could define a function that would format and display the properties of the previously-defined Car objects; for example,

- -
function displayCar() {
-  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
-  pretty_print(result);
-}
-
- -

where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

- -

You can make this function a method of Car by adding the statement

- -
this.displayCar = displayCar;
-
- -

to the object definition. So, the full definition of Car would now look like

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-  this.displayCar = displayCar;
-}
-
- -

Then you can call the displayCar method for each of the objects as follows:

- -
car1.displayCar();
-car2.displayCar();
-
- -

Using this for object references

- -

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have 2 objects, Managerand Intern. Each object have their own nameage and job.  In the function sayHi(), notice there is this.name. When added to the 2 objects they can be called and returns the 'Hello, My name is' then adds the name value from that specific object. As shown below. 

- -
const Manager = {
-  name: "John",
-  age: 27,
-  job: "Software Engineer"
-}
-const Intern= {
-  name: "Ben",
-  age: 21,
-  job: "Software Engineer Intern"
-}
-
-function sayHi() {
-    console.log('Hello, my name is', this.name)
-}
-
-// add sayHi function to both objects
-Manager.sayHi = sayHi;
-Intern.sayHi = sayHi;
-
-Manager.sayHi() // Hello, my name is John'
-Intern.sayHi() // Hello, my name is Ben'
-
- -

The this refers to the object that it is in. You can create a new function called howOldAmI()which logs a sentence saying how old the person is. 

- -
function howOldAmI (){
-  console.log('I am ' + this.age + ' years old.')
-}
-Manager.howOldAmI = howOldAmI;
-Manager.howOldAmI() // I am 27 years old.
-
- -

Defining getters and setters

- -

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -

The following illustrates how getters and setters could work for a user-defined object o.

- -
var o = {
-  a: 7,
-  get b() {
-    return this.a + 1;
-  },
-  set c(x) {
-    this.a = x / 2;
-  }
-};
-
-console.log(o.a); // 7
-console.log(o.b); // 8
-o.c = 50;
-console.log(o.a); // 25
-
- -

The o object's properties are:

- - - -

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using {{jsxref("Object.defineProperty")}} (or the {{jsxref("Object.defineGetter", "Object.prototype.__defineGetter__")}} legacy fallback).

- -

The following code illustrates how getters and setters can extend the {{jsxref("Date")}} prototype to add a year property to all instances of the predefined Date class. It uses the Date class's existing getFullYear and setFullYear methods to support the year property's getter and setter.

- -

These statements define a getter and setter for the year property:

- -
var d = Date.prototype;
-Object.defineProperty(d, 'year', {
-  get: function() { return this.getFullYear(); },
-  set: function(y) { this.setFullYear(y); }
-});
-
- -

These statements use the getter and setter in a Date object:

- -
var now = new Date();
-console.log(now.year); // 2000
-now.year = 2001; // 987617605170
-console.log(now);
-// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
-
- -

In principle, getters and setters can be either

- - - -

When defining getters and setters using object initializers all you need to do is to prefix a getter method with get and a setter method with set. Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

- -
var o = {
-  a: 7,
-  get b() { return this.a + 1; },
-  set c(x) { this.a = x / 2; }
-};
-
- -

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

- -
var o = { a: 0 };
-
-Object.defineProperties(o, {
-    'b': { get: function() { return this.a + 1; } },
-    'c': { set: function(x) { this.a = x / 2; } }
-});
-
-o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
-console.log(o.b); // Runs the getter, which yields a + 1 or 6
-
- -

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

- -

Deleting properties

- -

You can remove a non-inherited property by using the delete operator. The following code shows how to remove a property.

- -
// Creates a new object, myobj, with two properties, a and b.
-var myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// Removes the a property, leaving myobj with only the b property.
-delete myobj.a;
-console.log ('a' in myobj); // output: "false"
-
- -

You can also use delete to delete a global variable if the var keyword was not used to declare the variable:

- -
g = 17;
-delete g;
-
- -

Comparing objects

- -

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

- -
// Two variables, two distinct objects with the same properties
-var fruit = {name: 'apple'};
-var fruitbear = {name: 'apple'};
-
-fruit == fruitbear; // return false
-fruit === fruitbear; // return false
- -
// Two variables, a single object
-var fruit = {name: 'apple'};
-var fruitbear = fruit;  // Assign fruit object reference to fruitbear
-
-// Here fruit and fruitbear are pointing to same object
-fruit == fruitbear; // return true
-fruit === fruitbear; // return true
-
-fruit.name = 'grape';
-console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }
-
- -

For more information about comparison operators, see Comparison operators.

- -

See also

- - - -

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git a/files/tr/web/javascript/index.html b/files/tr/web/javascript/index.html deleted file mode 100644 index 578ff9261e..0000000000 --- a/files/tr/web/javascript/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: JavaScript -slug: Web/JavaScript -tags: - - JavaScript - - JavaScript öğrenmek - - öğren -translation_of: Web/JavaScript ---- -

{{JsSidebar}}

- -

JavaScript® (genellikle js olarak kısaltılır) basit şekilde yorumlanmış ve birinci sınıf fonksiyonlar ile harmanlanmış nesne tabanlı bir programlama dilidir. Daha çok web sayfaları için kullanılan bir betik dili olarak bilinir, ancak node.js veya Apache CouchDB gibi tarayıcı olmayan ortamlarda da sıkça kullanılır. Prototip tabanlı olması ve çoklu paradigma içeren bir dil olması dinamik ve fonksiyonel bir yapı sağlar. JavaScript hakkında detaylı bilgi edinin.

- -

JavaScript standardı ECMAScript olarak adlandırılır. 2012 yılı itibariyle tüm modern tarayıcılar ECMAScript 5.1'i desteklerken eski tarayıcılar ECMAScript 3'e kadar destekler. 17 Haziran 2015'de resmi olarak ECMAScript 2015 adı verilen 6. versiyon yayınlandı çoğunlukla ES2015 olarak ifade edildi. Bu döküman şu an için ECMAScript 2015'yı kapsıyor, ancak yakında ECMAScript 2016'yi kapsayacak şekilde güncellenecektir.

- -

Sitenin bu kısmı JavaScript'in kendisine, web sitesiyle doğrudan alakalı olmayan parçalara ve diğer ortamlara ayrılmıştır. {{Glossary("API","APIs")}} hakkında bilgi için lütfen Web APIs ve DOM sayfalarını inceleyin.

- -

JavaScript, Java programlama dili'nden farklıdır. Java, A.B.D. ve diğer ülkelerde Oracle firmasının kayıtlı markasıdır.

- -
-
-

Eğitim Setleri

- -

Rehberlerimiz ve eğitim setlerimiz ile JavaScript programlamayı öğrenin.

- -

Başlangıç

- -
-
JavaScript Rehberi
-
JavaScript'te yeniyseniz, bu rehber sizi adım adım JavaScript'e götürecek.
-
JavaScript teknolojilerine genel bakış
-
Web tarayıcısı için JavaScript.
-
Nesne tabanlı JavaScript
-
Nesne tabanlı JavaScript'e giriş.
-
- -

Orta seviye

- -
-
JavaScript ile yeniden tanışma
-
JavaScript az buçuk haberdar olanlar için açıklama.
-
- -
-
JavaScript veri yapıları
-
JavaScript'te bulunan veri yapılarına genel bakış.
-
Eşitlik kıyaslamaları ve aynılık
-
JavaScript üç farklı değer kıyaslama işlemi sağlar: katı eşitlik (===), zayıf eşitlik (==) ve {{jsxref("Global_Objects/Object/is", "Object.is()")}} metodu.
-
- -

Üst seviye

- -
-
Kalıtım ve prototip zinciri
-
Büyük ölçüde yanlış anlaşılan ifadeler ve eksik değerlendirilmiş prototip tabanlı kalıtım.
-
Katı Mod
-
Kısıtlı bir JavaScript varyantı.
-
JavaScript Tanımlanmış Diziler
-
JavaScript typed arrays, ikilik sayı sistemindeki taslak veriye erişmek için bir mekanizma sağlar.
-
Bellek yönetimi
-
JavaScript'te bellek yaşam döngüsü ve atık veri toplama işlemleri.
-
Eş zamanlılık modeli ve olay döngüsü
-
JavaScript, olay döngüsüne dayandırışmış bir eş zamanlılık modeline sahiptir.
-
-
- -
-

Referanslar

- -

JS referanslar dökümanını inceleyin.

- -
-
Standart nesneler
-
Array, Boolean, Date, Error, Function, JSON, Math, Number, Object, RegExp, StringMap, Set, WeakMap, WeakSet ve diğer yerleşik nesneler hakkında bilgi edinin.
-
Matematiksel ifadeler ve operatörler
-
JavaScript'te bulunan instanceof, typeof, new, this gibi birçok operatörün işlevsellikleri hakkında daha fazla bilgi edinin.
-
İfadeler ve deklarasyonlar
-
do-while, for-in, for-of, try-catch, let, var, const, if-else, switch gibi birçok ifadenin ve anahtar kelimenin nasıl işlediğini öğrenin.
-
Fonksiyonlar
-
Kendi uygulamanızı geliştirmek için JavaScript fonksiyonlarını öğrenin.
-
- -

Araçlar & Kaynaklar

- -

JavaScript'te kod yazarken ve hata ayıklarken kullanılabilecek yardımcı kaynaklar.

- -
-
Firefox Geliştirici Araçları
-
Scratchpad, Web Console, JavaScript Profiler, Debugger ve daha fazlası.
-
Firebug
-
Herhangi bir sayfada CSS, HTML ve JavaScript'i canlı olarak düzenleyin, hata ayıklayın.
-
JavaScript Terminalleri
-
Bir JavaScript terminali, ufak JavaScript kodlarını hızlı bir şekilde test etmenizi sağlar.
-
TogetherJS
-
-

TogetherJS size eş zamanlı bir şekilde takım çalışması yapmanızı sağlar.

-
-
Stack Overflow
-
Stack Overflow'da sorular "JavaScript" etiketi altında yer alır.
-
JavaScript sürümleri ve sürüm notları
-
JavaScript'in özellik geçmişine ve uygulanma durumuna bir göz atın.
-
JSFiddle
-
Javascript, CSS, HTML içerikleri düzenleyin ve canlı sonuçlar edinin. Harici kaynaklar kullanarak ekibiniz ile birlikte çevirimiçi çalışın.
-
-
-
diff --git a/files/tr/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/tr/web/javascript/inheritance_and_the_prototype_chain/index.html deleted file mode 100644 index 3996834ab3..0000000000 --- a/files/tr/web/javascript/inheritance_and_the_prototype_chain/index.html +++ /dev/null @@ -1,561 +0,0 @@ ---- -title: Türkçe -slug: Web/JavaScript/Inheritance_and_the_prototype_chain -translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain ---- -
{{jsSidebar("Advanced")}}
- -

JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++), as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in ES2015, but is syntactical sugar, JavaScript remains prototype-based).

- -

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

- -

Nearly all objects in JavaScript are instances of {{jsxref("Object")}} which sits on the top of a prototype chain.

- -

While this confusion is often considered to be one of JavaScript's weaknesses, the prototypal inheritance model itself is, in fact, more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model.

- -

Inheritance with the prototype chain

- -

Inheriting properties

- -

JavaScript objects are dynamic "bags" of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

- -
-

Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}. This is equivalent to the JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers.

- -

It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the {{jsxref("Object")}} prototype object.

-
- -

Here is what happens when trying to access a property:

- -
// Let's create an object o from function f with its own properties a and b:
-let f = function () {
-   this.a = 1;
-   this.b = 2;
-}
-let o = new f(); // {a: 1, b: 2}
-
-// add properties in f function's prototype
-f.prototype.b = 3;
-f.prototype.c = 4;
-
-// do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain
-// o.[[Prototype]] has properties b and c.
-// o.[[Prototype]].[[Prototype]] is Object.prototype.
-// Finally, o.[[Prototype]].[[Prototype]].[[Prototype]] is null.
-// This is the end of the prototype chain, as null,
-// by definition, has no [[Prototype]].
-// Thus, the full prototype chain looks like:
-// {a: 1, b: 2} ---> {b: 3, c: 4} ---> Object.prototype ---> null
-
-console.log(o.a); // 1
-// Is there an 'a' own property on o? Yes, and its value is 1.
-
-console.log(o.b); // 2
-// Is there a 'b' own property on o? Yes, and its value is 2.
-// The prototype also has a 'b' property, but it's not visited.
-// This is called Property Shadowing
-
-console.log(o.c); // 4
-// Is there a 'c' own property on o? No, check its prototype.
-// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
-
-console.log(o.d); // undefined
-// Is there a 'd' own property on o? No, check its prototype.
-// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
-// o.[[Prototype]].[[Prototype]] is Object.prototype and there is no 'd' property by default, check its prototype.
-// o.[[Prototype]].[[Prototype]].[[Prototype]] is null, stop searching,
-// no property found, return undefined.
-
- -

Code Link

- -

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter.

- -

Inheriting "methods"

- -

JavaScript does not have "methods" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

- -

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

- -
var o = {
-  a: 2,
-  m: function() {
-    return this.a + 1;
-  }
-};
-
-console.log(o.m()); // 3
-// When calling o.m in this case, 'this' refers to o
-
-var p = Object.create(o);
-// p is an object that inherits from o
-
-p.a = 4; // creates a property 'a' on p
-console.log(p.m()); // 5
-// when p.m is called, 'this' refers to p.
-// So when p inherits the function m of o,
-// 'this.a' means p.a, the property 'a' of p
-
-
-
- -

Using prototypes in JavaScript

- -

Let's look at what happens behind the scenes in a bit more detail.

- -

In JavaScript, as mentioned above, functions are able to have properties. All functions have a special property named prototype. Please note that the code below is free-standing (it is safe to assume there is no other JavaScript on the webpage other than the below code). For the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below JavaScript code, and run it by pressing the Enter/Return key. (The console is included in most web browser's Developer Tools. More information is available for Firefox Developer Tools, Chrome DevTools, and Edge DevTools.)

- -
function doSomething(){}
-console.log( doSomething.prototype );
-//  It does not matter how you declare the function, a
-//  function in JavaScript will always have a default
-//  prototype property.
-//  (Ps: There is one exception that arrow function doesn't have a default prototype property)
-var doSomething = function(){};
-console.log( doSomething.prototype );
-
- -

As seen above, doSomething() has a default prototype property, as demonstrated by the console. After running this code, the console should have displayed an object that looks similar to this.

- -
{
-    constructor: ƒ doSomething(),
-    __proto__: {
-        constructor: ƒ Object(),
-        hasOwnProperty: ƒ hasOwnProperty(),
-        isPrototypeOf: ƒ isPrototypeOf(),
-        propertyIsEnumerable: ƒ propertyIsEnumerable(),
-        toLocaleString: ƒ toLocaleString(),
-        toString: ƒ toString(),
-        valueOf: ƒ valueOf()
-    }
-}
- -

We can add properties to the prototype of doSomething(), as shown below.

- -
function doSomething(){}
-doSomething.prototype.foo = "bar";
-console.log( doSomething.prototype );
- -

This results in:

- -
{
-    foo: "bar",
-    constructor: ƒ doSomething(),
-    __proto__: {
-        constructor: ƒ Object(),
-        hasOwnProperty: ƒ hasOwnProperty(),
-        isPrototypeOf: ƒ isPrototypeOf(),
-        propertyIsEnumerable: ƒ propertyIsEnumerable(),
-        toLocaleString: ƒ toLocaleString(),
-        toString: ƒ toString(),
-        valueOf: ƒ valueOf()
-    }
-}
-
- -

We can now use the new operator to create an instance of doSomething() based on this prototype. To use the new operator, simply call the function normally except prefix it with new. Calling a function with the new operator returns an object that is an instance of the function. Properties can then be added onto this object.

- -

Try the following code:

- -
function doSomething(){}
-doSomething.prototype.foo = "bar"; // add a property onto the prototype
-var doSomeInstancing = new doSomething();
-doSomeInstancing.prop = "some value"; // add a property onto the object
-console.log( doSomeInstancing );
- -

This results in an output similar to the following:

- -
{
-    prop: "some value",
-    __proto__: {
-        foo: "bar",
-        constructor: ƒ doSomething(),
-        __proto__: {
-            constructor: ƒ Object(),
-            hasOwnProperty: ƒ hasOwnProperty(),
-            isPrototypeOf: ƒ isPrototypeOf(),
-            propertyIsEnumerable: ƒ propertyIsEnumerable(),
-            toLocaleString: ƒ toLocaleString(),
-            toString: ƒ toString(),
-            valueOf: ƒ valueOf()
-        }
-    }
-}
- -

As seen above, the __proto__ of doSomeInstancing is doSomething.prototype. But, what does this do? When you access a property of doSomeInstancing, the browser first looks to see if doSomeInstancing has that property.

- -

If doSomeInstancing does not have the property, then the browser looks for the property in the __proto__ of doSomeInstancing (a.k.a. doSomething.prototype). If the __proto__ of doSomeInstancing has the property being looked for, then that property on the __proto__ of doSomeInstancing is used.

- -

Otherwise, if the __proto__ of doSomeInstancing does not have the property, then the __proto__ of the __proto__ of doSomeInstancing is checked for the property. By default, the __proto__ of any function's prototype property is window.Object.prototype. So, the __proto__ of the __proto__ of doSomeInstancing (a.k.a. the __proto__ of doSomething.prototype (a.k.a. Object.prototype)) is then looked through for the property being searched for.

- -

If the property is not found in the __proto__ of the __proto__ of doSomeInstancing, then the __proto__ of the __proto__ of the __proto__ of doSomeInstancing is looked through. However, there is a problem: the __proto__ of the __proto__ of the __proto__ of doSomeInstancing does not exist. Then, and only then, after the entire prototype chain of __proto__'s is looked through, and there are no more __proto__s does the browser assert that the property does not exist and conclude that the value at the property is undefined.

- -

Let's try entering some more code into the console:

- -
function doSomething(){}
-doSomething.prototype.foo = "bar";
-var doSomeInstancing = new doSomething();
-doSomeInstancing.prop = "some value";
-console.log("doSomeInstancing.prop:      " + doSomeInstancing.prop);
-console.log("doSomeInstancing.foo:       " + doSomeInstancing.foo);
-console.log("doSomething.prop:           " + doSomething.prop);
-console.log("doSomething.foo:            " + doSomething.foo);
-console.log("doSomething.prototype.prop: " + doSomething.prototype.prop);
-console.log("doSomething.prototype.foo:  " + doSomething.prototype.foo);
- -

This results in the following:

- -
doSomeInstancing.prop:      some value
-doSomeInstancing.foo:       bar
-doSomething.prop:           undefined
-doSomething.foo:            undefined
-doSomething.prototype.prop: undefined
-doSomething.prototype.foo:  bar
- -

Different ways to create objects and the resulting prototype chain

- -

Objects created with syntax constructs

- -
var o = {a: 1};
-
-// The newly created object o has Object.prototype as its [[Prototype]]
-// o has no own property named 'hasOwnProperty'
-// hasOwnProperty is an own property of Object.prototype.
-// So o inherits hasOwnProperty from Object.prototype
-// Object.prototype has null as its prototype.
-// o ---> Object.prototype ---> null
-
-var b = ['yo', 'whadup', '?'];
-
-// Arrays inherit from Array.prototype
-// (which has methods indexOf, forEach, etc.)
-// The prototype chain looks like:
-// b ---> Array.prototype ---> Object.prototype ---> null
-
-function f() {
-  return 2;
-}
-
-// Functions inherit from Function.prototype
-// (which has methods call, bind, etc.)
-// f ---> Function.prototype ---> Object.prototype ---> null
-
- -

With a constructor

- -

A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

- -
function Graph() {
-  this.vertices = [];
-  this.edges = [];
-}
-
-Graph.prototype = {
-  addVertex: function(v) {
-    this.vertices.push(v);
-  }
-};
-
-var g = new Graph();
-// g is an object with own properties 'vertices' and 'edges'.
-// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
-
- -

With Object.create

- -

ECMAScript 5 introduced a new method: {{jsxref("Object.create()")}}. Calling this method creates a new object. The prototype of this object is the first argument of the function:

- -
var a = {a: 1};
-// a ---> Object.prototype ---> null
-
-var b = Object.create(a);
-// b ---> a ---> Object.prototype ---> null
-console.log(b.a); // 1 (inherited)
-
-var c = Object.create(b);
-// c ---> b ---> a ---> Object.prototype ---> null
-
-var d = Object.create(null);
-// d ---> null
-console.log(d.hasOwnProperty);
-// undefined, because d doesn't inherit from Object.prototype
-
- -

delete Operator with Object.create and new operator

- -

Using Object.create of another object demonstrates prototypical inheritance with the delete operation:

- -
var a = {a: 1};
-
-var b = Object.create(a);
-
-console.log(a.a); // print 1
-console.log(b.a); // print 1
-b.a=5;
-console.log(a.a); // print 1
-console.log(b.a); // print 5
-delete b.a;
-console.log(a.a); // print 1
-console.log(b.a); // print 1(b.a value 5 is deleted but it showing value from its prototype chain)
-delete a.a;
-console.log(a.a); // print undefined
-console.log(b.a); // print undefined
- -

The new operator has a shorter chain in this example:

- -
function Graph() {
-  this.vertices = [4,4];
-}
-
-var g = new Graph();
-console.log(g.vertices); // print [4,4]
-g.vertices = 25;
-console.log(g.vertices); // print 25
-delete g.vertices;
-console.log(g.vertices); // print undefined
-
- -

With the class keyword

- -

ECMAScript 2015 introduced a new set of keywords implementing classes. The new keywords include {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, and {{jsxref("Operators/super", "super")}}.

- -
'use strict';
-
-class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(sideLength) {
-    super(sideLength, sideLength);
-  }
-  get area() {
-    return this.height * this.width;
-  }
-  set sideLength(newLength) {
-    this.height = newLength;
-    this.width = newLength;
-  }
-}
-
-var square = new Square(2);
-
- -

Performance

- -

The lookup time for properties that are high up on the prototype chain can have a negative impact on the performance, and this may be significant in the code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

- -

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated. To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. To give you a concrete example, let's take the above graph example code to illustrate it:

- -
console.log(g.hasOwnProperty('vertices'));
-// true
-
-console.log(g.hasOwnProperty('nope'));
-// false
-
-console.log(g.hasOwnProperty('addVertex'));
-// false
-
-console.log(g.__proto__.hasOwnProperty('addVertex'));
-// true
-
- -

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

- -

Note: It is not enough to check whether a property is undefined. The property might very well exist, but its value just happens to be set to undefined.

- -

Bad practice: Extension of native prototypes

- -

One misfeature that is often used is to extend Object.prototype or one of the other built-in prototypes.

- -

This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality.

- -

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like Array.forEach.

- -

Summary of methods for extending the prototype chain

- -

Here are all 4 ways and their pros/cons. All of the examples listed below create exactly the same resulting inst object (thus logging the same results to the console), except in different ways for the purpose of illustration.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameExample(s)Pro(s)Con(s)
New-initialization -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = new foo;
-proto.bar_prop = "bar val";
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
-
Supported in every browser imaginable (support goes all the way back to IE 5.5!). Also, it is very fast, very standard, and very JIST-optimizable.In order to use this method, the function in question must be initialized. During this initialization, the constructor may store unique information that must be generated per-object. However, this unique information would only be generated once, potentially leading to problems. Additionally, the initialization of the constructor may put unwanted methods onto the object. However, both these are generally not problems at all (in fact, usually beneficial) if it is all your own code and you know what does what where.
Object.create -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = Object.create(
-  foo.prototype
-);
-proto.bar_prop = "bar val";
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = Object.create(
-  foo.prototype,
-  {
-    bar_prop: {
-      value: "bar val"
-    }
-  }
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the direct setting of __proto__ in a way that is one-time-only so that the browser can better optimize the object. Also allows the creation of objects without a prototype via Object.create(null).Not supported in IE8 and below. However, as Microsoft has discontinued extended support for systems running these old browsers, this should not be a concern for most applications. Additionally, the slow object initialization can be a performance black hole if using the second argument because each object-descriptor property has its own separate descriptor object. When dealing with hundreds of thousands of object descriptors in the form of object, there can arise a serious issue with lag.
-

Object.setPrototypeOf

-
-
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = {
-  bar_prop: "bar val"
-};
-Object.setPrototypeOf(
-  proto, foo.prototype
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto;
-proto=Object.setPrototypeOf(
-  { bar_prop: "bar val" },
-  foo.prototype
-);
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the dynamic manipulation of an objects prototype and can even force a prototype on a prototype-less object created with Object.create(null).Should-be-deprecated and ill-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE8 and below.
__proto__ -
-function foo(){}
-foo.prototype = {
-  foo_prop: "foo val"
-};
-function bar(){}
-var proto = {
-  bar_prop: "bar val",
-  __proto__: foo.prototype
-};
-bar.prototype = proto;
-var inst = new bar;
-console.log(inst.foo_prop);
-console.log(inst.bar_prop);
-
- -
-var inst = {
-  __proto__: {
-    bar_prop: "bar val",
-    __proto__: {
-      foo_prop: "foo val",
-      __proto__: Object.prototype
-    }
-  }
-};
-console.log(inst.foo_prop);
-console.log(inst.bar_prop)
-
Support in all in-use-today browsers which are all non-microsoft browsers plus IE11 and up. Setting __proto__ to something that is not an object only fails silently. It does not throw an exception.Grossly deprecated and non-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE10 and below.
- -

prototype and Object.getPrototypeOf

- -

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

- -

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

- -

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

- -

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

- -

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null.

- -

So, when you call

- -
var o = new Foo();
- -

JavaScript actually just does

- -
var o = new Object();
-o.[[Prototype]] = Foo.prototype;
-Foo.call(o);
- -

(or something like that) and when you later do

- -
o.someProp;
- -

it checks whether o has a property someProp. If not, it checks Object.getPrototypeOf(o).someProp, and if that doesn't exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp, and so on.

- -

In conclusion

- -

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

diff --git a/files/tr/web/javascript/language_resources/index.html b/files/tr/web/javascript/language_resources/index.html deleted file mode 100644 index b9790c06d4..0000000000 --- a/files/tr/web/javascript/language_resources/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: JavaScript language resources -slug: Web/JavaScript/Language_Resources -tags: - - ECMA JavaScript Türkçe - - ECMA Türkçe - - ECMAScript6 - - Türkçe JavaScript -translation_of: Web/JavaScript/Language_Resources ---- -
{{JsSidebar}}
- -

ECMAScript is the scripting language that forms the basis of JavaScript. ECMAScript standardized by the ECMA International standards organization in the ECMA-262 and ECMA-402 specifications. The following ECMAScript standards have been approved or are being worked on:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameLinksRelease dateDescription
Current editions
ECMA-262 10th Edition -

PDF, HTMLWorking draft, repository

-
2019ECMAScript 2019 Language Specification
ECMA-262 9th Edition -

PDF, HTML
- Working draft, repository

-
2018ECMAScript 2018 Language Specification
ECMA-402 5th EditionWorking draft, repository2018ECMAScript 2018 Internationalization API Specification
Obsolete/historical editions
ECMA-262PDFJune 1997ECMAScript: A general purpose, cross-platform programming language. This was the first version of the ECMAScript standard.
ECMA-262 2nd EditionPDFAugust 1998ECMAScript Language Specification. This is the second revision of the ECMAScript standard; also ISO standard 16262.
ECMA-262 3rd EditionPDFDecember 1999ECMAScript Language Specification. This is the third revision of the ECMAScript standard; corresponds to JavaScript 1.5.
- See also the errata
ECMA-262 5th EditionPDFDecember 2009ECMAScript Language Specification. This is the fifth revision of the ECMAScript standard.
- See also the ES5 errata and ECMAScript 5 support in Mozilla
ECMA-357PDFJune 2004ECMAScript for XML (E4X).
- See also the E4X errata.
ECMA-262 5.1 EditionPDF, HTMLJune 2011This version is fully aligned with the 3rd edition of the international standard ISO/IEC 16262:2011.
- It includes ES5 errata fixes, no new features.
ECMA-402 1st EditionPDF, HTMLDecember 2012ECMAScript Internationalization API Specification
ECMA-262 6th EditionPDF, HTMLJune 2015ECMAScript 2015 Language Specification
ECMA-402 2nd EditionPDFJune 2015ECMAScript 2015 Internationalization API Specification
ECMA-262 7th EditionHTMLJune 2016ECMAScript 2016 Language Specification
ECMA-402 3rd EditionHTMLJune 2016ECMAScript 2016 Internationalization API Specification
ECMA-262 8th EditionHTMLJune 2017ECMAScript 2017 Language Specification
ECMA-402 4th EditionHTMLJune 2017ECMAScript 2017 Internationalization API Specification
- -

ES.Next is a dynamic name that refers to whatever the next version is at the time of‍ writing. ES.Next features are more correctly called proposals, because, by definition, the specification has not been finalized yet.

- -

See Wikipedia ECMAScript entry for more information on ECMAScript history.

- -

You can participate in or just track the work on the next revisions of the ECMAScript Language Specification, code-named "Harmony", and the ECMAScript Internationalization API Specification via public wiki and the es-discuss mailing list linked from ecmascript.org.

- -

Implementations

- - - -

See also

- - diff --git a/files/tr/web/javascript/memory_management/index.html b/files/tr/web/javascript/memory_management/index.html deleted file mode 100644 index 50c5a36819..0000000000 --- a/files/tr/web/javascript/memory_management/index.html +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Bellek Yönetimi -slug: Web/JavaScript/Memory_Management -translation_of: Web/JavaScript/Memory_Management ---- -
{{JsSidebar("Advanced")}}
- -

Low-level languages like C, have manual memory management primitives such as malloc() and free(). In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automaticity is a potential source of confusion: it can give developers the false impression that they don't need to worry about memory management.

- -

Memory life cycle

- -

Regardless of the programming language, the memory life cycle is pretty much always the same:

- -
    -
  1. Allocate the memory you need
  2. -
  3. Use the allocated memory (read, write)
  4. -
  5. Release the allocated memory when it is not needed anymore
  6. -
- -

The second part is explicit in all languages. The first and last parts are explicit in low-level languages but are mostly implicit in high-level languages like JavaScript.

- -

Allocation in JavaScript

- -

Value initialization

- -

In order to not bother the programmer with allocations, JavaScript will automatically allocate memory when values are initially declared.

- -
var n = 123; // allocates memory for a number
-var s = 'azerty'; // allocates memory for a string
-
-var o = {
-  a: 1,
-  b: null
-}; // allocates memory for an object and contained values
-
-// (like object) allocates memory for the array and
-// contained values
-var a = [1, null, 'abra'];
-
-function f(a) {
-  return a + 2;
-} // allocates a function (which is a callable object)
-
-// function expressions also allocate an object
-someElement.addEventListener('click', function() {
-  someElement.style.backgroundColor = 'blue';
-}, false);
-
- -

Allocation via function calls

- -

Some function calls result in object allocation.

- -
var d = new Date(); // allocates a Date object
-
-var e = document.createElement('div'); // allocates a DOM element
- -

Some methods allocate new values or objects:

- -
var s = 'azerty';
-var s2 = s.substr(0, 3); // s2 is a new string
-// Since strings are immutable values,
-// JavaScript may decide to not allocate memory,
-// but just store the [0, 3] range.
-
-var a = ['ouais ouais', 'nan nan'];
-var a2 = ['generation', 'nan nan'];
-var a3 = a.concat(a2);
-// new array with 4 elements being
-// the concatenation of a and a2 elements.
-
- -

Using values

- -

Using values basically means reading and writing in allocated memory. This can be done by reading or writing the value of a variable or an object property or even passing an argument to a function.

- -

Release when the memory is not needed anymore

- -

The majority of memory management issues occur at this phase. The most difficult aspect of this stage is determining when the allocated memory is no longer needed. 

- -

Low-level languages require the developer to manually determine at which point in the program the allocated memory is no longer needed and to release it.

- -

Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it. This automatic process is an approximation since the general problem of determining whether or not a specific piece of memory is still needed is undecidable.

- -

Garbage collection

- -

As stated above, the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collectors implement a restriction of a solution to the general problem. This section will explain the concepts that are necessary for understanding the main garbage collection algorithms and their respective limitations.

- -

References

- -

The main concept that garbage collection algorithms rely on is the concept of reference. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to its prototype (implicit reference) and to its properties values (explicit reference).

- -

In this context, the notion of an "object" is extended to something broader than regular JavaScript objects and also contain function scopes (or the global lexical scope).

- -

Reference-counting garbage collection

- -

This is the most naive garbage collection algorithm. This algorithm reduces the problem from determining whether or not an object is still needed to determining if an object still has any other objects referencing it. An object is said to be "garbage", or collectible if there are zero references pointing to it.

- -

Example

- -
var x = {
-  a: {
-    b: 2
-  }
-};
-// 2 objects are created. One is referenced by the other as one of its properties.
-// The other is referenced by virtue of being assigned to the 'x' variable.
-// Obviously, none can be garbage-collected.
-
-
-var y = x;      // The 'y' variable is the second thing that has a reference to the object.
-
-x = 1;          // Now, the object that was originally in 'x' has a unique reference
-                //   embodied by the 'y' variable.
-
-var z = y.a;    // Reference to 'a' property of the object.
-                //   This object now has 2 references: one as a property,
-                //   the other as the 'z' variable.
-
-y = 'mozilla';  // The object that was originally in 'x' has now zero
-                //   references to it. It can be garbage-collected.
-                //   However its 'a' property is still referenced by
-                //   the 'z' variable, so it cannot be freed.
-
-z = null;       // The 'a' property of the object originally in x
-                //   has zero references to it. It can be garbage collected.
-
- -

Limitation: Circular references

- -

There is a limitation when it comes to circular references. In the following example, two objects are created with properties that reference one another, thus creating a cycle. They will go out of scope after the function call has completed. At that point they become unneeded and their allocated memory should be reclaimed. However, the reference-counting algorithm will not consider them reclaimable since each of the two objects has at least one reference pointing to them, resulting in neither of them being marked for garbage collection. Circular references are a common cause of memory leaks.

- -
function f() {
-  var x = {};
-  var y = {};
-  x.a = y;        // x references y
-  y.a = x;        // y references x
-
-  return 'azerty';
-}
-
-f();
-
- -

Real-life example

- -

Internet Explorer 6 and 7 are known to have reference-counting garbage collectors for DOM objects. Cycles are a common mistake that can generate memory leaks:

- -
var div;
-window.onload = function() {
-  div = document.getElementById('myDivElement');
-  div.circularReference = div;
-  div.lotsOfData = new Array(10000).join('*');
-};
-
- -

In the above example, the DOM element "myDivElement" has a circular reference to itself in the "circularReference" property. If the property is not explicitly removed or nulled, a reference-counting garbage collector will always have at least one reference intact and will keep the DOM element in memory even if it was removed from the DOM tree. If the DOM element holds a large amount of data (illustrated in the above example with the "lotsOfData" property), the memory consumed by this data will never be released and can lead to memory related issues such as the browser becoming increasingly slower.

- -

Mark-and-sweep algorithm

- -

This algorithm reduces the definition of "an object is no longer needed" to "an object is unreachable".

- -

This algorithm assumes the knowledge of a set of objects called roots. In JavaScript, the root is the global object. Periodically, the garbage collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

- -

This algorithm is an improvement over the previous one since an object having zero references is effectively unreachable. The opposite does not hold true as we have seen with circular references.

- -

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when "an object is no longer needed".

- -

Cycles are no longer a problem

- -

In the first example above, after the function call returns, the two objects are no longer referenced by any resource that is reachable from the global object. Consequently, they will be found unreachable by the garbage collector and have their allocated memory reclaimed.

- -

Limitation: Releasing memory manually

- -

There are times when it would be convenient to manually decide when and what memory is released. In order to release the memory of an object, it needs to be made explicitly unreachable.

- -

As of 2019, it is not possible to explicitly or programmatically trigger garbage collection in JavaScript.

- -

Node.js

- -

Node.js offers additional options and tools for configuring and debugging memory issues that may not be available for JavaScript executed within a browser environment.

- -

V8 Engine Flags

- -

The max amount of available heap memory can be increased with a flag:

- -

node --max-old-space-size=6000 index.js

- -

We can also expose the garbage collector for debugging memory issues using a flag and the Chrome Debugger:

- -
node --expose-gc --inspect index.js
- -

See also

- - diff --git a/files/tr/web/javascript/reference/classes/index.html b/files/tr/web/javascript/reference/classes/index.html deleted file mode 100644 index 77a29ab167..0000000000 --- a/files/tr/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Constructors - - ECMAScript6 - - Inheritance - - Intermediate - - JavaScript - - Kalıtım - - NeedsTranslation - - TopicStub - - sınıf -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

ECMAScript 2015 ile tanıtılan Javascript sınıfları,  aslında halihazırdaki prototype temelli kalıtımın, sözdizi daha kolaylaştırılmış halidir. Class sözdizimi yeni bir nesne tabanlı Javascript modeli sunmamaktadır.

- -

Sınıf tanımlama

- -


- Aslında sınıflar class oluşturmak için kullanılan özel fonksiyonlardır. Javascript sınıfları klasik fonksiyon tanımladığınız gibi tanımlayabilir veya fonksiyonlar ile yapabildiğiniz gibi bir değişkene atayabilirsiniz.

- -

Sınıf Tanımları

- -

Bir sınıf tanımlamanın bir yolu class ifadesini sınıf adınızla birlikte kullanmaktır. (Örn: Dikdortgen)

- -
class Dikdortgen {
-  constructor(yukseklik, genislik) {
-    this.yukseklik = yukseklik;
-    this.genislik = genislik;
-  }
-}
- -

Erişim

- -

Sınıf tanımları ve fonksiyon tanımları arasındaki önemli bir fark, fonksiyonlara tanımlandığı satırdan önce {{Glossary("Hoisting", "erişim sağlanabilir")}}. Sınıflara tanımlandığı satırdan önce  erişilemezler. Önce sınıfları tanımlamanız ve ardından ona erişmeniz gerekir.  Aksi halde aşağıdakine benzer bir hatayla karşılaşırsınız. {{jsxref("ReferenceError")}}:

- -
var p = new Galeri(); // ReferenceError
-
-class Galeri {}
-
- -

Class expressions

- -

Bir class'ı tanımlamanın bir başka yolu ise "class" ifadesidir. Class ifadelerine isim verilebilir. İsimli olan bir class ifadesi class body'sinin localidir.

- -

 

- -
// isimsiz class
-var Dikdortgen = class {
-  constructor(yukseklik, genislik) {
-    this.yukseklik= yukseklik;
-    this.genislik= genislik;
-  }
-};
-
-// isimli class
-var Dikdortgen = class Dikdortgen {
-  constructor(yukseklik, genislik) {
-    this.yukseklik= yukseklik;
-    this.genislik= genislik;
-  }
-};
-
- -

Class body and method definitions

- -

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructors.

- -

Strict mode

- -

The bodies of class declarations and class expressions are executed in strict mode.

- -

Constructor

- -

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a constructor method.

- -

A constructor can use the super keyword to call the constructor of a parent class.

- -

Prototype methods

- -

See also method definitions.

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
- -

Static methods

- -

The static keyword defines a static method for a class. Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.

- -
class Point {
-    constructor(x, y) {
-        this.x = x;
-        this.y = y;
-    }
-
-    static distance(a, b) {
-        const dx = a.x - b.x;
-        const dy = a.y - b.y;
-
-        return Math.sqrt(dx*dx + dy*dy);
-    }
-}
-
-const p1 = new Point(5, 5);
-const p2 = new Point(10, 10);
-
-console.log(Point.distance(p1, p2));
- -

Sub classing with extends

- -

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
- -

Super class calls with super

- -

The super keyword is used to call functions on an object's parent.

- -
class Cat {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Lion extends Cat {
-  speak() {
-    super.speak();
-    console.log(this.name + ' roars.');
-  }
-}
-
- -

Mix-ins

- -

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

- -

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

- -
var CalculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-var RandomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

A class that uses these mix-ins can then be written like this:

- -
class Foo { }
-class Bar extends CalculatorMixin(RandomizerMixin(Foo)) { }
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
4513{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}45{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
-
- -

[1] Requires strict mode. Non-strict mode support is behind the flag "Enable Experimental JavaScript", disabled by default.

- -

See also

- - diff --git a/files/tr/web/javascript/reference/classes/static/index.html b/files/tr/web/javascript/reference/classes/static/index.html deleted file mode 100644 index 2214e7e227..0000000000 --- a/files/tr/web/javascript/reference/classes/static/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: static -slug: Web/JavaScript/Reference/Classes/static -tags: - - metod - - statik - - sınıf - - tanım -translation_of: Web/JavaScript/Reference/Classes/static ---- -
{{jsSidebar("Classes")}}
- -

static anahtar kelimesi, bir sınıf için statik bir metod tanımlar.

- -

Syntax

- -
static metodAdi() { ... }
- -

Description

- -

Statik metodlar, kendi sınıfları gerçeklenmeden çağırılır ve aynı zamanda sınıf gerçeklendiği anda çağrılabilir olma özelliklerini yitirirler. Statik metodlar, bir uygulama için yardımcı fonksiyonlar tanımlamak için kullanılırlar.

- -

Examples

- -

Aşağıdaki örnek, bir statik metodun sınıfa nasıl entegre edildiğini ve statik metodu olan başka bir sınıfın onun içerisinde nasıl kullanıldığını gösteriyor. Son olarak, statik bir metodun nasıl çağırıldığını ve çağrılma özelliğini nasıl yitirdiğini gösteriyor. 

- -
class Triple {
-  static triple(n) {
-    n = n || 1; //should not be a bitwise operation
-    return n * 3;
-  }
-}
-
-class BiggerTriple extends Triple {
-  static triple(n) {
-    return super.triple(n) * super.triple(n);
-  }
-}
-
-console.log(Triple.triple());        // 3
-console.log(Triple.triple(6));       // 18
-console.log(BiggerTriple.triple(3)); // 81
-var tp = new Triple();
-console.log(BiggerTriple.triple(3)); // 81 (not affected by parent's instantiation)
-console.log(tp.triple());            // 'tp.triple is not a function'.
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/errors/index.html b/files/tr/web/javascript/reference/errors/index.html deleted file mode 100644 index c295fccea6..0000000000 --- a/files/tr/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: JavaScript error reference -slug: Web/JavaScript/Reference/Errors -tags: - - Debugging - - Error - - Errors - - Exception - - JavaScript - - NeedsTranslation - - TopicStub - - exceptions -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

- -

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

- -

List of errors

- -

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 2a811725bf..0000000000 --- a/files/tr/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: 'SyntaxError: missing ; before statement' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -tags: - - JavaScript - - Noktalı virgül - - Sentaks Hatası -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
-

{{jsSidebar("Errors")}}

- -

Mesaj

- -
Syntax Error: Missing ; before statement
-//Sentaks Hatası: ifadeden önce ; eksik
-
- -

Hata Tipi

- -

{{jsxref("SyntaxError")}}.

- -

Ne Ters Gitti?

- -

Kodunuzda bir yerlerde noktalı virgül (;) eksik. JavaScript ifadeleri noktalı virgül ile sonlandırılmalıdır. Bu ifadelerden bazılarına otomatik noktalı virgül eklenmektedir (ASI), fakat bu durumda, JavaScript'in kaynak kodunu doğru bir şekilde çözümleyebilmesi için noktalı virgülü sizin eklemeniz gerekmektedir. 

- -

Bununla birlikte, çoğunlukla bu hata, başka bir hatanın sonucudur, var ifadesinin yanlış kullanımı, string ifadelerinin yazımında tırnakların yanlış kullanımı sebebiyle olabilir, belki de bir yerlerde fazladan bir parantez unuttunuz. Bu hata ile karşılaştığınızda, sentaksınızı kontrol edin, yazım hatalarınızı gözden geçirin.
-  

- -

Örnekler

- -

Kaçınılan metin ifadeleri

- -

Metin ifadelerindeki tırnak kullanımında, metin içinde yer almakta olan tırnakları görüntülemek için önlerine \ yatay çizgi koymalısınız ki JavaScript motoru, sizin metin ifadenizin çoktan bitmiş olduğu izlenimine kapılmasın. Örnek olarak:

- -
var foo = 'Tomris'in barı';
-Sentaks Hatası: ifadeden önce ; eksik
- -

Çift tırnak kullanarak tek tırnağın yanlış kullanımından kaçınabilirsiniz. 

- -
var foo = "Tomris'in barı";
-var foo = 'Tomris\'in barı';
-
- -

var ile Özellikleri Deklare Etmek

- -

var ile bir nesneye veya diziye ait bir özellik tanımlayamazsınız

- -
var nesne = {};
-var nesne.foo = 'hey'; Sentaks Hatası: ifadeden önce ; eksik
-
-var dizi = [];
-var dizi[0] = 'selam'; Sentaks Hatası: ifadeden önce ; eksik
-
- -

Bunun yerine, var anahtar sözcüğünü kaldırın:

- -
var nesne = {};
-nesne.foo = 'hey';
-
-var dizi= [];
-dizi[0] = 'selam';
-
- -

Ayrıca Göz Atın

- - -
diff --git a/files/tr/web/javascript/reference/functions/arrow_functions/index.html b/files/tr/web/javascript/reference/functions/arrow_functions/index.html deleted file mode 100644 index 68d6fb3cc7..0000000000 --- a/files/tr/web/javascript/reference/functions/arrow_functions/index.html +++ /dev/null @@ -1,359 +0,0 @@ ---- -title: Arrow functions -slug: Web/JavaScript/Reference/Functions/Arrow_functions -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -
Arrow fonksiyonlar normal fonksiyonların kısa yoldan yazılabilen türüdür ve kendi içerisinde this, arguments, super, ya da new.target erişimine sahip değildir. Bu fonksiyon tanımlaması özellikle methodsuz fonksiyonlar için çok uygundur. Constructor olarak kullanılamaz. 
- -

Söz Dizimi

- -

Temel Söz Dizimi

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// buna eşittir: (param1, param2, …, paramN) => { return expression; }
-
-// Eğer tek parametre var ise parantezsiz kullanılabilir:
-(singleParam) => { statements }
-singleParam => { statements }
-singleParam => expression
-
-
-// Parametre beklenmeyen durumlarda parantez çifti kullanılmalıdır
-() => { statements }
-
- -

İleri Düzey Söz Dizimi

- -
// Parantez çifti kullanılarak obje tipi veri dönüşü yapılır.
-params => ({foo: bar})
-
-// Rest parameters ve default parameters desteklenmektedir
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
-
-// Destructuring parametre listesi içinde de desteklenir
-let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f();
-// 6
-
- -

Description

- -

Şunu da inceleyin "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

- -

Arrow fonksiyonlarının iki dikkat çekici özelliği vardır: daha kısa fonksiyonlara ihtiyaç ve this anahtar kelimesinin kullanımı.

- -

Kısa fonksiyonlar

- -
var materials = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-materials.map(function(material) {
-  return material.length;
-}); // [8, 6, 7, 9]
-
-materials.map((material) => {
-  return material.length;
-}); // [8, 6, 7, 9]
-
-materials.map(({length}) => length); // [8, 6, 7, 9]
-
- -

No separate this

- -

Arrow fonksiyonlara kadar, her yeni fonksiyon nasıl çağrıldığına bağlı olarak kendi this değerini belirlerdi:

- -

Constructor durumunda yeni bir nesne.
- Strict mode fonksiyon çağrılması durumunda undefined.
- Eğer fonksiyon "nesne metodu" olarak çağrılmışsa temel nesne.
- etc.
-
- Bu kullanım nesne-yönelimli programla içerisinde ideal kullanım değildi.

- -
function Person() {
-  // The Person() fonksiyonu kendini temsil eden this değerini oluşturuyor
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // non-strict modda, growUp() fonksiyonuda her fonksiyon gibi
-    // kendi this değerini tanımlar
-    // bu sayede bir üstteki this değerine artık ulaşamıyor oluruz
-    this.age++; //bu işlem Person() fonksiyonundaki age değerine işlemez.
-  }, 1000);
-}
-
-var p = new Person();
- -

ECMAScript 3/5'te bu this sorunu this değerinin başka bir değişkene atanarak aşılabilmekteydi.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // 'that' bir üstteki this değerine etki eder.
-    that.age++;
-  }, 1000);
-}
- -

Alternatif olarak, bound function tanımlaması yaparak önceden atanmış this değeri growUp() fonksiyonuna bu işlevi kazandırabilir.

- -

Fakat arrow fonksiyonlar kendi this değerine sahip değildir;  kapsayıcı yürütme fonksiyonunun this değeri kullanılır. Böylelikle aşağıdaki örnekte olduğu gibi setInterval'e atanmış arrow fonksiyon kendi this değeri olmadığı için Person() fonksiyonunun this değerine etki eder.

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| person objesine atıfta bulunur
-  }, 1000);
-}
-
-var p = new Person();
- -

Strict mode ile ilişkisi

- -

Kapsayıcı sözcüksel bağlamından gelen this değeri, strict mode kuralları uygulandığında görmezden gelinir

- -
var f = () => { 'use strict'; return this; };
-f() === window; // or the global object
- -

Diğer strict mode kuralları normal olarak geçerlidir.

- -

Invoked through call or apply

- -

Arrow fonksiyonların this değeri olmadığı için,  call() ve apply() methotları sadece parametre verilebilir. thisArg görmezden gelinir.

- -
var adder = {
-  base: 1,
-
-  add: function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base: 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // This would log to 2
-console.log(adder.addThruCall(1)); // This would log to 2 still
- -

No binding of arguments

- -

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the the arguments of the enclosing scope:

- -
var arguments = [1, 2, 3];
-var arr = () => arguments[0];
-
-arr(); // 1
-
-function foo(n) {
-  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
-  return f(10);
-}
-
-foo(1); // 2
- -

Çoğu durumda rest parametreleriarguments nesnesinin iyi bir alternatifidir.

- -
function foo(n) {
-  var f = (...args) => args[0] + n;
-  return f(10);
-}
-
-foo(1); // 11
- -

Method olarak kullanılan Arrow fonksiyonları

- -

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

- -
'use strict';
-var obj = {
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-obj.b(); // prints undefined, Window {...} (or the global object)
-obj.c(); // prints 10, Object {...}
- -

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this);
-    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
-  }
-});
-
- -

new operatörü kullanımı

- -

Arrow functions cannot be used as constructors and will throw an error when used with new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

prototype özelliği kullanımı

- -

Arrow fonksiyonlarının prototype özelliği yoktur.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

yield anahtarının kullanımı

- -

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

- -

Function body

- -

Arrow functions can have either a "concise body" or the usual "block body".

- -

In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit return statement.

- -
var func = x => x * x;
-// concise body syntax, implied "return"
-
-var func = (x, y) => { return x + y; };
-// with block body, explicit "return" needed
-
- -

Returning object literals

- -

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

- -
var func = () => { foo: 1 };
-// Calling func() returns undefined!
-
-var func = () => { foo: function() {} };
-// SyntaxError: function statement requires a name
- -

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

- -

Remember to wrap the object literal in parentheses.

- -
var func = () => ({foo: 1});
- -

Line breaks

- -

An arrow function cannot contain a line break between its parameters and its arrow.

- -
var func = ()
-           => 1;
-// SyntaxError: expected expression, got '=>'
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-
-callback = callback || () => {};
-// SyntaxError: invalid arrow-function arguments
-
-callback = callback || (() => {});    // ok
-
- -

More examples

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')();
-// Returns "foobar"
-// (this is an Immediately Invoked Function Expression
-// see 'IIFE' in glossary)
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-
-var sum = arr.reduce((a, b) => a + b);
-// 66
-
-var even = arr.filter(v => v % 2 == 0);
-// [6, 0, 18]
-
-var double = arr.map(v => v * 2);
-// [10, 12, 26, 0, 2, 36, 46]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-  // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.functions.arrow_functions")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/functions/index.html b/files/tr/web/javascript/reference/functions/index.html deleted file mode 100644 index 0b67f9aa30..0000000000 --- a/files/tr/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,596 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Function - - Functions - - JavaScript - - NeedsTranslation - - Parameter - - TopicStub - - parameters -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Description

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-  theObject.brand = "Toyota";
-}
-
-/*
- * Declare variable 'mycar';
- * create and initialize a new Object;
- * assign reference to it to 'mycar'
- */
-var mycar = {
-  brand: "Honda",
-  model: "Accord",
-  year: 1998
-};
-
-/* Logs 'Honda' */
-console.log(mycar.brand);
-
-/* Pass object reference to the function */
-myFunc(mycar);
-
-/*
- * Logs 'Toyota' as the value of the 'brand' property
- * of the object, as changed to by the function.
- */
-console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Defining functions

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

- -
(function() {
-    statements
-})();
- -

IIFE are function expressions that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Function parameters

- -

Default parameters

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Rest parameters

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

The arguments object

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Defining method functions

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Constructor vs. declaration vs. expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -
/*
- * Declare and initialize a variable 'p' (global)
- * and a function 'myFunc' (to change the scope) inside which
- * declare a varible with same name 'p' (current) and
- * define three functions using three different ways:-
- *     1. function declaration
- *     2. function expression
- *     3. function constructor
- * each of which will log 'p'
- */
-var p = 5;
-function myFunc() {
-    var p = 9;
-
-    function decl() {
-        console.log(p);
-    }
-    var expr = function() {
-        console.log(p);
-    };
-    var cons = new Function('\tconsole.log(p);');
-
-    decl();
-    expr();
-    cons();
-}
-myFunc();
-
-/*
- * Logs:-
- * 9  - for 'decl' by function declaration (current scope)
- * 9  - for 'expr' by function expression (current scope)
- * 5  - for 'cons' by Function constructor (global scope)
- */
-
- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x === 0) {           // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y === 10) {    // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (shouldDefineZero) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Examples

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' === typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.functions")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/concat/index.html b/files/tr/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index dbeaff447e..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Array.prototype.concat -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array - - JavaScript - - Method - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef("Global_Objects", "Array")}}
- -

Özet

- -

concat() metodu eklendigi dizi ile parametre olarak aldığı dizi(leri) birleştirerek yeni bir dizi döndürür.

- -

Söz Dizimi

- -
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
- -

Parmetreler

- -
-
valueN
-
Yeni diziye eklenecek dizi ve/veya değerler. Detaylar için aşağıdaki açıklamayı okuyunuz.
-
- -

Açıklama

- -

concat çağırılan nesnelerin elemanlarını içeren yeni bir dizi oluşturur. Çağırılma sırasıyla, diziyse elemanlarını, değerse kendisini ekler.

- -

concat , this veya çağırılan dizilerden herhangi birini değiştirmez. Onları kopyalayarak yeni bir dizi oluşturur. Orjinal dizilerin öğeleri yeni diziye aşağıdaki gibi kopyalanır:

- - - -
-

Not: Dizi/değerlerin birleştirilmesi orjinallerini değiştirmez. Ayrıca, yeni dizi (eleman nesne referansı değilse) üzerindeki herhangi bir operasyon orjinal dizileri etkilemez. Tam tersi de geçerlidir.

-
- -

Örnekler

- -

Örnek: İki diziyi birleştirme

- -

Aşağıdaki kod iki diziyi birleştiriyor:

- -
var alpha = ['a', 'b', 'c'],
-    numeric = [1, 2, 3];
-
-var alphaNumeric = alpha.concat(numeric);
-
-console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
-
- -

Örnek: Üç diziyi birleştirme

- -

Aşağıdaki kod üç diziyi birleştiriyor:

- -
var num1 = [1, 2, 3],
-    num2 = [4, 5, 6],
-    num3 = [7, 8, 9];
-
-var nums = num1.concat(num2, num3);
-
-console.log(nums); // Result: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Örnek: Değerleri dizi ile birleştirme

- -

Aşağıdaki kod değerler ile diziyi birleştiriyor:

- -
var alpha = ['a', 'b', 'c'];
-
-var alphaNumeric = alpha.concat(1, [2, 3]);
-
-console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - -
ÖzelliklerDurumYorumlar
ECMAScript 3rd EditionStandardInitial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
- -

Tarayıcı Uyumluluğu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/entries/index.html b/files/tr/web/javascript/reference/global_objects/array/entries/index.html deleted file mode 100644 index 7e2d7b6a82..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/entries/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Array/entries -tags: - - Dizi - - döngü - - gezinilebilir -translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries ---- -
{{JSRef}}
- -

entries() metodu, içerisinde, her bir elemanı için anahtar/değer çifti içeren yeni bir Gezinilebilir Dizi nesnesi döndürür.

- -
var a = ['a', 'b', 'c'];
-var iterator = a.entries();
-
-console.log(iterator.next().value); // [0, 'a']
-console.log(iterator.next().value); // [1, 'b']
-console.log(iterator.next().value); // [2, 'c']
-
- -

Söz dizimi

- -
a.entries()
- -

Dönüş değeri

- -

Yeni bir gezinilebilir {{jsxref("Array")}} nesnesi.

- -

Örnekler

- -

Bir for…of döngüsü kullanımı

- -
var a = ['a', 'b', 'c'];
-var iterator = a.entries();
-
-for (let e of iterator) {
-  console.log(e);
-}
-// [0, 'a']
-// [1, 'b']
-// [2, 'c']
-
- -

Tanımlamalar

- - - - - - - - - - - - - - - - - - - -
TanımlamaDurumYorum
{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destekli{{CompatChrome("38")}}{{CompatGeckoDesktop("28")}}{{CompatNo}}{{CompatOpera("25")}}{{CompatSafari("7.1")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destekli{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("28")}}{{CompatNo}}{{CompatNo}}8.0
-
- -

Ayrıca bknz.

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/every/index.html b/files/tr/web/javascript/reference/global_objects/array/every/index.html deleted file mode 100644 index 1cab33d6fe..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/every/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Array.prototype.every() -slug: Web/JavaScript/Reference/Global_Objects/Array/every -translation_of: Web/JavaScript/Reference/Global_Objects/Array/every ---- -
{{JSRef}}
- -
every() metodu bir dizideki tüm elemanların verilen fonksiyonun testini geçip geçmediği kontrol eder. Bu metot true (doğru) yada false (yanlış) olarak ikilik değer döndürür. 
- -
-

Note: Test edilen array boş ise bu metot true deger döndürür.

-
- -
{{EmbedInteractiveExample("pages/js/array-every.html")}}
- - - -

Söz dizimi

- -
arr.every(callback(element[, index[, array]])[, thisArg])
- -

Parametreler

- -
-
callback
-
Her elemanı test eden üç değişken alan bir fonksiyon: -
-
element
-
İşlemde olan geçerli dizi elemanı.
-
index{{Optional_inline}}
-
İşlemde olan geçerli dizi elemanın indeksi .
-
array{{Optional_inline}}
-
every tarafından çağrılan dizi.
-
-
-
thisArg{{Optional_inline}}
-
Geri dönüş yapıldığında this olarak kullanıcak bir değer.
-
- -

Dönüş değeri

- -

Geri dönüş fonksiyonu her bir dizi elemanı için bir {{Glossary("truthy")}} deger dondürse true. Aksi takdirde, false.

- -

Description

- -

The every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a {{Glossary("falsy")}} value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a {{Glossary("truthy")}} value for all elements, every returns true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

- -

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

- -

If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

every does not mutate the array on which it is called.

- -

The range of elements processed by every is set before the first invocation of callback. Therefore, callback will not run on elements that are appended to the array after the call to every begins. If existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them. Elements that are deleted are not visited.

- -

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

- -

Örnekler

- -

Tüm dizi elemanlarının büyüklüğünün test edilmesi

- -

Aşağıdaki örnekte tüm dizi elemanlarının 10'dan büyük yada eşit olma durumu test edilir.

- -
function isBigEnough(element, index, array) {
-  return element >= 10;
-}
-[12, 5, 8, 130, 44].every(isBigEnough);   // false
-[12, 54, 18, 130, 44].every(isBigEnough); // true
-
- -

Ok fonksiyonlarını kullanma

- -

Ok fonksiyonları aynı testin daha kısa söz dizimi ile yapılmasını sağlar.

- -
[12, 5, 8, 130, 44].every(x => x >= 10); // false
-[12, 54, 18, 130, 44].every(x => x >= 10); // true
- -

Polyfill

- -

every was added to the ECMA-262 standard in the 5th edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that callbackfn.call evaluates to the original value of {{jsxref("Function.prototype.call")}}

- -
if (!Array.prototype.every) {
-  Array.prototype.every = function(callbackfn, thisArg) {
-    'use strict';
-    var T, k;
-
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    // 1. Let O be the result of calling ToObject passing the this
-    //    value as the argument.
-    var O = Object(this);
-
-    // 2. Let lenValue be the result of calling the Get internal method
-    //    of O with the argument "length".
-    // 3. Let len be ToUint32(lenValue).
-    var len = O.length >>> 0;
-
-    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
-    if (typeof callbackfn !== 'function') {
-      throw new TypeError();
-    }
-
-    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
-    if (arguments.length > 1) {
-      T = thisArg;
-    }
-
-    // 6. Let k be 0.
-    k = 0;
-
-    // 7. Repeat, while k < len
-    while (k < len) {
-
-      var kValue;
-
-      // a. Let Pk be ToString(k).
-      //   This is implicit for LHS operands of the in operator
-      // b. Let kPresent be the result of calling the HasProperty internal
-      //    method of O with argument Pk.
-      //   This step can be combined with c
-      // c. If kPresent is true, then
-      if (k in O) {
-
-        // i. Let kValue be the result of calling the Get internal method
-        //    of O with argument Pk.
-        kValue = O[k];
-
-        // ii. Let testResult be the result of calling the Call internal method
-        //     of callbackfn with T as the this value and argument list
-        //     containing kValue, k, and O.
-        var testResult = callbackfn.call(T, kValue, k, O);
-
-        // iii. If ToBoolean(testResult) is false, return false.
-        if (!testResult) {
-          return false;
-        }
-      }
-      k++;
-    }
-    return true;
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.every")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/filter/index.html b/files/tr/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 4dfc8eaeae..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -tags: - - Dizi - - ECMAScript 5 - - JavaScript - - Method - - Prototype - - ployfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -
 
- -

filter() metotu sağlanan işlev tarafından uygulanan testi geçen tüm öğelerle birlikte yeni bir dizi oluşturur.

- -
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
- - - -

Söz Dizimi

- -
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- -

Parametreler

- -
-
callback
-
Function , dizinin her öğesini sınamak için bir yordamdır. Öğeyi saklamak için true , aksi takdirde false değerini döndürün. Üç argümanı kabul eder:
-
-
-
element
-
Dizide işlenen mevcut elementtir.
-
index{{optional_inline}}
-
Dizide işlenen geçerli öğenin dizini
-
array{{optional_inline}}
-
The array filter was called upon.
-
-
-
thisArg{{optional_inline}}
-
callback  çalıştığı zaman this olarak kullanmak için değerdir.
-
- -

Dönüş değer

- -

Testi geçen öğeler içeren yeni bir dizi. Hiçbir öğe testi geçemezse, boş bir dizi döndürülür.

- -

Açıklama

- -

filter (), bir dizideki her öğe için sağlanan bir geri çağırma işlevini çağırır ve geri çağrmanın (callback) doğru olan bir değer döndürdüğü tüm değerler için yeni bir dizisini oluşturur. Geri çağırma (callback), yalnızca atanmış değerleri olan dizinin dizinleri için çağrılır; silinmiş veya hiçbir zaman değer atanmamış indeksler için çağrılmaz. Filtre testini geçmeyen dizi öğeleri basitçe atlanır ve yeni diziye dahil edilmez.

- -

Geri Çağırma (callback)  3 argüman ile çağırılır.

- -
    -
  1. elementin değeri
  2. -
  3. elementin indeksi
  4. -
  5. Array nesnesinin geçişi
  6. -
- -

Filtrelemek için bir thisArg parametresi varsa, geri çağırma (callback) bu değer olarak kullanılacaktır. Aksi halde undefined değeri bu değer olarak kullanılacaktır. Sonuçta geri çağırma ile gözlenebilen this değeri, bir işlev tarafından görülenlerin belirlenmesi için kullanılan genel kurallara göre belirlenir.

- -

filter() çağrıldığı diziyi değiştirmez.

- -

filter() tarafından işlenen elemanların aralığı, ilk geri çağırma callback çağrısından önce ayarlanır. filter() çağrısı başladıktan sonra diziye eklenen öğeler, geri çağırma  callback tarafından ziyaret edilmeyecektir. Dizinin mevcut elemanları değiştirilir veya silinirse, geri çağırmaya callback iletilen değerleri filter() tarafından ziyaret edilen zamanın değeri olacaktır; silinen öğeler ziyaret edilmez.

- -

Örnekler

- -

Tüm küçük değerleri filtrelemek

- -

Aşağıdaki örnek, tüm öğeleri 10'dan daha küçük değerlere sahip filtreli bir dizi oluşturmak için filter() kullanır.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

JSON'dan geçersiz girişleri filtrelemek

- -

Aşağıdaki örnek, 0 olmayan,numeric id olan tüm öğelerin filtrelenmiş bir jsonunu oluşturmak için filter() işlevini kullanır. 

- -
var arr = [
-  { id: 15 },
-  { id: -1 },
-  { id: 0 },
-  { id: 3 },
-  { id: 12.2 },
-  { },
-  { id: null },
-  { id: NaN },
-  { id: 'undefined' }
-];
-
-var invalidEntries = 0;
-
-function isNumber(obj) {
-  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
-}
-
-function filterByID(item) {
-  if (isNumber(item.id) && item.id !== 0) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Filtered Array
-// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Number of Invalid Entries = ', invalidEntries);
-// Number of Invalid Entries = 5
-
- -

Array içinde arama yapmak

- -

 

- -

Aşağıdaki örnek, arama keriterlerine göre dizi içeriğini filtrelemek için filter() işlevini kullanır

- -

 

- -
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-function filterItems(query) {
-  return fruits.filter(function(el) {
-      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
-  })
-}
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
- -

ES2015 İmplementasyonu

- -
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-const filterItems = (query) => {
-  return fruits.filter(el => el.toLowerCase().indexOf(query.toLowerCase()) > -1);
-};
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
-
-
- -

Polyfill

- -

5. basımda ECMA-262 standardına filter () eklenmiştir; bu nedenle standardın tüm uygulamalarında bulunmayabilir. Bu kodu, komut dosyalarınızın başına aşağıdaki kodu ekleyerek ve doğal olarak desteklemeyen ECMA-262 uygulamalarında filter() kullanımına izin vererek çözebilirsiniz. Bu algoritma, fn.call öğesinin {{jsxref ("Function.prototype.bind ()")}} özgün değerini değerlendirdiğini varsayarsak, ECMA-262, 5. basımda belirtilene tamamen eşdeğerdir ve bu {{jsxref ("Array.prototype.push ()")}} orijinal değerine sahiptir

- -
if (!Array.prototype.filter){
-  Array.prototype.filter = function(func, thisArg) {
-    'use strict';
-    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
-        throw new TypeError();
-
-    var len = this.length >>> 0,
-        res = new Array(len), // preallocate array
-        t = this, c = 0, i = -1;
-    if (thisArg === undefined){
-      while (++i !== len){
-        // checks to see if the key was set
-        if (i in this){
-          if (func(t[i], i, t)){
-            res[c++] = t[i];
-          }
-        }
-      }
-    }
-    else{
-      while (++i !== len){
-        // checks to see if the key was set
-        if (i in this){
-          if (func.call(thisArg, t[i], i, t)){
-            res[c++] = t[i];
-          }
-        }
-      }
-    }
-
-    res.length = c; // shrink down array to proper size
-    return res;
-  };
-}
- -

 

- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - -
ÖzelliklerStatülerYorumlar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}İlk tanım JavaScript 1.6'da uygulanmıştır.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.filter")}}

-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/find/index.html b/files/tr/web/javascript/reference/global_objects/array/find/index.html deleted file mode 100644 index 76d5e38687..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/find/index.html +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: Array.prototype.find() -slug: Web/JavaScript/Reference/Global_Objects/Array/find -translation_of: Web/JavaScript/Reference/Global_Objects/Array/find ---- -
{{JSRef}}
- -

find() metodu parametre olarak verilen, true/false değer döndüren test fonksiyonunu karşılayan dizi içerisindeki ilk elemanın değerini döndürür. Aksi halde {{jsxref("undefined")}} döndürür.

- -
function yeterinceBuyuk(eleman) {
-  return eleman >= 15;
-}
-
-[12, 5, 8, 130, 44].find(yeterinceBuyuk); // 130
- -

Ayrıca {{jsxref("Array.findIndex", "findIndex()")}} metoduna bakınız, bu metod dizi içerisinde bulunan elemanın değeri yerine indeksini döndürür.

- -

Dizi içerisindeki elemanın pozizyonunu bulmak ya da var olup olmadığına bakmak için {{jsxref("Array.prototype.indexOf()")}} veya {{jsxref("Array.prototype.includes()")}} kullanabilirsiniz.

- -

Sözdizim

- -
arr.find(gericagrim[, thisArg])
- -

Parametreler

- -
-
gericagrim
-
Dizi içerisindeki her bir değer için çalıştırılacak fonksiyon, üç parametre alır: -
-
eleman
-
Dizideki işlenen mevcut eleman.
-
indeks
-
Dizideki işlenen mevcut elemanın indeksi.
-
dizi
-
find metodunun çağırıldığı dizi.
-
-
-
thisArg {{Optional_inline}}
-
 gericagrim çalıştığında this olarak kullanılan nesne.
-
- -

Dönüş değeri

- -

Eğer test doğrulanırsa dizi içerisindeki bir değer; değilse, {{jsxref("undefined")}}.

- -

Açıklama

- -

find metodu gericagrim fonksiyonu doğru bir değer döndürene kadar her bir indeks için bir sefer gericagrim fonksiyonunu çalıştırır. Eğer böyle bir eleman bulunduysa, find derhal bu elemanın değerini döndürür. Aksi halde, find {{jsxref("undefined")}} döndürür. gericagrim 0 dan  length - 1 dahil olmak üzere değer atanan ya da atanmayan dizinin her bir elemanı için çağırılır. Bu, aralıklı diziler için sadece değer atanan indeksleri ziyaret eden diğer metodlardan daha verimsiz olduğu anlamına gelmektedir. 

- -

gericagrim üç parametre ile çağırılır: dizi elemanının değeri, dizi elemanının indeksi, ve geçilen dizi nesnesi.

- -

Eğer bir thisArg parametresi find için sağlanırsa, bu parametre gericagrim fonksiyonunun her çağırılışı için this olarak kullanılacaktır. Eğer sağlanmazsa, {{jsxref("undefined")}} kullanılır.

- -

find üzerinde çağırıldığı diziyi değiştirmez.

- -

find tarafından işlenilen elemanların aralığı gericagrim fonksiyonunun ilk çağırılışından önce atanır. find çağırılmaya başlandığından sonra diziye eklenen elemanlar gericagrim tarafından ziyaret edilmeyecektir. Eğer varolan, ziyaret edilmeyen eleman gericagrim tarafından değiştirilirse, bu elemanı ziyaret eden gericagrim fonkisyonuna aktarılan değeri find metodunun bu elemanın indeksini ziyaret edeceği andaki değer olacaktır; silenen elemanlar yine de ziyaret edilecektir.

- -

Örnekler

- -

Dizi içerisindeki nesneyi bir özelliğinden bulmak

- -
var envanter = [
-    {isim: 'elma', miktar: 2},
-    {isim: 'muz', miktar: 0},
-    {isim: 'kiraz', miktar: 5}
-];
-
-function kirazlariBul(meyve) {
-    return meyve.isim === 'kiraz';
-}
-
-console.log(envanter.find(kirazlariBul));
-// { isim: 'kiraz', miktar: 5 }
- -

Dizi içerisindeki bir asal sayıyı bulmak

- -

Aşağıdaki örnek dizi içerisindeki bir asal sayı olan elemanı bulur (ya da eğer asal sayı yoksa {{jsxref("undefined")}} döndürür).

- -
function asalMi(eleman, indeks, dizi) {
-  var baslangic = 2;
-  while (baslangic <= Math.sqrt(eleman)) {
-    if (eleman % baslangic++ < 1) {
-      return false;
-    }
-  }
-  return eleman > 1;
-}
-
-console.log([4, 6, 8, 12].find(asalMi)); // undefined, bulunamadı
-console.log([4, 5, 8, 12].find(asalMi)); // 5
-
- -

Aşağıdaki örnek varolmayan ve silinen elemanların ziyaret edildiğini ve gericağrım fonksiyonuna gönderilen değerin ziyaret edildikleri andaki değerleri olduğunu gösterir.

- -
// İndeks 2, 3 ve 4 için elemanı bulunmayan bir dizi tanımlar
-var a = [0,1,,,,5,6];
-
-// Sadece değer atanmış olanlar değil, tüm indeksleri gösterir
-a.find(function(deger, indeks) {
-  console.log('Ziyaret edilen indeks ' + indeks + ' ve değeri ' + deger);
-});
-
-// Silinenler dahil, bütün indeksleri gösterir
-a.find(function(deger, indeks) {
-
-  // İndeksi 5 olan elamanı birinci iterasyonda siler
-  if (indeks == 0) {
-    console.log('a[5] siliniyor ve değeri ' + a[5]);
-    delete a[5];
-  }
-  // İndeksi 5 olan elaman silinse bile yine de ziyaret edilir
-  console.log('Ziyaret edilen indeks ' + indeks + ' ve değeri ' + deger);
-});
-
-
- -

Polyfill

- -

Bu metod ECMAScript 2015 spesifikasyonuna eklenmiştir ve tüm JavaScript implementasyonlarında kullanıma hazır olmayabilir. Fakat,  aşağıdaki kod parçacığı ile Array.prototype.find polyfill yapabilirsiniz:

- -
// https://tc39.github.io/ecma262/#sec-array.prototype.find
-if (!Array.prototype.find) {
-  Object.defineProperty(Array.prototype, 'find', {
-    value: function(predicate) {
-     // 1. Let O be ? ToObject(this value).
-      if (this == null) {
-        throw new TypeError('"this" is null or not defined');
-      }
-
-      var o = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(O, "length")).
-      var len = o.length >>> 0;
-
-      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
-      if (typeof predicate !== 'function') {
-        throw new TypeError('predicate must be a function');
-      }
-
-      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
-      var thisArg = arguments[1];
-
-      // 5. Let k be 0.
-      var k = 0;
-
-      // 6. Repeat, while k < len
-      while (k < len) {
-        // a. Let Pk be ! ToString(k).
-        // b. Let kValue be ? Get(O, Pk).
-        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
-        // d. If testResult is true, return kValue.
-        var kValue = o[k];
-        if (predicate.call(thisArg, kValue, k, o)) {
-          return kValue;
-        }
-        // e. Increase k by 1.
-        k++;
-      }
-
-      // 7. Return undefined.
-      return undefined;
-    }
-  });
-}
-
- -

Eğer Object.defineProperty desteği bulunmayan tamamen eskimiş JavaScript motorları için ihtiyacınız varsa, Array.prototype metodlarını polyfill yapmamanız en doğrusudur, çünkü bu metodlar numaralandırılabilir olmayan metodlardır.

- -

Spesifikasyonlar

- - - - - - - - - - - - - - - - - - - -
SpesifikasyonDurumAçıklama
{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.find")}}

-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/findindex/index.html b/files/tr/web/javascript/reference/global_objects/array/findindex/index.html deleted file mode 100644 index 8933892986..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/findindex/index.html +++ /dev/null @@ -1,177 +0,0 @@ ---- -title: Array.prototype.findIndex() -slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex -translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex ---- -
{{JSRef}}
- -

FindIndex () yöntemi, sağlanan test işlevini karşılayan dizideki ilk öğenin dizinini döndürür. Aksi takdirde -1 iade edilir.

- -
{{EmbedInteractiveExample("pages/js/array-findindex.html")}}
- - - -
 
- -

Ayrıca, dizinde bulunan dizinin yerine bulunan bir öğenin değerini döndüren {{jsxref ("Array.find", "find ()")}} yöntemine de bakın.

- -

Syntax

- -
arr.findIndex(callback[, thisArg])
- -

Parameters

- -
-
callback
-
Function to execute on each value in the array, taking three arguments: -
-
element
-
The current element being processed in the array.
-
index{{optional_inline}}
-
The index of the current element being processed in the array.
-
array{{optional_inline}}
-
The array findIndex was called upon.
-
-
-
thisArg{{optional_inline}}
-
Optional. Object to use as this when executing callback.
-
- -

Return value

- -

An index in the array if an element passes the test; otherwise, -1.

- -

Description

- -

The findIndex method executes the callback function once for every array index 0..length-1 (inclusive) in the array until it finds one where callback returns a truthy value (a value that coerces to true). If such an element is found, findIndex immediately returns the index for that iteration. If the callback never returns a truthy value or the array's length is 0, findIndex returns -1. Unlike some other array methods such as Array#some, in sparse arrays the callback is called even for indexes of entries not present in the array.

- -

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

- -

If a thisArg parameter is provided to findIndex, it will be used as the this for each invocation of the callback. If it is not provided, then {{jsxref("undefined")}} is used.

- -

findIndex does not mutate the array on which it is called.

- -

The range of elements processed by findIndex is set before the first invocation of callback. Elements that are appended to the array after the call to findIndex begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that findIndex visits that element's index; elements that are deleted are still visited.

- -

Examples

- -

Find the index of a prime number in an array

- -

The following example finds the index of an element in the array that is a prime number (or returns -1 if there is no prime number).

- -
function isPrime(element, index, array) {
-  var start = 2;
-  while (start <= Math.sqrt(element)) {
-    if (element % start < 1) {
-      return false;
-    } else {
-        start++;
-    }
-  }
-  return element > 1;
-}
-
-console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
-console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
-
- -

Find index using arrow function

- -

The following example finds the index of a fruit using an arrow function.

- -
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
-
-const index = fruits.findIndex(fruit => fruit === "blueberries");
-
-console.log(index); // 3
-console.log(fruits[index]); // blueberries
-
- -

Polyfill

- -
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
-if (!Array.prototype.findIndex) {
-  Object.defineProperty(Array.prototype, 'findIndex', {
-    value: function(predicate) {
-     // 1. Let O be ? ToObject(this value).
-      if (this == null) {
-        throw new TypeError('"this" is null or not defined');
-      }
-
-      var o = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(O, "length")).
-      var len = o.length >>> 0;
-
-      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
-      if (typeof predicate !== 'function') {
-        throw new TypeError('predicate must be a function');
-      }
-
-      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
-      var thisArg = arguments[1];
-
-      // 5. Let k be 0.
-      var k = 0;
-
-      // 6. Repeat, while k < len
-      while (k < len) {
-        // a. Let Pk be ! ToString(k).
-        // b. Let kValue be ? Get(O, Pk).
-        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
-        // d. If testResult is true, return k.
-        var kValue = o[k];
-        if (predicate.call(thisArg, kValue, k, o)) {
-          return k;
-        }
-        // e. Increase k by 1.
-        k++;
-      }
-
-      // 7. Return -1.
-      return -1;
-    },
-    configurable: true,
-    writable: true
-  });
-}
-
- -

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.findIndex")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/foreach/index.html b/files/tr/web/javascript/reference/global_objects/array/foreach/index.html deleted file mode 100644 index 46d677f17a..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: Array.prototype.forEach() -slug: Web/JavaScript/Reference/Global_Objects/Array/forEach -translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach ---- -
{{JSRef}}
- -

forEach() metodu dizideki her eleman için verilen metodu çalıştırır.

- -
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
- - - -

Syntax

- -
arr.forEach(function callback(currentValue[, index[, array]]) {
-    //your iterator
-}[, thisArg]);
- -

Parametreler

- -
-
callback
-
Aşağıdaki üç parametreyi alan ve dizinin her elemanı için çalışan fonksiyon.
-
-
-
currentValue{{optional_inline}}
-
İşlenmekte olan dizi elemanı.
-
index{{optional_inline}}
-
İşlenmekte olan dizi elemanının indeksi, yani dizideki sırası.
-
array{{optional_inline}}
-
forEach() in uygulanmakta olduğu dizi.
-
-
-
thisArg {{Optional_inline}}
-
-

callback fonksiyonu çağırılırken, fonksiyon içerisinde this yerine kullanılılabilecek değer.

-
-
- -

Dönüş Değeri

- -

{{jsxref("undefined")}}.

- -

Tanım

- -

forEach() tanımlanmış olan callback fonksiyonunu dizideki her eleman için bir kere olmak üzere, indeks sırasına göre artan şekilde çalıştırır. Silinmiş ya da tanımsız olan elemanlar için fonksiyon çalışmaz (örnek: seyrek diziler).

- -

Dizinin

- -

callback çağırılırken aşağıdaki üç parametre kullanılır:

- - - -

If a thisArg parameter is provided to forEach(), it will be used as callback's this value.  Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.

- -

forEach() executes the callback function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.

- -

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

- -
-

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

- -

Early termination may be accomplished with:

- - - -

The other Array methods: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.

-
- -

Examples

- -

Converting a for loop to forEach

- -

before

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-for (let i=0; i<items.length; i++) {
-  copy.push(items[i])
-}
-
- -

after

- -
const items = ['item1', 'item2', 'item3'];
-const copy = [];
-
-items.forEach(function(item){
-  copy.push(item)
-});
-
-
- -

 

- -

Printing the contents of an array

- -

The following code logs a line for each element in an array:

- -
function logArrayElements(element, index, array) {
-  console.log('a[' + index + '] = ' + element);
-}
-
-// Notice that index 2 is skipped since there is no item at
-// that position in the array.
-[2, 5, , 9].forEach(logArrayElements);
-// logs:
-// a[0] = 2
-// a[1] = 5
-// a[3] = 9
-
- -

Using thisArg

- -

The following (contrived) example updates an object's properties from each entry in the array:

- -
function Counter() {
-  this.sum = 0;
-  this.count = 0;
-}
-Counter.prototype.add = function(array) {
-  array.forEach(function(entry) {
-    this.sum += entry;
-    ++this.count;
-  }, this);
-  // ^---- Note
-};
-
-const obj = new Counter();
-obj.add([2, 5, 9]);
-obj.count;
-// 3
-obj.sum;
-// 16
-
- -

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

- -
-

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.

-
- -

An object copy function

- -

The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

- -
function copy(obj) {
-  const copy = Object.create(Object.getPrototypeOf(obj));
-  const propNames = Object.getOwnPropertyNames(obj);
-
-  propNames.forEach(function(name) {
-    const desc = Object.getOwnPropertyDescriptor(obj, name);
-    Object.defineProperty(copy, name, desc);
-  });
-
-  return copy;
-}
-
-const obj1 = { a: 1, b: 2 };
-const obj2 = copy(obj1); // obj2 looks like obj1 now
-
- -

If the array is modified during iteration, other elements might be skipped.

- -

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

- -
var words = ['one', 'two', 'three', 'four'];
-words.forEach(function(word) {
-  console.log(word);
-  if (word === 'two') {
-    words.shift();
-  }
-});
-// one
-// two
-// four
-
- -

Polyfill

- -

forEach() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of forEach() in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that callback.call() evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.18
-// Reference: http://es5.github.io/#x15.4.4.18
-if (!Array.prototype.forEach) {
-
-  Array.prototype.forEach = function(callback/*, thisArg*/) {
-
-    var T, k;
-
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    // 1. Let O be the result of calling toObject() passing the
-    // |this| value as the argument.
-    var O = Object(this);
-
-    // 2. Let lenValue be the result of calling the Get() internal
-    // method of O with the argument "length".
-    // 3. Let len be toUint32(lenValue).
-    var len = O.length >>> 0;
-
-    // 4. If isCallable(callback) is false, throw a TypeError exception.
-    // See: http://es5.github.com/#x9.11
-    if (typeof callback !== 'function') {
-      throw new TypeError(callback + ' is not a function');
-    }
-
-    // 5. If thisArg was supplied, let T be thisArg; else let
-    // T be undefined.
-    if (arguments.length > 1) {
-      T = arguments[1];
-    }
-
-    // 6. Let k be 0.
-    k = 0;
-
-    // 7. Repeat while k < len.
-    while (k < len) {
-
-      var kValue;
-
-      // a. Let Pk be ToString(k).
-      //    This is implicit for LHS operands of the in operator.
-      // b. Let kPresent be the result of calling the HasProperty
-      //    internal method of O with argument Pk.
-      //    This step can be combined with c.
-      // c. If kPresent is true, then
-      if (k in O) {
-
-        // i. Let kValue be the result of calling the Get internal
-        // method of O with argument Pk.
-        kValue = O[k];
-
-        // ii. Call the Call internal method of callback with T as
-        // the this value and argument list containing kValue, k, and O.
-        callback.call(T, kValue, k, O);
-      }
-      // d. Increase k by 1.
-      k++;
-    }
-    // 8. return undefined.
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.forEach")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/from/index.html b/files/tr/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index d0d45add78..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,258 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Array.from() metodu bir dizi-benzeri veya gezinilebilir bir nesneden yeni bir Dizi örneği oluşturur.

- -
Array.from("birşey");
-// ["b", "i", "r", "ş", "e", "y"]
- -

Söz dizimi

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Parametreler

- -
-
arrayLike
-
Diziye çevrilecek olan dizi-benzeri ya da gezinilebilir nesnedir.
-
mapFn
-
İsteğe bağlı. Map fonksiyonu tüm dizi öğeleri için çağrılır.
-
thisArg
-
İsteğe bağlı. mapFn fonksiyonu işletilirken kullanılacak olan this argüman değeridir.
-
- -

Dönüş değeri

- -

Yeni bir {{jsxref("Array")}} örneği.

- -

Açıklama

- -

Array.from(), aşağıdaki yapılardan Diziler oluşturmanıza izin verir:

- - - -

Array.from() has an optional parameter mapFn, which allows you to execute a {{jsxref("Array.prototype.map", "map")}} function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

- -

The length property of the from() method is 1.

- -

In ES2015, the class syntax allows for sub-classing of both built-in and user defined classes; as a result, static methods such as Array.from are "inherited" by subclasses of Array and create new instances of the subclass, not Array.

- -

Örnekler

- -

Bir metinden Dizi oluşturma

- -
Array.from("birşey");
-// ["b", "i", "r", "ş", "e", "y"]
- -

Bir Set nesnesinden Dizi oluşturma

- -
var s = new Set(["birşey", window]);
-Array.from(s);
-// ["birşey", window]
- -

Bir Map nesnesinden Dizi oluşturma

- -
var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
- -

Bir dizi-benzeri nesneden dizi oluşturma (argümanlar)

- -
function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-
-// [1, 2, 3]
- -

Ok işlevleri ve Array.from kullanma

- -
// Bir işlevini, map işlevi olarak kullanıp
-// öğeler üzerinde oynama yapmak
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Generate a sequence of numbers
-// Since the array is initialized with `undefined` on each position,
-// the value of `v` below will be `undefined`
-Array.from({length: 5}, (v, i) => i);
-// [0, 1, 2, 3, 4]
-
- -

Polyfill

- -

Array.from was added to the ECMA-262 standard in the 6th edition (ES2015); as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of Array.from in implementations that don't natively support it.  This algorithm is exactly the one specified in ECMA-262, 6th edition, assuming Object and TypeError have their original values and that callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}. In addition, since true iterables can not be polyfilled, this implementation does not support generic iterables as defined in the 6th edition of ECMA-262.

- -
// Production steps of ECMA-262, Edition 6, 22.1.2.1
-if (!Array.from) {
-  Array.from = (function () {
-    var toStr = Object.prototype.toString;
-    var isCallable = function (fn) {
-      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
-    };
-    var toInteger = function (value) {
-      var number = Number(value);
-      if (isNaN(number)) { return 0; }
-      if (number === 0 || !isFinite(number)) { return number; }
-      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
-    };
-    var maxSafeInteger = Math.pow(2, 53) - 1;
-    var toLength = function (value) {
-      var len = toInteger(value);
-      return Math.min(Math.max(len, 0), maxSafeInteger);
-    };
-
-    // The length property of the from method is 1.
-    return function from(arrayLike/*, mapFn, thisArg */) {
-      // 1. Let C be the this value.
-      var C = this;
-
-      // 2. Let items be ToObject(arrayLike).
-      var items = Object(arrayLike);
-
-      // 3. ReturnIfAbrupt(items).
-      if (arrayLike == null) {
-        throw new TypeError("Array.from requires an array-like object - not null or undefined");
-      }
-
-      // 4. If mapfn is undefined, then let mapping be false.
-      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
-      var T;
-      if (typeof mapFn !== 'undefined') {
-        // 5. else
-        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
-        if (!isCallable(mapFn)) {
-          throw new TypeError('Array.from: when provided, the second argument must be a function');
-        }
-
-        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
-        if (arguments.length > 2) {
-          T = arguments[2];
-        }
-      }
-
-      // 10. Let lenValue be Get(items, "length").
-      // 11. Let len be ToLength(lenValue).
-      var len = toLength(items.length);
-
-      // 13. If IsConstructor(C) is true, then
-      // 13. a. Let A be the result of calling the [[Construct]] internal method
-      // of C with an argument list containing the single item len.
-      // 14. a. Else, Let A be ArrayCreate(len).
-      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
-
-      // 16. Let k be 0.
-      var k = 0;
-      // 17. Repeat, while k < len… (also steps a - h)
-      var kValue;
-      while (k < len) {
-        kValue = items[k];
-        if (mapFn) {
-          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
-        } else {
-          A[k] = kValue;
-        }
-        k += 1;
-      }
-      // 18. Let putStatus be Put(A, "length", len, true).
-      A.length = len;
-      // 20. Return A.
-      return A;
-    };
-  }());
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}9.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/includes/index.html b/files/tr/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index 7ccb8cebc9..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -
{{JSRef}}
- -

includes() metodu bir dizinin belirli bir elemanı içerip içermediğini belirler, içeriyorsa true içermiyorsa false değeri döndürür. Aranan öğenin bulunup bulunmadığını belirlemek için sameValueZero algoritmasını kullanır.

- -
var a = [1, 2, 3];
-a.includes(2); // true
-a.includes(4); // false
-
- -

{{EmbedInteractiveExample("pages/js/array-includes.html")}} 

- -
- -
- -

Söz Dizimi

- -
arr.includes(searchElement)
-arr.includes(searchElement, fromIndex)
-
- -

Parametreler

- -
-
searchElement
-
Aranan eleman.
-
fromIndex {{optional_inline}}
-
Dizide searchElement için aramanın başlatılacağı indis. Negatif bir değer, dizinin sonundan aramaya başlar. Varsayılan değer 0'dır.
-
- -

Return value

- -

A {{jsxref("Boolean")}}.

- -

Örnekler

- -
[1, 2, 3].includes(2);     // true
-[1, 2, 3].includes(4);     // false
-[1, 2, 3].includes(3, 3);  // false
-[1, 2, 3].includes(3, -1); // true
-[1, 2, NaN].includes(NaN); // true
-
- -

fromIndex dizi uzunluğundan büyük veya eşitse

- -

Eğer fromIndex dizinin uzunluğundan büyük veya eşitse, false döndürülür. Dizi aranmaz.

- -
var arr = ['a', 'b', 'c'];
-
-arr.includes('c', 3);   //false
-arr.includes('c', 100); // false
- -

Hesaplanan indis 0'dan küçükse

- -

Eğer fromIndex negatifse, hesaplanan indis, searchElement için aramaya başlanacak konum olarak belirlenir. Hesaplanmış indis 0'dan küçükse, dizinin tamamı aranır.

- -
// array length is 3
-// fromIndex is -100
-// computed index is 3 + (-100) = -97
-
-var arr = ['a', 'b', 'c'];
-
-arr.includes('a', -100); // true
-arr.includes('b', -100); // true
-arr.includes('c', -100); // true
- -

includes() genel bir yöntem olarak kullanılması

- -

includes() yöntemi kasıtlı olarak geneldir. this değerinin bir Array nesnesi türünde olmasını gerektirmez, böylece diğer türlerdeki nesnelere (örn: dizi benzeri nesneler) uygulanabilir. Aşağıdaki örnek, fonksiyonun sahip olduğu argümanlar nesnesi için uygulanan includes() metodunu göstermektedir.

- -
(function() {
-  console.log([].includes.call(arguments, 'a')); // true
-  console.log([].includes.call(arguments, 'd')); // false
-})('a','b','c');
- -

Polyfill

- -
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
-if (!Array.prototype.includes) {
-  Object.defineProperty(Array.prototype, 'includes', {
-    value: function(searchElement, fromIndex) {
-
-      if (this == null) {
-        throw new TypeError('"this" is null or not defined');
-      }
-
-      // 1. Let O be ? ToObject(this value).
-      var o = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(O, "length")).
-      var len = o.length >>> 0;
-
-      // 3. If len is 0, return false.
-      if (len === 0) {
-        return false;
-      }
-
-      // 4. Let n be ? ToInteger(fromIndex).
-      //    (If fromIndex is undefined, this step produces the value 0.)
-      var n = fromIndex | 0;
-
-      // 5. If n ≥ 0, then
-      //  a. Let k be n.
-      // 6. Else n < 0,
-      //  a. Let k be len + n.
-      //  b. If k < 0, let k be 0.
-      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
-
-      function sameValueZero(x, y) {
-        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
-      }
-
-      // 7. Repeat, while k < len
-      while (k < len) {
-        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
-        // b. If SameValueZero(searchElement, elementK) is true, return true.
-        if (sameValueZero(o[k], searchElement)) {
-          return true;
-        }
-        // c. Increase k by 1.
-        k++;
-      }
-
-      // 8. Return false
-      return false;
-    }
-  });
-}
-
- -

Object.defineProperty desteklemeyen eski JavaScript motorlarını desteklemeniz gerekiyorsa, Array.prototype metodlarını non-enumerable yapamadığımız için polyfill uygulamamak daha iyidir.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.includes")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/index.html b/files/tr/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 7cebdbba0f..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,371 +0,0 @@ ---- -title: Diziler -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - JavaScript -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

JavaScript Array nesnesi, üst düzey, liste benzeri dizi yapıları için kullanılan genel bir nesnedir.

- -

Bir dizi oluşturma

- -
var meyveler = ["Elma", "Muz"];
-
-console.log(meyveler.length);
-// 2
- -

Dizideki (indeks ile) elemana ulaşma

- -
var ilk = meyveler[0];
-// Elma
-
-var son = meyveler[meyveler.length - 1];
-/* Diziler sıfır-tabanlı olduğu için uzunluk-1'inci eleman son elemandır.
-// Muz
- -

Bir dizi üzerinde döngü kurma

- -
meyveler.forEach(function (item, index, array) {
-  console.log(item, index);
-});
-// Elma 0
-// Muz 1
- -

Dizinin sonuna eleman ekleme

- -
var yeniDizi = meyveler.push("Portakal");
-// ["Elma", "Muz", "Portakal"]
- -

Dizi sonundan eleman kaldırma

- -
var son = meyveler.pop(); // Portakal elemanını kaldır(sondan)
-// ["Elma", "Muz"];
- -

Dizi başından eleman kaldırma

- -
var ilk = fruits.shift(); // Elma elemanını kaldır(baştan)
-// ["Muz"];
- -

Dizi başına eleman ekleme

- -
var yeniDizi = fruits.unshift("Çilek") // Başa ekle
-// ["Çilek", "Muz"];
- -

Dizideki elemanın kaçıncı sırada olduğunu bulma

- -
meyveler.push("Mango");
-// ["Çilek", "Muz", "Mango"]
-
-var pos = meyveler.indexOf("Muz");
-// 1
- -

Belirli bir sıradaki elemanı silme

- -
var silinenEleman = meyveler.splice(pos, 1); // bir elemanı kaldırma
-// ["Çilek", "Mango"]
-
- -

Dizi kopyalama

- -
var kopyalananDizi = meyveler.slice(); //
-// ["Çilek", "Mango"]
- -

Söz Dizimi

- -
[element0, element1, ..., elementN]
-new Array(element0, element1, ..., elementN)
-new Array(diziUzunlugu)
-
- -
-

Not: N + 1 = dizi uzunluğu

-
- -
-
element0, element1, ..., elementN
-
Bir dizi new Array() nesnesine verilen argüman dışında(yukarıdaki diziUzunluğu argümanı gibi), verilen elemanlar ile oluşturulabilir.(Yukarıda görüldüğü üzere) Bu özel durum sadece new Array() nesnesiyle (Array Constructor) oluşturulan dizilere uygulanabilir, köşeli parantezler ( [ ve ] ) ile oluşturulan dizilere uygulanamaz.
-
arrayLength (dizi uzunluğu)
-
array nesnesinden sadece 0 ve 232-1 (dahil) arasındaki tam sayılardan biri argüman olarak geçirilebilir.
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), a new, empty JavaScript array and its length is set to that number. If the argument is any other number, a {{jsxref("Global_Objects/RangeError", "RangeError")}} exception is thrown.
-
- -

Tanım

- -

Diziler liste benzeri nesnelerdir ve dönüştürme, tekrarlama gibi işlemlerini uygulamak için dahili methotlarla gelmektedir. JavaScript dizilerinin ne uzunlukları nede elemanları sabit değildir. Önceden tanımlamak gerekmez. Listenin uzunluğu her daim değişebilir ve dizi elemanları ayrık yerleştirilebilir. JavaScript dizilerin düzenli olmasını garanti etmez. Kullanımı tamamen geliştiricinin kullanım senaryosuna bağlıdır. Genel olarak bu yapı esnek ve kullanışlıdır fakat bu özelliklerin sizin belirli kullanım senaryonuzla uyuşup uyuşmadığını dikkate almalısınız.

- -

Note that you shouldn't use an array as an associative array. You can use plain {{jsxref("Global_Objects/Object", "objects")}} instead, although doing so comes with its own caveats. See the post Lightweight JavaScript dictionaries with arbitrary keys as an example.

- -

Dizi nesnelerine erişme

- -

JS dizileri sıfır-tabanlı'dır. Yani ilk elemanın dizideki index'i 0'dır. Son elemanın index'i {{jsxref("Array.length", "length")}} değerinin bir eksiğine eşittir.

- -
var arr = ["bu ilk eleman", "bu ikinci eleman"];
-console.log(arr[0]);              // ilk elemanı yazdırır
-console.log(arr[1]);              // ikinci elemanı yazdırır
-console.log(arr[arr.length - 1]); // son elemanı yazdırır
-
- -

Dizi öğeleri, {{jsxref("Array.toString", "toString")}} gibi sadece nesne özellikleridir. Geçersiz index numarası ile eleman çağırdığınız zaman undefined değerini alırsınız. Ancak, dizinin bir elemanına aşağıdaki gibi erişmeye çalışırsanız söz dizimi hatası alırsınız, çünkü özellik adı geçerli değildir.

- -
console.log(arr.0); // bir söz dizimi hatasıdır
-
- -

Yukardaki kullanımın söz dizimi hatasına yol açmasında özel bir durum yoktur nokta ile gösterim sayı değeri ile başlayamaz tıpkı değişken tanımlamalarında olduğu gibi. Eğer '3d' isimli bir obje değerine ulaşmak istiyorsanız obj['3d'] çağırımını yapmalısınız.

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // söz dizimi hatası
-console.log(years[0]);  // çalışır
-
- -
renderer.3d.setTexture(model, "character.png");     // söz dizimi hatası
-renderer["3d"].setTexture(model, "character.png");  // çalışır
-
- -

Note that in the 3d example, "3d" had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years["2"] instead of years[2]), although it's not necessary. The 2 in years[2] eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion. It is for this reason that "2" and "02" would refer to two different slots on the years object and the following example logs true:

- -
console.log(years["2"] != years["02"]);
-
- -

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation:

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['array']);
- -

Uzunluk ve sayısal özellikler arasındaki ilişki

- -

Bir JavaScript dizisinin {{jsxref("Array.length", "length")}} özelliği ve sayısal özellikleri bağlıdır. Bir takım ön tanımlı dizi metotları (örn., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, vb.) çağrıldıklarında, dizinin {{jsxref("Array.length", "length")}} özellik değerini hesaba katar. Diğer metotlar (örn., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, vb.) daha çok dizinin {{jsxref("Array.length", "length")}} özelliğinin güncellenmesine neden olur.

- -
var meyveler = [];
-meyveler.push("muz", "elma", "şeftali");
-
-console.log(meyveler.length); // 3
- -

Uygun bir index değeri ile beraber, bir dizi elemanı güncellenirse ve ilgili index sayısı dizi sınırları dışında ise; dizi boyutu, verilen index'e uyum sağlayacak biçimde büyüyecek ve Javascript motoru, dizinin {{jsxref("Array.length", "length")}} özelliğini uygun şekilde güncelleyecektir.

- -
fruits[3] = "mango";
-console.log(fruits[3]);
-console.log(fruits.length); // 4
- -

Uzunluk özelliğini doğrudan ayarlamak, özel bir davranışa neden olur.

- -
fruits.length = 10;
-console.log(fruits);        // Dizi, tanımsız olarak doldurulur
-console.log(fruits.length); // 10
-
- -

Bu özellik {{jsxref("Array.length")}} sayfasında daha ayrıntılı olarak anlatılmıştır.

- -

Bir diziyi eşleşen bir sonuç ile oluşturmak

- -

Bir düzenli ifadeye yollanan metin sonucu bir JavaScript dizisi oluşturulabilir. Bu dizi, eşleşen sonuca ait özellikleri ve ifadeleri içerir. Böyle bir dizi {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, ve {{jsxref("String.replace")}} tarafından döndürülür. Bu özellikler ve öğeleri açıklamaya yardımcı olabilmesi için aşağıdaki örneği ve altındaki tabloyu inceleyin.

- -
// Match one d followed by one or more b's followed by one d
-// Remember matched b's and the following d
-// Ignore case
-
-var myRe = /d(b+)(d)/i;
-var myArray = myRe.exec("cdbBdbsbz");
-
- -

Eşleşen sonucun öğeleri ve özellikleri aşağıdaki gibidir:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Özellik/ÖğeAçıklamaÖrnek
inputDüzenli ifadeye yollanan metni işaret eden salt-okunur bir özelliktir.cdbBdbsbz
indexDüzenli ifadeye yollanan metindeki eşleşmenin sıfır-tabanlı ve salt-okunur index özelliğidir.1
[0]Son eşleşen karakteri belirten salt-okunur bir özelliktir.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
- [2]: d
- -

Özellikler

- -
-
{{jsxref("Array.length")}}
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Yöntemler

- -
-
{{jsxref("Array.from()")}} {{experimental_inline}}
-
Bir dizi benzeri veya bir yinelenebilir nesneden yeni bir Dizi örneği oluşturur.
-
{{jsxref("Array.isArray()")}}
-
Eğer bir dizi ise true, değilse false döndürür.
-
{{jsxref("Array.observe()")}} {{experimental_inline}}
-
Asynchronously observes changes to Arrays, similar to {{jsxref("Object.observe()")}} for objects. It provides a stream of changes in order of occurrence.
-
{{jsxref("Array.of()")}} {{experimental_inline}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Dizi örnekleri

- -

Tüm dizi örnekleri, {{jsxref("Array.prototype")}} 'dan türer. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Özellikler

- -
{{page('/tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Metodlar

- -

Mutator methods

- -
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('tr/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

- -
function isLetter(character) {
-  return (character >= "a" && character <= "z");
-}
-
-if (Array.prototype.every.call(str, isLetter))
-  alert("The string '" + str + "' contains only letters!");
-
- -

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

- -
if (Array.every(isLetter, str))
-  alert("The string '" + str + "' contains only letters!");
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("Global_Objects/String", "String")}}.

- -

These are currently not part of ECMAScript standards (though the ES6 {{jsxref("Array.from()")}} can be used to achieve this). The following is a shim to allow its use in all browsers:

- -
// Assumes Array extras already present (one may use polyfills for these as well)
-(function () {
-    'use strict';
-
-    var i,
-        // We could also build the array of methods with the following, but the
-        //   getOwnPropertyNames() method is non-shimable:
-        // Object.getOwnPropertyNames(Array).filter(function (methodName) {return typeof Array[methodName] === 'function'});
-        methods = [
-            'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
-            'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
-            'forEach', 'map', 'reduce', 'reduceRight', 'filter',
-            'some', 'every', 'isArray'
-        ],
-        methodCount = methods.length,
-        assignArrayGeneric = function (methodName) {
-            var method = Array.prototype[methodName];
-            Array[methodName] = function (arg1) {
-                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
-            };
-        };
-
-    for (i = 0; i < methodCount; i++) {
-        assignArrayGeneric(methods[i]);
-    }
-}());
- -

Örnekler

- -

Bir dizi oluşturmak

- -

Aşağıdaki örnekte uzunluğu [0] olan bir dizi tanımlanıyor(msgArray), daha sonra msgArray[0] ve msgArray[99] indexlerine değer atanıyor ve böylece dizinin uzunluğu 100'e çıkıyor.

- -
var msgArray = new Array();
-msgArray[0] = "Hello";
-msgArray[99] = "world";
-
-if (msgArray.length == 100)
-   print("The length is 100.");
-
- -

2 boyutlu dizi oluşturmak

- -

Aşağıdaki örnekte elemanları stringler olan 2 boyutlu bir diziden oluşturulmuş satranç tahtası bulunuyor. İlk hamle 'p' elemanının 6,4 indeksinden 4,4 indexine kopyalanarak yapılmış. Eski bulunduğu index olan 6,4 boş olarak işaretlenmiş.

- -
var board =
-[ ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r']];
-print(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-print(board.join('\n'));
-
- -

Çıktı:

- -
R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
- , , , , , , ,
-p,p,p,p,p,p,p,p
-r,n,b,q,k,b,n,r
-
-R,N,B,Q,K,B,N,R
-P,P,P,P,P,P,P,P
- , , , , , , ,
- , , , , , , ,
- , , , ,p, , ,
- , , , , , , ,
-p,p,p,p, ,p,p,p
-r,n,b,q,k,b,n,r
-
- -

Tarayıcı Uyumluluk Tablosu

- -

{{Compat("javascript.builtins.Array")}}

- -

Daha fazlası

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/indexof/index.html b/files/tr/web/javascript/reference/global_objects/array/indexof/index.html deleted file mode 100644 index f53a9980d7..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/indexof/index.html +++ /dev/null @@ -1,246 +0,0 @@ ---- -title: Array.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---- -
{{JSRef}}
- -

indexOf() metodu, argüman olarak verilen elemanın array de ilk görüldüğü index'i verir. Eğer bu eleman array de bulunmuyorsa -1 değeri döner.

- -
var a = [2, 9, 9];
-a.indexOf(2); // 0
-a.indexOf(7); // -1
-
-if (a.indexOf(7) === -1) {
-  // eleman array de bulunmamaktadır.
-}
-
- -

Yazım

- -
arr.indexOf(aranacakEleman)
-arr.indexOf(aranacakEleman, aramayaBaşlanacakİndex)
-
- -

Parametreler

- -
-
aranacakEleman
-
Array içerisinde aranacak elemanı karşılayacak metod parametresidir.
-
aramayaBaşlanacakİndex{{optional_inline}}
-
Aramaya başlanacak index değerini karşılayacak metod parametresidir. Eğer index olarak gönderilmiş argümanın değeri array'in uzunluğuna eşit veya daha büyükse, metod -1 değerini döndürür, bu array'in hiç aranmayacağı anlamına gelmektedir. Eğer argümanın değeri negatif bir değerse bu durumda argüman değeri array'in sonundan offset olarak algılanacaktır. Not: eğer index argümanı negatif ise, array hala baştan sona aranacaktır. Bu durumda elemanın bulunduğu index negatif hesaplanırsa, bütün array baştan aranacaktır. Default: 0 (tüm array baştan aranacaktır).
-
- -

Dönüş değeri

- -

Elemanın array de ilk görüldüğü index; eğer eleman bulunamazsa -1 dir.

- -

Açıklama

- -

indexOf() aranacakEleman'ı katı eşitlik ilkesine göre dizi elemanları ile karşılaştırır (aynı yöntem === veya üç eşittir operatörü tarafından da kullanılır).

- -

Örnekler

- -

indexOf()'u kullanma

- -

Aşağıdaki örnekte indexOf() metodu kullanılarak, değerlerin bir dizideki konumları bulunuyor.

- -
var array = [2, 9, 9];
-array.indexOf(2);     // 0
-array.indexOf(7);     // -1
-array.indexOf(9, 2);  // 2
-array.indexOf(2, -1); // -1
-array.indexOf(2, -3); // 0
-
- -

Bir öğenin tüm konumlarını bulma

- -
var indices = [];
-var array = ['a', 'b', 'a', 'c', 'a', 'd'];
-var element = 'a';
-var idx = array.indexOf(element);
-while (idx != -1) {
-  indices.push(idx);
-  idx = array.indexOf(element, idx + 1);
-}
-console.log(indices);
-// [0, 2, 4]
-
- -

Bir öğenin dizide olup olmadığını öğrenme ve diziyi güncelleme

- -
function updateVegetablesCollection (veggies, veggie) {
-    if (veggies.indexOf(veggie) === -1) {
-        veggies.push(veggie);
-        console.log('New veggies collection is : ' + veggies);
-    } else if (veggies.indexOf(veggie) > -1) {
-        console.log(veggie + ' already exists in the veggies collection.');
-    }
-}
-
-var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
-
-updateVegetablesCollection(veggies, 'spinach');
-// New veggies collection is : potato,tomato,chillies,green-papper,spinach
-updateVegetablesCollection(veggies, 'spinach');
-// spinach already exists in the veggies collection.
-
- -

Polyfill

- -

indexOf() ECMA-262 standartlarına 5. sürümde eklendi; bu yüzden henüz tüm tarayıcılarda mevcut olmayabilir. Aşağıdaki kod parçasını kendi kodunuzun başına ekleyerek kullanabilirsiniz. Böylelikle indexOf() metodunu tarayıcı desteklemese bile kullanabilirsiniz. Aşağıdaki algoritma  {{jsxref("Global_Objects/TypeError", "TypeError")}} ve {{jsxref("Math.abs()")}} öğelerinin orijinal değerlerine sahip olduğu varsayılarak ECMA-262, 5. sürümde belirtilenle eşleşir.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.14
-// Reference: http://es5.github.io/#x15.4.4.14
-if (!Array.prototype.indexOf) {
-  Array.prototype.indexOf = function(searchElement, fromIndex) {
-
-    var k;
-
-    // 1. Let o be the result of calling ToObject passing
-    //    the this value as the argument.
-    if (this == null) {
-      throw new TypeError('"this" is null or not defined');
-    }
-
-    var o = Object(this);
-
-    // 2. Let lenValue be the result of calling the Get
-    //    internal method of o with the argument "length".
-    // 3. Let len be ToUint32(lenValue).
-    var len = o.length >>> 0;
-
-    // 4. If len is 0, return -1.
-    if (len === 0) {
-      return -1;
-    }
-
-    // 5. If argument fromIndex was passed let n be
-    //    ToInteger(fromIndex); else let n be 0.
-    var n = fromIndex | 0;
-
-    // 6. If n >= len, return -1.
-    if (n >= len) {
-      return -1;
-    }
-
-    // 7. If n >= 0, then Let k be n.
-    // 8. Else, n<0, Let k be len - abs(n).
-    //    If k is less than 0, then let k be 0.
-    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
-
-    // 9. Repeat, while k < len
-    while (k < len) {
-      // a. Let Pk be ToString(k).
-      //   This is implicit for LHS operands of the in operator
-      // b. Let kPresent be the result of calling the
-      //    HasProperty internal method of o with argument Pk.
-      //   This step can be combined with c
-      // c. If kPresent is true, then
-      //    i.  Let elementK be the result of calling the Get
-      //        internal method of o with the argument ToString(k).
-      //   ii.  Let same be the result of applying the
-      //        Strict Equality Comparison Algorithm to
-      //        searchElement and elementK.
-      //  iii.  If same is true, return k.
-      if (k in o && o[k] === searchElement) {
-        return k;
-      }
-      k++;
-    }
-    return -1;
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Compatibility notes

- - - -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/isarray/index.html b/files/tr/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index aafa47718c..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Dizi - - dizi kontrol -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Array.isArray() metodu değerin Array olup olmadığını kontrol eder. 

- -

Söz dizimi

- -
Array.isArray(obj)
- -

Parametreler

- -
-
obj
-
Kontrol edilecek nesne.
-
- -

Açıklamalar

- -

Nesne eğer {{jsxref("Array")}} ise true değilse false döndürür.

- -

Daha fazla detay için makaleye göz atın:  “Determining with absolute accuracy whether or not a JavaScript object is an array” 

- -

Örnekler

- -
// Aşağıdaki tüm örnekler true döndürür
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Az bilinen gerçek: Array.prototype bir dizinin kendisidir:
-Array.isArray(Array.prototype);
-
-// Aşağıdaki tüm örnekler false döndürür
-Array.isArray();
-Array.isArray({});
-Array.isArray(null);
-Array.isArray(undefined);
-Array.isArray(17);
-Array.isArray('Array');
-Array.isArray(true);
-Array.isArray(false);
-Array.isArray({ __proto__: Array.prototype });
-
- -

Kod Parçası

- -

Aşağıdaki kod, diğer kodlardan önce çalıştırılırsa; doğal olarak var olmaması durumunda Array.isArray() 'i oluşturacaktır.

- -
if (!Array.isArray) {
-  Array.isArray = function(arg) {
-    return Object.prototype.toString.call(arg) === '[object Array]';
-  };
-}
-
- -

Tanımlamalar

- - - - - - - - - - - - - - - - - - - - - - - - -
TanımlamaDurumAçıklama
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}İlk tanım. JavaScript 1.8.5 sürümünde uygulamaya koyuldu.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
- - - - - - - -
Temel Destek 
-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/join/index.html b/files/tr/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 37d876dc97..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

join() metodu bir array içerisinde yer alan bütün elemanları birleştirerek string bir ifade olarak geri döndürür. (veya array benzeri bir obje olarak) Elemanlar varsayılan olarak virgül ile ayıracı ile ayrılır. İsteğe bağlı olarak elementleri birbirinden ayırmak için farklı ayıraçlar da kullanılabilir.

- -
{{EmbedInteractiveExample("pages/js/array-join.html")}}
- - - -

Sözdizimi (Syntax)

- -
arr.join([separator])
- -

Parametreler

- -
-
ayıraç {{optional_inline}}
-
Bir diziye (array) ait elemanları birleştirerek string bir ifade haline getiir. Dizi içinde yer alan elamanları birbirine bağlarken istediğiniz ifadeyi ayıraç olarak kullanabilirsiniz. Eğer ayıraç kullanılmaz ise varsayılan ayıraç olarak virgül kullanılır. Eğer ayıraç olarak boş ifade ("") kullanılırsa, bütün dizinin bütün elemanları birbirine bitişik olacak şekilde dönüştürülür.
-
- -

String ifade oluşturulurken dizi (array) içerisinde yer alan bütün elemanlar kullanılır. Eğer array içerisinde eleman yok ise (array.length değeri sıfıra eşit ise) join metodu boş string ("") döndürür.

- -

Açıklamalar

- -

Dizi (array) içerisinde yer alan bütün elemanları tek bir ifade (string) haline getirir.

- -

 

- -
-

Eğer dizi içerisinde yer alan elemanlardan birinin değeri undefined veya null ise, o eleman boş ifadeye ("") dönüştürülür.

-
- -

Örnekler

- -

Bir arrayi birleştirmenin dört farklı yolu

- -

Aşağıda yer alan örnekte örnekte üç elemandan oluşan a dizisi oluşturup, farklı ayıraçlar kullanarak dört defa birleştirdik. İlk örnekte hiç bir ayıraç kullanmadık, ikinci örnekte virgül ve boşluk, üçüncü örnekte boşluk ve + işareti, son örnekte ise boş ifade (string) değeri kullandık

- -
var a = ['Rüzgar', 'Yağmur', 'Ateş'];
-a.join();      // 'Rüzgar,Yağmur,Ateş'
-a.join(', ');  // 'Rüzgar, Yağmur, Ateş'
-a.join(' + '); // 'Rüzgar + Yağmur + Ateş'
-a.join('');    // 'RüzgarYağmurAteş'
- -

Array benzeri obje nasıl birleştirlir ?

- -

Aşağıda yer alan örnekte array benzeri obje olarak bilinen (argümanlar), yapıyı Array.prototype.join üzerinden call {{jsxref("Function.prototype.call")}} metodu kullanarak birleştireceğiz. 

- -
function f(a, b, c) {
-  var s = Array.prototype.join.call(arguments);
-  console.log(s); // '1,a,true'
-}
-f(1, 'a', true);
-//expected output: "1,a,true"
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- - - -

{{Compat("javascript.builtins.Array.join")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/length/index.html b/files/tr/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index b0ff9d264b..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/length/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Array.length -slug: Web/JavaScript/Reference/Global_Objects/Array/length -tags: - - Dizi - - dizi uzunluğu - - uzunluk -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -
{{JSRef}}
- -
Dizinin length özelliği -yani uzunluğu-, bir dizideki öğe sayısını döndürür veya ayarlar. 32-bit işaretsiz bir tam sayı (integer) ile ifade edilir, sayısal değeri her zaman dizinin en yüksek değerli index'inden büyüktür.
- -
 
- -
var elemanlar = ["ayakkabılar", "gömlekler", "çoraplar", "kazaklar"];
-elemanlar.length;
-
-// 4 döndürür
- -

Açıklama

- -

Uzunluk(length) özellik değeri, artı işaretli bir tam sayıdır ve değeri 2'nin 32. kuvvetinden küçüktür (232).

- -

Uzunluk(length) özellik değerini ayarlayarak bir diziyi istenen bir zamanda budayabilirsiniz. Bir diziyi length özelliğini ayarlayarak genişletirseniz, asıl öğe sayısı artmayacaktır; örneğin, uzunluğu 2 olan dizinin uzunluğunu 3 olarak ayarlarsanız, dizide hala 2 eleman olacaktır. Bu durumda, length özelliğinin her zaman dizideki tanımlı öğe sayısını göstermesi şart değildir. Ayrıca bkz. Bir diziyi eşleşen bir sonuç ile oluşturmak.

- -

{{js_property_attributes(1, 0, 0)}}

- -

Örnekler

- -

Bir dizi üzerinde gezinim

- -

Aşağıdaki örnekte, numaralar dizisinde, length özelliği kullanılarak gezinim yapılıyor. Her öğe değeri ikiye katlanıyor.

- -
var numaralar = [1, 2, 3, 4, 5];
-var uzunluk = numaralar.length;
-for (var i = 0; i < uzunluk; i++) {
-  numaralar[i] *= 2;
-}
-// numaralar şimdi [2, 4, 6, 8, 10] şeklindedir
-
- -

Bir diziyi kısaltmak

- -

Aşağıdaki örnekte numaralar dizi uzunluğu 3'ten büyükse, dizi kısaltılıyor.

- -
var numaralar = [1, 2, 3, 4, 5];
-
-if (numaralar.length > 3) {
-  numaralar.length = 3;
-}
-
-console.log(numaralar); // [1, 2, 3]
-console.log(numaralar.length); // 3
-
- -

Tanımlamalar

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TanımlamaDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/map/index.html b/files/tr/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index 0c8d66f4de..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,307 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -
{{JSRef}}
- -

map() , dizinin her elemanı için, parametre olarak verilen fonksiyonu çağırır ve oluşan sonuçlarla da yeni bir dizi oluşturur.

- -
{{EmbedInteractiveExample("pages/js/array-map.html")}}
- - - -

Sözdizimi

- -
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
-    // Return element for new_array
-}[, thisArg])
- -

Parameters

- -
-
callback
-
Yeni oluşan dizinin elemanlarını döndürdüğü değerlerle oluşturur, üç parametre alır: -
-
 
-
currentValue
-
Dizinin o anda işlem yapılan elemanı.
-
index{{optional_inline}}
-
Dizinin o anda işlem yapılan elemanının indeksi.
-
array{{optional_inline}}
-
map tarafından çağırılan dizi.
-
-
-
thisArg{{optional_inline}}
-
callback fonsiyonu çalışırken kullanacağı this değeri.
-
- -

Return value

- -

Elemanları, callback fonksiyonunun sonuçları olan yeni bir dizi.

- -

Açıklama

- -

map, kendisine özel tahsis edilmiş geri çağırma (callback) fonksiyonunu çağırarak, sıraya uygun olarak döngüye giren her eleman için sonuçtan yeni bir dizi(array) inşa eder. callback sadece değere tanımlanmış dizinin indeksleri için tetiklenir, undefined de buna dahildir. Dizinin kayıp elemanları için çağrılmaz ( kayıp elemanlar: silinmiş veya hiçbir değere eşitlenmemiş veya oluşmamış indeksleri ifade eder. )

- -

callback şu üç argüman ile tetiklenir; Elemanın değeri, elemanın indeks numarası ve elemanları gezilecek olan dizi objesi...

- -
dizi.map( (deger, index) => /* yapılacak işlem */ ) 
- -

If a thisArg parameter is provided to map, it will be used as callback's this value. Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

map does not mutate the array on which it is called (although callback, if invoked, may do so).

- -

The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, their value as passed to callback will be the value at the time map visits them. Elements that are deleted after the call to map begins and before being visited are not visited.
-
- Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.

- -

Examples

- -

Mapping an array of numbers to an array of square roots

- -

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

- -
var numbers = [1, 4, 9];
-var roots = numbers.map(Math.sqrt);
-// roots is now [1, 2, 3]
-// numbers is still [1, 4, 9]
-
- -

Using map to reformat objects in an array

- -

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

- -
var kvArray = [{key: 1, value: 10},
-               {key: 2, value: 20},
-               {key: 3, value: 30}];
-
-var reformattedArray = kvArray.map(obj =>{
-   var rObj = {};
-   rObj[obj.key] = obj.value;
-   return rObj;
-})
-// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}],
-
-// kvArray is still:
-// [{key: 1, value: 10},
-//  {key: 2, value: 20},
-//  {key: 3, value: 30}]
-
- -

Mapping an array of numbers using a function containing an argument

- -

The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

- -
var numbers = [1, 4, 9];
-var doubles = numbers.map(function(num) {
-  return num * 2;
-});
-
-// doubles is now [2, 8, 18]
-// numbers is still [1, 4, 9]
-
- -

Using map generically

- -

This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:

- -
var map = Array.prototype.map;
-var a = map.call('Hello World', function(x) {
-  return x.charCodeAt(0);
-});
-// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
-
- -

Using map generically querySelectorAll

- -

This example shows how to iterate through a collection of objects collected by querySelectorAll. In this case we get all selected options on the screen and printed on the console:

- -
var elems = document.querySelectorAll('select option:checked');
-var values = Array.prototype.map.call(elems, function(obj) {
-  return obj.value;
-});
-
- -

Easier way would be using {{jsxref("Array.from()")}} method.

- -

Tricky use case

- -

(inspired by this blog post)

- -

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.

- -
// Consider:
-['1', '2', '3'].map(parseInt);
-// While one could expect [1, 2, 3]
-// The actual result is [1, NaN, NaN]
-
-// parseInt is often used with one argument, but takes two.
-// The first is an expression and the second is the radix.
-// To the callback function, Array.prototype.map passes 3 arguments:
-// the element, the index, the array
-// The third argument is ignored by parseInt, but not the second one,
-// hence the possible confusion. See the blog post for more details
-
-function returnInt(element) {
-  return parseInt(element, 10);
-}
-
-['1', '2', '3'].map(returnInt); // [1, 2, 3]
-// Actual result is an array of numbers (as expected)
-
-// Same as above, but using the concise arrow function syntax
-['1', '2', '3'].map( str => parseInt(str) );
-
-// A simpler way to achieve the above, while avoiding the "gotcha":
-['1', '2', '3'].map(Number); // [1, 2, 3]
-// but unlike `parseInt` will also return a float or (resolved) exponential notation:
-['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
-
- -

One alternative output of the map method being called with parseInt as a parameter runs as follows:

- -
var xs = ['10', '10', '10'];
-
-xs = xs.map(parseInt);
-
-console.log(xs);
-// Actual result of 10,NaN,2 may be unexpected based on the above description.
- -

Polyfill

- -

map was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.19
-// Reference: http://es5.github.io/#x15.4.4.19
-if (!Array.prototype.map) {
-
-  Array.prototype.map = function(callback/*, thisArg*/) {
-
-    var T, A, k;
-
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    // 1. Let O be the result of calling ToObject passing the |this|
-    //    value as the argument.
-    var O = Object(this);
-
-    // 2. Let lenValue be the result of calling the Get internal
-    //    method of O with the argument "length".
-    // 3. Let len be ToUint32(lenValue).
-    var len = O.length >>> 0;
-
-    // 4. If IsCallable(callback) is false, throw a TypeError exception.
-    // See: http://es5.github.com/#x9.11
-    if (typeof callback !== 'function') {
-      throw new TypeError(callback + ' is not a function');
-    }
-
-    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
-    if (arguments.length > 1) {
-      T = arguments[1];
-    }
-
-    // 6. Let A be a new array created as if by the expression new Array(len)
-    //    where Array is the standard built-in constructor with that name and
-    //    len is the value of len.
-    A = new Array(len);
-
-    // 7. Let k be 0
-    k = 0;
-
-    // 8. Repeat, while k < len
-    while (k < len) {
-
-      var kValue, mappedValue;
-
-      // a. Let Pk be ToString(k).
-      //   This is implicit for LHS operands of the in operator
-      // b. Let kPresent be the result of calling the HasProperty internal
-      //    method of O with argument Pk.
-      //   This step can be combined with c
-      // c. If kPresent is true, then
-      if (k in O) {
-
-        // i. Let kValue be the result of calling the Get internal
-        //    method of O with argument Pk.
-        kValue = O[k];
-
-        // ii. Let mappedValue be the result of calling the Call internal
-        //     method of callback with T as the this value and argument
-        //     list containing kValue, k, and O.
-        mappedValue = callback.call(T, kValue, k, O);
-
-        // iii. Call the DefineOwnProperty internal method of A with arguments
-        // Pk, Property Descriptor
-        // { Value: mappedValue,
-        //   Writable: true,
-        //   Enumerable: true,
-        //   Configurable: true },
-        // and false.
-
-        // In browsers that support Object.defineProperty, use the following:
-        // Object.defineProperty(A, k, {
-        //   value: mappedValue,
-        //   writable: true,
-        //   enumerable: true,
-        //   configurable: true
-        // });
-
-        // For best browser support, use the following:
-        A[k] = mappedValue;
-      }
-      // d. Increase k by 1.
-      k++;
-    }
-
-    // 9. return A
-    return A;
-  };
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.map")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/of/index.html b/files/tr/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 07bd40a430..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -tags: - - Dizi - - ECMAScript 2015 - - JavaScript - - metod - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Array.of() metodu, verilen argümanları içeren yeni bir dizi (Array) oluşturur. Argüman sayısı ve tipi konusunda herhangi bir kısıtı yoktur.

- -

Array.of() ile Array yapıcı (constructor) arasındaki fark, sayısal argümanları kullanma biçimidir: Array.of(7) tek öğesi 7 olan bir dizi oluştururken, Array(7), 7 öğe kapasiteli -length özelliği 7 olan- boş bir dizi oluşturur (Not: Bu ifade 7 boş yeri olan bir dizi oluştur, kapasitesi kadar tanımsız öğe içeren bir dizi değil).

- -
Array.of(7);       // [7]
-Array.of(1, 2, 3); // [1, 2, 3]
-
-Array(7);          // [ , , , , , , ]
-Array(1, 2, 3);    // [1, 2, 3]
-
- -

Sözdizimi

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

Parametreler

- -
-
elementN
-
Diziyi oluşturacak öğeler.
-
- -

Dönüş değeri

- -

Yeni bir {{jsxref("Array")}} örneği.

- -

Açıklama

- -

Bu fonksiyon ECMAScript 2015 standardının bir parçasıdır. Daha fazla bilgi için Array.of ve Array.from proposal ve Array.of polyfill linklerine bakabilirsiniz.

- -

Örnekler

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

Polyfill

- -

Eğer Array.of() doğal olarak mevcut değilse, aşağıdaki kodu diğer kodlardan önce çalıştırarak oluşturabilirsiniz.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-  };
-}
-
- -

Şartnameler

- - - - - - - - - - - - - - - - - - - -
ŞartnameDurumYorum
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumu

- -
- - -

{{Compat("javascript.builtins.Array.of")}}

-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/pop/index.html b/files/tr/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index 649cb88921..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

pop() yöntemi, bir dizideki son öğeyi kaldırır ve o öğeyi döndürür. Bu yöntem dizinin uzunluğunu değiştirir.

- - - -
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
- - - -

Syntax

- -
arr.pop()
- -

Return value

- -

The removed element from the array; {{jsxref("undefined")}} if the array is empty.

- -

Description

- -

The pop method removes the last element from an array and returns that value to the caller.

- -

pop is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

- -

If you call pop() on an empty array, it returns {{jsxref("undefined")}}.

- -

{{jsxref("Array.prototype.shift()")}} has similar behavior to pop, but applied to the first element in an array.

- -

Examples

- -

Removing the last element of an array

- -

The following code creates the myFish array containing four elements, then removes its last element.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-var popped = myFish.pop();
-
-console.log(myFish); // ['angel', 'clown', 'mandarin' ]
-
-console.log(popped); // 'sturgeon'
- - - -

Using apply( ) or call ( ) on array-like objects

- -

The following code creates the myFish array-like object containing four elements and a length parameter, then removes its last element and decrements the length parameter.

- -
var myFish = {0:'angel', 1:'clown', 2:'mandarin', 3:'sturgeon', length: 4};
-
-var popped = Array.prototype.pop.call(myFish); //same syntax for using apply( )
-
-console.log(myFish); // {0:'angel', 1:'clown', 2:'mandarin', length: 3}
-
-console.log(popped); // 'sturgeon'
-
- - - -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.pop")}}

-
- -

See also

- - - -
-
-
diff --git a/files/tr/web/javascript/reference/global_objects/array/push/index.html b/files/tr/web/javascript/reference/global_objects/array/push/index.html deleted file mode 100644 index a5cd57980b..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/push/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Array.prototype.push() -slug: Web/JavaScript/Reference/Global_Objects/Array/push -tags: - - Dizi - - JavaScript - - Metot - - Prototype - - Referans -translation_of: Web/JavaScript/Reference/Global_Objects/Array/push ---- -
{{JSRef}}
- -

push() metotu dizinin sonuna bir yada daha fazla element ekler ve dizinin yeni uzunluğunu geri döndürür.

- -

Söz dizimi

- -
arr.push(element1, ..., elementN)
- -

Parametreler

- -
-
elementN
-
Dizinin sonuna eklenecek elementler.
-
- -

Geri döndürür

- -

Nesnenin yeni {{jsxref("Array.length", "length")}} özelliğini metotun çağrılması üzerine geri döndürür.

- -

Tanım

- -

push metotu değerleri bir diziye ekler.

- -

push kasıtlı olarak genelleyicidir. Bu metot benzeyen nesnelerin dizilerinde {{jsxref("Function.call", "call()")}} veya {{jsxref("Function.apply", "apply()")}} ile kullanılabilir. push metotu verilen değerleri eklemeye nereden başlayacağını tespit etmek için length özelliğine dayanır. Eğer length özelliği bir sayıya dönüştürülemezse indeks 0 kabul edilir. Bu durum length özelliğinin bulunmama ihtimalini de kapsar, bu durumda length ayrıca oluşturulacaktır.

- -

Sadece yerel dizi benzeri nesneler {{jsxref("Global_Objects/String", "strings", "", 1)}} olduğu halde stringlerin değişmez olduğu gibi bu metotun uygulamalarına uygun değildirler.

- -

Örnekler

- -

Bir diziye element ekleme

- -

Aşağıda bulunan kod iki elementi bulunan sports dizisini oluşturuyor, daha sonra iki diziye iki element daha ekliyor. total değişkeni dizinin yeni uzunluğunu tutuyor.

- -
var sports = ['soccer', 'baseball'];
-var total = sports.push('football', 'swimming');
-
-console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
-console.log(total);  // 4
-
- -

İki diziyi birleştirme

- -

Bu örnek ikinci bir diziden bütün elemanları eklemek için {{jsxref("Function.apply", "apply()")}} kullanıyor.

- -
var vegetables = ['parsnip', 'potato'];
-var moreVegs = ['celery', 'beetroot'];
-
-// İkinci diziyi birinciyle birleştir
-// Şuna eşdeğer, vegetables.push('celery', 'beetroot');
-Array.prototype.push.apply(vegetables, moreVegs);
-
-console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
-
- -

Şartnameler

- - - - - - - - - - - - - - - - - - - - - - - - -
ŞartnameDurumYorum
{{SpecName('ES3')}}{{Spec2('ES3')}}İlk tanım. JavaScript 1.2'de uygulandı.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
- -

Tarayıcı uyumu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basit destek{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basit destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca göz at

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/reverse/index.html b/files/tr/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index d9bdb98b76..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - JavaScript - - dizi ters çevirme - - fonksiyon -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

reverse() metodu dizi elemanlarını tersten sıralar . Dizinin ilk elemanı son eleman olur, son elemanı ilk eleman olur.

- -
{{EmbedInteractiveExample("pages/js/array-reverse.html")}}
- - - -

Syntax

- -
a.reverse()
- -

Dönen Değer

- -

Ters dizi.

- -

Açıklama

- -

reverse metodu dizinin olduğu halini kalıcı olarak değiştirir ve değiştirilmiş diziyi döndürür.

- -

reverse bilinçli olarak generic metodtur; bu şekilde dizilere benzeyen nesneler çağrılabilir veya uygulanabilir. Bir dizi ardışık, sıfır tabanlı sayısal özellikte sonuncuyu yansıtan length özelliği içermeyen nesneler anlamlı bir şekilde davranmayabilir.

- -

Örnekler

- -

Bir dizideki öğeleri tersine çevirme

- -

Aşağıdaki örnek, üç öğe içeren bir a dizisi oluşturur, ardından diziyi tersine çevirir. reverse() çağrısı, ters çevrilmiş a dizisine bir referans döndürür.

- -
const a = [1, 2, 3];
-
-console.log(a); // [1, 2, 3]
-
-a.reverse();
-
-console.log(a); // [3, 2, 1]
-
-
- -

Dizi benzeri bir nesnedeki öğeleri tersine çevirme

- -

Aşağıdaki örnek, üç öğe ve length özelliği içeren dizi benzeri bir nesne a oluşturur, sonra dizi benzeri nesneyi tersine çevirir. reverse () çağrısı, ters dizi benzeri nesneye a bir referans döndürür.

- -
const a = {0: 1, 1: 2, 2: 3, length: 3};
-
-console.log(a); // {0: 1, 1: 2, 2: 3, length: 3}
-
-Array.prototype.reverse.call(a); //same syntax for using apply()
-
-console.log(a); // {0: 3, 1: 2, 2: 1, length: 3}
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}}
- -

Tarayıcı Uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.reverse")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/shift/index.html b/files/tr/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index 3a85e72ca7..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -tags: - - Dizi - - JavaScript - - Prototype - - metod -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

shift() metodu bir dizinin ilk elementini diziden kaldırır ve kaldırılmış bu elementi geri döndürür. Bu metod dizinin boyunu değiştirir.

- -
{{EmbedInteractiveExample("pages/js/array-shift.html")}}
- - - -

Dildizimi

- -
arr.shift()
- -

Dönen değer

- -

Diziden kaldırılan element; eğer dizi boş ise de {{jsxref("undefined")}} değerini döndürür.

- -

Tanımlama

- -

shift metodu sıfırıncı indeksteki elementi kaldırır ve ardışık indeksleri aşağı düşürür, daha sonra kaldırılan değeri geri döndürür. Eğer metod uygulandığında {{jsxref("Array.length", "length")}} değeri 0 ise, {{jsxref("undefined")}} geri döndürür.

- -

shift özellikle geniş kapsamlıdır; bu metod {{jsxref("Function.call", "called", "", 1)}} veya {{jsxref("Function.apply", "applied", "", 1)}} dizilere benzeyen nesnelere de uygulanabilir. Ardışık bir serinin sonuncusu özelliği olan, sıfır-temelli, sayısal özellikleri olan ancak length özelliği bulundurmayan nesneler, anlamli bir davranış göstermeyebilirler.

- -

Örnekler

- -

Bir diziden bir elementi kaldırmak

- -

Aşağıdaki kod  myFish dizisinin ilk elementini kaldırmadan önceki ve kaldırdıktan sonraki halini göstermektedir. Aynı zamanda kaldırılan elementi de gösterir:

- -
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
-
-console.log('myFish öncesinde:', JSON.stringify(myFish));
-// myFish öncesinde: ['angel', 'clown', 'mandarin', 'surgeon']
-
-var shifted = myFish.shift();
-
-console.log('myFish sonrasında:', myFish);
-// myFish sonrasında: ['clown', 'mandarin', 'surgeon']
-
-console.log('Bu element kaldırıldı:', shifted);
-// Bu element kaldırıldı: angel
-
- -

shift() metodunu while döngüsü içerisinde kullanmak

- -

shift metodu sıklıkla while döngüsü içerisindeki şartlarda kullanılır . Takip eden örnekte her döngü dizi boşalana kadar bir sonraki elementi diziden kaldıracaktır:

- -
var isimler = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
-
-while( (i = isimler.shift()) !== undefined ) {
-    console.log(i);
-}
-// Andrew, Edward, Paul, Chris, John
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}İlk tanımlama. JavaScript 1.2. de uygulandı.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.shift")}}

-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/sort/index.html b/files/tr/web/javascript/reference/global_objects/array/sort/index.html deleted file mode 100644 index 783a3048f3..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/sort/index.html +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: Array.prototype.sort() -slug: Web/JavaScript/Reference/Global_Objects/Array/sort -tags: - - Dizi - - Dizi methodu - - Sıralama - - metod -translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort ---- -
{{JSRef}}
- -

sort() metodu dizi ögelerini sıralayarak, ilgili dizini sıralanmış olarak geri döndürür. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

- -

The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.

- -
{{EmbedInteractiveExample("pages/js/array-sort.html")}}
- - - -

Syntax

- -
arr.sort([compareFunction])
-
- -

Parametreler

- -
-
compareFunction {{optional_inline}}
-
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. -
-
firstEl
-
The first element for comparison.
-
secondEl
-
The second element for comparison.
-
-
-
- -

Geri dönen değer

- -

The sorted array. Note that the array is sorted in place, and no copy is made.

- -

Açıklama

- -

If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.

- -
-

Note : In UTF-16, Unicode characters above \uFFFF are encoded as two surrogate code units, of the range \uD800-\uDFFF. The value of each code unit is taken separately into account for the comparison. Thus the character formed by the surrogate pair \uD655\uDE55 will be sorted before the character \uFF3A.

-
- -

If compareFunction is supplied, all non-undefined array elements are sorted according to the return value of the compare function (all undefined elements are sorted to the end of the array, with no call to compareFunction). If a and b are two elements being compared, then:

- - - -

So, the compare function has the following form:

- -
function compare(a, b) {
-  if (a is less than b by some ordering criterion) {
-    return -1;
-  }
-  if (a is greater than b by the ordering criterion) {
-    return 1;
-  }
-  // a must be equal to b
-  return 0;
-}
-
- -

To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN):

- -
function compareNumbers(a, b) {
-  return a - b;
-}
-
- -

The sort method can be conveniently used with {{jsxref("Operators/function", "function expressions", "", 1)}}:

- -
var numbers = [4, 2, 5, 1, 3];
-numbers.sort(function(a, b) {
-  return a - b;
-});
-console.log(numbers);
-
-// [1, 2, 3, 4, 5]
-
- -

ES2015 provides {{jsxref("Functions/Arrow_functions", "arrow function expressions", "", 1)}} with even shorter syntax.

- -
let numbers = [4, 2, 5, 1, 3];
-numbers.sort((a, b) => a - b);
-console.log(numbers);
-
-// [1, 2, 3, 4, 5]
- -

Objects can be sorted, given the value of one of their properties.

- -
var items = [
-  { name: 'Edward', value: 21 },
-  { name: 'Sharpe', value: 37 },
-  { name: 'And', value: 45 },
-  { name: 'The', value: -12 },
-  { name: 'Magnetic', value: 13 },
-  { name: 'Zeros', value: 37 }
-];
-
-// sort by value
-items.sort(function (a, b) {
-  return a.value - b.value;
-});
-
-// sort by name
-items.sort(function(a, b) {
-  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
-  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
-  if (nameA < nameB) {
-    return -1;
-  }
-  if (nameA > nameB) {
-    return 1;
-  }
-
-  // names must be equal
-  return 0;
-});
- -

Örnekler

- -

Creating, displaying, and sorting an array

- -

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one.

- -
var stringArray = ['Blue', 'Humpback', 'Beluga'];
-var numericStringArray = ['80', '9', '700'];
-var numberArray = [40, 1, 5, 200];
-var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
-
-function compareNumbers(a, b) {
-  return a - b;
-}
-
-console.log('stringArray:', stringArray.join());
-console.log('Sorted:', stringArray.sort());
-
-console.log('numberArray:', numberArray.join());
-console.log('Sorted without a compare function:', numberArray.sort());
-console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
-
-console.log('numericStringArray:', numericStringArray.join());
-console.log('Sorted without a compare function:', numericStringArray.sort());
-console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
-
-console.log('mixedNumericArray:', mixedNumericArray.join());
-console.log('Sorted without a compare function:', mixedNumericArray.sort());
-console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
-
- -

This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

- -
stringArray: Blue,Humpback,Beluga
-Sorted: Beluga,Blue,Humpback
-
-numberArray: 40,1,5,200
-Sorted without a compare function: 1,200,40,5
-Sorted with compareNumbers: 1,5,40,200
-
-numericStringArray: 80,9,700
-Sorted without a compare function: 700,80,9
-Sorted with compareNumbers: 9,80,700
-
-mixedNumericArray: 80,9,700,40,1,5,200
-Sorted without a compare function: 1,200,40,5,700,80,9
-Sorted with compareNumbers: 1,5,9,40,80,200,700
-
- -

ASCII olmayan karakterleri sıralama

- -

For sorting strings with non-ASCII characters, i.e. strings with accented characters (e, é, è, a, ä, etc.), strings from languages other than English, use {{jsxref("String.localeCompare")}}. This function can compare those characters so they appear in the right order.

- -
var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
-items.sort(function (a, b) {
-  return a.localeCompare(b);
-});
-
-// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
-
- -

Map ile sıralama

- -

The compareFunction can be invoked multiple times per element within the array. Depending on the compareFunction's nature, this may yield a high overhead. The more work a compareFunction does and the more elements there are to sort, it may be more efficient to use map for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order.

- -
// the array to be sorted
-var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
-
-// temporary array holds objects with position and sort-value
-var mapped = list.map(function(el, i) {
-  return { index: i, value: el.toLowerCase() };
-})
-
-// sorting the mapped array containing the reduced values
-mapped.sort(function(a, b) {
-  if (a.value > b.value) {
-    return 1;
-  }
-  if (a.value < b.value) {
-    return -1;
-  }
-  return 0;
-});
-
-// container for the resulting order
-var result = mapped.map(function(el){
-  return list[el.index];
-});
-
- -

There is an open source library available called mapsort which applies this approach.

- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}
- -

Tarayıcı uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.sort")}}

-
- -

Bunlarada göz at

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/splice/index.html b/files/tr/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index b853160481..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Dizi - - Referans - - metod - - prototip -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

splice() metodu; bir Dizi'nin içeriklerini, diziye ait öğeleri kaldırarak veya yeni öğeler ekleyerek ve/veya mevcut öğeleri silerek değiştirir.

- -
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
- -

Syntax

- -
array.splice(başlangıç[, silinecekAdet[, item1[, item2[, ...]]]])
-
- -

Parametreler

- -
-
başlangıç
-
Dizi'yi değiştirmek için başlanılacak indeks (0 kökenli indeks). Dizi'nin uzunluğundan daha büyük ise, başlangıç indeksi Dizi'nin uzunluğuna ayarlanacak. Negatif ise, Dizi'nin sonundaki öğeler toplamından başlayacak (-1 kökenli indeks) ve eğer kesin değer Dizi'nin uzunluğundan büyük ise, başlangıç değeri 0 olacak.
-
silinecekAdet {{optional_inline}}
-
Eski Dizi'nden silinecek öğelerin sayısını belirten bir tamsayı.
-
silinecekAdet belirlenmemiş ise, veya değeri dizi.uzunluk - başlangıç 'tan büyük ise (daha sade bir tanımı,  başlangıç başlayarak, Dizi'nde kalmış öğelerin toplam sayısından fazla ise), start sayısından Dizi'nin sonuna kadar yer alan bütün öğeler silinecek.
-
silinecekAdet 0 veya negatif ise, hiçbir öğe silinmeyecek. Bu durumda, en az yeni bir öğe tanımlamalısın (aşağı bkz.).
-
item1, item2, ... {{optional_inline}}
-
Dizi'ne eklenecek olan öğeler, başlangıç indeksinden başlayarak. hiçbir öğe tanımlamaz isen, splice() sadece Dizi'den öğeleri kaldıracak.
-
- -

Geri dönüş değeri

- -

Silinen öğeleri barındıran bir Dizi. Sadece bir öğe silinmiş ise, tek öğeli bir Dizi geri dönülecek. Hiçbir öğe silinmemiş ise, boş bir Dizi dönecek.

- -

Açıklama

- -

Sileceğin öğe sayısından farklı bir sayıda öğe tanımlıyorsan, çağrının sonunda Dizi farklı bir uzunluğa sahip olacak.

- -

Örnekler

- -

2 indeksinden önce 0 öğe sil, ve "drum" öğesini ekle

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish dizi öğeleri ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// silinen [], hiçbir öğe silinmedi
-
- -

3 indeksinden 1 öğe sil

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// silinen ["mandarin"]
-// myFish Dizi'si ["angel", "clown", "drum", "sturgeon"]
-
- -

2 indeksinden 1 öğe sil, ve "trumpet" öğesini ekle

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var silinen = myFish.splice(2, 1, 'trumpet');
-
-// myFish is ["angel", "clown", "trumpet", "sturgeon"]
-// silinen ["drum"]
- -

0 indeksinden başlayarak 2 öğe sil, "parrot", "anemone" ve "blue" öğelerini ekle

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var silinen = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// silinen ["angel", "clown"]
- -

2 indeksinden 2 öğe sil

- -
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
-var silinen = myFish.splice(myFish.length - 3, 2);
-
-// myFish is ["parrot", "anemone", "sturgeon"]
-// silinen ["blue", "trumpet"]
- -

-2 indeksinden 1 öğe sil

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var silinen = myFish.splice(-2, 1);
-
-// myFish ["angel", "clown", "sturgeon"]
-// silinen ["mandarin"]
- -

2 indeksinden sonra bütün öğeleri sil (2 indeksi de dahil)

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var silinen = myFish.splice(2);
-
-// myFish ["angel", "clown"]
-// silinen ["mandarin", "sturgeon"]
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumYorum
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
- -

Tarayıcı Uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.splice")}}

-
- -

Bkz.

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/unshift/index.html b/files/tr/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index a34d4d8713..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

unshift() metodu dizinin başına bir veya daha fazla element ekler ve yeni dizinin uzunluğunu size geri döndürür.

- -
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
- -

Sözdizimi Kuralları

- -
dizi.unshift(element1[, ...[, elementN]])
- -

Parametreler

- -
-
elementN
-
Dizinin başına eklenecek değer.
-
- -

Döndürülen değer

- -

Üzerinde işlem yapılan dizinin yeni {{jsxref("Array.length", "length")}} değerini verir.

- -

Açıklama

- -

unshift, girilen değerleri bir dizinin başına ekler.

- -

unshiftkasıtlı olarak geneldir; bu yöntem, benzer nesnelere {{jsxref("Function.call", "called", "", 1)}} veya {{jsxref("Function.apply", "applied", "", 1)}} olabilir. diziler. Birbirini length ardışık, sıfıra dayalı sayısal özellikler dizisinde sonuncuyu yansıtan bir özellik içermeyen nesneler , anlamlı şekilde davranamazlar.

- -

Birden fazla eleman parametre olarak girildiğinde, elemanlar parametre sırasına göre dizinin başına yerleştirilmektedir. Parametreleri ayrı unshift metodlarıyla eklemek ve sadece bir unshift metodunda eklemek aynı sonucu vermez.

- -
let dizi = [4, 5, 6];
-dizi.unshift(1, 2, 3);
-console.log(dizi);
-// [1, 2, 3, 4, 5, 6]
-
-dizi = [4, 5, 6]; // dizi sıfırlanır.
-
-dizi.unshift(1);
-dizi.unshift(2);
-dizi.unshift(3);
-
-console.log(dizi);
-// [3, 2, 1, 4, 5, 6]
-
- -

Örnekler

- -
let dizi = [1, 2];
-
-dizi.unshift(0); // dizinin uzunluğu 3 olur.
-// dizi: [0, 1, 2]
-
-dizi.unshift(-2, -1); // dizinin uzunluğu 5 olur.
-// dizi: [-2, -1, 0, 1, 2]
-
-dizi.unshift([-4, -3]); // dizinin uzunluğu 6 olur.
-// dizi: [[-4, -3], -2, -1, 0, 1, 2]
-
-dizi.unshift([-7, -6], [-5]); // dizinin uzunluğu 8 olur.
-// dizi: [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}}
- -

Tarayıcı desteği

- -
- - -

{{Compat("javascript.builtins.Array.unshift")}}

-
- -

Benzer Makaleler

- - diff --git a/files/tr/web/javascript/reference/global_objects/array/values/index.html b/files/tr/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index 1c949e93a5..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -tags: - - Dizi yineleyici - - Iterator - - JavaScript - - metod - - prototip -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -
 
- -

values() methodu dizideki tüm elemanları içeren yeni bir (Dizi yineleyici)  nesnesi döner

- -
var a = ['e', 'l', 'm', 'a'];
-var yineleyici = a.values();
-
-console.log(yineleyici.next().value); // e
-console.log(yineleyici.next().value); // l
-console.log(yineleyici.next().value); // m
-console.log(yineleyici.next().value); // a
-
-
- -

Sintaks

- -
arr.values()
- -

Dönüş değeri

- -

Yeni bir {{jsxref("Array")}} yineleyici nesne.

- -

Örnekler

- -

for...of loop ile yineleme

- -
var arr = ['e', 'l', 'm', 'a'];
-var yineleyici = arr.values();
-
-for (let harf of yineleyici) {
-  console.log(harf);
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
- -

Web tarayıcı uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Array.values")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/arraybuffer/index.html b/files/tr/web/javascript/reference/global_objects/arraybuffer/index.html deleted file mode 100644 index 8109b3f667..0000000000 --- a/files/tr/web/javascript/reference/global_objects/arraybuffer/index.html +++ /dev/null @@ -1,222 +0,0 @@ ---- -title: ArrayBuffer -slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer -tags: - - ArrayBuffer - - Constructor - - JavaScript - - Yazılı Diziler -translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer ---- -
{{JSRef}}
- -

Bir ArrayBuffer nesnesi, kapsamlı ve sabit uzunluktaki raw binary data buffer'ını temsil etmek için kullanılır. Bir ArrayBuffer'ın içeriklerini direkt olarak manipüle edemezsiniz; bunun yerine, yazılmış dizi nesnelerini veya buffer'ı özel bir formatta temsil eden bir {{jsxref("DataView")}} nesnesini oluşturursunuz, buffer'a içerik yazmak veya buffer'dan içerik okumak için kullanırsınız.

- -

Syntax

- -
new ArrayBuffer(length)
-
- -

Parametreler

- -
-
length
-
Byte cinsinden, oluşturulan array buffer'ın boyutudur.
-
- -

Döndürülen Değer

- -

Belirlenen boyutta yeni bir ArrayBuffer nesnesi. İçeriği 0 atanmış durumdadır.

- -

İstisnalar

- -

Eğer uzunluk {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ifadesinden büyük ya da negatif ise bir {{jsxref("RangeError")}} fırlatılır.

- -

Tanım

- -

ArrayBuffer constructor'ı, byte cinsinden verilen boyutta yeni bir ArrayBuffer oluşturur.

- -

Var olan bir data'dan array buffer çekmek

- - - -

Özellikler

- -
-
ArrayBuffer.length
-
ArrayBuffer constructor'ının 1 değerine sahip uzunluk özelliği.
-
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
-
Türetilmiş nesneleri oluşturmak için kullanılan constructor fonksiyonu.
-
{{jsxref("ArrayBuffer.prototype")}}
-
Bütün ArrayBuffer nesnelerine özellik eklemeye izin verir.
-
- -

Metodlar

- -
-
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
-
Eğer arg bir ArrayBuffer view'i ise true döndürür, tıpkı yazılmış dizi nesneleri veya bir {{jsxref("DataView")}}gibi. Aksi halde false döndürür.
-
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
-
-
oldBuffer'ın alınmış, ardından kesilmiş veya newByteLength tarafından sıfır-uzatılmış datasını içeren yeni bir ArrayBuffer döndürür.
-
-
- -

ArrayBuffer oluşumları

- -

Bütün ArrayBuffer oluşumları {{jsxref("ArrayBuffer.prototype")}} tarafından miras alınır.

- -

Özellikler

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}

- -

Metodlar

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}

- -
-
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
-
{{jsxref("ArrayBuffer.prototype.slice()")}} ile aynı fonksiyonelliğe sahiptir.
-
- -

Örnek

- -

Bu örnekte,  {{jsxref("Global_Objects/Int32Array", "Int32Array")}} view'i aracılığıyla 8-byte'lık bir buffer oluştururuz.

- -
var buffer = new ArrayBuffer(8);
-var view   = new Int32Array(buffer);
- -

Belirtmeler

- - - - - - - - - - - - - - - - - - - - - - - - -
BelirtmeDurumYorumlar
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}ECMAScript 6 tarafından yenilenmiştir.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}}Bir ECMA standardı için başlangıç tanımı. new'in gerekli olduğu belirtilmiştir.
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek7.0{{CompatGeckoDesktop("2")}}1011.65.1
ArrayBuffer() new fırlatmadan{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}
- {{CompatNo}} {{CompatGeckoDesktop("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel Destek4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
ArrayBuffer() new fırlatmadan{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
- {{CompatNo}} {{CompatGeckoMobile("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
-
- -

Uyumluluk Notları

- -

 ECMAScript 2015'ten başlamak üzere, ArrayBuffer constructor'ları bir {{jsxref("Operators/new", "new")}} operatörü aracılığıyla inşa edilmeye ihtiyaç duymaktadır. Artık new fonksiyonu kullanmadan bir ArrayBuffer constructor'ı çağırmak, bir  {{jsxref("TypeError")}} fırlatacaktır.

- -
var dv = ArrayBuffer(10);
-// TypeError:new komutu olmadan
-// Gömülü bir ArrayBuffer constructor'u çağırmak 
- -
var dv = new ArrayBuffer(10);
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/boolean/index.html b/files/tr/web/javascript/reference/global_objects/boolean/index.html deleted file mode 100644 index 532b7b02c9..0000000000 --- a/files/tr/web/javascript/reference/global_objects/boolean/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Boolean (Mantıksal Veri Tipi) -slug: Web/JavaScript/Reference/Global_Objects/Boolean -tags: - - Boolean - - JavaScript - - Veri - - kurucu - - mantıksal - - tipi -translation_of: Web/JavaScript/Reference/Global_Objects/Boolean ---- -
{{JSRef}}
- -

Boolean nesnesi, bir boolean değeri için bir nesne sarmalayıcıdır.

- -

Sözdizimi

- -
new Boolean([değer])
- -

Parametreler

- -
-
değer
-
Opsiyonel. Boolean nesnesinin başlangıç değeri.
-
- -

Açıklama

- -

Eğer gerekli ise ilk parametre yerine geçen değer boolean değerine dönüştürülür.Eğer değer verilmediyse , 0 ,-0, {{jsxref("null")}}, false, {{jsxref("NaN")}}, {{jsxref("undefined")}}, ya da boş string ("") ise nesnenin ilk değeri false olur.DOM nesnesi {{domxref ("document.all")}} parametre olarak iletilirse, yeni boolean nesnesinin başlangıç değeri de false olur. Herhangi bir nesne veya "false" dizesi dahil olmak üzere diğer tüm değerler, başlangıç değeri true olan bir nesne oluşturur.

- -

İlkel Boolean değerlerini true ve false ile Boolean nesnesinin true ve false değerleriyle karıştırmayın.

- -

Değeri false olan bir Boolean nesnesi de dahil olmak üzere, {{jsxref ("undefined")}} veya {{jsxref ("null")}} olmayan herhangi bir nesne, şartlı ifadeye geçirildiğinde true olarak değerlendirilir. Örneğin, aşağıdaki {{jsxref ("İfadeler/if...else", "if")}} deyimindeki koşul true olarak değerlendirilir:

- -
var x = new Boolean(false);
-if (x) {
-  // bu kod gerçekleşti.
-}
-
- -

Bu davranış, Boolean ilkelleri için geçerli değildir. Örneğin, aşağıdaki {{jsxref ("İfadeler / if ... else", "if")}} deyimindeki koşul false olarak değerlendirilir:

- -
var x = false;
-if (x) {
-  // bu kod gerçekleşmedi.
-}
-
- -

Boolean olmayan bir değeri bir boolean değerine dönüştürmek için bir Boolean nesnesi kullanmayın. Bunun yerine, bu görevi yerine getirmek için bir işlev olarak Boolean'ı kullanın:

- -
var x = Boolean(expression);     // tercih edilen
-var x = new Boolean(expression); // kullanma
-
- -

Bir Boolean nesnesi de dahil olmak üzere herhangi bir nesneyi bir Boolean nesnesinin başlangıç değerini false olarak belirterseniz, yeni Boolean nesnesinin değeri true olur.

- -
var myFalse = new Boolean(false);   // ilk değer false
-var g = Boolean(myFalse);       // ilk değer true
-var myString = new String('Hello'); // string nesnesi
-var s = Boolean(myString);      // ilk değer true
-
- -

Boolean ilkelinin yerine bir Boolean nesnesi kullanmayın.

- -

Özellikleri

- -
-
Boolean.length
-
Uzunluk özelliğinin değeri 1.
-
{{jsxref("Boolean.prototype")}}
-
Boolean yapıcısının prototipini temsil eder.
-
- -

Metodlar

- -

Genel Boolean nesnesi kendine özgü bir yöntem içermese de, prototip zinciri boyunca bazı yöntemleri devralır:

- -

Boolean örnekleri

- -

Tüm Boolean örnekleri {{jsxref ("Boolean.prototype")}} 'den devralınır. Tüm yapıcılarda olduğu gibi, prototip nesne örneklerin kalıtsal özelliklerini ve yöntemlerini belirler.

- -

Özellikleri

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}
- -

Metodlar

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}
- -

Örnekler

- -

ilk değeri false olan Boolean nesnesi oluşturma 

- -
var bNoParam = new Boolean();
-var bZero = new Boolean(0);
-var bNull = new Boolean(null);
-var bEmptyString = new Boolean('');
-var bfalse = new Boolean(false);
-
- -

ilk değeri true olan Boolean nesnesi oluşturma

- -
var btrue = new Boolean(true);
-var btrueString = new Boolean('true');
-var bfalseString = new Boolean('false');
-var bSuLin = new Boolean('Su Lin');
-var bArrayProto = new Boolean([]);
-var bObjProto = new Boolean({});
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumYorum
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım. JavaScript 1.0'da uygulanmaktadır.
{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Boolean")}} 

-
- -


- Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html b/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html deleted file mode 100644 index 1d304fc29f..0000000000 --- a/files/tr/web/javascript/reference/global_objects/boolean/tosource/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Boolean.prototype.toSource() -slug: Web/JavaScript/Reference/Global_Objects/Boolean/toSource -translation_of: Web/JavaScript/Reference/Global_Objects/Boolean/toSource ---- -
{{JSRef}} {{non-standard_header}}
- -

ToSource () metodu, nesnenin kaynak kodunu temsil eden bir dize döndürür.

- -

Sözdizimi

- -
booleanObj.toSource()
-Boolean.toSource()
- -

Return değeri

- -

Nesnenin kaynak kodunu temsil eden bir dize.

- -

Açıklama

- -

toSource metodu aşağıdaki değerleri döndürür:

- - - -

This method is usually called internally by JavaScript and not explicitly in code.

- -

Özellikler

- -

Herhangi bir standardın parçası değil. JavaScript 1.3'te uygulandı. 1.3.

- -

Tarayıcı Uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Boolean.toSource")}}

-
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/eval/index.html b/files/tr/web/javascript/reference/global_objects/eval/index.html deleted file mode 100644 index 1b91b418ce..0000000000 --- a/files/tr/web/javascript/reference/global_objects/eval/index.html +++ /dev/null @@ -1,318 +0,0 @@ ---- -title: eval() -slug: Web/JavaScript/Reference/Global_Objects/eval -translation_of: Web/JavaScript/Reference/Global_Objects/eval ---- -
{{jsSidebar("Objects")}}
- -

eval() fonksiyonu JavaScript kodunu bir String gibi değerlendirir.

- -
{{EmbedInteractiveExample("pages/js/globalprops-eval.html")}}
- - - -

Sözdizimi

- -
eval(string)
- -

Parametreler

- -
-
string
-
A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.
-
- -

Return değeri

- -

The completion value of evaluating the given code. If the completion value is empty, {{jsxref("undefined")}} is returned.

- -

Description

- -

eval() is a function property of the global object.

- -

The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript statements, eval() evaluates the statements. Do not call eval() to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

- -

If you construct an arithmetic expression as a string, you can use eval() to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval() at a later point in your script.

- -

If the argument of eval() is not a string, eval() returns the argument unchanged. In the following example, the String constructor is specified and eval() returns a String object rather than evaluating the string.

- -
eval(new String('2 + 2')); // returns a String object containing "2 + 2"
-eval('2 + 2');             // returns 4
-
- -

You can work around this limitation in a generic fashion by using toString().

- -
var expression = new String('2 + 2');
-eval(expression.toString());            // returns 4
-
- -

If you use the eval function indirectly, by invoking it via a reference other than evalas of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

- -
function test() {
-  var x = 2, y = 4;
-  console.log(eval('x + y'));  // Direct call, uses local scope, result is 6
-  var geval = eval; // equivalent to calling eval in the global scope
-  console.log(geval('x + y')); // Indirect call, uses global scope, throws ReferenceError because `x` is undefined
-  (0, eval)('x + y'); // another example of Indirect call
-}
-
- -

Do not ever use eval!

- -

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar {{jsxref("Global_Objects/Function", "Function")}} is not susceptible.

- -

eval() is also slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.

- -

Additionally, modern javascript interpreters convert javascript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of eval will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additonally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to reevaluate all of the generated machine code to compensate. However, there (thankfully) exists a very good alternative to eval: simply using window.Function. As an example of how you convert code using evil eval() to using  Function(), see below.

- -

Bad code with eval:

- -
function looseJsonParse(obj){
-    return eval(obj);
-}
-console.log(looseJsonParse(
-   "{a:(4-1), b:function(){}, c:new Date()}"
-))
-
- -

Better code without eval:

- -
function looseJsonParse(obj){
-    return Function('"use strict";return (' + obj + ')')();
-}
-console.log(looseJsonParse(
-   "{a:(4-1), b:function(){}, c:new Date()}"
-))
-
- -

Comparing the two code snippets above, the two code snippets might seem to work the same way, but think again: the eval one is a huge amount slower. Notice c: new Date() in the evaluated object. In the function without the eval, the object is being evaluated in the global scope, so it is safe for the browser to assume that Date refers to window.Date instead of a local variable called Date. But, in the code using eval(), the browser cannot assume this since what if your code looked like the following:

- -
function Date(n){
-    return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
-}
-function looseJsonParse(obj){
-    return eval(obj);
-}
-console.log(looseJsonParse(
-   "{a:(4-1), b:function(){}, c:new Date()}"
-))
-
- -

Thus, in the eval() version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called Date(). This is incredibly inefficient compared to Function().

- -

In a related circumstance, what if you actually wanted your Date function to be able to be called from the code inside Function(). Should you just wimp out and fall back to eval()? Absolutely not, never ever. Instead try the approach below.

- -
function Date(n){
-    return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0];
-}
-function runCodeWithDateFunction(obj){
-    return Function('"use strict";return (' + obj + ')')()(
-        Date
-    );
-}
-console.log(runCodeWithDateFunction(
-   "function(Date){ return Date(5) }"
-))
-
- -

The code above may seem inefficiently slow because of the triple nested function, but let's analyse the benefits of the above efficient method:

- -

1. It allows the code in the string passed to runCodeWithDateFunction to be minified.

- -

2. Function call overhead is minimal, making the far smaller code size well worth the benefit

- -

3. Function() more easily allows your code to utilize the performance buttering "use strict";

- -

4. The code does not use eval(), making it orders of magnitude faster than otherwise.

- -

Lastly, let's examine minification. With using  Function() as shown above, you can minify the code string passed to runCodeWithDateFunction far more efficiently because the function arguments names can be minified too as seen in the minified code below.

- -
console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){
-return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]}));
- -

There are also additional safer (and faster!) alternatives to eval() or Function() for common use-cases.

- -

Accessing member properties

- -

You should not use eval() to convert property names into properties. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with eval:

- -
var obj = { a: 20, b: 30 };
-var propName = getPropName();  // returns "a" or "b"
-
-eval( 'var result = obj.' + propName );
-
- -

However, eval() is not necessary here. In fact, its use here is discouraged. Instead, use the property accessors, which are much faster and safer:

- -
var obj = { a: 20, b: 30 };
-var propName = getPropName();  // returns "a" or "b"
-var result = obj[ propName ];  //  obj[ "a" ] is the same as obj.a
- -

You can even use this method to access descendant properties. Using eval() this would look like:

- -
var obj = {a: {b: {c: 0}}};
-var propPath = getPropPath();  // returns e.g. "a.b.c"
-
-eval( 'var result = obj.' + propPath );
-
- -

Avoiding eval() here could be done by splitting the property path and looping through the different properties:

- -
function getDescendantProp(obj, desc) {
-  var arr = desc.split('.');
-  while (arr.length) {
-    obj = obj[arr.shift()];
-  }
-  return obj;
-}
-
-var obj = {a: {b: {c: 0}}};
-var propPath = getPropPath();  // returns e.g. "a.b.c"
-var result = getDescendantProp(obj, propPath);
- -

Setting a property that way works similarly:

- -
function setDescendantProp(obj, desc, value) {
-  var arr = desc.split('.');
-  while (arr.length > 1) {
-    obj = obj[arr.shift()];
-  }
-  return obj[arr[0]] = value;
-}
-
-var obj = {a: {b: {c: 0}}};
-var propPath = getPropPath();  // returns e.g. "a.b.c"
-var result = setDescendantProp(obj, propPath, 1);  // test.a.b.c will now be 1
- -

Use functions instead of evaluating snippets of code

- -

JavaScript has first-class functions, which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write:

- -
// instead of setTimeout(" ... ", 1000) use:
-setTimeout(function() { ... }, 1000);
-
-// instead of elt.setAttribute("onclick", "...") use:
-elt.addEventListener('click', function() { ... } , false); 
- -

Closures are also helpful as a way to create parameterized functions without concatenating strings.

- -

Parsing JSON (converting strings to JavaScript objects)

- -

If the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data. See also Downloading JSON and JavaScript in extensions.

- -

Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.

- -

Pass data instead of code

- -

For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in XPath instead of JavaScript code.

- -

Run code with limited privileges

- -

If you must run the code, consider running it with reduced privileges. This advice applies mainly to extensions and XUL applications, which can use Components.utils.evalInSandbox for this.

- -

Examples

- -

Using eval

- -

In the following code, both of the statements containing eval() return 42. The first evaluates the string "x + y + 1"; the second evaluates the string "42".

- -
var x = 2;
-var y = 39;
-var z = '42';
-eval('x + y + 1'); // returns 42
-eval(z);           // returns 42
-
- -

Using eval to evaluate a string of JavaScript statements

- -

The following example uses eval() to evaluate the string str. This string consists of JavaScript statements that open an alert dialog box and assign z a value of 42 if x is five, and assigns 0 to z otherwise. When the second statement is executed, eval() will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z.

- -
var x = 5;
-var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;";
-
-console.log('z is ', eval(str));
- -

If you define multiple values then the last value is returned.

- -
var x = 5;
-var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;";
-
-console.log('x is ', eval(str)); // z is 42  x is 420
-
- - - -

Last expression is evaluated

- -

eval() returns the value of the last expression evaluated.

- -
var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }';
-var a = true;
-var b = eval(str);  // returns 2
-
-console.log('b is : ' + b);
-
-a = false;
-b = eval(str);  // returns 3
-
-console.log('b is : ' + b);
- -

eval as a string defining function requires "(" and ")" as prefix and suffix

- -
var fctStr1 = 'function a() {}'
-var fctStr2 = '(function a() {})'
-var fct1 = eval(fctStr1)  // return undefined
-var fct2 = eval(fctStr2)  // return a function
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.1', 'eval')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-eval-x', 'eval')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-eval-x', 'eval')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.eval")}}

- -

Firefox-specific notes

- - - -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/function/apply/index.html b/files/tr/web/javascript/reference/global_objects/function/apply/index.html deleted file mode 100644 index 5a82d226a3..0000000000 --- a/files/tr/web/javascript/reference/global_objects/function/apply/index.html +++ /dev/null @@ -1,262 +0,0 @@ ---- -title: Function.prototype.apply() -slug: Web/JavaScript/Reference/Global_Objects/Function/apply -translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply ---- -
{{JSRef}}
- -

apply() methodu ile verilen bir "this" değeri ve diziyi(ya da dizi benzeri bir nesneyi) kullanarak bağımsız değişkenlerle bir işlevi(function) çağırır.

- -
-

Not: call() , apply() syntaxları sizin de dikkat ettiğiniz gibi aynıdır. farkları şudur: call() : bir argüman listesini argüman olarak alırken, apply() argümanlardan oluşmuş bir array'ı argüman olarak kabul alır.  

-
- -

Syntax

- -
fun.apply(thisArg, [argsArray])
- -

Parametreler

- -
-
thisArg
-
fun' ı çağırmak için atanan this in değeridir. Unutmayın, this,method tarafından görülen gerçek değer olmayabilir.: eğer method{{jsxref("Strict_mode", "non-strict mode", "", 1)}} içindeki bir kod ise{{jsxref("null")}}ve {{jsxref("undefined")}}global object ile yer değiştirecek, ve ilk değerleri saklanacak.
-
argsArray
-
-

Eğer fonkiyona hiç bir parametre verilmeyecekse dizi benzeri bir nesne (çağrılacak fun'ın argümanlarını belirler), veya {{jsxref("null")}} veya {{jsxref("undefined")}}. ECMAScript 5 ile, bu argümanlar dizi yerine eşdeğer dizi benzeri nesne olabilir. {{anch("Browser_compatibility", "browser compatibility")}} için aşağıya bakın.

-
-
- -

Dönen değer

- -

this değeri ve argümanlar ile çağrılan fonksiyonun sonucu.

- -

Açıklama

- -

Varolan bir fonksiyonu çağırdığınızda farklı bir this objesi atayabilirsiniz. Burada this geçerli nesneyi (çağıran objeyi ) ifade eder. Apply ile bir kez yazılmış bir methodu  başka bir objeden miras alarak aynı fonksiyonu tekrar yazmaktan kurtulmuş  olursunuz.  

- -

apply is very similar to {{jsxref("Function.call", "call()")}}, except for the type of arguments it supports. You can use an arguments array instead of a named set of parameters. With apply, you can use an array literal, for example, fun.apply(this, ['eat', 'bananas']), or an {{jsxref("Array")}} object, for example, fun.apply(this, new Array('eat', 'bananas')).

- -

You can also use {{jsxref("Functions/arguments", "arguments")}} for the argsArray parameter. arguments is a local variable of a function. It can be used for all unspecified arguments of the called object. Thus, you do not have to know the arguments of the called object when you use the apply method. You can use arguments to pass all the arguments to the called object. The called object is then responsible for handling the arguments.

- -

Since ECMAScript 5th Edition you can also use any kind of object which is array-like, so in practice this means it's going to have a property length and integer properties in the range (0...length-1). As an example you can now use a {{domxref("NodeList")}} or a custom object like { 'length': 2, '0': 'eat', '1': 'bananas' }.

- -
-

Most browsers, including Chrome 14 and Internet Explorer 9, still do not accept array-like objects and will throw an exception.

-
- -

Examples

- -

Using apply to chain constructors

- -

You can use apply to chain {{jsxref("Operators/new", "constructors", "", 1)}} for an object, similar to Java. In the following example we will create a global {{jsxref("Function")}} method called construct, which will enable you to use an array-like object with a constructor instead of an arguments list.

- -
Function.prototype.construct = function (aArgs) {
-  var oNew = Object.create(this.prototype);
-  this.apply(oNew, aArgs);
-  return oNew;
-};
-
- -
-

Note: The Object.create() method used above is relatively new. For an alternative method using closures, please consider the following alternative:

- -
Function.prototype.construct = function(aArgs) {
-  var fConstructor = this, fNewConstr = function() {
-    fConstructor.apply(this, aArgs);
-  };
-  fNewConstr.prototype = fConstructor.prototype;
-  return new fNewConstr();
-};
-
- -

Example usage:

- -
function MyConstructor() {
-  for (var nProp = 0; nProp < arguments.length; nProp++) {
-    this['property' + nProp] = arguments[nProp];
-  }
-}
-
-var myArray = [4, 'Hello world!', false];
-var myInstance = MyConstructor.construct(myArray);
-
-console.log(myInstance.property1);                // logs 'Hello world!'
-console.log(myInstance instanceof MyConstructor); // logs 'true'
-console.log(myInstance.constructor);              // logs 'MyConstructor'
-
- -
-

Note: This non-native Function.construct method will not work with some native constructors (like {{jsxref("Date")}}, for example). In these cases you have to use the {{jsxref("Function.prototype.bind")}} method (for example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "Date")}} constructor: [2012, 11, 4]; in this case you have to write something like: new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))() — anyhow this is not the best way to do things and probably should not be used in any production environment).

-
- -

Using apply and built-in functions

- -

Clever usage of apply allows you to use built-ins functions for some tasks that otherwise probably would have been written by looping over the array values. As an example here we are going to use Math.max/Math.min to find out the maximum/minimum value in an array.

- -
// min/max number in an array
-var numbers = [5, 6, 2, 3, 7];
-
-// using Math.min/Math.max apply
-var max = Math.max.apply(null, numbers);
-// This about equal to Math.max(numbers[0], ...)
-// or Math.max(5, 6, ...)
-
-var min = Math.min.apply(null, numbers);
-
-// vs. simple loop based algorithm
-max = -Infinity, min = +Infinity;
-
-for (var i = 0; i < numbers.length; i++) {
-  if (numbers[i] > max) {
-    max = numbers[i];
-  }
-  if (numbers[i] < min) {
-    min = numbers[i];
-  }
-}
-
- -

But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time:

- -
function minOfArray(arr) {
-  var min = Infinity;
-  var QUANTUM = 32768;
-
-  for (var i = 0, len = arr.length; i < len; i += QUANTUM) {
-    var submin = Math.min.apply(null,
-                                arr.slice(i, Math.min(i+QUANTUM, len)));
-    min = Math.min(submin, min);
-  }
-
-  return min;
-}
-
-var min = minOfArray([5, 6, 2, 3, 7]);
-
- -

Using apply in "monkey-patching"

- -

Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given someobject.foo function, you can modify the function in a somewhat hacky way, like so:

- -
var originalfoo = someobject.foo;
-someobject.foo = function() {
-  // Do stuff before calling function
-  console.log(arguments);
-  // Call the function as it would have been called normally:
-  originalfoo.apply(this, arguments);
-  // Run stuff after, here.
-}
-
- -

This method is especially handy where you want to debug events, or interface with something that has no API like the various .on([event]... events, such as those usable on the Devtools Inspector).

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/function/index.html b/files/tr/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 912f1acf1e..0000000000 --- a/files/tr/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - fonksiyon - - yapıcı -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Fonksiyon yapıcısı yeni bir Fonksiyon nesnesi yaratır. JavaScript'de her fonksiyon aslında bir Fonksiyon nesnesidir.

- -

Syntax

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Parametreler

- -
-
arg1, arg2, ... argN
-
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Açıklama

- -

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

- -

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Properties and Methods of Function

- -

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

- -

Function prototype object

- -

Properties

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
- -

Methods

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
- -

Function instances

- -

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

- -

Examples

- -

Specifying arguments with the Function constructor

- -

The following code creates a Function object that takes two arguments.

- -
// Example can be run directly in your JavaScript console
-
-// Create a function that takes two arguments and returns the sum of those arguments
-var adder = new Function('a', 'b', 'return a + b');
-
-// Call the function
-adder(2, 6);
-// > 8
-
- -

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

- -

Difference between Function constructor and function declaration

- -

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

- -
var x = 10;
-
-function createFunction1() {
-    var x = 20;
-    return new Function("return x;"); // this |x| refers global |x|
-}
-
-function createFunction2() {
-    var x = 20;
-    function f() {
-        return x; // this |x| refers local |x| above
-    }
-    return f;
-}
-
-var f1 = createFunction1();
-console.log(f1());          // 10
-var f2 = createFunction2();
-console.log(f2());          // 20
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/index.html b/files/tr/web/javascript/reference/global_objects/index.html deleted file mode 100644 index b03aa1f2d1..0000000000 --- a/files/tr/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: Global Objeler -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.

- -
-

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope (but only if ECMAScript 5 strict mode is not used; in that case it returns undefined). The global object itself can be accessed using the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope consists of the properties of the global object, including inherited properties, if any.

- -

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

- -

Standard objects (by category)

- -

Value properties

- -

These global properties return a simple value; they have no properties or methods.

- - - -

Function properties

- -

These global functions—functions which are called globally rather than on an object—directly return their results to the caller.

- - - -

Fundamental objects

- -

These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.

- - - -

Numbers and dates

- -

These are the base objects representing numbers, dates, and mathematical calculations.

- - - -

Text processing

- -

These objects represent strings and support manipulating them.

- - - -

Indexed collections

- -

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

- - - -

Keyed collections

- -

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

- - - -

Vector collections

- -

{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.

- - - -

Structured data

- -

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

- - - -

Control abstraction objects

- - - -

Reflection

- - - -

Internationalization

- -

Additions to the ECMAScript core for language-sensitive functionalities.

- - - -

Non-standard objects

- - - -

Other

- - -
diff --git a/files/tr/web/javascript/reference/global_objects/isfinite/index.html b/files/tr/web/javascript/reference/global_objects/isfinite/index.html deleted file mode 100644 index 43268d42b7..0000000000 --- a/files/tr/web/javascript/reference/global_objects/isfinite/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: isFinite() -slug: Web/JavaScript/Reference/Global_Objects/isFinite -tags: - - JavaScript - - Sonlu Sayı - - Sonsuz Sayı - - isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/isFinite ---- -
{{jsSidebar("Objects")}}
- -

Global isFinite() fonksiyonu girilen değerin sonlu sayı olup olmadığını kararlaştırır. Gerekliyse, parametre ilk önce sayıya çevrilir.

- -

Söz Dizimi

- -
isFinite(testDegeri)
- -

Parametreler

- -
-
testDegeri
-
Sonluluğu test edilecek sayı.
-
- -

Açıklama

- -

isFinite en üst seviye fonksiyondur ve herhangi bir nesne ile ilişkilendirilemez.

- -

Bu fonksiyonu bir sayının sonlu olup olmadığını kararlaştırmak için kullanabilirsiniz. isFinite fonksiyonu argümanı olan sayıyı sorgular. Eğer argümanın değeri NaN, pozitif sonsuz veya negatif sonsuz ise, metod false döndürür; değilse, true döndürür.

- -

Örnekler

- -
isFinite(SonsuzSayı);  // false
-isFinite(NaN);         // false
-isFinite(-SonsuzSayı); // false
-
-isFinite(0);         // true
-isFinite(2e64);      // true
-isFinite(null);      // true
-
-
-isFinite("0");       // true, daha güçlü bir ifade olan Number.isFinite("0")
-                     // ile kullanılsaydı false olacaktı.
-
- -

Tanımlamalar

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TanımDurumAçıklama
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel Destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel Destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/isnan/index.html b/files/tr/web/javascript/reference/global_objects/isnan/index.html deleted file mode 100644 index 7a098629e6..0000000000 --- a/files/tr/web/javascript/reference/global_objects/isnan/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: isNaN() -slug: Web/JavaScript/Reference/Global_Objects/isNaN -translation_of: Web/JavaScript/Reference/Global_Objects/isNaN ---- -
{{jsSidebar("Objects")}}
- -

isNaN() bir değerin NaN olup olmadığını belirler. Not: isNaN işlevi içindeki zorlamanın ilginç kuralları vardır; alternatif olarak ECMAScript 2015'te tanımlandığı gibi Number.isNaN() yöntemini kullanmak isteyebilirsiniz.

- -
{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}
- -

Sözdizimi

- -
isNaN(deger)
- -

Parametre(ler)

- -
-
değer
-
Test edilecek değer.
-
- -

Verilecek değer

- -

Verilen değer {{jsxref("NaN")}} ise true; değilse false.

- -

Açıklama

- -

isNaN işlevi gerekliliği

- -

JavaScript'teki diğer tüm olası değerlerden farklı olarak, bir değerin {{jsxref ("NaN")}} olup olmadığını belirlemek için eşitlik operatörlerine (== ve ===) güvenmek mümkün değildir, çünkü NaN == NaN ve NaN === NaN false olarak değerlendirilir. BU yüzden isNaN işlevi.

- -

NaN değerlerinin kaynağı

- -

NaN değerleri, aritmetik işlemler tanımsız (undefined) veya tekrarlanamayan değerlerle sonuçlandığında üretilir. Bu tür değerler mutlaka taşma koşullarını temsil etmez. NaN ayrıca, ilkel sayısal değerin bulunmadığı sayısal olmayan değerlerin sayısal değerlerine zorlama girişiminden de kaynaklanır.

- -

Örneğin, sıfıra sıfıra bölmek bir NaN ile sonuçlanır - ancak diğer sayıları sıfıra bölmek olmaz.

- -

Özel durum davranışlarını karıştırmak

- -

İsNaN işlev belirtiminin en eski sürümleri olduğundan, sayısal olmayan bağımsız değişkenler için davranışı kafa karıştırıcı olur. İsNaN işlevinin bağımsız değişkeni Number türünde değilse, değer önce bir Number öğesine zorlanır. Dağa sonra elde edilen değer daha sonra {{jsxref ("NaN")}} olup olmadığını belirlemek için test edilir. Bu nedenle, sayısal tipe zorlandığında, geçerli bir NaN olmayan sayısal değerle sonuçlanan sayılar için (özellikle boş dize ve boolean ilkelleri, zorlandığında sayısal değerler sıfır veya bir verir), "false" döndürülen değer beklenmedik olabilir; örneğin, boş dize mutlaka "bir sayı değildir". Karışıklık, "sayı değil" teriminin IEEE-754 kayan nokta değerleri olarak gösterilen sayılar için özel bir anlamı olduğu gerçeğinden kaynaklanmaktadır. İşlev, "bu değer, sayısal değere zorlandığında IEEE-754 'Sayı Değil' değeri mi?" Sorusunu yanıtlıyor olarak yorumlanmalıdır.

- -

ECMAScript 2015, {{jsxref ("Number.isNaN ()")}} işlevini içerir. Number.isNaN(x), x'in NaN olup olmadığını test etmenin güvenilir bir yoludur. Bununla birlikte, Number.isNaN ile bile, NaN'nin anlamı, basitçe "bir sayı değil", kesin sayısal anlam olarak kalır. Alternatif olarak, Number.isNaN yokluğunda, (x != x) ifadesi, x değişkeninin NaN olup olmadığını test etmenin daha güvenilir bir yoludur, çünkü sonuç isNaN'yi güvenilir olmayan sahte pozitiflere tabi değildir.

- -

isNaN için bir çoklu dolgu (çoklu dolgu, NaN'nin kendine özgü asla eşit olmayan özelliğini kullanır):

- -
var isNaN = function(deger) {
-    var n = Number(deger);
-    return n !== n;
-};
- -

Examples

- -
isNaN(NaN);       // true
-isNaN(undefined); // true
-isNaN({});        // true
-
-isNaN(true);      // false
-isNaN(null);      // false
-isNaN(37);        // false
-
-// strings
-isNaN('37');      // false: "37", NaN olmayan 37 sayısına dönüştürülür
-isNaN('37.37');   // false: "37.37", NaN olmayan 37.37 sayısına dönüştürülür
-isNaN("37,5");    // true
-isNaN('123ABC');  // true:  parseInt("123ABC") 123, ancak Number("123ABC")
-isNaN('');        // false: boş dize, NaN olmayan 0'a dönüştürülür
-isNaN(' ');       // false: boşluklu bir dize, NaN olmayan 0'a dönüştürülür
-
-// tarihler
-isNaN(new Date());                // false
-isNaN(new Date().toString());     // true
-
-// Bu yanlış bir pozitiftir ve isNaN'ın tamamen güvenilir olmamasının nedenidir
-isNaN('blabla');   // true: "blabla" bir sayıya dönüştürülür.
-                   // Bunu bir sayı olarak ayrıştırma başarısız olur ve NaN döndürür
- -

Faydalı özel durum davranışı

- -

İsNaN() yöntemini düşünmek için daha çok kullanıma yönelik bir yol vardır: isNaN(x) false değerini döndürürse, ifadeyi NaN döndürmeyen bir aritmetik ifadede x kullanabilirsiniz. true değerini döndürürse, x her aritmetik ifadeyi NaN döndürür. Bu, JavaScript'te, isNaN(x) == true değerinin, NaN döndüren x - 0'a eşdeğer olduğu anlamına gelir (JavaScript x - 0 == NaN'de her zaman false döndürür, bu nedenle test edemezsiniz). Aslında, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0) ve Number.isNaN(Number(x)) her zaman aynı döndürür ve JavaScript isNaN(x) bu terimlerin her birini ifade etmek için mümkün olan en kısa biçimdir.

- -

Örneğin, bir işleve ait bir argümanın aritmetik olarak işlenebilir (bir sayı gibi "kullanılabilir") veya değilse ve varsayılan bir değer veya başka bir şey sağlamanız gerekip gerekmediğini test etmek için kullanabilirsiniz. Bu şekilde, içeriğe bağlı olarak değerleri dolaylı olarak dönüştürerek JavaScript'in sağladığı çok yönlülüğü kullanan bir işleve sahip olabilirsiniz.

- -

Örnekler

- -
function artım(x) {
-  if (isNaN(x)) x = 0;
-  return x + 1;
-}
-
-// Number.isNaN() ile aynı etki:
-function artım(x) {
-  if (Number.isNaN(Number(x))) x = 0;
-  return x + 1;
-}
-
-// Aşağıdaki durumlarda işlevin x argümanı için,
-// isNaN(x) her zaman yanlıştır, ancak x gerçekten bir
-// ancak aritmetik olarak kullanılabilir
-// ifadeler
-increment('');            // 1: "", 0'a dönüştürülür
-increment(new String());  // 1: Boş bir dizeyi temsil eden dize nesnesi 0'a dönüştürülür
-increment([]);            // 1: [], 0'a dönüştürülür
-increment(new Array());   // 1: Boş bir diziyi temsil eden dizi nesnesi 0'a dönüştürülür
-increment('0');           // 1: "0", 0'a dönüştürülür
-increment('1');           // 2: "1", 1'e dönüştürülür
-increment('0.1');         // 1.1: "0.1", 0.1'a dönüştürülür.
-increment('Infinity');    // Infinity: "Infinity", Infinity dönüştürülür
-increment(null);          // 1: null değeri 0'a dönüştürülür
-increment(false);         // 1: false değeri 0'a dönüştürülür
-increment(true);          // 2: true değeri 1'e dönüştürülür
-increment(new Date());    // milisaniye cinsinden geçerli tarih/saati döndürür artı 1
-
-// Aşağıdaki durumlarda işlevin x argümanı için,
-// isNaN (x) her zaman falsetır ve x gerçekten bir sayıdır.
-increment(-1);            // 0
-increment(-0.1);          // 0.9
-increment(0);             // 1
-increment(1);             // 2
-increment(2);             // 3
-// ...ve bunun gibi...
-increment(Infinity);      // Infinity
-
-// Aşağıdaki durumlarda işlevin x argümanı için,
-// isNaN(x) her zaman doğrudur ve x gerçekten bir sayı değildir,
-// böylece fonksiyon 0 ile değiştirilir ve 1 döndürür
-increment(String);            // 1
-increment(Array);             // 1
-increment('blabla');          // 1
-increment('-blabla');         // 1
-increment(0 / 0);               // 1
-increment('0 / 0');             // 1
-increment(Infinity / Infinity); // 1
-increment(NaN);               // 1
-increment(undefined);         // 1
-increment();                  // 1
-
-// isNaN(x) her zaman isNaN(Number(x)) ile aynıdır,
-// ama x'in varlığı burada zorunludur!
-isNaN(x) == isNaN(Number(x)); // x == undefined dahil, x'in her değeri için true,
-                              // çünkü isNaN(undefined) == true ve Number(undefined) NaN değerini döndürür,
-                              // ama...
-isNaN() == isNaN(Number());   // false, çünküisNaN() == true ve Number() == 0
-
- -

Özellikler

- - - - - - - - - - -
Şartname
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}
- -

Tarayıcı Uyumluluğu

- - - -

{{Compat("javascript.builtins.isNaN")}}

- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/json/index.html b/files/tr/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index f458b5390e..0000000000 --- a/files/tr/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -tags: - - JSON - - JavaScript Nesneler - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

JSON nesnesi, JavaScript Object Notasyonunu çözümlemek ve değerleri JSON'a çevirmek için kullanılan metodları içinde barındırır. Çağırılamaz veya inşa edilemez, ve iki özelliği haricinde kendisine ait başka ilginç bir kullanılabilirliği de yoktur.

- -

Açıklama

- -

JavaScript Obje Notasyonu

- -

JSON; nesneleri, dizileri, sayıları, dizeleri, boolean değerleri ve {{jsxref("null")}} değerini seri haline getirmek için kullanılan bir sözdizimidir. JavaScript sözdizimine bağlıdır ama farklılıkları da vardır: Her JavaScript, JSON olmadığı gibi her JSON da JavaScript olmayabilir. Buna da göz atın: JSON: The JavaScript subset that isn't.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript ve JSON farklılıkları
JavaScript tipiJSON farklılıkları
Nesneler ve DizilerProperty isimleri çift tırnaklı dizeler olmalıdır; sona konulan virgüller yasaktır.
SayılarÖne gelecek sıfırlar yasaktır( JSON.stringify'da sıfırlar göz ardı edilirler, ama JSON.parse'da SyntaxError döndürürler); bir ondalik noktanın devamında en az bir sayı gelmelidir.
Dizeler -

Sadece sınırlı sayıda karakterin kaçmasına izin verilebilir; belli kontrol karakterleri yasaklanmıştır; Unicode satır ayırıcı (U+2028) ve paragraf ayırıcı (U+2029) karakterlerine izin verilir; dizeler çift tırnaklı olmalıdır. Aşağıdaki örneğe göz atarsanız; {{jsxref("JSON.parse()")}}'ın düzgün çalıştığını ve JavaScript olarak değerlendiği zaman bir {{jsxref("SyntaxError")}} döndürüldüğünü görebilirsiniz:

- -
-var code = '"\u2028\u2029"';
-JSON.parse(code); // düzgün çalışıyor.
-eval(code); // hata veriyor.
-
-
- -

Tüm JSON söz dizimi aşağıdaki gibidir:

- -
JSON = null
-    or true or false
-    or JSONNumber
-    or JSONString
-    or JSONObject
-    or JSONArray
-
-JSONNumber = - PositiveNumber
-          or PositiveNumber
-PositiveNumber = DecimalNumber
-              or DecimalNumber . Digits
-              or DecimalNumber . Digits ExponentPart
-              or DecimalNumber ExponentPart
-DecimalNumber = 0
-             or OneToNine Digits
-ExponentPart = e Exponent
-            or E Exponent
-Exponent = Digits
-        or + Digits
-        or - Digits
-Digits = Digit
-      or Digits Digit
-Digit = 0 through 9
-OneToNine = 1 through 9
-
-JSONString = ""
-          or " StringCharacters "
-StringCharacters = StringCharacter
-                or StringCharacters StringCharacter
-StringCharacter = any character
-                  except " or \ or U+0000 through U+001F
-               or EscapeSequence
-EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
-              or \u HexDigit HexDigit HexDigit HexDigit
-HexDigit = 0 through 9
-        or A through F
-        or a through f
-
-JSONObject = { }
-          or { Members }
-Members = JSONString : JSON
-       or Members , JSONString : JSON
-
-JSONArray = [ ]
-         or [ ArrayElements ]
-ArrayElements = JSON
-             or ArrayElements , JSON
-
- -

Önemsiz boşluklar; JSONNumber ve JSONString dışında herhangi bir yerde kullanılabilirler (sayılar boşluk içeremezler) veya (Dizeler için, dizede karşılık gelen karakter olarak yorumlanır, veye hataya sebep verir). Tab karakteri (U+0009), satırbaşı (U+000D), line feed (U+000A), ve boşluk (U+0020) karakterleri tek kabul edilen boşluk karakterleridir.

- -

Metotlar

- -
-
{{jsxref("JSON.parse()")}}
-
Bir dizeyi; JSON olarak çözümler, opsiyonel olarak üretilen değer ve değerin özelliklerini de dönüştürebilir. Sonrasında değeri döndürür.
-
{{jsxref("JSON.stringify()")}}
-
Belirtilen değerle ilişkili JSON dizesini döndürür, opsiyonel olarak sadece belirlenen özellikleri ekler veya özellik değerlerini kullanıcı tanımlı biçimde değiştirir.
-
- -

Polyfill

- -

JSON nesnesi eski tarayıcılar tarafından desteklenmemektedir. Bunun üstesinden geçici bir şekilde gelmek için scriptinizin başına aşağıdaki kodu ekleyebilirsiniz, bu şekilde aslen destenlenmediğinde JSON nesnesinin kullanımına izin verilmiş olur (Internet Explorer 6 gibi).

- -

Aşağıdaki algoritma asıl JSON nesnesinin bir taklididir.

- -
if (!window.JSON) {
-  window.JSON = {
-    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
-    stringify: (function () {
-      var toString = Object.prototype.toString;
-      var hasOwnProperty = Object.prototype.hasOwnProperty;
-      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
-      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
-      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
-      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
-      return function stringify(value) {
-        if (value == null) {
-          return 'null';
-        } else if (typeof value === 'number') {
-          return isFinite(value) ? value.toString() : 'null';
-        } else if (typeof value === 'boolean') {
-          return value.toString();
-        } else if (typeof value === 'object') {
-          if (typeof value.toJSON === 'function') {
-            return stringify(value.toJSON());
-          } else if (isArray(value)) {
-            var res = '[';
-            for (var i = 0; i < value.length; i++)
-              res += (i ? ', ' : '') + stringify(value[i]);
-            return res + ']';
-          } else if (toString.call(value) === '[object Object]') {
-            var tmp = [];
-            for (var k in value) {
-              // in case "hasOwnProperty" has been shadowed
-              if (hasOwnProperty.call(value, k))
-                tmp.push(stringify(k) + ': ' + stringify(value[k]));
-            }
-            return '{' + tmp.join(', ') + '}';
-          }
-        }
-        return '"' + value.toString().replace(escRE, escFunc) + '"';
-      };
-    })()
-  };
-}
-
- -

JSON nesnesi için daha karmaşık ve bilindik polyfilller ise: JSON2 ve JSON3'tür.

- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}İlk tanım.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -
-
- - -

{{Compat("javascript.builtins.JSON")}}

-
-
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/json/stringify/index.html b/files/tr/web/javascript/reference/global_objects/json/stringify/index.html deleted file mode 100644 index 541e87d523..0000000000 --- a/files/tr/web/javascript/reference/global_objects/json/stringify/index.html +++ /dev/null @@ -1,313 +0,0 @@ ---- -title: JSON.stringify() -slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify -translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify ---- -
{{JSRef}}
- -

JSON.stringify() metodu(fonksyionu) Javascript objesinin değerlerini JSON string'ine çevirir. Bu javascript nesnesi üzerinde değişiklik yapabilecek bir fonksiyon tanımlı ise nesne üzerinde çevirme işlemi yanında bunlar da yapılabilir.

- -
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
- - - -

Syntax

- -
JSON.stringify(value[, replacer[, space]])
- -

Parameters

- -
-
value
-
The value to convert to a JSON string.
-
replacer {{optional_inline}}
-
A function that alters the behavior of the stringification process, or an array of {{jsxref("String")}} and {{jsxref("Number")}} objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
-
space {{optional_inline}}
-
A {{jsxref("String")}} or {{jsxref("Number")}} object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
-
- -

Return value

- -

A JSON string representing the given value.

- -

Exceptions

- -

Throws a {{jsxref("TypeError")}} ("cyclic object value") exception when a circular reference is found.

- -

Description

- -

JSON.stringify() converts a value to JSON notation representing it:

- - - -
JSON.stringify({});                    // '{}'
-JSON.stringify(true);                  // 'true'
-JSON.stringify('foo');                 // '"foo"'
-JSON.stringify([1, 'false', false]);   // '[1,"false",false]'
-JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
-JSON.stringify({ x: 5 });              // '{"x":5}'
-
-JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
-// '"2006-01-02T15:04:05.000Z"'
-
-JSON.stringify({ x: 5, y: 6 });
-// '{"x":5,"y":6}'
-JSON.stringify([new Number(3), new String('false'), new Boolean(false)]);
-// '[3,"false",false]'
-
-// String-keyed array elements are not enumerable and make no sense in JSON
-let a = ['foo', 'bar'];
-a['baz'] = 'quux';      // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]
-JSON.stringify(a);
-// '["foo","bar"]'
-
-JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
-// '{"x":[10,null,null,null]}'
-
-// Standard data structures
-JSON.stringify([new Set([1]), new Map([[1, 2]]), new WeakSet([{a: 1}]), new WeakMap([[{a: 1}, 2]])]);
-// '[{},{},{},{}]'
-
-// TypedArray
-JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);
-// '[{"0":1},{"0":1},{"0":1}]'
-JSON.stringify([new Uint8Array([1]), new Uint8ClampedArray([1]), new Uint16Array([1]), new Uint32Array([1])]);
-// '[{"0":1},{"0":1},{"0":1},{"0":1}]'
-JSON.stringify([new Float32Array([1]), new Float64Array([1])]);
-// '[{"0":1},{"0":1}]'
-
-// toJSON()
-JSON.stringify({ x: 5, y: 6, toJSON(){ return this.x + this.y; } });
-// '11'
-
-// Symbols:
-JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
-// '{}'
-JSON.stringify({ [Symbol('foo')]: 'foo' });
-// '{}'
-JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
-// '{}'
-JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
-  if (typeof k === 'symbol') {
-    return 'a symbol';
-  }
-});
-// undefined
-
-// Non-enumerable properties:
-JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
-// '{"y":"y"}'
-
- -

The replacer parameter

- -

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty string as key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:

- - - -
Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
- -
Note: If you wish the replacer to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).
- -

Example with a function

- -
function replacer(key, value) {
-  // Filtering out properties
-  if (typeof value === 'string') {
-    return undefined;
-  }
-  return value;
-}
-
-var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
-JSON.stringify(foo, replacer);
-// '{"week":45,"month":7}'
-
- -

Example with an array

- -

If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.

- -
JSON.stringify(foo, ['week', 'month']);
-// '{"week":45,"month":7}', only keep "week" and "month" properties
-
- -

The space argument

- -

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).

- -
JSON.stringify({ a: 2 }, null, ' ');
-// '{
-//  "a": 2
-// }'
-
- -

Using a tab character mimics standard pretty-print appearance:

- -
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
-// returns the string:
-// '{
-//     "uno": 1,
-//     "dos": 2
-// }'
-
- -

toJSON() behavior

- -

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. JSON.stringify() calls toJSON with one parameter:

- - - -

For example:

- -
var obj = {
-    data: 'data',
-
-    toJSON(key){
-        if(key)
-            return `Now I am a nested object under key '${key}'`;
-
-        else
-            return this;
-    }
-};
-
-JSON.stringify(obj);
-// '{"data":"data"}'
-
-JSON.stringify({ obj })
-// '{"obj":"Now I am a nested object under key 'obj'"}'
-
-JSON.stringify([ obj ])
-// '["Now I am a nested object under key '0'"]'
-
- -

Issue with JSON.stringify() when serializing circular references

- -

Note that since the JSON format doesn't support object references (although an IETF draft exists), a {{jsxref("TypeError")}} will be thrown if one attempts to encode an object with circular references.

- -
const circularReference = {};
-circularReference.myself = circularReference;
-
-// Serializing circular references throws "TypeError: cyclic object value"
-JSON.stringify(circularReference);
-
- -

To serialize circular references you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

- -

Issue with plain JSON.stringify for use as JavaScript

- -

Note that JSON is not a completely strict subset of JavaScript, with two line terminators (Line separator and Paragraph separator) not needing to be escaped in JSON but needing to be escaped in JavaScript. Therefore, if the JSON is meant to be evaluated or directly utilized within JSONP, the following utility can be used:

- -
function jsFriendlyJSONStringify (s) {
-    return JSON.stringify(s).
-        replace(/\u2028/g, '\\u2028').
-        replace(/\u2029/g, '\\u2029');
-}
-
-var s = {
-    a: String.fromCharCode(0x2028),
-    b: String.fromCharCode(0x2029)
-};
-try {
-    eval('(' + JSON.stringify(s) + ')');
-} catch (e) {
-    console.log(e); // "SyntaxError: unterminated string literal"
-}
-
-// No need for a catch
-eval('(' + jsFriendlyJSONStringify(s) + ')');
-
-// console.log in Firefox unescapes the Unicode if
-//   logged to console, so we use alert
-alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
- -

Example of using JSON.stringify() with localStorage

- -

In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify():

- -
// Creating an example of JSON
-var session = {
-  'screens': [],
-  'state': true
-};
-session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
-session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
-session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
-session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
-session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
-session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
-
-// Converting the JSON string with JSON.stringify()
-// then saving with localStorage in the name of session
-localStorage.setItem('session', JSON.stringify(session));
-
-// Example of how to transform the String generated through
-// JSON.stringify() and saved in localStorage in JSON object again
-var restoredSession = JSON.parse(localStorage.getItem('session'));
-
-// Now restoredSession variable contains the object that was saved
-// in localStorage
-console.log(restoredSession);
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.JSON.stringify")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/map/index.html b/files/tr/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 67f46594f6..0000000000 --- a/files/tr/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ECMAScript 2015 - - JavaScript - - Map - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

The Map object holds key-value pairs. Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.

- -

Syntax

- -
new Map([iterable])
- -

Parameters

- -
-
iterable
-
An {{jsxref("Array")}} or other iterable object whose elements are key-value pairs (arrays with two elements, e.g. [[ 1, 'one' ],[ 2, 'two' ]]). Each key-value pair is added to the new Map; null values are treated as undefined.
-
- -

Description

- -

A Map object iterates its elements in insertion order — a {{jsxref("Statements/for...of", "for...of")}} loop returns an array of [key, value] for each iteration.
-
- It should be noted that a Map which is a map of an object, especially a dictionary of dictionaries, will only map to the object's insertion order—which is random and not ordered.

- -

Key equality

- -

Key equality is based on the "SameValueZero" algorithm: NaN is considered the same as NaN (even though NaN !== NaN) and all other values are considered equal according to the semantics of the === operator. In the current ECMAScript specification -0 and +0 are considered equal, although this was not so in earlier drafts. See "Value equality for -0 and 0" in the browser compatibility table for details.

- -

Objects and maps compared

- -

{{jsxref("Object", "Objects")}} are similar to Maps in that both let you set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. Because of this (and because there were no built-in alternatives), Objects have been used as Maps historically; however, there are important differences that make using a Map preferable in certain cases:

- - - -

Properties

- -
-
Map.length
-
The value of the length property is 0.
-
{{jsxref("Map.@@species", "get Map[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Map.prototype")}}
-
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
-
- -

Map instances

- -

All Map instances inherit from {{jsxref("Map.prototype")}}.

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

- -

Examples

- -

Using the Map object

- -
var myMap = new Map();
-
-var keyString = 'a string',
-    keyObj = {},
-    keyFunc = function() {};
-
-// setting the values
-myMap.set(keyString, "value associated with 'a string'");
-myMap.set(keyObj, 'value associated with keyObj');
-myMap.set(keyFunc, 'value associated with keyFunc');
-
-myMap.size; // 3
-
-// getting the values
-myMap.get(keyString);    // "value associated with 'a string'"
-myMap.get(keyObj);       // "value associated with keyObj"
-myMap.get(keyFunc);      // "value associated with keyFunc"
-
-myMap.get('a string');   // "value associated with 'a string'"
-                         // because keyString === 'a string'
-myMap.get({});           // undefined, because keyObj !== {}
-myMap.get(function() {}) // undefined, because keyFunc !== function () {}
-
- -

Using NaN as Map keys

- -

NaN can also be used as a key. Even though every NaN is not equal to itself (NaN !== NaN is true), the following example works because NaNs are indistinguishable from each other:

- -
var myMap = new Map();
-myMap.set(NaN, 'not a number');
-
-myMap.get(NaN); // "not a number"
-
-var otherNaN = Number('foo');
-myMap.get(otherNaN); // "not a number"
-
- -

Iterating Maps with for..of

- -

Maps can be iterated using a for..of loop:

- -
var myMap = new Map();
-myMap.set(0, 'zero');
-myMap.set(1, 'one');
-for (var [key, value] of myMap) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// 0
-// 1
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// zero
-// one
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
- -

Iterating Maps with forEach()

- -

Maps can be iterated using the forEach() method:

- -
myMap.forEach(function(value, key) {
-  console.log(key + ' = ' + value);
-});
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Relation with Array objects

- -
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
-
-// Use the regular Map constructor to transform a 2D key-value Array into a map
-var myMap = new Map(kvArray);
-
-myMap.get('key1'); // returns "value1"
-
-// Use the Array.from function to transform a map into a 2D key-value Array
-console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray
-
-// Or use the keys or values iterators and convert them to an array
-console.log(Array.from(myMap.keys())); // Will show ["key1", "key2"]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map-objects', 'Map')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Map")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/math/index.html b/files/tr/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 774ed159f2..0000000000 --- a/files/tr/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - Namespace - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
- -
{{JSRef}}
- -

Math is a built-in object that has properties and methods for mathematical constants and functions. It’s not a function object.

- -

Math works with the {{jsxref("Number")}} type. It doesn't work with {{jsxref("BigInt")}}.

- -

Description

- -

Unlike many other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument. Constants are defined with the full precision of real numbers in JavaScript.

- -
-

Note: Many Math functions have a precision that’s implementation-dependent.

- -

This means that different browsers can give a different result. Even the same JavaScript engine on a different OS or architecture can give different results!

-
- -

Static properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms; approximately 2.718.
-
{{jsxref("Math.LN2")}}lllllđđlđ
-
lllllđđ vili ga ti tu of 2; approximately 0.693.
-
{{jsxref("Math.LN10")}}
-
Natural logarithm of 10; approximately 2.303.
-
{{jsxref("Math.LOG2E")}}
-
Base-2 logarithm of E; approximately 1.443.
-
{{jsxref("Math.LOG10E")}}
-
Base-10 logarithm of E; approximately 0.434.
-
{{jsxref("Math.PI")}}
-
Ratio of the a circle's circumference to its diameter; approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of ½ (or equivalently, 1/√2); approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2; approximately 1.414.
-
- -

Static methods

- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of x.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of x.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of x.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of x.
-
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
-
Returns the hyperbolic arcsine of a number.
-
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
-
Returns the arctangent of x.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of x.
-
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
-
Returns the arctangent of the quotient of its arguments.
-
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
-
Returns the cube root of x.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to x.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of the 32-bit integer x.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of x.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of x.
-
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
-
Returns Ex, where x is the argument, and E is Euler's constant (2.718…, the base of the natural logarithm).
-
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
-
Returns subtracting 1 from exp(x).
-
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
-
Returns the largest integer less than or equal to x.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of x.
-
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
-
Returns the square root of the sum of squares of its arguments.
-
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
-
Returns the result of the 32-bit integer multiplication of x and y.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (㏒e; also, ㏑) of x.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm (㏒e; also ㏑) of 1 + x for the number x.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base-10 logarithm of x.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base-2 logarithm of x.
-
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
-
Returns the largest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
-
Returns the smallest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
-
Returns base x to the exponent power y (that is, xy).
-
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
-
Returns a pseudo-random number between 0 and 1.
-
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
-
Returns the value of the number x rounded to the nearest integer.
-
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
-
Returns the sign of the x, indicating whether x is positive, negative, or zero.
-
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
-
Returns the sine of x.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of x.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of x.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of x.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of x.
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integer portion of x, removing any fractional digits.
-
- -

Examples

- -

Converting between degrees and radians

- -

The trigonometric functions sin(), cos(), tan(), asin(), acos(), atan(), and atan2() expect (and return) angles in radians.

- -

Since humans tend to think in degrees, and some functions (such as CSS transforms) can accept degrees, it is a good idea to keep functions handy that convert between the two:

- -
function degToRad(degrees) {
-  return degrees * (Math.PI / 180);
-};
-
-function radToDeg(rad) {
-  return rad / (Math.PI / 180);
-};
- -

Calculating the height of an equalateral triangle

- -

If we want to calculate the height of an equalateral triangle, and we know its side length is 100, we can use the formulae length of the adjacent multiplied by the tangent of the angle is equal to the opposite.

- -

- -

In JavaScript, we can do this with the following:

- -
50 * Math.tan(degToRad(60)).
- -

We use our degToRad() function to convert 60 degrees to radians, as Math.tan() expects an input value in radians.

- -

Returning a random integer between two bounds

- -

This can be achieved with a combination of Math.random() and Math.floor():

- -
function random(min, max) {
-  const num = Math.floor(Math.random() * (max - min + 1)) + min;
-  return num;
-}
-
-random(1, 10);
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Math")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/math/sign/index.html b/files/tr/web/javascript/reference/global_objects/math/sign/index.html deleted file mode 100644 index cbed44a438..0000000000 --- a/files/tr/web/javascript/reference/global_objects/math/sign/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Math.sign() -slug: Web/JavaScript/Reference/Global_Objects/Math/sign -translation_of: Web/JavaScript/Reference/Global_Objects/Math/sign ---- -
{{JSRef}}
- -
Math.sign() fonksiyonu, parametre olarak aldığı sayının negatif (-1) veya pozitif (1) olduğu bilgisini döndürür. Parametre olarak 0 gönderilirse, +/- 0 döndürür. Sayı pozitifse ayrıca + işareti döndürülmez.
- -
- -
{{EmbedInteractiveExample("pages/js/math-sign.html")}}
- - - -

Syntax

- -
Math.sign(x)
- -

Parameters

- -
-
x
-
A number. If this argument is not a number, it is implicitly converted to one.
-
- -

Return value

- -

A number representing the sign of the given argument:

- - - -

Description

- -

Because sign() is a static method of Math, you always use it as Math.sign(), rather than as a method of a Math object you created (Math is not a constructor).

- -

Polyfill

- -
if (!Math.sign) {
-  Math.sign = function(x) {
-    // If x is NaN, the result is NaN.
-    // If x is -0, the result is -0.
-    // If x is +0, the result is +0.
-    // If x is negative and not -0, the result is -1.
-    // If x is positive and not +0, the result is +1.
-    return ((x > 0) - (x < 0)) || +x;
-    // A more aesthetic pseudo-representation:
-    //
-    // ( (x > 0) ? 1 : 0 )  // if x is positive, then positive one
-    //          +           // else (because you can't be both - and +)
-    // ( (x < 0) ? -1 : 0 ) // if x is negative, then negative one
-    //         ||           // if x is 0, -0, or NaN, or not a number,
-    //         +x           // then the result will be x, (or) if x is
-    //                      // not a number, then x converts to number
-  };
-}
-
- -

In the above polyfill, no extra type-coercing is needed to make (x > 0) or (x < 0) numbers because subtracting them from each other forces a type conversion from booleans to numbers.

- -

Examples

- -

Using Math.sign()

- -
Math.sign(3);     //  1
-Math.sign(-3);    // -1
-Math.sign('-3');  // -1
-Math.sign(0);     //  0
-Math.sign(-0);    // -0
-Math.sign(NaN);   // NaN
-Math.sign('foo'); // NaN
-Math.sign();      // NaN
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-math.sign', 'Math.sign')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Math.sign")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/assign/index.html b/files/tr/web/javascript/reference/global_objects/object/assign/index.html deleted file mode 100644 index 9490bcec2d..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/assign/index.html +++ /dev/null @@ -1,311 +0,0 @@ ---- -title: Object.assign() -slug: Web/JavaScript/Reference/Global_Objects/Object/assign -translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign ---- -
{{JSRef}}
- -

Object.assign() metodu bir ya da daha fazla kaynaktaki sayılabilir özellikteki nesnelerin tüm değerlerini hedef kaynaktaki nesneye kopyalamak için kullanılır. Hedef nesnesini geri döndürür.

- -

Yazım Şekli

- -
Object.assign(hedef_nesne, ...kaynak_nesneler)
- -

Değişkenler

- -
-
hedef_nesne
-
Kaydedilecek olan hedef nesne.
-
kaynak_nesneler
-
Kaynak nesne(ler).
-
- -

Dönüş Değeri

- -

Hedef nesne.

- -

Açıklama

- -

Hedef nesnedeki değişkenlerin özellikleri kaynak nesnedeklerle aynı anahtar değerlerine sahipse üzerine yazılır. Daha sonra kaynaklardaki değerler benzer şekilde bir öncekiler gibi üzerine yazılır.

- -

Object.assign() metodu bir kaynak nesnesinden bir hedef nesnesine sadece sayılabilir ve sahip olduğu özellikleri kopyalar. Kaynak nesne için [[Get]] ve hedef nesne için [[Set]]'i kullanır, böylelikle getter ve setter metodlarını çağırır. Bu nedenle yeni özellikleri sadece kopyalama ya da tanımlamaya karşı hedef nesneye atama yapar. Birleştirme kaynakları getter içeriyorsa, yeni özelliklerin bir prototip halinde birleştirilmesi uygun olmayabilir. Sayılabilir özellikler de dahil olmak üzere özellik tanımlamalarını kopyalamak için, prototiplerdeki {{jsxref("Object.getOwnPropertyDescriptor()")}} yerine {{jsxref("Object.defineProperty()")}} kullanılmalıdır.

- -

{{jsxref("String")}} ve  {{jsxref("Symbol")}}  özelliklerin her ikisi de kopyalanır.

- -

Hata durumunda,örneğin bir özelliklik yazılamaz durumda ise, bir {{jsxref("TypeError")}} durumu oluşacaktır ve hedef nesne değişmeden kalacaktır.

- -

Object.assign() metodu kaynak nesnelerdeki {{jsxref("null")}} ya da {{jsxref("undefined")}} durumlarını fırlatmayacağını not ediniz.

- -

Örnekler

- -

Nesne klonlama

- -
var obj = { a: 1 };
-var copy = Object.assign({}, obj);
-console.log(copy); // { a: 1 }
-
- -

Derin Klonlamada Bir Uyarı

- -

Derin klonlama(kopyalama) için, diğer alternatiflere ihtiyacımız vardır. Çünkü Object.assign() özellikleri kopyalar. Eğer kaynak değeri bir nesnenin referansı ise sadece referans değerini kopyalar.

- -
function test() {
-  'use strict';
-
-  let obj1 = { a: 0 , b: { c: 0}};
-  let obj2 = Object.assign({}, obj1);
-  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
-
-  obj1.a = 1;
-  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
-  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
-
-  obj2.a = 2;
-  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
-  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}
-
-  obj2.b.c = 3;
-  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
-  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
-
-  // Deep Clone
-  obj1 = { a: 0 , b: { c: 0}};
-  let obj3 = JSON.parse(JSON.stringify(obj1));
-  obj1.a = 4;
-  obj1.b.c = 4;
-  console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}
-}
-
-test();
- -

Nesneleri Birleştirme

- -
var o1 = { a: 1 };
-var o2 = { b: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign(o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
-console.log(o1);  // { a: 1, b: 2, c: 3 } // hedef nesnenin kendisi değişti.
- -

Nesneleri Aynı Özelliklerde Birleştirme

- -
var o1 = { a: 1, b: 1, c: 1 };
-var o2 = { b: 2, c: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign({}, o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
-
- -

Özellikler diğer nesneler tarafından parametreler içindeki sonra gelen aynı özelliklerdeki nesnelerin özellikleri olarak üzerine yazıldı.

- -

Sembol-Tipdeki Özellikleri Kopyalama 

- -
var o1 = { a: 1 };
-var o2 = { [Symbol('foo')]: 2 };
-
-var obj = Object.assign({}, o1, o2);
-console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
-Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
-
-
- -

Prototipteki Zincirleme Özellikler ve Sayılamayan Özellikler Kopyalanamaz

- -
var obj = Object.create({ foo: 1 }, { // foo is on obj's prototype chain.
-  bar: {
-    value: 2  // bar sayılamayan özellik
-  },
-  baz: {
-    value: 3,
-    enumerable: true  // baz sayılabilen özellik
-  }
-});
-
-var copy = Object.assign({}, obj);
-console.log(copy); // { baz: 3 }
-
-
- -

Değişken Tipleri Objelere Sarmalanır

- -
var v1 = 'abc';
-var v2 = true;
-var v3 = 10;
-var v4 = Symbol('foo');
-
-var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
-// Değişken tipleri sarmalanır, null ve undefined görmezden gelinir.
-// Sadece string tipteki değişkenler sayılabilir özelliktedir.
-console.log(obj); // { "0": "a", "1": "b", "2": "c" }
-
-
- -

Hatalar Devam Eden Kopyalama İşlemlerini Kesintiye Uğratır

- -
var target = Object.defineProperty({}, 'foo', {
-  value: 1,
-  writable: false
-}); // target.foo sadece-okunabilir özellik
-
-Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
-// TypeError: "foo" sadece-okunabilir özellik
-// foo hedefe aktarma sırasında hata fırlatır
-
-console.log(target.bar);  // 2: ilk kaynak başarıyla kopyalandı.
-console.log(target.foo2); // 3: ikinci kaynağın ilk özelliği başarıyla kopyalandı.
-console.log(target.foo);  // 1: burada hata oluşur.
-console.log(target.foo3); // undefined: atama metodu bitti, foo3 kopyalanmayacak.
-console.log(target.baz);  // undefined: üçüncü kaynak da kopyalanmayacak.
-
- -

Erişimcileri Kopyalama

- -
var obj = {
-  foo: 1,
-  get bar() {
-    return 2;
-  }
-};
-
-var copy = Object.assign({}, obj);
-console.log(copy);
-// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.
-
-// This is an assign function that copies full descriptors
-function completeAssign(target, ...sources) {
-  sources.forEach(source => {
-    let descriptors = Object.keys(source).reduce((descriptors, key) => {
-      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
-      return descriptors;
-    }, {});
-    // by default, Object.assign copies enumerable Symbols too
-    Object.getOwnPropertySymbols(source).forEach(sym => {
-      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
-      if (descriptor.enumerable) {
-        descriptors[sym] = descriptor;
-      }
-    });
-    Object.defineProperties(target, descriptors);
-  });
-  return target;
-}
-
-var copy = completeAssign({}, obj);
-console.log(copy);
-// { foo:1, get bar() { return 2 } }
-
- -

Polyfill

- -

 ES5 sembol özelliğine sahip olmadığından {{Glossary("Polyfill","polyfill")}} sembol özelliği  desteklenmez:

- -
if (typeof Object.assign != 'function') {
-  Object.assign = function(target, varArgs) { // .length of function is 2
-    'use strict';
-    if (target == null) { // TypeError if undefined or null
-      throw new TypeError('Cannot convert undefined or null to object');
-    }
-
-    var to = Object(target);
-
-    for (var index = 1; index < arguments.length; index++) {
-      var nextSource = arguments[index];
-
-      if (nextSource != null) { // Skip over if undefined or null
-        for (var nextKey in nextSource) {
-          // Avoid bugs when hasOwnProperty is shadowed
-          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
-            to[nextKey] = nextSource[nextKey];
-          }
-        }
-      }
-    }
-    return to;
-  };
-}
-
- -

Belirtimler

- - - - - - - - - - - - - - - - - - - -
BelirtimDurumlarAçıklama
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
- -

Tarayıcı Destekleme Durumu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome("45")}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatOpera("32")}}{{CompatSafari("9")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("45")}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
-
- -

Daha Fazlası İçin

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html deleted file mode 100644 index ae72df74e5..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/defineproperty/index.html +++ /dev/null @@ -1,391 +0,0 @@ ---- -title: Object.defineProperty() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty ---- -
{{JSRef}}
- -

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

- -

Syntax

- -
Object.defineProperty(obj, prop, descriptor)
- -

Parameters

- -
-
obj
-
The object on which to define the property.
-
prop
-
The name of the property to be defined or modified.
-
descriptor
-
The descriptor for the property being defined or modified.
-
- -

Description

- -

This method allows precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable.

- -

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

- -

Both data and accessor descriptors are objects. They share the following required keys:

- -
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -

A data descriptor also has the following optional keys:

- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -

An accessor descriptor also has the following optional keys:

- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
- Defaults to {{jsxref("undefined")}}.
-
- -

Bear in mind that these options are not necessarily own properties so, if inherited, will be considered too. In order to ensure these defaults are preserved you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} as {{jsxref("Object.prototype.__proto__", "__proto__")}} property.

- -
// using __proto__
-var obj = {};
-Object.defineProperty(obj, 'key', {
-  __proto__: null, // no inherited properties
-  value: 'static'  // not enumerable
-                   // not configurable
-                   // not writable
-                   // as defaults
-});
-
-// being explicit
-Object.defineProperty(obj, 'key', {
-  enumerable: false,
-  configurable: false,
-  writable: false,
-  value: 'static'
-});
-
-// recycling same object
-function withValue(value) {
-  var d = withValue.d || (
-    withValue.d = {
-      enumerable: false,
-      writable: false,
-      configurable: false,
-      value: null
-    }
-  );
-  d.value = value;
-  return d;
-}
-// ... and ...
-Object.defineProperty(obj, 'key', withValue('static'));
-
-// if freeze is available, prevents adding or
-// removing the object prototype properties
-// (value, get, set, enumerable, writable, configurable)
-(Object.freeze || Object)(Object.prototype);
-
- -

Examples

- -

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

- -

Creating a property

- -

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to {{jsxref("undefined")}}. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

- -
var o = {}; // Creates a new object
-
-// Example of an object property added with defineProperty with a data property descriptor
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: true,
-  enumerable: true,
-  configurable: true
-});
-// 'a' property exists in the o object and its value is 37
-
-// Example of an object property added with defineProperty with an accessor property descriptor
-var bValue = 38;
-Object.defineProperty(o, 'b', {
-  get: function() { return bValue; },
-  set: function(newValue) { bValue = newValue; },
-  enumerable: true,
-  configurable: true
-});
-o.b; // 38
-// 'b' property exists in the o object and its value is 38
-// The value of o.b is now always identical to bValue, unless o.b is redefined
-
-// You cannot try to mix both:
-Object.defineProperty(o, 'conflict', {
-  value: 0x9f91102,
-  get: function() { return 0xdeadbeef; }
-});
-// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
-
- -

Modifying a property

- -

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be “non-configurable”), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

- -

If a property is non-configurable, its writable attribute can only be changed to false.

- -

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

- -

Writable attribute

- -

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

- -
var o = {}; // Creates a new object
-
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: false
-});
-
-console.log(o.a); // logs 37
-o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
-console.log(o.a); // logs 37. The assignment didn't work.
-
- -

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

- -

Enumerable attribute

- -

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

- -
var o = {};
-Object.defineProperty(o, 'a', { value: 1, enumerable: true });
-Object.defineProperty(o, 'b', { value: 2, enumerable: false });
-Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false
-o.d = 4; // enumerable defaults to true when creating a property by setting it
-
-for (var i in o) {
-  console.log(i);
-}
-// logs 'a' and 'd' (in undefined order)
-
-Object.keys(o); // ['a', 'd']
-
-o.propertyIsEnumerable('a'); // true
-o.propertyIsEnumerable('b'); // false
-o.propertyIsEnumerable('c'); // false
-
- -

Configurable attribute

- -

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

- -
var o = {};
-Object.defineProperty(o, 'a', {
-  get: function() { return 1; },
-  configurable: false
-});
-
-Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError
-Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError
-Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously)
-Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing)
-Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError
-
-console.log(o.a); // logs 1
-delete o.a; // Nothing happens
-console.log(o.a); // logs 1
-
- -

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

- -

Adding properties and default values

- -

It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

- -
var o = {};
-
-o.a = 1;
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: true,
-  configurable: true,
-  enumerable: true
-});
-
-
-// On the other hand,
-Object.defineProperty(o, 'a', { value: 1 });
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: false,
-  configurable: false,
-  enumerable: false
-});
-
- -

Custom Setters and Getters

- -

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

- -
function Archiver() {
-  var temperature = null;
-  var archive = [];
-
-  Object.defineProperty(this, 'temperature', {
-    get: function() {
-      console.log('get!');
-      return temperature;
-    },
-    set: function(value) {
-      temperature = value;
-      archive.push({ val: temperature });
-    }
-  });
-
-  this.getArchive = function() { return archive; };
-}
-
-var arc = new Archiver();
-arc.temperature; // 'get!'
-arc.temperature = 11;
-arc.temperature = 13;
-arc.getArchive(); // [{ val: 11 }, { val: 13 }]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}} [1]{{CompatOpera("11.60")}}{{CompatSafari("5.1")}} [2]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
-
- -

[1] In Internet Explorer 8 only on DOM objects and with some non-standard behaviors.

- -

[2] Also supported in Safari 5, but not on DOM objects.

- -

Compatibility notes

- -

Redefining the length property of an Array object

- -

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array it is possible to change the {{jsxref("Array.length", "length")}} property's value, or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

- -

Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

- -

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

- -

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

- -

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

- -

Internet Explorer 8 specific notes

- -

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

- - - -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/entries/index.html b/files/tr/web/javascript/reference/global_objects/object/entries/index.html deleted file mode 100644 index 456bfd6afa..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/entries/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Object.entries() -slug: Web/JavaScript/Reference/Global_Objects/Object/entries -tags: - - JavaScript - - Metot - - Referans - - nesne -translation_of: Web/JavaScript/Reference/Global_Objects/Object/entries ---- -
{{JSRef}}
- -

The Object.entries() metodu, verilen bir nesnenin sıralanabilir [anahtar, değer] çiftlerini {{jsxref("Statements/for...in", "for...in")}} döngüsünün sunacağı sırayla (for-in döngüsü, farklı olarak nesnenin prototip zincirindeki özelliklerini de sıralar) dizi olarak döner.

- -
{{EmbedInteractiveExample("pages/js/object-entries.html")}}
- - - -

Sözdizimi

- -
Object.entries(obj)
- -

Parametreler

- -
-
obj
-
Sıralanabilir özellik çiftleri [key, value] dönülecek olan nesne.
-
- -

Dönüş değeri

- -

Verilen nesnenin sıralanabilir özellik çiftlerini [key, value] içeren dizi

- -

Tanım

- -

Object.entries() elemanları object nesnesinin sıralanabilir özellik çiftlerine [key, value] karşılık gelen diziler olan bir dizi döner. Özelliklerin sırası, özellikler üzerinde döngü ile dönülmesi durumunda oluşacak sırayla aynıdır.

- -

Örnekler

- -
const obj = { foo: 'bar', baz: 42 };
-console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
-
-// dizi benzeri nesne
-const obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
-
-// anahtarları rastgele sıralı olan dizi benzeri nesne
-const anObj = { 100: 'a', 2: 'b', 7: 'c' };
-console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
-
-// getFoo, sıralanabilir bir özellik değildir
-const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } });
-myObj.foo = 'bar';
-console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]
-
-// nesne olmayan parametre nesneye dönüştürülür
-console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
-
-// ilkel tiplerin kendi özellikleri olmadığı için, boş dizi döner
-console.log(Object.entries(100)); // [ ]
-
-// anahtar-değer çiftlerinin üzerinden for-of döngüsü ile geçelim
-const obj = { a: 5, b: 7, c: 9 };
-for (const [key, value] of Object.entries(obj)) {
-  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
-}
-
-// Veya, Array ekstra metotlarını kullanarak geçelim
-Object.entries(obj).forEach(([key, value]) => {
-console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
-});
-
- -

Bir Object'in bir Map'e dönüştürülmesi

- -

{{jsxref("Map", "new Map()")}} yapıcısı, entries üzerinde ilerlenebilir nesnesini ister. Object.entries ile, {{jsxref("Object")}}'ten {{jsxref("Map")}}'e kolayca dönüşüm yapabilirsiniz:

- -
const obj = { foo: 'bar', baz: 42 };
-const map = new Map(Object.entries(obj));
-console.log(map); // Map { foo: "bar", baz: 42 }
-
- -

Bir Object'in üzerinde ilerlemek

- -

Array Destructuring kullanarak, nesnelerin üzerinde kolayca ilerleyebilirsiniz.

- -
const obj = { foo: 'bar', baz: 42 };
-Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`)); // "foo: bar", "baz: 42"
-
- -

Polyfill

- -

Doğal olarak desteklemeyen eski ortamlara Object.entries desteği eklemek için, Object.entries'in gösterme amaçlı gerçeklemesini tc39/proposal-object-values-entries'de (IE desteğine ihtiyacınız yoksa), es-shims/Object.entries repertuarındaki polyfill ile, veya aşağıdaki gibi kullanıma hazır basit polyfill kullanabilirsiniz.

- -

if (!Object.entries)   Object.entries = function( obj ){ var ownProps = Object.keys( obj ),   i = ownProps.length, resArray = new Array(i); // diziyi önden ayıralım     while (i--)   resArray[i] = [ownProps[i], obj[ownProps[i]]];     return resArray; };

- -

Yukardaki polyfill kod parçası için IE < 9 desteğine ihtiyacınız varsa, aynı zamanda Object.keys polyfill desteğine de ihtiyaç duyacaksınız ({{jsxref("Object.keys")}} sayfasındaki gibi)

- -

Şartnameler

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.entries', 'Object.entries')}}{{Spec2('ESDraft')}}İlk tanım.
{{SpecName('ES8', '#sec-object.entries', 'Object.entries')}}{{Spec2('ES8')}} 
- -

Gezgin uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Object.entries")}}

-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/freeze/index.html b/files/tr/web/javascript/reference/global_objects/object/freeze/index.html deleted file mode 100644 index 058f34011b..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/freeze/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Object.freeze() -slug: Web/JavaScript/Reference/Global_Objects/Object/freeze -translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze ---- -
{{JSRef}}
- -

Object.freeze() metodu bir objeyi dondurmak amaçlı kullanılır. Bir obje dondurulduktan sonra artık değiştirilemez, yeni bir property eklenemez, çıkarılamaz veya değiştirilemez. Objenin propertyleri üzerinde herhangi bir düzenleme veya konfigurasyon yapılamaz. Bir obje dondurulduktan sonra sadece property'lerini değil bu objeye bağlı olan prototype da değiştir. freeze() metodu kendisine verilen objeyi dondurulmuş olarak geri döndürür ancak gelen değişkenin yeniden atanması zorunlu değildir.  freeze() metoduna gönderdiğiniz obje referans yoluyla geçeceği için tekrardan bir atama işlemi yapmak zorunda değilsiniz. Redux dahil bir çok state yönetim sistemleri bu metodu kullanarak state objesini immutable - değiştirilemez - yapmakta ve bu işleme bağlı olarak store üzerinden gerçekleştirilen işlemleri yenilemektedir. 

- -
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
- - - -

Syntax

- -
Object.freeze(obje)
- -

Parametreler

- -
-
obje
-
Dondurmak istediğiniz obje.
-
- -

Dönüt

- -

Metoda gönderilen obje dondurularak geri döndürülür

- -

Description

- -

Dondurulmuş obje üzerinde hiç bir düzenleme, ekleme ve çıkarma işlemi yapılamaz. Bu amaçla yapılan herhangi bir değişim {{jsxref("TypeError")}} hatası verir (Farklı çevrelerde daha alt seviye hatalar vermesine karşın, {{jsxref("Strict_mode", "strict mode", "", 1)}} etkinleştirildiği durumlarda  {{jsxref("TypeError")}} hatası kesin olarak alınır).

- -

Dondurulmuş bir objeye ait değer değiştirilemez, writeable ve configurable özellikleri false olarka atanır. Accessor properties (getter and setter) work the same (and still give the illusion that you are changing the value). Note that values that are objects can still be modified, unless they are also frozen. As an object, an array can be frozen; after doing so, its elements cannot be altered and no elements can be added to or removed from the array.

- -

freeze() returns the same object that was passed into the function. It does not create a frozen copy.

- -

In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be treated as if it were a frozen ordinary object, and be simply returned.

- -
> Object.freeze(1)
-TypeError: 1 is not an object // ES5 code
-
-> Object.freeze(1)
-1                             // ES2015 code
-
- -

An ArrayBufferView with elements will cause a {{jsxref("TypeError")}}, as they are views over memory and will definitely cause other possible issues:

- -
> Object.freeze(new Uint8Array(0)) // No elements
-Uint8Array []
-
-> Object.freeze(new Uint8Array(1)) // Has elements
-TypeError: Cannot freeze array buffer views with elements
-
-> Object.freeze(new DataView(new ArrayBuffer(32))) // No elements
-DataView {}
-
-> Object.freeze(new Float64Array(new ArrayBuffer(64), 63, 0)) // No elements
-Float64Array []
-
-> Object.freeze(new Float64Array(new ArrayBuffer(64), 32, 2)) // Has elements
-TypeError: Cannot freeze array buffer views with elements
-
- -

Note that; as the standard three properties (buf.byteLength, buf.byteOffset and buf.buffer) are read-only (as are those of an {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}), there is no reason for attempting to freeze these properties.

- -

Comparison to Object.seal()

- -

Objects sealed with {{jsxref("Object.seal()")}} can have their existing properties changed. Existing properties in objects frozen with Object.freeze() are made immutable.

- -

Examples

- -

Freezing objects

- -
var obj = {
-  prop: function() {},
-  foo: 'bar'
-};
-
-// Before freezing: new properties may be added,
-// and existing properties may be changed or removed
-obj.foo = 'baz';
-obj.lumpy = 'woof';
-delete obj.prop;
-
-// Freeze.
-var o = Object.freeze(obj);
-
-// The return value is just the same object we passed in.
-o === obj; // true
-
-// The object has become frozen.
-Object.isFrozen(obj); // === true
-
-// Now any changes will fail
-obj.foo = 'quux'; // silently does nothing
-// silently doesn't add the property
-obj.quaxxor = 'the friendly duck';
-
-// In strict mode such attempts will throw TypeErrors
-function fail(){
-  'use strict';
-  obj.foo = 'sparky'; // throws a TypeError
-  delete obj.foo; // throws a TypeError
-  delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added
-  obj.sparky = 'arf'; // throws a TypeError
-}
-
-fail();
-
-// Attempted changes through Object.defineProperty;
-// both statements below throw a TypeError.
-Object.defineProperty(obj, 'ohai', { value: 17 });
-Object.defineProperty(obj, 'foo', { value: 'eit' });
-
-// It's also impossible to change the prototype
-// both statements below will throw a TypeError.
-Object.setPrototypeOf(obj, { x: 20 })
-obj.__proto__ = { x: 20 }
-
- -

Freezing arrays

- -
let a = [0];
-Object.freeze(a); // The array cannot be modified now.
-
-a[0] = 1; // fails silently
-
-// In strict mode such attempt will throw a TypeError
-function fail() {
-  "use strict"
-  a[0] = 1;
-}
-
-fail();
-
-// Attempted to push
-a.push(2); // throws a TypeError
- -

The object being frozen is immutable. However, it is not necessarily constant. The following example shows that a frozen object is not constant (freeze is shallow).

- -
obj1 = {
-  internal: {}
-};
-
-Object.freeze(obj1);
-obj1.internal.a = 'aValue';
-
-obj1.internal.a // 'aValue'
- -

To be a constant object, the entire reference graph (direct and indirect references to other objects) must reference only immutable frozen objects. The object being frozen is said to be immutable because the entire object state (values and references to other objects) within the whole object is fixed. Note that strings, numbers, and booleans are always immutable and that Functions and Arrays are objects.

- -

What is "shallow freeze"?

- -

The result of calling Object.freeze(object) only applies to the immediate properties of object itself and will prevent future property addition, removal or value re-assignment operations only on object. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.

- -
var employee = {
-  name: "Mayank",
-  designation: "Developer",
-  address: {
-    street: "Rohini",
-    city: "Delhi"
-  }
-};
-
-Object.freeze(employee);
-
-employee.name = "Dummy"; // fails silently in non-strict mode
-employee.address.city = "Noida"; // attributes of child object can be modified
-
-console.log(employee.address.city) // Output: "Noida"
-
- -

To make an object immutable, recursively freeze each property which is of type object (deep freeze). Use the pattern on a case-by-case basis based on your design when you know the object contains no cycles in the reference graph, otherwise an endless loop will be triggered. An enhancement to deepFreeze() would be to have an internal function that receives a path (e.g. an Array) argument so you can suppress calling deepFreeze() recursively when an object is in the process of being made immutable. You still run a risk of freezing an object that shouldn't be frozen, such as [window].

- -
function deepFreeze(object) {
-
-  // Retrieve the property names defined on object
-  var propNames = Object.getOwnPropertyNames(object);
-
-  // Freeze properties before freezing self
-
-  for (let name of propNames) {
-    let value = object[name];
-
-    if(value && typeof value === "object") {
-      deepFreeze(value);
-    }
-  }
-
-  return Object.freeze(object);
-}
-
-var obj2 = {
-  internal: {
-    a: null
-  }
-};
-
-deepFreeze(obj2);
-
-obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode
-obj2.internal.a; // null
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Object.freeze")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html deleted file mode 100644 index c6bf7acbbf..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/getprototypeof/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Object.getPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf -tags: - - ECMAScript5 - - JavaScript - - nesne - - prototip -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf ---- -
{{JSRef}}
- -

Object.getPrototypeOf() metodu, belirtilen nesnenin prototipini döndürür.

- -

Syntax

- -
Object.getPrototypeOf(nesne)
- -

Parametreler

- -
-
nesne
-
Prototipi döndürülecek olan nesne.
-
- -

Örnekler

- -
var proto = {};
-var nesne = Object.create(proto);
-Object.getPrototypeOf(nesne) === proto; // true
-
- -

Notlar

- -

ES5'te, nesne parametresi bir nesne değilse sistem bir {{jsxref("TypeError")}} fırlatır. ES6'da ise, parametre bir nesne olmaya zorlanır.

- -
Object.getPrototypeOf("foo");
-// TypeError: "foo" bir nesne değil (ES5 kodu)
-Object.getPrototypeOf("foo");
-// String.prototype                 (ES6 kodu)
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationDurumYorum
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}İlk tanımlama.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Opera'ya özel notlar

- -

Eski Opera versiyonları Object.getPrototypeOf() fonksiyonunu desteklemiyor olsa da, Opera, 10.50 sürümünden beri standartlarda yer almayan {{jsxref("Object.proto", "__proto__")}} özelliğini desteklemektedir.

- -

Bunlara da göz atın

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/index.html b/files/tr/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index 7e5dfd4c7b..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - NeedsTranslation - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

The Object constructor creates an object wrapper.

- -

Syntax

- -
// Object initialiser or literal
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Called as a constructor
-new Object([value])
- -

Parameters

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
-
value
-
Any value.
-
- -

Description

- -

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("Global_Objects/null", "null")}} or {{jsxref("Global_Objects/undefined", "undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

- -

When called in a non-constructor context, Object behaves identically to new Object().

- -

See also the object initializer / literal syntax.

- -

Properties of the Object constructor

- -
-
Object.length
-
Has a value of 1.
-
{{jsxref("Object.prototype")}}
-
Allows the addition of properties to all objects of type Object.
-
- -

Methods of the Object constructor

- -
-
{{jsxref("Object.assign()")}} {{experimental_inline}}
-
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
-
{{jsxref("Object.create()")}}
-
Creates a new object with the specified prototype object and properties.
-
{{jsxref("Object.defineProperty()")}}
-
Adds the named property described by a given descriptor to an object.
-
{{jsxref("Object.defineProperties()")}}
-
Adds the named properties described by the given descriptors to an object.
-
{{jsxref("Object.freeze()")}}
-
Freezes an object: other code can't delete or change any properties.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Returns a property descriptor for a named property on an object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
-
{{jsxref("Object.getOwnPropertySymbols()")}} {{ experimental_inline() }}
-
Returns an array of all symbol properties found directly upon a given object.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Returns the prototype of the specified object.
-
{{jsxref("Object.is()")}} {{ experimental_inline() }}
-
Compares if two values are distinguishable (ie. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Determines if extending of an object is allowed.
-
{{jsxref("Object.isFrozen()")}}
-
Determines if an object was frozen.
-
{{jsxref("Object.isSealed()")}}
-
Determines if an object is sealed.
-
{{jsxref("Object.keys()")}}
-
Returns an array containing the names of all of the given object's own enumerable properties.
-
{{jsxref("Object.observe()")}} {{experimental_inline}}
-
Asynchronously observes changes to an object.
-
{{jsxref("Object.preventExtensions()")}}
-
Prevents any extensions of an object.
-
{{jsxref("Object.seal()")}}
-
Prevents other code from deleting properties of an object.
-
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
-
Sets the prototype (i.e., the internal [[Prototype]] property)
-
- -

Object instances and Object prototype object

- -

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
- -

Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
- -

Examples

- -

Example: Using Object given undefined and null types

- -

The following examples store an empty Object object in o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Example: Using Object to create Boolean objects

- -

The following examples store {{jsxref("Global_Objects/Boolean", "Boolean")}} objects in o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/tostring/index.html b/files/tr/web/javascript/reference/global_objects/object/tostring/index.html deleted file mode 100644 index 23593555e1..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/tostring/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Object.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Object/toString -translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString ---- -
{{JSRef}}
- -

toString() methodu verilen nesneyi String'e dönüştürür.

- -

Syntax

- -
obj.toString()
- -

Açıklama

- -

Every object has a toString() method that is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. By default, the toString() method is inherited by every object descended from Object. If this method is not overridden in a custom object, toString() returns "[object type]", where type is the object type. The following code illustrates this:

- -
var o = new Object();
-o.toString(); // returns [object Object]
-
- -
-

Note: Starting in JavaScript 1.8.5 toString() called on {{jsxref("null")}} returns [object Null], and {{jsxref("undefined")}} returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata. See {{anch("Using_toString_to_detect_object_type", "Using toString to detect object type")}}.

-
- -

Examples

- -

Overriding the default toString method

- -

You can create a function to be called in place of the default toString() method. The toString() method takes no arguments and should return a string. The toString() method you create can be any value you want, but it will be most useful if it carries information about the object.

- -

The following code defines the Dog object type and creates theDog, an object of type Dog:

- -
function Dog(name, breed, color, sex) {
-  this.name = name;
-  this.breed = breed;
-  this.color = color;
-  this.sex = sex;
-}
-
-theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
-
- -

If you call the toString() method on this custom object, it returns the default value inherited from {{jsxref("Object")}}:

- -
theDog.toString(); // returns [object Object]
-
- -

The following code creates and assigns dogToString() to override the default toString() method. This function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;".

- -
Dog.prototype.toString = function dogToString() {
-  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
-  return ret;
-}
-
- -

With the preceding code in place, any time theDog is used in a string context, JavaScript automatically calls the dogToString() function, which returns the following string:

- -
"Dog Gabby is a female chocolate Lab"
-
- -

Using toString() to detect object class

- -

toString() can be used with every object and allows you to get its class. To use the Object.prototype.toString() with every object, you need to call {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} on it, passing the object you want to inspect as the first parameter called thisArg.

- -
var toString = Object.prototype.toString;
-
-toString.call(new Date);    // [object Date]
-toString.call(new String);  // [object String]
-toString.call(Math);        // [object Math]
-
-// Since JavaScript 1.8.5
-toString.call(undefined);   // [object Undefined]
-toString.call(null);        // [object Null]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Call on {{jsxref("Global_Objects/null", "null")}} returns [object Null], and {{jsxref("Global_Objects/undefined", "undefined")}} returns [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/object/values/index.html b/files/tr/web/javascript/reference/global_objects/object/values/index.html deleted file mode 100644 index 82ee284be2..0000000000 --- a/files/tr/web/javascript/reference/global_objects/object/values/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Object.values() -slug: Web/JavaScript/Reference/Global_Objects/Object/values -tags: - - Javascripts Metot Nesneler -translation_of: Web/JavaScript/Reference/Global_Objects/Object/values ---- -
{{JSRef}}
- -

Object.values()  yöntemi belirli bir nesnenin kendi numaralandırılabilir özellik değerlerinin {{jsxref("Statements/for...in", "for...in")}} döngüsü tarafından sağlanan sırayla dizileri döndürür (fark şu ki; bir for-in döngüsü prototip zincirindeki özelliklerle numaralandırılır).

- -

Sözdizimi

- -
Object.values(obj)
- -

Parametre

- -
-
Nesne, sayısız numaralandırılabilir kendi özellikleri döndürülendir.
-
- -

Return değeri

- -

Diziler verilen nesnenin kendi numaralandırılabilir özellik değerlerini içerir.

- -

Tanım

- -

Object.values() Nesne, nesne üzerinde bulunan özellik değerleri  numaralandırılabilir elemanları olan dizileri döndürür. Özelliklerin sıralaması nesnenin özellik değerleri üzerinde manul olarak döndürülenle aynıdır.

- -

Örnekler

- -
var obj = { foo: 'bar', baz: 42 };
-console.log(Object.values(obj)); // ['bar', 42]
-
-// nesne gibi olan diziler
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.values(obj)); // ['a', 'b', 'c']
-
-// nesneler gibi rast gele anahtar sıralamalı diziler
-// numerik anahtarları kullandığımızda değerler, anahtarlara göre numerik sırayla döndürülür.
-var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
-console.log(Object.values(an_obj)); // ['b', 'c', 'a']
-
-// getFoo bir sayılamayan özelliktir.
-var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
-my_obj.foo = 'bar';
-console.log(Object.values(my_obj)); // ['bar']
-
-// nesne olmayan değişken nesne olmaya zorlanır.
-console.log(Object.values('foo')); // ['f', 'o', 'o']
-
- -

Polyfill

- -

Uyumlu Object.values eklemek için doğal olarak desteklenmeyen daha eski ortamları destekler. Siz şu adreste " tc39/proposal-object-values-entries " veya "es-shims/Object.values "repositorilerde bir polyfill bulabilirsiniz.

- -

Specificatsupport in older environments that do not natively support it, you can find a Polyfill in the ions

- - - - - - - - - - - - - - - - - - - -
TanımKonumYorum
{{SpecName('ESDraft', '#sec-object.values', 'Object.values')}}{{Spec2('ESDraft')}}Ilk tanım.
{{SpecName('ES8', '#sec-object.values', 'Object.values')}}{{Spec2('ES8')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Object.values")}}

-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/promise/all/index.html b/files/tr/web/javascript/reference/global_objects/promise/all/index.html deleted file mode 100644 index cc57749d77..0000000000 --- a/files/tr/web/javascript/reference/global_objects/promise/all/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Promise.all() -slug: Web/JavaScript/Reference/Global_Objects/Promise/all -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all ---- -
{{JSRef}}
- -

The Promise.all() method returns a single {{jsxref("Promise")}} that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

- -
{{EmbedInteractiveExample("pages/js/promise-all.html")}}
- - - -

Söz dizimi

- -
Promise.all(iterable);
- -

Parametreler

- -
-
iterable
-
{{jsxref("Array")}} yada {{jsxref("String")}} gibi iterable nesnesi.
-
- -

Dönen değer

- - - -

Açıklama

- -

This method can be useful for aggregating the results of multiple promises.

- -

Fulfillment

- -

The returned promise is fulfilled with an array containing all the values of the iterable passed as argument (also non-promise values).

- - - -

Rejection

- -

If any of the passed-in promises reject, Promise.all asynchronously rejects with the value of the promise that rejected, whether or not the other promises have resolved.

- -

Örnekler

- -

Promise.all Kullanımı

- -

Promise.all tüm işlemler yerine getirilene kadar bekler (yada ilk reddedilmeye kadar).

- -
var p1 = Promise.resolve(3);
-var p2 = 1337;
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(() => {
-    resolve("foo");
-  }, 100);
-});
-
-Promise.all([p1, p2, p3]).then(values => {
-  console.log(values); // [3, 1337, "foo"]
-});
- -

If the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):

- -
// this will be counted as if the iterable passed is empty, so it gets fulfilled
-var p = Promise.all([1,2,3]);
-// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled
-var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
-// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected
-var p3 = Promise.all([1,2,3, Promise.reject(555)]);
-
-// using setTimeout we can execute code after the stack is empty
-setTimeout(function() {
-    console.log(p);
-    console.log(p2);
-    console.log(p3);
-});
-
-// logs
-// Promise { <state>: "fulfilled", <value>: Array[3] }
-// Promise { <state>: "fulfilled", <value>: Array[4] }
-// Promise { <state>: "rejected", <reason>: 555 }
- -

Asynchronicity or synchronicity of Promise.all

- -

This following example demonstrates the asynchronicity (or synchronicity, if the iterable passed is empty) of Promise.all:

- -
// we are passing as argument an array of promises that are already resolved,
-// to trigger Promise.all as soon as possible
-var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)];
-
-var p = Promise.all(resolvedPromisesArray);
-// immediately logging the value of p
-console.log(p);
-
-// using setTimeout we can execute code after the stack is empty
-setTimeout(function() {
-    console.log('the stack is now empty');
-    console.log(p);
-});
-
-// logs, in order:
-// Promise { <state>: "pending" }
-// the stack is now empty
-// Promise { <state>: "fulfilled", <value>: Array[2] }
-
- -

The same thing happens if Promise.all rejects:

- -
var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
-var p = Promise.all(mixedPromisesArray);
-console.log(p);
-setTimeout(function() {
-    console.log('the stack is now empty');
-    console.log(p);
-});
-
-// logs
-// Promise { <state>: "pending" }
-// the stack is now empty
-// Promise { <state>: "rejected", <reason>: 44 }
-
- -

But, Promise.all resolves synchronously if and only if the iterable passed is empty:

- -
var p = Promise.all([]); // will be immediately resolved
-var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously
-console.log(p);
-console.log(p2)
-setTimeout(function() {
-    console.log('the stack is now empty');
-    console.log(p2);
-});
-
-// logs
-// Promise { <state>: "fulfilled", <value>: Array[0] }
-// Promise { <state>: "pending" }
-// the stack is now empty
-// Promise { <state>: "fulfilled", <value>: Array[2] }
-
- -

Promise.all fail-fast behaviour

- -

Promise.all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

- -
var p1 = new Promise((resolve, reject) => {
-  setTimeout(() => resolve('one'), 1000);
-});
-var p2 = new Promise((resolve, reject) => {
-  setTimeout(() => resolve('two'), 2000);
-});
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(() => resolve('three'), 3000);
-});
-var p4 = new Promise((resolve, reject) => {
-  setTimeout(() => resolve('four'), 4000);
-});
-var p5 = new Promise((resolve, reject) => {
-  reject(new Error('reject'));
-});
-
-
-// Using .catch:
-Promise.all([p1, p2, p3, p4, p5])
-.then(values => {
-  console.log(values);
-})
-.catch(error => {
-  console.log(error.message)
-});
-
-//From console:
-//"reject"
-
-
- -

It is possible to change this behaviour by handling possible rejections:

- -
var p1 = new Promise((resolve, reject) => {
-  setTimeout(() => resolve('p1_delayed_resolvement'), 1000);
-});
-
-var p2 = new Promise((resolve, reject) => {
-  reject(new Error('p2_immediate_rejection'));
-});
-
-Promise.all([
-  p1.catch(error => { return error }),
-  p2.catch(error => { return error }),
-]).then(values => {
-  console.log(values[0]) // "p1_delayed_resolvement"
-  console.log(values[1]) // "Error: p2_immediate_rejection"
-})
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Promise.all")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/promise/catch/index.html b/files/tr/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index 3360f87fbb..0000000000 --- a/files/tr/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -tags: - - JavaScript - - Promise - - Prototype - - fonksiyon - - metod -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)). This means, that you have to provide onRejected function even if you want to fallback to undefined result value - for example obj.catch(() => {}).

- -
{{EmbedInteractiveExample("pages/js/promise-catch.html")}}
- - - - - - - -

Sözdizimi

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Parametreler

- -
-
onRejected
-
A {{jsxref("Function")}} called when the Promise is rejected. This function has one argument: -
-
reason
-
The rejection reason.
-
- The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.
-
- -

Dönen değer

- -

Internally calls Promise.prototype.then on the object upon which is called, passing the parameters undefined and the onRejected handler received; then returns the value of that call (which is a {{jsxref("Promise")}}).

- -
-

Note the examples below are throwing instances of Error. This is considered good practice in contrast to throwing Strings: Otherwise the part doing the catching would have to make checks to see if the argument was a string or an error, and you might lose valuable information like stack traces.

-
- -

Demonstration of the internal call:

- -
// overriding original Promise.prototype.then/catch just to add some logs
-(function(Promise){
-    var originalThen = Promise.prototype.then;
-    var originalCatch = Promise.prototype.catch;
-
-    Promise.prototype.then = function(){
-        console.log('> > > > > > called .then on %o with arguments: %o', this, arguments);
-        return originalThen.apply(this, arguments);
-    };
-    Promise.prototype.catch = function(){
-        console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments);
-        return originalCatch.apply(this, arguments);
-    };
-
-})(this.Promise);
-
-
-
-// calling catch on an already resolved promise
-Promise.resolve().catch(function XXX(){});
-
-// logs:
-// > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()]
-// > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()]
-
- -

Açıklama

- -

The catch method can be useful for error handling in your promise composition.

- -

Örnekler

- -

Using and chaining the catch method

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw new Error('oh, no!');
-}).catch(function(e) {
-  console.log(e.message); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
-// The following behaves the same as above
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  return Promise.reject('oh, no!');
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
- -

Gotchas when throwing errors

- -
// Throwing an error will call the catch method most of the time
-var p1 = new Promise(function(resolve, reject) {
-  throw new Error('Uh-oh!');
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-// Errors thrown inside asynchronous functions will act like uncaught errors
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw new Error('Uncaught Exception!');
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
-
-// Errors thrown after resolve is called will be silenced
-var p3 = new Promise(function(resolve, reject) {
-  resolve();
-  throw new Error('Silenced Exception!');
-});
-
-p3.catch(function(e) {
-   console.log(e); // This is never called
-});
- -

If it is resolved

- -
//Create a promise which would not call onReject
-var p1 = Promise.resolve("calling next");
-
-var p2 = p1.catch(function (reason) {
-    //This is never called
-    console.log("catch p1!");
-    console.log(reason);
-});
-
-p2.then(function (value) {
-    console.log("next promise's onFulfilled"); /* next promise's onFulfilled */
-    console.log(value); /* calling next */
-}, function (reason) {
-    console.log("next promise's onRejected");
-    console.log(reason);
-});
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.builtins.Promise.catch")}}

- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/promise/index.html b/files/tr/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 90f9dcabc0..0000000000 --- a/files/tr/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -tags: - - JavaScript - - Promise - - Referans -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -
Promise nesnesi eşzamansız olan ve ertelenen işlemlerde kullanılır. Bir Promise nesnesi henüz işlemin tamamlamadığını ama sonradan tamamlanabileceğini gösterir.
- -
- -

Sözdizimi

- -
new Promise(function(resolve, reject) { ... });
- -

Parametreler

- -
-
executor
-
resolve ve reject içeren iki parametreli bir fonksiyon nesnesidir. İlk parametre promise nesnesi tamamlandığında, ikinci parametre ise reddettiğinde çağrılır. Bu fonksiyonları işlemimiz bittiğinde (başarılı yada başarısız) çağırırız.
-
- -

Açıklama

- -

Oluşturulan bir promise başka bir promise için proxy görevi görür.
- Başarılı yada başarısız bir şekilde sonuç üreten asenkron işlemlerin ilişkilendirilmesine olanak tanır.Bu asenkron methodların senkron methodlar gibi sonuç döndürmesi'ni sağlar.Asenkron method hemen sonuçlanmaz.Bunun yerine işlemin tamamlandığı noktayı temsil eden bir promise döndürür.

- -

Bir Promise şu durumları içerir:

- - - -

Bekleyen bir Promise, bir sonuç döndürerek tamamlanabilir veya bir nedenle reddedilebilir(hata).Bunlardan herhanbiri gerçekleştiğinde (resolve/reject) sıraya konulmuş ilişkili methodlar sıra ile çağrılır.(Promise tamamlandığında yada red edildiğinde sırada bağlanmış bir method var ise o method çalıştırılır.Böylece asenkron işlemler arasında bir rekabet/mücadele olmaz.Sırası gelen çalışır.)

- -

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, bunlar zincirlenebilirler—an operation called composition.

- -

- -
-

Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending. You will also hear the term resolved used with promises — this means that the promise is settled, or it is locked into a promise chain. Domenic Denicola's States and fates contains more details about promise terminology.

-
- -

Özellikler

- -
-
Promise.length
-
Değeri 1 olan Length özelliği (constructor argümanları sayısı).
-
{{jsxref("Promise.prototype")}}
-
Represents the prototype for the Promise constructor.
-
- -

Metodlar

- -
-
{{jsxref("Promise.all", "Promise.all(iterable)")}}
-
Returns a promise that either resolves when all of the promises in the iterable argument have resolved or rejects as soon as one of the promises in the iterable argument rejects. If the returned promise resolves, it is resolved with an array of the values from the resolved promises in the iterable. If the returned promise rejects, it is rejected with the reason from the promise in the iterable that rejected. This method can be useful for aggregating results of multiple promises together.
-
{{jsxref("Promise.race", "Promise.race(iterable)")}}
-
Returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.
-
- -
-
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
-
Belirtilen bir nedenden dolayı reddedilen Promise nesnesini döndürür.
-
- -
-
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
-
Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. Generally, if you want to know if a value is a promise or not - {{jsxref("Promise.resolve", "Promise.resolve(value)")}} it instead and work with the return value as a promise.
-
- -

Promise prototype

- -

Özellikler

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

- -

Metodlar

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

- -

Örnekler

- -

Promise Oluşturma

- - - -

Bu küçük örnek Promise mekanizmasını gösterir. {{HTMLElement("button")}} her tıklandığında testPromise() metodu çağrılır . It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the string "result" every 1-3 seconds, at random. The Promise() constructor is used to create the promise.

- -

The fulfillment of the promise is simply logged, via a fulfill callback set using {{jsxref("Promise.prototype.then()","p1.then()")}}. A few logs shows how the synchronous part of the method is decoupled of the asynchronous completion of the promise.

- -
'use strict';
-var promiseCount = 0;
-
-function testPromise() {
-    var thisPromiseCount = ++promiseCount;
-
-    var log = document.getElementById('log');
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Started (<small>Sync code started</small>)<br/>');
-
-    // We make a new promise: we promise the string 'result' (after waiting 3s)
-    var p1 = new Promise(
-        // The resolver function is called with the ability to resolve or
-        // reject the promise
-        function(resolve, reject) {
-            log.insertAdjacentHTML('beforeend', thisPromiseCount +
-                ') Promise started (<small>Async code started</small>)<br/>');
-            // This is only an example to create asynchronism
-            window.setTimeout(
-                function() {
-                    // We fulfill the promise !
-                    resolve(thisPromiseCount);
-                }, Math.random() * 2000 + 1000);
-        });
-
-    // We define what to do when the promise is resolved/fulfilled with the then() call,
-    // and the catch() method defines what to do if the promise is rejected.
-    p1.then(
-        // Log the fulfillment value
-        function(val) {
-            log.insertAdjacentHTML('beforeend', val +
-                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
-        })
-    .catch(
-        // Log the rejection reason
-        function(reason) {
-            console.log('Handle rejected promise ('+reason+') here.');
-        });
-
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Promise made (<small>Sync code terminated</small>)<br/>');
-}
- - - -

Bu örnek buton'a tıkladığınızda çalışır. Promise destekleyen bir tarayıcıya ihtiyacınız var. Buton'a birden fazla tıklamanız durumunda farklı promise nesnelerinin kısa sürede tamamlandığını göreceksiniz.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

new XMLHttpRequest() Kullanım Örneği

- -

Promise Oluşturma

- -

Bu örnekte {{domxref("XMLHttpRequest")}} nesnesinin başarılı yada başarısız durumunu Promise kullanarak nasıl raporlanabildiğini göstermektedir.

- -
'use strict';
-
-// A-> $http function is implemented in order to follow the standard Adapter pattern
-function $http(url){
-
-  // A small example of object
-  var core = {
-
-    // Method that performs the ajax request
-    ajax : function (method, url, args) {
-
-      // Creating a promise
-      var promise = new Promise( function (resolve, reject) {
-
-        // Instantiates the XMLHttpRequest
-        var client = new XMLHttpRequest();
-        var uri = url;
-
-        if (args && (method === 'POST' || method === 'PUT')) {
-          uri += '?';
-          var argcount = 0;
-          for (var key in args) {
-            if (args.hasOwnProperty(key)) {
-              if (argcount++) {
-                uri += '&';
-              }
-              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
-            }
-          }
-        }
-
-        client.open(method, uri);
-        client.send();
-
-        client.onload = function () {
-          if (this.status >= 200 && this.status < 300) {
-            // Performs the function "resolve" when this.status is equal to 2xx
-            resolve(this.response);
-          } else {
-            // Performs the function "reject" when this.status is different than 2xx
-            reject(this.statusText);
-          }
-        };
-        client.onerror = function () {
-          reject(this.statusText);
-        };
-      });
-
-      // Return the promise
-      return promise;
-    }
-  };
-
-  // Adapter pattern
-  return {
-    'get' : function(args) {
-      return core.ajax('GET', url, args);
-    },
-    'post' : function(args) {
-      return core.ajax('POST', url, args);
-    },
-    'put' : function(args) {
-      return core.ajax('PUT', url, args);
-    },
-    'delete' : function(args) {
-      return core.ajax('DELETE', url, args);
-    }
-  };
-};
-// End A
-
-// B-> Here you define its functions and its payload
-var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
-var payload = {
-  'topic' : 'js',
-  'q'     : 'Promise'
-};
-
-var callback = {
-  success : function(data){
-     console.log(1, 'success', JSON.parse(data));
-  },
-  error : function(data){
-     console.log(2, 'error', JSON.parse(data));
-  }
-};
-// End B
-
-// Executes the method call
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .catch(callback.error);
-
-// Executes the method call but an alternative way (1) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success, callback.error);
-
-// Executes the method call but an alternative way (2) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .then(undefined, callback.error);
-
- -

XHR ile görsel yükleme

- -

Another simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationDurumYorum
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}}
- -

Tarayıcı uyumluluğu

- - - -
- - -

{{Compat("javascript.builtins.Promise")}}

-
- - - -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/global_objects/regexp/index.html b/files/tr/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index f60e06d0df..0000000000 --- a/files/tr/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,606 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}
- -

The RegExp constructor creates a regular expression object for matching text with a pattern.

- -

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

- -

Syntax

- -

Literal, constructor, and factory notations are possible:

- -
/pattern/flags
-new RegExp(pattern[, flags])
-RegExp(pattern[, flags])
-
- -

Parameters

- -
-
pattern
-
Duzenli ifadenin metni.
-
flags
-
-

If specified, flags can have any combination of the following values:

- -
-
g
-
global match; find all matches rather than stopping after the first match
-
i
-
ignore case
-
m
-
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
-
u
-
unicode; treat pattern as a sequence of unicode code points
-
y
-
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
-
-
-
- -

Description

- -

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

- -
/ab+c/i;
-new RegExp('ab+c', 'i');
-new RegExp(/ab+c/, 'i');
-
- -

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

- -

The constructor of the regular expression object, for example, new RegExp('ab+c'), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

- -

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

- -

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

- -
var re = /\w+/;
-var re = new RegExp('\\w+');
-
- -

Düzenli İfadelerde (Regular Expressions) Özel Karakterlerin Anlamları

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter Sınıfları
KarakterAnlamı
. -

(The dot, the decimal point) matches any single character except line terminators: \n, \r, \u2028 or \u2029.

- -

Inside a character set, the dot loses its special meaning and matches a literal dot.

- -

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

- -

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

-
\d -

Matches any digit (Arabic numeral). Equivalent to [0-9].

- -

For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".

-
\D -

Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9].

- -

For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

-
\w -

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

- -

For example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3D".

-
\W -

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

- -

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".

-
\s -

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\s\w*/ matches " bar" in "foo bar".

-
\S -

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\S\w*/ matches "foo" in "foo bar".

-
\tMatches a horizontal tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX -

Where X is a letter from A - Z. Matches a control character in a string.

- -

For example, /\cM/ matches control-M in a string.

-
\xhhMatches the character with the code hh (two hexadecimal digits).
\uhhhhMatches a UTF-16 code-unit with the value hhhh (four hexadecimal digits).
\u{hhhh} or \u{hhhhh}(only when u flag is set) Matches the character with the Unicode value U+hhhh or U+hhhhh (hexadecimal digits).
\ -

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

- -

For example, /b/ matches the character "b". By placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.

- -

or

- -

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

- -

For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches "a*".

-
Karakter Kümeleri
KarakterAnlamı
[xyz]
- [a-c]
-

A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. It is also possible to include a character class in a character set.

- -

For example, [abcd] is the same as [a-d]. They match the "b" in "brisket" and the "c" in "chop".

- -

For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".

- -

For example, [\w-] is the same as [A-Za-z0-9_-]. They match the "b" in "brisket", the "c" in "chop" and the "n" in "non-profit".

-
-

[^xyz]
- [^a-c]

-
-

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.

- -

For example, [^abc] is the same as [^a-c]. They initially match "o" in "bacon" and "h" in "chop".

-
Değişim
KarakterAnlamı
x|y -

Matches either x or y.

- -

For example, /green|red/ matches "green" in "green apple" and "red" in "red apple".

-
Kısıtlar
KarakterAnlamı
^ -

Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

- -

For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".

-
$ -

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

- -

For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

-
\b -

Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.

- -

Examples:
- /\bm/ matches the 'm' in "moon" ;
- /oo\b/ does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;
- /oon\b/ matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;
- /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

-
\B -

Matches a non-word boundary. This is a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. Such as between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word bondary is also not included in the match.

- -

For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".

-
Gruplama ve Referansa Geri Dönme
KarakterAnlamı
(x) -

Matches x and remembers the match. These are called capturing groups.

- -

For example, /(foo)/ matches and remembers "foo" in "foo bar". 

- -

The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

- -

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

-
\n -

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

- -

For example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". A more complete example follows this table.

-
(?:x)Matches x but does not remember the match. These are called non-capturing groups. The matched substring can not be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Niceleyiciler
KarakterAnlamı
x* -

Matches the preceding item x 0 or more times.

- -

For example, /bo*/ matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".

-
x+ -

Matches the preceding item x 1 or more times. Equivalent to {1,}.

- -

For example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".

-
x? -

Matches the preceding item x 0 or 1 time.

- -

For example, /e?le?/ matches the "el" in "angel" and the "le" in "angle."

- -

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).

-
x{n} -

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

- -

For example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".

-
x{n,} -

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

- -

For example, /a{2,}/ doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".

-
x{n,m} -

Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding item x.

- -

For example, /a{1,3}/ matches nothing in "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more "a"'s in it.

-
-

x*?
- x+?
- x??
- x{n}?
- x{n,}?
- x{n,m}?

-
-

Matches the preceding item x like *, +, ?, and {...} from above, however the match is the smallest possible match.

- -

For example, /<.*?>/ matches "<foo>" in "<foo> <bar>", whereas /<.*>/ matches "<foo> <bar>".

- -

Quantifiers without ? are said to be greedy. Those with ? are called "non-greedy".

-
Onaylamalar
KarakterAnlamı
x(?=y) -

Matches x only if x is followed by y.

- -

For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
- /Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.

-
x(?!y) -

Matches x only if x is not followed by y.

- -

For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.
- /\d+(?!\.)/.exec('3.141') matches "141" but not "3.141".

-
- -

Properties

- -
-
{{jsxref("RegExp.prototype")}}
-
Allows the addition of properties to all objects.
-
RegExp.length
-
The value of RegExp.length is 2.
-
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("RegExp.lastIndex")}}
-
The index at which to start the next match.
-
- -

Methods

- -

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

- -

RegExp prototype objects and instances

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Properties')}}
- -

Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/prototype', 'Methods')}}
- -

Examples

- -

Using a regular expression to change data format

- -

The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

- -
var re = /(\w+)\s(\w+)/;
-var str = 'John Smith';
-var newstr = str.replace(re, '$2, $1');
-console.log(newstr);
-
- -

This displays "Smith, John".

- -

Using regular expression to split lines with different line endings/ends of line/line breaks

- -

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

- -
var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
-var lines = text.split(/\r\n|\r|\n/);
-console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
-
- -

Note that the order of the patterns in the regular expression matters.

- -

Using regular expression on multiple lines

- -
var s = 'Please yes\nmake my day!';
-s.match(/yes.*day/);
-// Returns null
-s.match(/yes[^]*day/);
-// Returns ["yes\nmake my day"]
-
- -

Using a regular expression with the sticky flag

- -

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.

- -
var str = '#foo#';
-var regex = /foo/y;
-
-regex.lastIndex = 1;
-regex.test(str); // true
-regex.lastIndex = 5;
-regex.test(str); // false (lastIndex is taken into account with sticky flag)
-regex.lastIndex; // 0 (reset after match failure)
- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, "a" to "z", "A" to "Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

- -
var text = 'Образец text на русском языке';
-var regex = /[\u0400-\u04FF]+/g;
-
-var match = regex.exec(text);
-console.log(match[0]);        // logs 'Образец'
-console.log(regex.lastIndex); // logs '7'
-
-var match2 = regex.exec(text);
-console.log(match2[0]);       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex); // logs '15'
-
-// and so on
-
- -

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-unicode-block.

- -

Extracting sub-domain name from URL

- -
var url = 'http://xxx.domain.com';
-console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}}The RegExp constructor no longer throws when the first argument is a RegExp and the second argument is present. Introduces Unicode and sticky flags.
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.RegExp")}}

-
- -

Firefox-specific notes

- -

Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now undefined instead of an empty string:

- -
// Firefox 33 or older
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:'
-
-// Firefox 34 or newer
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:undefined'
-
- -

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined ({{bug(1053944)}}).

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/string/index.html b/files/tr/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index bbf4377f32..0000000000 --- a/files/tr/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript 2015 - - JavaScript - - NeedsTranslation - - Reference - - String - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
- -

Genel bir nesne olan String, dizgi veya karakter dizilerinin yapıcısıdır.

- -

 

- -

Sözdizimi

- -

String literals take the forms:

- -
'string text'
-"string text"
-"中文 español deutsch Türkçe हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
- -

Strings can also be created using the String global object directly:

- -
String(thing)
- -

Parameters

- -
-
thing
-
Anything to be converted to a string.
-
- -

Template literals

- -

Starting with ECMAScript 2015, string literals can also be so-called Template literals:

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -
-
- -

Escape notation

- -

Beside regular, printable characters, special characters can be encoded using escape notation:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
- -
-

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

-
- -
-
- -

Long literal strings

- -

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

- -

You can use the + operator to append multiple strings together, like this:

- -
let longString = "This is a very long string which needs " +
-                 "to wrap across multiple lines because " +
-                 "otherwise my code is unreadable.";
-
- -

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

- -
let longString = "This is a very long string which needs \
-to wrap across multiple lines because \
-otherwise my code is unreadable.";
-
- -

Both of these result in identical strings being created.

- -

Description

- -

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

- -

Character access

- -

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

- -
return 'cat'.charAt(1); // returns "a"
-
- -

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

- -
return 'cat'[1]; // returns "a"
-
- -

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

- -

Comparing strings

- -

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // true
-  console.log(a + ' is less than ' + b);
-} else if (a > b) {
-  console.log(a + ' is greater than ' + b);
-} else {
-  console.log(a + ' and ' + b + ' are equal.');
-}
-
- -

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

- -

Distinction between string primitives and String objects

- -

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

- -

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // Logs "string"
-console.log(typeof s_obj);  // Logs "object"
-
- -

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

- -
var s1 = '2 + 2';             // creates a string primitive
-var s2 = new String('2 + 2'); // creates a String object
-console.log(eval(s1));        // returns the number 4
-console.log(eval(s2));        // returns the string "2 + 2"
-
- -

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

- -

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

- -
console.log(eval(s2.valueOf())); // returns the number 4
-
- -
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
- -

Properties

- -
-
{{jsxref("String.prototype")}}
-
Allows the addition of properties to a String object.
-
- -

Methods

- -
-
{{jsxref("String.fromCharCode()")}}
-
Returns a string created by using the specified sequence of Unicode values.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Returns a string created by using the specified sequence of code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Returns a string created from a raw template string.
-
- -

String generic methods

- -
-

String generics are non-standard, deprecated and will get removed near future.

-
- -

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

- -

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

- -

String instances

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
- -

Methods

- -

Methods unrelated to HTML

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
- -

HTML wrapper methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
- -

Examples

- -

String conversion

- -

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.String")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/string/substring/index.html b/files/tr/web/javascript/reference/global_objects/string/substring/index.html deleted file mode 100644 index d3a177406c..0000000000 --- a/files/tr/web/javascript/reference/global_objects/string/substring/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: String.prototype.substring() -slug: Web/JavaScript/Reference/Global_Objects/String/substring -translation_of: Web/JavaScript/Reference/Global_Objects/String/substring ---- -
{{JSRef}}
- -

The substring() method returns a subset of a string between one index and another, or through the end of the string.

- -

Syntax

- -
str.substring(indexStart[, indexEnd])
- -

Parametreler

- -
-
indexStart
-
An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.
-
indexEnd
-
Optional. An integer between 0 and the length of the string, which specifies the offset into the string of the first character not to include in the returned substring.
-
- -

Dönen değer

- -

A new string containing the extracted section of the given string.

- -

Açıklama

- -

substring() extracts characters from indexStart up to but not including indexEnd. In particular:

- - - -

If indexStart is greater than indexEnd, then the effect of substring() is as if the two arguments were swapped; for example, str.substring(1, 0) == str.substring(0, 1).

- -

Örnekler

- -

Using substring()

- -

The following example uses substring() to display characters from the string 'Mozilla':

- -
var anyString = 'Mozilla';
-
-// Displays 'Moz'
-console.log(anyString.substring(0, 3));
-console.log(anyString.substring(3, 0));
-
-// Displays 'lla'
-console.log(anyString.substring(4, 7));
-console.log(anyString.substring(4));
-console.log(anyString.substring(7, 4));
-
-// Displays 'Mozill'
-console.log(anyString.substring(0, 6));
-
-// Displays 'Mozilla'
-console.log(anyString.substring(0, 7));
-console.log(anyString.substring(0, 10));
-
- -

Using substring() with length property

- -

The following example uses the substring() method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

- -
// Displays 'illa' the last 4 characters
-var anyString = 'Mozilla';
-var anyString4 = anyString.substring(anyString.length - 4);
-console.log(anyString4);
-
-// Displays 'zilla' the last 5 characters
-var anyString = 'Mozilla';
-var anyString5 = anyString.substring(anyString.length - 5);
-console.log(anyString5);
-
- -

Replacing a substring within a string

- -

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string 'Brave New World' into 'Brave New Web'.

- -
// Replaces oldS with newS in the string fullS
-function replaceString(oldS, newS, fullS) {
-  for (var i = 0; i < fullS.length; ++i) {
-    if (fullS.substring(i, i + oldS.length) == oldS) {
-      fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
-    }
-  }
-  return fullS;
-}
-
-replaceString('World', 'Web', 'Brave New World');
-
- -

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

- -
function replaceString(oldS, newS, fullS) {
-  return fullS.split(oldS).join(newS);
-}
-
- -

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.builtins.String.substring")}}

- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/index.html b/files/tr/web/javascript/reference/index.html deleted file mode 100644 index b54be98c56..0000000000 --- a/files/tr/web/javascript/reference/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: JavaScript Referansı -slug: Web/JavaScript/Reference -tags: - - JavaScript -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

- -

Global Objects

- -

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
- -

Statements

- -

This chapter documents all the JavaScript statements and declarations.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Expressions and operators

- -

This chapter documents all the JavaScript expressions and operators.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Functions

- -

This chapter documents how to work with JavaScript functions to develop your applications.

- - - -

Additional reference pages

- - diff --git a/files/tr/web/javascript/reference/lexical_grammar/index.html b/files/tr/web/javascript/reference/lexical_grammar/index.html deleted file mode 100644 index 8ee4c8ea5c..0000000000 --- a/files/tr/web/javascript/reference/lexical_grammar/index.html +++ /dev/null @@ -1,374 +0,0 @@ ---- -title: Lexical grammar -slug: Web/JavaScript/Reference/Lexical_grammar -translation_of: Web/JavaScript/Reference/Lexical_grammar ---- -

{{JsSidebar ("Daha çox")}}

- -

Bu səhifə JavaScript-in leksik qrammatikasını təsvir edir. ECMAScript skriptlərinin mənbə mətni soldan sağa taranır və ayələr, nəzarət simvolları, xətt terminatorları, şərhlər və ya ağ boşluq olan giriş elementlərinin ardıcıllığına çevrilir. ECMAScript, həmçinin müəyyən açar sözlər və hərfləri müəyyənləşdirir və ifadələri sona çatdırmaq üçün nöqtəli vergüllərə avtomatik qoşulma qaydalarına malikdir.

- -

Nəzarət simvolları
- İdarəetmə simvollarının vizual nümayəndəliyi yoxdur, ancaq mətnin şərhini idarə etmək üçün istifadə olunur.

- -

Unicode formatına nəzarət simvolları
- Kod nöqtəsi Adı Qısaldılması Təsviri
- U + 200C Sıfır eni qoşulmayan <ZWNJ> Müəyyən dillərdə ligaturlara qoşulmamaq üçün simvolların arasına yerləşdirilib (Wikipedia).
- U + 200D Sıfır eniştiricisi <ZWJ> İşarələrin müəyyən dillərdə (Wikipedia) əlaqəli formasından istifadə olunmasına səbəb olmaq üçün ümumiyyətlə bağlanmayacaq simvollar arasında yerləşdirilmişdir.
- U + FEFF Bayt sifariş nişanı <BOM> Skriptin əvvəlində onu Unicode və mətnin bayt sifarişi (Wikipedia) kimi qeyd etmək üçün istifadə olunur.
- Ağ boşluq
- Ağ boşluq simvolları mənbə mətninin oxunuşunu yaxşılaşdırır və ayələrini bir-birindən ayırır. Bu işarələr ümumiyyətlə kodun işləməsi üçün lazımsızdır. Transfer edilməsi lazım olan məlumatların miqdarını azaltmaq üçün tez-tez boşluq silmək üçün minifikasiya vasitələri istifadə olunur.

- -

Ağ boşluq simvolları
- Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı
- U + 0009 Xarakter cədvəli <HT> Üfüqi cədvəl \ t
- U + 000B Xətt cədvəli <VT> Şaquli cədvəl \ v
- U + 000C Forma yemi <FF> Səhifəni pozan idarəetmə xarakteri (Wikipedia). \ f
- U + 0020 Məkan <SP> Normal yer
- U + 00A0 Arası olmayan yer <NBSP> Normal yer, lakin xəttin qırıla biləcəyi nöqtə yoxdur
- Digərləri Digər Unicode kosmik simvolları <USP> Wikipedia'dakı Unicode'dakı boşluqlar
- Xətt terminatorları
- Ağ boşluq simvollarına əlavə olaraq, mənbə mətninin oxunuşunu yaxşılaşdırmaq üçün xətt terminatoru simvolları istifadə olunur. Bununla birlikdə, bəzi hallarda, xətt terminatorları JavaScript kodunun icrasına təsir göstərə bilər, çünki qadağan edilmiş bir neçə yer var. Xətt terminatorları avtomatik nöqtəli vergül daxil edilməsi prosesinə də təsir göstərir. Sətir terminatorları müntəzəm ifadələrdə siniflər tərəfindən uyğunlaşdırılır.

- -

Yalnız aşağıdakı Unicode kod nöqtələrinə ECMAScript-də xətt terminatoru kimi baxılır, digər xətt kəsici simvollara ağ boşluq kimi baxılır (məsələn, Next Line, NEL, U + 0085 ağ boşluq sayılır).

- -

Xətt terminatoru simvolları
- Kod nöqtəsi Adı Qısaldılması Təsvir Escape ardıcıllığı
- U + 000A Line Feed <LF> UNIX sistemlərində yeni xətt xarakteri. \ n
- U + 000D Daşımanın qaytarılması <CR> Commodore və erkən Mac sistemlərində yeni xətt xarakteri. \ r
- U + 2028 Xət ayırıcı <LS> Vikipediya
- U + 2029 Paraqraf ayırıcı <PS> Wikipedia
- Şərhlər
- Şərhlər JavaScript koduna işarə, qeyd, təklif və ya xəbərdarlıq əlavə etmək üçün istifadə olunur. Bu oxumağı və başa düşməyi asanlaşdıra bilər. Kodun icra edilməməsi üçün deaktiv edilmək üçün istifadə edilə bilər; bu dəyərli ayıklama vasitəsi ola bilər.

- -

JavaScript'də şərhə əlavə etmək üçün uzun müddətdir davam edən iki yol var.

- -

Birinci yol // şərh; bu eyni sətirdə onu izləyən bütün mətnləri bir şərh halına gətirir. Misal üçün:

- -

funksiya comment () {
-   // Bu bir xəttli JavaScript şərhidir
-   console.log ('Salam dünya!');
- }
- Şərh();
- İkinci yol daha çevik olan / * * / üslubdur.

- -

Məsələn, bir xəttdə istifadə edə bilərsiniz:

- -

funksiya comment () {
-   / * Bu bir xəttli JavaScript şərhidir * /
-   console.log ('Salam dünya!');
- }
- Şərh();
- Bununla yanaşı, çox sətirli şərhlər edə bilərsiniz:

- -

funksiya comment () {
-   / * Bu şərh çox sətri əhatə edir. Xəbərdarlıq
-      başa çatana qədər şərhə son qoymaq lazım deyil. * /
-   console.log ('Salam dünya!');
- }
- Şərh();
- İstəsəniz, bir xəttin ortasında da istifadə edə bilərsiniz, baxmayaraq ki bu kodunuzu oxumağı çətinləşdirə bilər, buna görə ehtiyatla istifadə olunmalıdır:

- -

funksiya şərhi (x) {
-   console.log ('Salam' + x / * x * / + '!' dəyərini daxil edin);
- }
- şərh ('dünya');
- Bundan əlavə, kodu bir şərhə bağlayaraq işə salmamaq üçün kodu deaktiv etmək üçün istifadə edə bilərsiniz:

- -

funksiya comment () {
-   / * console.log ('Salam dünya!'); * /
- }
- Şərh();
- Bu vəziyyətdə, konsol.log () çağırışı heç bir şərh daxilində olmadığı üçün verilmir. İstənilən sayda kod xətti bu şəkildə əlil ola bilər.

- -

Hashbang şərhləri
- Xüsusi üçüncü bir şərh sintaksisi, hashbang comment, ECMAScript-də standartlaşdırılma mərhələsindədir (Hashbang Qrammatikası təklifinə baxın).

- -

Bir hashbang şərhini yalnız bir xətt (yalnız) şərh kimi edir. Bunun əvəzinə # ilə başlayır! və yalnız bir yazı və ya modulun mütləq başlanğıcında etibarlıdır. Nəzərə alın ki, hər hansı bir boşluq # # -dan əvvəl icazə verilmir. Şərh # sonrakı bütün simvollardan ibarətdir! birinci sətrin sonuna qədər; yalnız bir belə şərhə icazə verilir.

- -

Hashbang şərh, skriptin icrası üçün istifadə etmək istədiyiniz xüsusi JavaScript tərcüməçisinə gedən yolu göstərir. Nümunə aşağıdakı kimidir:

- -

#! / usr / bin / env node

- -

console.log ("Salam dünya");
- Qeyd: JavaScript-dəki Hashbang şərhləri Unix-də təqlid olunan shebangs-ləri faylları düzgün tərcüməçi ilə işlədirdi.

- -

Hashbang şərhindən əvvəl BOM bir brauzerdə işləsə də, BOM-u hasbang yazılmış bir skriptdə istifadə etmək tövsiyə edilmir. Unix / Linux-da skript işə saldığınız zaman BOM işləməyəcək. Skriptləri birbaşa işlətmək istəyirsinizsə UTF-8-ni BOM olmadan istifadə edin

- -

qabıqdan.

- -

Yalnız # istifadə etməlisiniz! JavaScript tərcüməçisini təyin etmək üçün şərh tərzi. Digər bütün hallarda sadəcə bir // şərh (və ya mulitiline comment) istifadə edin.

- -

Açar sözlər
- ECMAScript 2015 kimi qorunan açar sözlər
- {{jsxref ("Bəyanatlar / break", "break")}}
- {{jsxref ("Bəyanatlar / keçid", "dava")}}
- {{jsxref ("Bəyanatlar / çalışın ... tutun", "tutun")}}
- {{jsxref ("Bəyanatlar / sinif", "sinif")}}
- {{jsxref ("Bəyanatlar / const", "const")}}
- {{jsxref ("Bəyanatlar / davam et", "davam et")}}
- {{jsxref ("Bəyanatlar / debugger", "debugger")}}
- {{jsxref ("Bəyanatlar / default", "default")}}
- {{jsxref ("Operatorlar / silmək", "Sil")}}
- {{jsxref ("Bəyanatlar / etmək ... edərkən", "etmək")}}
- {{jsxref ("Bəyanatlar / əgər ... başqa", "başqa")}}
- {{jsxref ("Bəyanatlar / ixrac", "ixrac")}}
- {{jsxref ("Bəyanatlar / sinif", "uzanır")}}
- {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "nəhayət")}}
- {{jsxref ("Bəyanatlar / üçün", "üçün")}}
- {{jsxref ("Bildirişlər / funksiya", "funksiya")}}
- {{jsxref ("Bəyanatlar / əgər ... başqa", "əgər")}}
- {{jsxref ("Bəyanatlar / idxal", "idxal")}}
- {{jsxref ("Operatorlar / ilə", "in")}}
- {{jsxref ("Əməliyyatçılar / instanceof", "instanceof")}}
- {{jsxref ("Operatorlar / yeni", "yeni")}}
- {{jsxref ("Bəyanatlar / qayıt", "qayıt")}}
- {{jsxref ("Əməliyyatçılar / super", "super")}}
- {{jsxref ("Bəyanatlar / keçid", "keçid")}}
- {{jsxref ("Əməliyyatçılar / bu", "bu")}}
- {{jsxref ("Bəyanatlar / atmaq", "atmaq")}}
- {{jsxref ("Bəyanatlar / cəhd edin ... tutun", "cəhd edin")}}
- {{jsxref ("Operatorlar / typeof", "typeof")}}
- {{jsxref ("Bəyanatlar / var", "var")}}
- {{jsxref ("Operatorlar / etibarsız", "etibarsız")}}
- {{jsxref ("Bəyanatlar / edərkən", "isə")}}
- {{jsxref ("Bəyanatlar / ilə", "ilə")}}
- {{jsxref ("Əməliyyatçılar / məhsuldarlıq", "gəlir")}}
- Gələcək qorunan açar sözlər
- Aşağıdakılar ECMAScript spesifikasiyası ilə gələcək açar sözlər kimi qorunur. Hal-hazırda onların heç bir xüsusi funksionallığı yoxdur, lakin gələcəkdə də ola bilər, buna görə identifikator kimi istifadə edilə bilməzlər.

- -

Bunlar həmişə qorunur:

- -

enum
- Aşağıdakılar yalnız ciddi rejim kodlarında tapıldıqda qorunur:

- -

tətbiq edir
- interfeysi
- {{jsxref ("Bəyanatlar / qoy", "qoy")}}
- paket
- özəl
- qorunur
- ictimai
- statik
- Aşağıdakılar yalnız modul kodu tapdıqda qorunur:

- -

gözləmək
- Gələcəkdə köhnə standartlarda qorunan açar sözlər
- Aşağıdakılar köhnə ECMAScript xüsusiyyətlərinə görə gələcək açar sözlər olaraq qorunur (ECMAScript 1-dən 3-ə qədər).

- -

mücərrəd
- boolean
- bayt
- char
- ikiqat
- final
- sal
- getmək
- int
- uzun
- doğma
- qısa
- sinxronizasiya olunur
- atır
- keçici
- uçucu
- Bundan əlavə, null, əsl və yalnış hərflər ECMAScript-də identifikator kimi istifadə edilə bilməz.

- -

Ehtiyat söz istifadəsi
- Qorunan sözlər əslində yalnız identifikatorlara aiddir (identifikator adları). Es5.github.com/#A.1-də təsvir olunduğu kimi, bunlar hamısı ReserveWords-ı istisna etməyən identifikator adlarıdır.

- -

a.import
- a ['idxal']
- a = {idxal: 'test'}.
- Digər tərəfdən aşağıdakılar qanunsuzdur, çünki qorunan sözlər olmadan bir identifikator adıdır. Eyniləşdiricilər FunctionDeclaration, FunctionExpression, Dəyişən Deklarasiya və s. Üçün istifadə olunur. Identifikator adları MemberExpression, CallExpression və s. Üçün istifadə olunur.

- -

funksiya import () {} // qeyri-qanuni.
- Xüsusi mənaları olan identifikatorlar
- Bəzi identifikatorların heç bir növ açar sözlər olmadan bəzi məzmunlarda xüsusi bir mənası var. Bunlara daxildir:

- -

bu sintaksis ECMAScript 2015-də yenidir, brauzer uyğunluğu cədvəlinə baxın. 0o-dan sonrakı rəqəmlər (01234567) aralığın xaricindədirsə, aşağıdakı {{jsxref ("SyntaxError")}} atılır: "0o-dan sonra itmiş səkkizbucaqlı rəqəmlər".

- -

var n = 0O755; // 493
- var m = 0o644; // 420

- -

// Yalnız bir aparıcı sıfır ilə mümkündür (yuxarıdakı onluğa dair qeydə baxın)
- 0755
- 0644
- Altıbucaqlıdır
- Hexadecimal nömrə sintaksisində kiçik və ya böyük hərfli Latın "X" (0x və ya 0X) hərfinin ardınca aparıcı sıfır istifadə olunur. 0x-dən sonra rəqəmlər aralığın xaricindədirsə (0123456789ABCDEF), aşağıdakı {{jsxref ("SyntaxError")}} atılır: "Identifikator rəqəmli hərfdən dərhal sonra başlayır".

- -

0xFFFFFFFFFFFFFFFFF // 295147905179352830000
- 0x123456789ABCDEF // 81985529216486900
- 0XA // 10
- BigInt hərfi
- {{Jsxref ("BigInt")}} növü JavaScript-də ixtiyari dəqiqliklə tam ədədləri təmsil edə bilən ədədi ibtidai. BigInt hərfləri tam ədədin sonuna n əlavə etməklə yaradılır.

- -

123456789123456789n // 123456789123456789
- 0o777777777777n // 68719476735
- 0x123456789ABCDEFn // 81985529216486895
- 0b11101001010101010101n // 955733
- Qeyd edək ki, yalnız bir lider sıfır olan köhnə səkkizbucaqlı rəqəmlər BigInt üçün işləməyəcək:

- -

// 0755n
- // SyntaxError: etibarsız BigInt sintaksisi
- Səkkizbucaqlı BigInt nömrələri üçün hər zaman sıfırdan sonra "o" hərfi ilə (böyük və ya kiçik hərf) istifadə edin:

- -

0o755n
- BigInt haqqında daha çox məlumat üçün JavaScript məlumat strukturlarına da baxın.

- -

Sayısal ayırıcılar
- Rəqəmsal hərflərin oxunuşunu yaxşılaşdırmaq üçün alt nöqtələrdən (_, U + 005F) ayırıcı kimi istifadə edilə bilər

- -

// onluq sayda ayırıcılar
- 1_000_000_000_000
- 1_050.95

- -

// ikili nömrələrdə ayırıcılar
- 0b1010_0001_1000_0101

- -

// səkkizbucaqlı ədədlərdə ayrıcılar
- 0o2_2_5_6

- -

// hex ədədlərindəki ayırıcılar
- 0xA0_B0_C0

- -

// BigInts-də ayırıcılar
- 1_000_000_000_000_000_000_000n
- Bu məhdudiyyətlərə diqqət yetirin:

- -

// Bir dəfədən çox alt qeyd etməyə icazə verilmir
- 100__000; // Söz düzümü səhvi

- -

// Rəqəmsal hərflərin sonunda icazə verilmir
- 100_; // Söz düzümü səhvi

- -

// 0-dan sonra istifadə edilə bilməz
- 0_1; // Söz düzümü səhvi
- Obyekt hərfləri
- Əlavə məlumat üçün {{jsxref ("Obyekt")}} və Obyekt başlatıcısına da baxın.

- -

var o = {a: 'foo', b: 'bar', c: 42};

- -

// stenoqram notation. ES2015-də yenidir
- var a = 'foo', b = 'bar', c = 42;
- var o = {a, b, c};

- -

// əvəzinə
- var o = {a: a, b: b, c: c};
- Sıra hərfləri
- Əlavə məlumat üçün {{jsxref ("Array")}} da baxın.

- -

[1954, 1974, 1990, 2014]
- Simli hərflər
- Sətir hərfi sıfır və ya daha çox və ya ikiqat tirnoqla əlavə olunmuş Unicode kod nöqtələridir. Unicode kod nöqtələri də bir qaçış ardıcıllığı ilə təmsil oluna bilər. Bütün bağ nöqtələri sözün həqiqi kod nöqtələri istisna olmaqla hərfi mənada bir simli olaraq görünə bilər:

- -

U + 005C \ (arxa cığır),
- U + 000D <CR>,
- və U + 000A <LF>.
- Bütün JSON mətnini etibarlı ECMA-262, U + 2028 <LS> və U + 2029 <PS> etiketli etmək təklifindən əvvəl də simli hərflərdə görünməməsi qadağan edildi.

- -

Hər hansı bir kod nöqtəsi qaçış ardıcıllığı şəklində görünə bilər. String hərfləri ECMAScript String dəyərlərini qiymətləndirir. Bu Sətir dəyərlərini yaradan zaman Unicode kod nöqtələri UTF-16 kodlanır.

- -

'foo'
- "bar"
- Hexadecimal escape ardıcıllığı
- Hexadecimal escape ardıcıllığı, 0x0000 ilə 0x00FF aralığında bir kod vahidi və ya kod nöqtəsini təmsil edən iki iki altıbucaqlı rəqəmin ardınca \ x ibarətdir.

- -

'\ xA9' // "©"
- Unicode qaçış ardıcıllığı
- Unicode qaçış ardıcıllığı tam olaraq dörd altıbucaqlı rəqəmlərdən ibarətdir \ u. UTF-16 kodlaşdırmada bir kod vahidini təmsil edir. U + 0000 ilə U + FFFF kod nöqtələri üçün kod vahidi kod nöqtəsinə bərabərdir. U + 10000 ilə U + 10FFFF kod nöqtələri, xarakteri kodlamaq üçün istifadə olunan iki kod vahidini (bir surroqat cütü) təmsil edən iki qaçış ardıcıllığını tələb edir; surroqat cütlüyü kod nöqtəsindən fərqlidir.

- -

Buna da baxın: {{jsxref ("String.fromCharCode ()")}} və {{jsxref ("String.prototype.charCodeAt ()")}}.

- -

'\ u00A9' // "©" (U + A9)
- Unicode kod nöqtəsi qaçır
- Unicode kod nöqtəsindən qaçış \ u {, ardından altıbucaqlı bazada kod nöqtəsi, ardınca} daxil edilir. Altıbucaqlı rəqəmlərin dəyəri 0 ilə 0x10FFFF arasında olmalıdır. U + 10000 ilə U + 10FFFF arasındakı kod nöqtələrinin surroqat cütü kimi göstərilməsinə ehtiyac yoxdur. Kod nöqtələrinin qaçışları ECMAScript 2015 (ES6) -də JavaScript-ə əlavə edildi.

- -

Buna da baxın: {{jsxref ("String.fromCodePoint ()")}} və {{jsxref ("String.prototype.codePointAt ()")}}.

- -

'\ u {2F804}' // CJK uyğunluğu İDEOĞRAF-2F804 (U + 2F804)

- -

// eyni xarakterli bir surroqat cütü olaraq təmsil olunur
- '\ uD87E \ uDC04'
- Daimi ifadə hərfi
- Əlavə məlumat üçün {{jsxref ("RegExp")}} də baxın.

- -

/ ab + c / g

- -

// Bir "boş" müntəzəm ifadə
- // Boş tutmayan qrup lazımdır
- // tək sətirli şərhlərlə qeyri-müəyyənliyə yol verməmək.
- / (?:) /
- Şablon hərfləri
- Daha çox məlumat üçün şablon iplərinə baxın.

- -

`simli mətn`

- -

`simli mətn xətti 1
-  simli mətn xətti 2`

- -

`string mətni $ {ifadə} simli mətn '

- -

etiketli "string mətni $ {ifadə} string mətni"
- Avtomatik nöqtəli vergül
- Bəzi JavaScript ifadələri nöqtəli vergul ilə dayandırılmalı və buna görə də

- -

avtomatik nöqtəli vergül daxil edilməsindən təsirləndi (ASI):

- -

Boş bəyanat
- qoy, const, dəyişən bir ifadə
- idxal, ixrac, modul bəyannaməsi
- İfadə ifadəsi
- debugger
- davam etmək, qırmaq, atmaq
- qayıtmaq
- ECMAScript spesifikasiyası nöqtəli vergül daxil edilməsinin üç qaydasını xatırladır.

- -

1. Bir xətt terminatoru və ya "}" ilə qarşılaşdıqda, qrammatika tərəfindən icazə verilməyən nöqtələrə vergül qoyulur.

- -

{1 2} 3

- -

// ASI tərəfindən çevrilir

- -

{1 2;} 3;
- 2. Ayələr giriş axınının sonu aşkar edildikdə və analizator bir giriş axını tam bir proqram olaraq təhlil edə bilmədikdə son nöqtəyə nöqtə qoyulur.

- -

Burada ++ dəyişən b tətbiq olunan bir postfiks operatoru kimi qəbul edilmir, çünki b və ++ arasında bir xətt terminatoru meydana gəlir.

- -

a = b
- ++ c

- -

// ASI tərəfindən dəyişdirilir

- -

a = b;
- ++ c;
- 3. Sonunda nöqtə vergül qoyulur, qrammatikada məhdud məhsullar olan bir söz bir xətt terminatoru izlədikdə. "Burada LineTerminator yoxdur" qaydaları olan bu ifadələr:

- -

Postfiks İfadə (++ və -)
- davam edin
- fasilə
- qayıtmaq
- gəlir, gəlir *
- modul
- qayıtmaq
- a + b

- -

// ASI tərəfindən çevrilir

- -

qayıtmaq;
- a + b;
- Texniki şərtlər
- Xüsusiyyət
- {{SpecName ('ESDraft', '# sec-ecmascript-language-leksik-qrammatika', 'Leksik qrammatika')}}
- Brauzer uyğunluğu
- Bu səhifədəki uyğunluq cədvəli strukturlaşdırılmış məlumatlardan hazırlanmışdır. Verilənlərə töhfə vermək istəyirsinizsə, lütfən https://github.com/mdn/browser-compat-data-ya baxın və bizə bir sorğu göndərin.
- {{Compat ("javascript.grammar")}}

- - -


- Həmçinin bax
- Jeff Walden: İkili və səkkizbucaqlı ədədlər
- Mathias Bynens: JavaScript xarakter qaçış ardıcıllığı
- {{jsxref ("Boolean")}}
- {{jsxref ("Sayı")}}
- {{jsxref ("RegExp")}}
- {{jsxref ("Sətir")}}

diff --git a/files/tr/web/javascript/reference/operators/function_star_/index.html b/files/tr/web/javascript/reference/operators/function_star_/index.html deleted file mode 100644 index bf871854a4..0000000000 --- a/files/tr/web/javascript/reference/operators/function_star_/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: function* expression -slug: Web/JavaScript/Reference/Operators/function* -translation_of: Web/JavaScript/Reference/Operators/function* -original_slug: Web/JavaScript/Reference/Operatörler/function* ---- -
{{jsSidebar("Operators")}}
- -

The function* keyword can be used to define a generator function inside an expression.

- -
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
- - - -

Syntax

- -
function* [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-}
- -

Parametreler

- -
-
name
-
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
-
paramN
-
Argüman adıdır, bir fonksiyon maxiumum 255 argüman alır.
-
statements
-
Fonksiyon kodları.
-
- -

Açıklama

- -

A function* expression is very similar to and has almost the same syntax as a {{jsxref('Statements/function*', 'function* statement')}}. The main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions. See also the chapter about functions for more information.

- -

Örnekler

- -

Aşağıdaki adlandırılmamış fonksiyondur ve gelen değer karesini verir.

- -
var x = function*(y) {
-   yield y * y;
-};
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.operators.function_star")}}

- -

Bakabilirsiniz

- - diff --git a/files/tr/web/javascript/reference/operators/index.html b/files/tr/web/javascript/reference/operators/index.html deleted file mode 100644 index 1163323350..0000000000 --- a/files/tr/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,278 +0,0 @@ ---- -title: İfadeler ve operatörler -slug: Web/JavaScript/Reference/Operators -translation_of: Web/JavaScript/Reference/Operators -original_slug: Web/JavaScript/Reference/Operatörler ---- -
{{jsSidebar("Operators")}}
- -

Bu döküman bütün JavaScript ifadelerini,operatörlerini ve anahtar kelimeleri içerir.

- -

Expressions and operators by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Birincil İfadeler

- -

Genel İfadeler ve basit anahtar kelimeler.

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
-
Pause and resume a generator function
-
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
- -

See also

- - diff --git a/files/tr/web/javascript/reference/operators/instanceof/index.html b/files/tr/web/javascript/reference/operators/instanceof/index.html deleted file mode 100644 index d94b35a526..0000000000 --- a/files/tr/web/javascript/reference/operators/instanceof/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: instanceof -slug: Web/JavaScript/Reference/Operators/instanceof -translation_of: Web/JavaScript/Reference/Operators/instanceof -original_slug: Web/JavaScript/Reference/Operatörler/instanceof ---- -
{{jsSidebar("Operators")}}
- -

Instanceof operatorü bir nesne'nin prototip (prototype) zincirinin, belirli bir prototipin kurucu(constructor) metodu olup olmadığını testeder.

- -

Syntax

- -
object instanceof constructor
- -

Parametreler

- -
-
object
-
Test edilecek nesne
-
- -
-
constructor
-
Test edilecek karşı kurucu fonksiyon
-
- -

Açıklama

- -

Instanceof operatorü nesnenin prototip zincirinde 'constructor.prototype' varlığını testeder.

- -
// defining constructors
-function C() {}
-function D() {}
-
-var o = new C();
-
-// true, because: Object.getPrototypeOf(o) === C.prototype
-o instanceof C;
-
-// false, because D.prototype is nowhere in o's prototype chain
-o instanceof D;
-
-o instanceof Object; // true, because:
-C.prototype instanceof Object // true
-
-C.prototype = {};
-var o2 = new C();
-
-o2 instanceof C; // true
-
-// false, because C.prototype is nowhere in
-// o's prototype chain anymore
-o instanceof C;
-
-D.prototype = new C(); // add C to [[Prototype]] linkage of D
-var o3 = new D();
-o3 instanceof D; // true
-o3 instanceof C; // true since C.prototype is now in o3's prototype chain
-
- -

Bir instanceof testinin değerinin yapıcıların prototip özelliklerinde yapılan değişikliklere göre değişebileceğini ve Object.setPrototypeOf kullanılarak bir nesne prototipini değiştirerek de değişebileceğini unutmayın. Standart olmayan __proto__ sözde-özelliği(pseudo-property) kullanarak da mümkündür.

- -

instanceof ve çoklu bağlam (multiple context) (e.g. frames or windows)

- -

Farklı kapsamların (Scopes) farklı yürütme (execution) ortamları vardır. Bu, farklı yerleşik yapılara sahip oldukları anlamına gelir (farklı global nesne, farklı yapıcılar, vb.). Bu, beklenmedik sonuçlara neden olabilir. Örneğin, [] instanceof window.frames [0] .Array false döndürür, çünkü Array.prototype! == window.frames [0] .Array ve diziler belli bir dizgeden (former) miras alırlar. Bu başlangıçta mantıklı gelmeyebilir, ancak betiğinizde (script) birden çok cerceve (frame) veya pencereyi (window) ele almaya başladığınızda ve nesneleri fonsiyonlarla bir bağlamdan diğerine geçirirken, bu geçerli ve güçlü bir sayı olacaktır. Örneğin, belirli bir nesnenin aslında Array.isArray (myObj) kullanarak bir Array olup olmadığını güvenli bir şekilde kontrol edebilirsiniz.

- -
Mozilla geliştiricleri için not: - -

Kodda XPCOM kullanımının özel bir etkisi vardır: obj instanceof xpcomInterface (ör. Components.interfaces.nsIFile), obj.QueryInterface (xpcomInterface) çağırır ve QueryInterface başarılı olursa true değerini döndürür. Bu tür bir aramanın bir yan etkisi, başarılı bir örnekleme sonucunda obj'de xpcomInterface özelliklerini kullanabilmenizdir. Standart JavaScript globals'ın aksine, test obj instance of xpcomInterface, obj farklı bir kapsamdan olsa bile beklendiği gibi çalışır.

-
- -

Examples

- -

Demonstrating that String and Date are of type Object and exceptional cases

- -

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

- -

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

- -
var simpleStr = 'This is a simple string';
-var myString  = new String();
-var newStr    = new String('String created with constructor');
-var myDate    = new Date();
-var myObj     = {};
-
-simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
-myString  instanceof String; // returns true
-newStr    instanceof String; // returns true
-myString  instanceof Object; // returns true
-
-myObj instanceof Object;    // returns true, despite an undefined prototype
-({})  instanceof Object;    // returns true, same case as above
-
-myString instanceof Date;   // returns false
-
-myDate instanceof Date;     // returns true
-myDate instanceof Object;   // returns true
-myDate instanceof String;   // returns false
-
- -

Demonstrating that mycar is of type Car and type Object

- -

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-var mycar = new Car('Honda', 'Accord', 1998);
-var a = mycar instanceof Car;    // returns true
-var b = mycar instanceof Object; // returns true
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/operators/super/index.html b/files/tr/web/javascript/reference/operators/super/index.html deleted file mode 100644 index 1248797b8e..0000000000 --- a/files/tr/web/javascript/reference/operators/super/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: super -slug: Web/JavaScript/Reference/Operators/super -translation_of: Web/JavaScript/Reference/Operators/super -original_slug: Web/JavaScript/Reference/Operatörler/super ---- -
{{jsSidebar("Operators")}}
- -

super, ebeveyn sınıftaki fonksiyonlara ulaşmak ve onları çağırmak için kullanılan bir ifadedir.

- -

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

- -

Sözdizimi (Syntax)

- -
super([arguments]); // ebeveyn sınıfın constructot'ını çağırır.
-super.functionOnParent([arguments]); // ebeveyn sınıftaki functionOnParent fonksiyonunu çalıştırır.
-
- -

Açıklama

- -

Constructor içinde super ifadesi tek başına kullanılır ve this ifadesinden önce kullanılması zorunludur. Aynı zamanda super ifadesi ebeveyn sınıftaki fonksiyonları çağırmak için de kullanılabilir.

- -

Örnekler

- -

Sınflarda super kullanımı

- -

This code snippet is taken from the classes sample (live demo). Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square.

- -
class Rectangle {
-  constructor(height, width) {
-    this.name = 'Rectangle';
-    this.height = height;
-    this.width = width;
-  }
-  sayName() {
-    console.log('Hi, I am a ', this.name + '.');
-  }
-  get area() {
-    return this.height * this.width;
-  }
-  set area(value) {
-    this._area = value;
-  }
-}
-
-class Square extends Rectangle {
-  constructor(length) {
-    this.height; // ReferenceError, super needs to be called first!
-
-    // Here, it calls the parent class's constructor with lengths
-    // provided for the Rectangle's width and height
-    super(length, length);
-
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-}
- -

Super-calling static methods

- -

You are also able to call super on static methods.

- -
class Rectangle {
-  static logNbSides() {
-    return 'I have 4 sides';
-  }
-}
-
-class Square extends Rectangle {
-  static logDescription() {
-    return super.logNbSides() + ' which are all equal';
-  }
-}
-Square.logDescription(); // 'I have 4 sides which are all equal'
-
- -

Deleting super properties will throw an error

- -

You cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a {{jsxref("ReferenceError")}}.

- -
class Base {
-  foo() {}
-}
-class Derived extends Base {
-  delete() {
-    delete super.foo; // this is bad
-  }
-}
-
-new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
- -

super.prop cannot overwrite non-writable properties

- -

When defining non-writable properties with e.g. {{jsxref("Object.defineProperty")}}, super cannot overwrite the value of the property.

- -
class X {
-  constructor() {
-    Object.defineProperty(this, 'prop', {
-      configurable: true,
-      writable: false,
-      value: 1
-    });
-  }
-}
-
-class Y extends X {
-  constructor() {
-    super();
-  }
-  foo() {
-    super.prop = 2;   // Cannot overwrite the value.
-  }
-}
-
-var y = new Y();
-y.foo(); // TypeError: "prop" is read-only
-console.log(y.prop); // 1
-
- -

Using super.prop in object literals

- -

Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of {{jsxref("Object.setPrototypeOf()")}} with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1.

- -
var obj1 = {
-  method1() {
-    console.log('method 1');
-  }
-}
-
-var obj2 = {
-  method2() {
-    super.method1();
-  }
-}
-
-Object.setPrototypeOf(obj2, obj1);
-obj2.method2(); // logs "method 1"
-
- -

Özellikler

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.operators.super")}}

- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/operators/this/index.html b/files/tr/web/javascript/reference/operators/this/index.html deleted file mode 100644 index a2ee362c2a..0000000000 --- a/files/tr/web/javascript/reference/operators/this/index.html +++ /dev/null @@ -1,348 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operators/this -translation_of: Web/JavaScript/Reference/Operators/this -original_slug: Web/JavaScript/Reference/Operatörler/this ---- -
{{jsSidebar("Operators")}}
- -

Fonksiyon'un this anahtar kelimesi diğer dillere göre birazcık farklı davranır. Ayrıca strict modu ve non-strict modu arasında farklılıklar bulunur.

- -

Çoğunlukla, this'in değeri fonksiyonun çağrılma biçimine göre belirlenir. Çalışma esnasında değeri değiştirilemez, ve her fonksiyonu çağırışta farklı olabilir. ES5 bu adreste bind method to set the value of a function's this regardless of how it's called.

- -

Sözdizimi

- -
this
- -

Global içerik

- -

Global konumda (fonksiyon dışında), this global nesnesini referans gösterir, strict modunda olmak bu durumu değiştirmez..

- -
console.log(this.document === document); // true
-
-// Web browserlerinde window objesi global objedir.:
-console.log(this === window); // true
-
-this.a = 37;
-console.log(window.a); // 37
-
- -

Function içerik

- -

Fonksiyon içerisinde, this'in değeri fonksiyonun nasıl çağrıldığına bağlıdır..

- -

Basit çağrı

- -
function f1(){
-  return this;
-}
-
-f1() === window; // global obje
-
- -

Bu durumda, this'in değeri çağrı ile ayarlanmaz. Kod strict modda olmadığı sürece, this'in değeri mutlaka obje olmalıdır bu yüzdende default değer olan global objesi döner.

- -
function f2(){
-  "use strict"; // strict modu içerisinde çalıştıralım
-  return this;
-}
-
-f2() === undefined;
-
- -

Strict modu içerisinde, this'in değeri çalıştırılma içeriğine nasıl girdiyse o şekilde kalır. Eğer tanımlanmamışsa, undefined olarak kalır. Ayrıca tüm değerlere eşitlenebilir, örneğin null yada 42 yada "I am not this".

- -
Not: İkinci örnekte, this undefined olmalıdır, çünkü f2 taban belirtilmeden çağrılmıştır. (örn: window.f2()). Bu özellik bazı browserlerde desteklenmemektedir. strict mod henüz geliştirme aşamasındayken çoğu browser yanlış davranarak window objesini döndürür.
- -

Obje methodu cağrısı

- -

Fonksiyon bir objenin methodu olarak çağrıldığında, this çağrıldığı obje olarak atanacaktır.

- -

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // logs 37
-
- -

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // logs 37
-
- -

This demonstrates that it matters only that the function was invoked from the f member of o.

- -

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

- -
o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // logs 42
-
- -

this on the object's prototype chain

- -

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

- -
var o = {f:function(){ return this.a + this.b; }};
-var p = Object.create(o);
-p.a = 1;
-p.b = 4;
-
-console.log(p.f()); // 5
-
- -

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

- -

this with a getter or setter

- -

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

- -
function modulus(){
-  return Math.sqrt(this.re * this.re + this.im * this.im);
-}
-
-var o = {
-  re: 1,
-  im: -1,
-  get phase(){
-    return Math.atan2(this.im, this.re);
-  }
-};
-
-Object.defineProperty(o, 'modulus', {
-    get: modulus, enumerable:true, configurable:true});
-
-console.log(o.phase, o.modulus); // logs -0.78 1.4142
-
- -

As a constructor

- -

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

- -

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

- -
/*
- * Constructors work like this:
- *
- * function MyConstructor(){
- *   // Actual function body code goes here.
- *   // Create properties on |this| as
- *   // desired by assigning to them.  E.g.,
- *   this.fum = "nom";
- *   // et cetera...
- *
- *   // If the function has a return statement that
- *   // returns an object, that object will be the
- *   // result of the |new| expression.  Otherwise,
- *   // the result of the expression is the object
- *   // currently bound to |this|
- *   // (i.e., the common case most usually seen).
- * }
- */
-
-function C(){
-  this.a = 37;
-}
-
-var o = new C();
-console.log(o.a); // logs 37
-
-
-function C2(){
-  this.a = 37;
-  return {a:38};
-}
-
-o = new C2();
-console.log(o.a); // logs 38
-
- -

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

- -

call and apply

- -

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

- -
function add(c, d){
-  return this.a + this.b + c + d;
-}
-
-var o = {a:1, b:3};
-
-// The first parameter is the object to use as
-// 'this', subsequent parameters are passed as
-// arguments in the function call
-add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
-
-// The first parameter is the object to use as
-// 'this', the second is an array whose
-// members are used as the arguments in the function call
-add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
-
- -

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7); // [object Number]
-
- -

The bind method

- -

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

- -
function f(){
-  return this.a;
-}
-
-var g = f.bind({a:"azerty"});
-console.log(g()); // azerty
-
-var o = {a:37, f:f, g:g};
-console.log(o.f(), o.g()); // 37, azerty
-
- -

As a DOM event handler

- -

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

- -
// When called as a listener, turns the related element blue
-function bluify(e){
-  // Always true
-  console.log(this === e.currentTarget);
-  // true when currentTarget and target are the same object
-  console.log(this === e.target);
-  this.style.backgroundColor = '#A5D9F3';
-}
-
-// Get a list of every element in the document
-var elements = document.getElementsByTagName('*');
-
-// Add bluify as a click listener so when the
-// element is clicked on, it turns blue
-for(var i=0 ; i<elements.length ; i++){
-  elements[i].addEventListener('click', bluify, false);
-}
- -

In an in–line event handler

- -

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

The above alert shows button. Note however that only the outer code has its this set this way:

- -
<button onclick="alert((function(){return this}()));">
-  Show inner this
-</button>
-
- -

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/operators/typeof/index.html b/files/tr/web/javascript/reference/operators/typeof/index.html deleted file mode 100644 index 1c5785a9b1..0000000000 --- a/files/tr/web/javascript/reference/operators/typeof/index.html +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: typeof -slug: Web/JavaScript/Reference/Operators/typeof -translation_of: Web/JavaScript/Reference/Operators/typeof -original_slug: Web/JavaScript/Reference/Operatörler/typeof ---- -
{{jsSidebar("Operatörler")}}
- -

Typeof operatörü, değerlendirilmemiş işlenenin türünü gösteren bir dize döndürür.

- -
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
- - - -

Sözdizimi

- -

The typeof operator is followed by its operand:

- -
typeof operand
-or
-typeof (operand)
-
- - - -

Parametreler

- -

operand is an expression representing the object or {{Glossary("Primitive", "primitive")}} whose type is to be returned.

- -

Parantez isteğe bağlıdır.

- -

Description

- -

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeResult
Undefined"undefined"
Null"object" (see below)
Boolean"boolean"
Number"number"
String"string"
Symbol (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
- -

Örnekler

- -
// Sayılar
-typeof 37 === 'number';
-typeof 3.14 === 'number';
-typeof(42) === 'number';
-typeof Math.LN2 === 'number';
-typeof Infinity === 'number';
-typeof NaN === 'number'; // Despite being "Not-A-Number"
-typeof Number(1) === 'number'; // but never use this form!
-
-
-// Metinler
-typeof '' === 'string';
-typeof 'bla' === 'string';
-typeof '1' === 'string'; // note that a number within a string is still typeof string
-typeof (typeof 1) === 'string'; // typeof always returns a string
-typeof String('abc') === 'string'; // but never use this form!
-
-
-// Booleans
-typeof true === 'boolean';
-typeof false === 'boolean';
-typeof Boolean(true) === 'boolean'; // but never use this form!
-
-
-// Symbols
-typeof Symbol() === 'symbol'
-typeof Symbol('foo') === 'symbol'
-typeof Symbol.iterator === 'symbol'
-
-
-// Undefined
-typeof undefined === 'undefined';
-typeof declaredButUndefinedVariable === 'undefined';
-typeof undeclaredVariable === 'undefined';
-
-
-// Objeler
-typeof {a: 1} === 'object';
-
-// use Array.isArray or Object.prototype.toString.call
-// to differentiate regular objects from arrays
-typeof [1, 2, 4] === 'object';
-
-typeof new Date() === 'object';
-
-
-// The following is confusing. Don't use!
-typeof new Boolean(true) === 'object';
-typeof new Number(1) === 'object';
-typeof new String('abc') === 'object';
-
-
-// Fonksiyonlar
-typeof function() {} === 'function';
-typeof class C {} === 'function';
-typeof Math.sin === 'function';
-
- -

null

- -
// This stands since the beginning of JavaScript
-typeof null === 'object';
-
- -

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)

- -

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

- -

new operatör kullanımı

- -
// All constructor functions while instantiated with 'new' keyword will always be typeof 'object'
-var str = new String('String');
-var num = new Number(100);
-
-typeof str; // It will return 'object'
-typeof num; // It will return 'object'
-
-// But there is a exception in case of Function constructor of Javascript
-
-var func = new Function();
-
-typeof func; // It will return 'function'
-
- -

Parantezlere ihtiyaç var

- -
// Parentheses will be very much useful to determine the data type for expressions.
-var iData = 99;
-
-typeof iData + ' Wisen'; // It will return 'number Wisen'
-typeof (iData + ' Wisen'); // It will return 'string'
-
-
-
- -

Düzenli İfadeler

- -

Callable regular expressions were a non-standard addition in some browsers.

- -
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
-typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
-
- -

Temporal Dead Zone errors

- -

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. But with the addition of non-hoisted, block-scoped let and const, using typeof on let and const variables in a block before they are declared will throw a ReferenceError. This is in contrast with undeclared variables, for which typeof will return 'undefined'. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

- -
typeof undeclaredVariable === 'undefined';
-typeof newLetVariable; let newLetVariable; // ReferenceError
-typeof newConstVariable; const newConstVariable = 'hello'; // ReferenceError
-
- -

İstisnalar

- -

All current browsers expose a non-standard host object {{domxref("document.all")}} with type Undefined.

- -
typeof document.all === 'undefined';
-
- -

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type tag 'undefined' must be classified as an exceptional violation of the rules.

- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.typeof")}}

- -

IE özel notlar

- -

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

- -
typeof alert === 'object'
- -

Bakabilirsiniz

- - diff --git a/files/tr/web/javascript/reference/statements/block/index.html b/files/tr/web/javascript/reference/statements/block/index.html deleted file mode 100644 index 7d77ce73aa..0000000000 --- a/files/tr/web/javascript/reference/statements/block/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: block -slug: Web/JavaScript/Reference/Statements/block -tags: - - Blok - - ifade -translation_of: Web/JavaScript/Reference/Statements/block ---- -
{{jsSidebar("Statements")}}
- -

Bir blok statement(ifade) (diğer bir deyişle birleşik ifade) sıfır ya da daha fazla ifadeyi gruplamak için kullanılır. Blok bir çift süslü parantezle sınırlandırılmakla beraber opsiyonel olarak {{jsxref("Statements/label", "etiketlenebilir")}}:

- -

Syntax

- -
[etiket:] {
-  statement_1;
-  statement_2;
-  ...
-  statement_n;
-}
-
- -
-
statement_1, statement_2, statement_n
-
İfadeler tek bir statement içinde sınırlandırılmıştır.
-
etiket
-
Görsel bir tanımlama yapmak ya da bir {{jsxref("Statements/break", "break(kırılım)")}}oluşturmak için opsiyonel bir {{jsxref("Statements/label", "etikettir.")}}.
-
- -

Açıklama

- -

Statement,sıklıkla akış tablolarıyla birlikte kullanılır. (örn. {{jsxref("Statements/if...else", "if...else")}}, {{jsxref("Statements/for", "for")}}, {{jsxref("Statements/while", "while")}}). Örnek:

- -
while (x < 10) {
-  x++;
-}
-
- -

Hatırlatma : statement noktalı virgül ile sonlanmaz.

- -

Block statement diğer dillerde birleşik ifade yani compound statement olarak ifade edilir. Javasacript tek bir statement beklerken, birden çok statement kullanmanızı sağlar. Blokların birleşmesi Javascript için yaygın bir kullanımdır. Bir diğer kullanım ise statement kullanmanız gereken ancak kullanmadığınız yerlerde boş bir statement kullanılmasıdır.

- -

Block Scoping Rules

- -

With var

- -

Variables declared with var do not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java. For example:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // logs 2
-
- -

Burada çıktı 2 oldu çünkü block için ayrı bir scope oluşmamıştır. C ya da Java'da çıktı 1 olur.

- -

let ve const ile

- -

Yukarıdakinin aksine {{jsxref("Statements/let", "let")}} ve {{jsxref("Statements/const", "const")}} ayrı bir scope olarak koşacaktır:

- -
let x = 1;
-{
-  let x = 2;
-}
-console.log(x); // logs 1
- -

x = 2 sınırlı bir statement içerisinde yer aldığından sadece o statement içerisinde geçerli olacaktır.

- -

Bu kural const içinde aynıdır:

- -
const c = 1;
-{
-  const c = 2;
-}
-console.log(c); // logs 1 and does not throw SyntaxError...
- -

Dikkat edin sınırlı blocktaki  const c = 2  ifadesi SyntaxError: Identifier 'c' zaten tanımlanmış hatası vermedi çünkü, her blok içerisinde benzersiz olarak tanımlanır.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-block', 'Block statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.1', 'Block statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.1', 'Block statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.1', 'Block statement')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/statements/break/index.html b/files/tr/web/javascript/reference/statements/break/index.html deleted file mode 100644 index a929634f58..0000000000 --- a/files/tr/web/javascript/reference/statements/break/index.html +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: break -slug: Web/JavaScript/Reference/Statements/break -translation_of: Web/JavaScript/Reference/Statements/break ---- -
{{jsSidebar("Statements")}}
- -

Break ifadesi içinde bulunduğu döngüyü , {{jsxref("Statements/switch", "switch")}}, or {{jsxref("Statements/label", "label")}} ifadelerini sonlandırır  ve programın kontrolünü sonlandırılan ifadeyi ardından takip eden ifadeye geçirir.

- -
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
- - - -

Syntax

- -
break [etiket];
- -
-
etiket
-
İsteğe bağlıdır.İfade etiketini tanımlamakta kullanılır. Eğer belirtilen ifade bir döngü ya da {{jsxref("Statements/switch", "switch")}} değilse, mutlaka kullanılması gerekir.
-
- -

Description

- -

The break statement includes an optional label that allows the program to break out of a labeled statement. The break statement needs to be nested within the referenced label. The labeled statement can be any {{jsxref("Statements/block", "block")}} statement; it does not have to be preceded by a loop statement.

- -

Examples

- -

The following function has a break statement that terminates the {{jsxref("Statements/while", "while")}} loop when i is 3, and then returns the value 3 * x.

- -
function testBreak(x) {
-  var i = 0;
-
-  while (i < 6) {
-    if (i == 3) {
-      break;
-    }
-    i += 1;
-  }
-
-  return i * x;
-}
- -

The following code uses break statements with labeled blocks. A break statement must be nested within any label it references. Notice that inner_block is nested within outer_block.

- -
outer_block: {
-  inner_block: {
-    console.log('1');
-    break outer_block; // breaks out of both inner_block and outer_block
-    console.log(':-('); // skipped
-  }
-  console.log('2'); // skipped
-}
-
- -

The following code also uses break statements with labeled blocks but generates a Syntax Error because its break statement is within block_1 but references block_2. A break statement must always be nested within any label it references.

- -
block_1: {
-  console.log('1');
-  break block_2; // SyntaxError: label not found
-}
-
-block_2: {
-  console.log('2');
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Unlabeled version.
{{SpecName('ES3')}}{{Spec2('ES3')}}Labeled version added.
{{SpecName('ES5.1', '#sec-12.8', 'Break statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-break-statement', 'Break statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-break-statement', 'Break statement')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.statements.break")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/statements/const/index.html b/files/tr/web/javascript/reference/statements/const/index.html deleted file mode 100644 index f04efc9a90..0000000000 --- a/files/tr/web/javascript/reference/statements/const/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: const -slug: Web/JavaScript/Reference/Statements/const -translation_of: Web/JavaScript/Reference/Statements/const ---- -
{{jsSidebar("Statements")}}
- -

Sabit değerler(const), let anahtar sözcüğü kullanılarak bildirilen değişkenler gibi blok kapsamlıdır. Bir sabitin değeri yeniden atama yoluyla değiştirilemez ve yeniden beyan edilemez.

- -
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
- - - -

Syntax

- -
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
- -
-
nameN
-
The constant's name, which can be any legal {{Glossary("identifier")}}.
-
valueN
-
The constant's value. This can be any legal expression, including a function expression.
-
- -

 The Destructuring Assignment syntax can also be used to declare variables.

- -
const { bar } = foo; // where foo = { bar:10, baz:12 };
-/* This creates a constant with the name 'bar', which has a value of 10 */
- -
-
- -

Description

- -

This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the {{domxref("window")}} object, unlike {{jsxref("Statements/var", "var")}} variables.

- -

An initializer for a constant is required. You must specify its value in the same statement in which it's declared. (This makes sense, given that it can't be changed later.)

- -

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

- -

All the considerations about the "temporal dead zone" apply to both {{jsxref("Statements/let", "let")}} and const.

- -

A constant cannot share its name with a function or a variable in the same scope.

- -

Examples

- -

Basic const usage

- -

Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.

- -
// define MY_FAV as a constant and give it the value 7
-const MY_FAV = 7;
-
-// this will throw an error - Uncaught TypeError: Assignment to constant variable.
-MY_FAV = 20;
-
-// MY_FAV is 7
-console.log('my favorite number is: ' + MY_FAV);
-
-// trying to redeclare a constant throws an error
-// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
-const MY_FAV = 20;
-
-// the name MY_FAV is reserved for constant above, so this will fail too
-var MY_FAV = 20;
-
-// this throws an error too
-let MY_FAV = 20;
-
-
- -

Block scoping

- -

It's important to note the nature of block scoping.

- -
if (MY_FAV === 7) {
-  // this is fine and creates a block scoped MY_FAV variable
-  // (works equally well with let to declare a block scoped non const variable)
-  let MY_FAV = 20;
-
-  // MY_FAV is now 20
-  console.log('my favorite number is ' + MY_FAV);
-
-  // this gets hoisted into the global context and throws an error
-  var MY_FAV = 20;
-}
-
-// MY_FAV is still 7
-console.log('my favorite number is ' + MY_FAV);
-
- -

const needs to be initialized

- -
// throws an error
-// Uncaught SyntaxError: Missing initializer in const declaration
-
-const FOO;
-
- -

const in objects and arrays

- -

const also works on objects and arrays.

- -
const MY_OBJECT = {'key': 'value'};
-
-// Attempting to overwrite the object throws an error
-// Uncaught TypeError: Assignment to constant variable.
-MY_OBJECT = {'OTHER_KEY': 'value'};
-
-// However, object keys are not protected,
-// so the following statement is executed without problem
-MY_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable
-
-// The same applies to arrays
-const MY_ARRAY = [];
-// It's possible to push items into the array
-MY_ARRAY.push('A'); // ["A"]
-// However, assigning a new array to the variable throws an error
-// Uncaught TypeError: Assignment to constant variable.
-MY_ARRAY = ['B'];
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-let-and-const-declarations', 'Let and Const Declarations')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.statements.const")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/statements/export/index.html b/files/tr/web/javascript/reference/statements/export/index.html deleted file mode 100644 index ccc8dd657e..0000000000 --- a/files/tr/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: export -slug: Web/JavaScript/Reference/Statements/export -translation_of: Web/JavaScript/Reference/Statements/export ---- -
{{jsSidebar("Statements")}}
- -

export ifadesi JavaScript modülleri oluştururken fonksiyonların, nesnelerin ve temel değerlerin dışarı aktarılmasını sağlayarak, diğer programlar tarafından {{jsxref("Statements/import", "import")}} ifadesiyle kullanılmasını sağlar.

- -
-

Bu özellik şu an için yerel olarak sadece Safari'de uygulanmıştır. Traceur Compiler, Babel veya Rollup gibi bir çok transpiler tarafından da uygulanmaktadır.

-
- -

Sözdizim

- -
export { isim1, isim2, …, isimN };
-export { degisken1 as isim1, degisken2 as isim2, …, isimN };
-export let isim1, isim2, …, isimN; // ayrıca var, function
-export let isim1 = …, isim2 = …, …, isimN; // ayrıca var, const
-
-export default ifade;
-export default function (…) { … } // ayrıca class, function*
-export default function isim1(…) { … } // ayrıca class, function*
-export { isim1 as default, … };
-
-export * from …;
-export { isim1, isim2, …, isimN } from …;
-export { import1 as isim1, import2 as isim2, …, isimN } from …;
- -
-
isimN
-
Dışa aktarılacak belirleyici (böylece {{jsxref("Statements/import", "import")}} kullanılarak diğer programda içe aktarılabilir).
-
- -

Açıklama

- -

İki çeşit dışa aktarım vardır. Her biri aşağıdaki sözdizimlerden birine karşılık gelmektedir:

- - - -

İsimlendirilmiş dışa aktarımlar birden fazla değeri dışarı aktarmak için kullanışlıdır. İçe aktarım sırasında, aynı isimle ve buna karşılık gelen değeri ile kullanılabilecektir.

- -

Varsayılan dışa aktarımla ilgili olarak, her bir modül için sadece bir adet varsayılan dışa aktarım vardır. Varsayılan dışa aktarım bir fonksiyon, bir sınıf, bir nesne veya başka bir şey olabilir. Dışa aktarımı en basit olacağından dolayı bu değer dışa aktarılan "ana" değer olarak nitelendirilecektir.

- -

Varsayılanların dışa aktarımı: Aşağıdaki sözdizimi varsayılan dışa aktarımı içe aktaran modülde gerçekleşmeyecektir:

- -
export * from …;
- -

Eğer varsayılanı dışa aktarmak isterseniz, aşağıdakini yazınız:

- -
import mod from "mod";
-export default mod;
- -

Örnekler

- -

İsimlendirilmiş dışa aktarımları kullanmak

- -

Modül içerisinde, aşağıdaki kodu kullanabiliriz:

- -
// modül "benim-modulum.js"
-function kup(x) {
-  return x * x * x;
-}
-const deger = Math.PI + Math.SQRT2;
-export { kup, deger };
-
- -

Bu yolla, başka bir kod içerisinde (karşılaştır import), şunu yapabiliriz:

- -
import { kup, deger } from 'benim-modulum';
-console.log(kup(3)); // 27
-console.log(deger); // 4.555806215962888
- -

Varsayılanın dışa aktarımının kullanılması

- -

Eğer modülümüz için tek bir değeri dışa aktarmak istiyorsak veya bir son değere sahip olmak istiyorsak, varsayılan dışa aktarımı kullanabiliriz:

- -
// modül "benim-modulum.js"
-export default function kup(x) {
-  return x * x * x;
-}
-
- -

Sonra, başka bir kod içerisinde,  varsayılan dışa aktarımı içe aktarmak anlaşılır olacaktır:

- -
import kup from 'benim-modulum';
-console.log(kup(3)); // 27
-
- -

Dikkate alınız ki var, let veya const anahtar kelimelerini export default ile kullanamazsınız.

- -

Spesifikasyonlar

- - - - - - - - - - - - - - - - - - - -
SpesifikasyonDurumAçıklama
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}İlk tanım.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek61 (60 w/ flag){{CompatNo}} (54 w/ flag){{CompatNo}} (15 w/flag){{CompatNo}}10.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}10.3
-
- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/statements/index.html b/files/tr/web/javascript/reference/statements/index.html deleted file mode 100644 index b9fd7f94a0..0000000000 --- a/files/tr/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Statements and declarations -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - NeedsTranslation - - Reference - - TopicStub - - statements -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

- -

Statements and declarations by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
-
{{jsxref("Statements/break", "break")}}
-
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Declarations

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Functions and classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declares a function with the specified parameters.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declares a class.
-
- -

Iterations

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Others

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
- -

See also

- - diff --git a/files/tr/web/javascript/reference/statements/return/index.html b/files/tr/web/javascript/reference/statements/return/index.html deleted file mode 100644 index 1a1188b3d5..0000000000 --- a/files/tr/web/javascript/reference/statements/return/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: return -slug: Web/JavaScript/Reference/Statements/return -tags: - - JavaScript - - fonksiyon durdurmak - - fonksiyon döndürmek - - komutlar - - return komutu -translation_of: Web/JavaScript/Reference/Statements/return ---- -
{{jsSidebar("Statements")}}
- -

return komutu fonskiyonun çalışmasını bitirir ve fonksiyondan döndürülecek değeri belirler.

- -

Sözdizimi

- -
return [[ifade]]; 
- -
-
ifade
-
Döndürülecek ifade. Eğer atlanırsa, undefined döndürülür.
-
- -

Açıklama

- -

Bir fonksiyonda return komutu çağırılırsa, o fonksiyonun çalışması durur. Eğer belirtilmişse, verilen değer fonksiyonu çağırana kadar döndürülür. Eğer ifade belirtilmemişse, undefined döndürülür. Aşağıdaki tüm return komutları çağırıldıkları fonksiyonun çalışmasını durdururlar:

- -
return;
-return true;
-return false;
-return x;
-return x + y / 3;
-
- -

Otomatik Noktalı Virgül İlavesi

- -

return komutu otomatik noktalı virgül ilavesi (ASI)'ne dahildir. return ile ifade aynı satırda olmalıdır. Aksi halde;

- -
return
-a + b;
-
- -

ASI tarafıdan aşağıdaki gibi değiştirilir:

- -
return;
-a + b;
-
- -

Ve konsol size şu uyarıyı verecektir:"unreachable code after return statement (return komutundan sonra ulaşılamayan kod)".

- -
 "return komutundan sonra ulaşılamayan kod"  uyarısı Gecko 40 {{geckoRelease(40)}} sürümü ile başlamıştır.
- -

Örnekler

- -

Değer döndürme

- -

Aşağıdaki fonksiyon x argümanının (burada x bir sayıdır), karesini döndürür.

- -
function square(x) {
-   return x * x;
-}
-
- -

Fonksiyonu yarıda kesme

- -

return çağırıldığında, çağırıldığı noktada o fonksiyon anında durur .

- -
function sayac() {
-  for (var sayim = 1; ; sayim++) {  // sonsuz döngü
-    console.log(sayim + "A"); // 5'e kadar çıktı verir.
-      if (sayim === 5) {
-        return;
-      }
-      console.log(sayim + "B");  // 4'e kadar çıktı verir.
-    }
-  console.log(sayim + "C");  // hiçbir çıktı vermez.
-}
-
-sayac();
-
-// Çıktı:
-// 1A
-// 1B
-// 2A
-// 2B
-// 3A
-// 3B
-// 4A
-// 4B
-// 5A
-
- -

Bir fonksiyonu döndürme

- -

Kapsanımlar hakkındaki şu makaleye de bakınız: Closures.

- -
function magic(x) {
-  return function calc(x) { return x * 42 };
-}
-
-var answer = magic();
-answer(1337); // 56154
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}Ön-tanımlı.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
ÖzellikChromeFirefox (Gecko)Internet ExplorerOperaSafari
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidAndroid için ChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Temel destek{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/statements/throw/index.html b/files/tr/web/javascript/reference/statements/throw/index.html deleted file mode 100644 index 5ad62b840f..0000000000 --- a/files/tr/web/javascript/reference/statements/throw/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Statements/throw -translation_of: Web/JavaScript/Reference/Statements/throw ---- -
{{jsSidebar("Statements")}}
- -

Throw ifadesi kullanıcı tanımlı bir istisna atar. Mevcut işlevin yürütülmesi durur (atmadan sonraki ifadeler yürütülmez) ve kontrol, çağrı yığındaki ilk yakalama blokuna geçirilir. Arayanlar arasında yakalama bloğu yoksa, program sonlanır.

- -
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
- - - -

Syntax

- -
throw ifade; 
- -
-
ifade
-
Hata fırlatmak için ifade.
-
- -

Açıklama

- -

Bir hata fırlatmak için throw ifadesini kullanın. Bir hata fırlatırken, ifade hatanın değerini belirtir. Aşağıdakilerin her biri bir hata fırlatır:

- -
throw 'Error2'; // String bir ifade ile hata oluşturur.
-throw 42;       // Integer bir değerde hata oluşturur.
-throw true;     // Boolean bir ifade de hata oluşturur.
-throw new Error('Required');  // `Required` adıyla bir hata nesnesi oluşturur.
-
- -

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

- -

Örnek

- -

İstisna Nesnesi Örneği

- -

Bir istisna atarken bir nesne belirtebilirsiniz. Daha sonra nesnenin özelliklerini catch bloğuna referansta bulabilirsiniz. Aşağıdaki örnek, UserException türünde bir nesne oluşturur ve bunu bir throw ifadesinde kullanır.

- -
function UserException(message) {
-   this.message = message;
-   this.name = 'UserException';
-}
-function getMonthName(mo) {
-   mo = mo - 1; // Dizi içinde bir ay sayısı belirlenir (1 = Jan, 12 = Dec)
-   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
-      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-   if (months[mo] !== undefined) {
-      return months[mo];
-   } else {
-      throw new UserException('InvalidMonthNo');
-   }
-}
-
-try {
-   // try bloğu
-   var myMonth = 15; // Bir yılda 15 ay bulunmaz.
-   var monthName = getMonthName(myMonth);
-} catch (e) {
-   monthName = 'unknown';
-   console.log(e.message, e.name); // catch bloğuna hata nesnesinin parametreleri giriliyor.
-}
-
- -

Bir istisnayı atmanın başka bir örneği

- -

Aşağıdaki örnek, ABD posta kodu için bir giriş dizesini sınar. Posta kodu geçersiz bir format kullanıyorsa, throw ifadesi bir nesne türü oluşturarak bir istisna atar .

- -

​​​​​​ZipCodeFormatException.

- -
/*
- * Zip Kodu objesi oluşturulur.
- *
- * Kabul edilen zip kodları:
- *    12345
- *    12345-6789
- *    123456789
- *    12345 6789
- *
- * parametre kabul edilen zip kodlara uygun değilse
- * bir istisna atılır.
- */
-
-function ZipCode(zip) {
-   zip = new String(zip);
-   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
-   if (pattern.test(zip)) {
-      // zip kodu değeri dizideki ilk eşleşme olacak
-      this.value = zip.match(pattern)[0];
-      this.valueOf = function() {
-         return this.value
-      };
-      this.toString = function() {
-         return String(this.value)
-      };
-   } else {
-      throw new ZipCodeFormatException(zip);
-   }
-}
-
-function ZipCodeFormatException(value) {
-   this.value = value;
-   this.message = 'bir posta kodu için beklenen değerlerle uyuşmuyor';
-   this.toString = function() {
-      return this.value + this.message;
-   };
-}
-
-/*
- * Zip kodlarını doğrulayan bir komut bloğu olabilir.
- */
-
-const ZIPCODE_INVALID = -1;
-const ZIPCODE_UNKNOWN_ERROR = -2;
-
-function verifyZipCode(z) {
-   try {
-      z = new ZipCode(z);
-   } catch (e) {
-      if (e instanceof ZipCodeFormatException) {
-         return ZIPCODE_INVALID;
-      } else {
-         return ZIPCODE_UNKNOWN_ERROR;
-      }
-   }
-   return z;
-}
-
-a = verifyZipCode(95060);         // 95060
-b = verifyZipCode(9560);          // -1
-c = verifyZipCode('a');           // -1
-d = verifyZipCode('95060');       // 95060
-e = verifyZipCode('95060 1234');  // 95060 1234
-
- -

Bir istisnayı tekrar atmak

- -

Hatayı yakaladıktan sonra bir özel durumu geri almak için throw kullanabilirsiniz. Aşağıdaki örnek,

- -

Seğer 50'nin üzerindeyse onu yeniden kullanır. Yeniden biçimlendirilmiş istisna, kullanıcının onu görebilmesi için kapama işlevine veya en üst düzeye kadar çoğalır..

- -
try {
-   throw n; // integer bir değerde istisna atar
-} catch (e) {
-   if (e <= 50) {
-      // değer 1 ile 50 arasında ise
-   } else {
-      // tekrar bir istisna atar
-      throw e;
-   }
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}} -

Başlangıç

- -

Javascript 1.4

-
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.statements.throw")}}

- -

See also

- - diff --git a/files/tr/web/javascript/reference/statements/while/index.html b/files/tr/web/javascript/reference/statements/while/index.html deleted file mode 100644 index e9135ab063..0000000000 --- a/files/tr/web/javascript/reference/statements/while/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: while -slug: Web/JavaScript/Reference/Statements/while -translation_of: Web/JavaScript/Reference/Statements/while ---- -
{{jsSidebar("Statements")}}
- -

while ifadesi tanımlanan koşul gerçekleştiği sürece belirtilen kodu çalıştırmaya devam eden  bir döngü oluşturur. Önce şart kontrol edilir, eğer şart sağlanıyorsa kod çalıştırılır.

- -
{{EmbedInteractiveExample("pages/js/statement-while.html")}}
- - - -

Sözdizimi (Syntax)

- -
while (condition)
-  statement
-
- -
-
condition
-
Döngüdeki her bir tekrarlamadan önce kontrol edilen koşul. Eğer koşul sağlanıyorsa (true) statement çalıştırılır. Ancak koşul sağlanmıyorsa (false) statement çalıştırılmaz ve while döngüsünden sonra yazılan kod bloğu ile program çalışmaya devam eder.
-
statement
-
Koşul sağlandığında çalıştırılacak olan kod. Döngü içerisinde birden fazla kod satırı çalıştırmak için block ({ ... }) ifade şeklini kullanabilirsiniz. 
-

- Not: break ifadesini kullanarak döngüyü dilediğiniz zaman sonlandırabilirsiniz.
-
- -

Örnekler

- -

while kullanımı

- -

Aşağıdaki örnekte bulunan (n < 3) ifadesi while döngüsünün koşulu yani condition kısmıdır. Süslü parantezler içerisinde bulunan kısım ise çalıştırılacak olan kod bloğu yani statement kısmıdır. Dolayısıyla aşağıdaki while döngüsü, n değişkeninin değeri üçten küçük olduğu sürece çalışmaya devam eder.

- -
var n = 0;
-var x = 0;
-
-while (n < 3) {
-  n++;
-  x += n;
-}
- -

Her tekrarlamada, döngü n değişkeninin değerini bir arttırır. Ardından n değişkeninin değerini x değişkeninin değerine ekler. Dolayısıyla, x ve n değişkenleri aşağıdaki değerlere sahip olurlar:

- - - -

Üçüncü tekrardan sonra, n < 3 koşulu artık sağlanmadığı için döngü sonlanır.

- -

Özellikler

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-while-statement', 'while statement')}}
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.statements.while")}}

- -

Ayrıca bakınız

- - diff --git a/files/tr/web/javascript/reference/strict_mode/index.html b/files/tr/web/javascript/reference/strict_mode/index.html deleted file mode 100644 index e87b630e1b..0000000000 --- a/files/tr/web/javascript/reference/strict_mode/index.html +++ /dev/null @@ -1,363 +0,0 @@ ---- -title: Sıkı mod -slug: Web/JavaScript/Reference/Strict_mode -translation_of: Web/JavaScript/Reference/Strict_mode ---- -
{{JsSidebar("More")}}
- -
Sometimes you'll see the default, non-strict mode referred to as "sloppy mode". This isn't an official term, but be aware of it, just in case.
- -

JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

- -

Strict mode makes several changes to normal JavaScript semantics:

- -
    -
  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. -
  3. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
  4. -
  5. Prohibits some syntax likely to be defined in future versions of ECMAScript.
  6. -
- -

See transitioning to strict mode, if you want to change your code to work in the restricted variant of JavaScript.

- -

Invoking strict mode

- -

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, Function code, event handler attributes, strings passed to WindowTimers.setTimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected.

- -

Strict mode for scripts

- -

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

- -
// Whole-script strict mode syntax
-'use strict';
-var v = "Hi! I'm a strict mode script!";
-
- -

This syntax has a trap that has already bitten a major site: it isn't possible to blindly concatenate conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis.

- -

You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope.

- -

Strict mode for functions

- -

Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements.

- -
function strict() {
-  // Function-level strict mode syntax
-  'use strict';
-  function nested() { return 'And so am I!'; }
-  return "Hi!  I'm a strict mode function!  " + nested();
-}
-function notStrict() { return "I'm not strict."; }
-
- -

Strict mode for modules

- -

ECMAScript 2015 introduced JavaScript modules and therefore a 3rd way to enter strict mode.  The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.

- -
function strict() {
-    // because this is a module, I'm strict by default
-}
-export default strict;
-
- -

Changes in strict mode

- -

Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories: changes converting mistakes into errors (as syntax errors or at runtime), changes simplifying how the particular variable for a given use of a name is computed, changes simplifying eval and arguments, changes making it easier to write "secure" JavaScript, and changes anticipating future ECMAScript evolution.

- -

Converting mistakes into errors

- -

Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they're discovered and promptly fixed.

- -

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments, which would accidentally create global variables, instead throw an error in strict mode:

- -
'use strict';
-                       // Assuming no global variable mistypedVariable exists
-mistypeVariable = 17;  // this line throws a ReferenceError due to the
-                       // misspelling of variable
-
- -

Second, strict mode makes assignments which would otherwise silently fail to throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. Any assignment that silently fails in normal code (assignment to a non-writable global or property, assignment to a getter-only property, assignment to a new property on a non-extensible object) will throw in strict mode:

- -
'use strict';
-
-// Assignment to a non-writable global
-var undefined = 5; // throws a TypeError
-var Infinity = 5; // throws a TypeError
-
-// Assignment to a non-writable property
-var obj1 = {};
-Object.defineProperty(obj1, 'x', { value: 42, writable: false });
-obj1.x = 9; // throws a TypeError
-
-// Assignment to a getter-only property
-var obj2 = { get x() { return 17; } };
-obj2.x = 5; // throws a TypeError
-
-// Assignment to a new property on a non-extensible object
-var fixed = {};
-Object.preventExtensions(fixed);
-fixed.newProp = 'ohai'; // throws a TypeError
-
- -

Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):

- -
'use strict';
-delete Object.prototype; // throws a TypeError
-
- -

Fourth, strict mode prior to Gecko 34 requires that all properties named in an object literal be unique. The normal code may duplicate property names, with the last one determining the property's value. But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance. Duplicate property names are a syntax error in strict mode:

- -
-

This is no longer the case in ECMAScript 2015 (bug 1041128).

-
- -
'use strict';
-var o = { p: 1, p: 2 }; // !!! syntax error
-
- -

Fifth, strict mode requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments[i], so they're not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:

- -
function sum(a, a, c) { // !!! syntax error
-  'use strict';
-  return a + a + c; // wrong if this code ran
-}
-
- -

Sixth, a strict mode in ECMAScript 5 forbids octal syntax. The octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%". In ECMAScript 2015 Octal number is supported by prefixing a number with "0o". i.e. 

- -
var a = 0o10; // ES2015: Octal
- -

Novice developers sometimes believe a leading zero prefix has no semantic meaning, so they use it as an alignment device — but this changes the number's meaning! A leading zero syntax for the octals is rarely useful and can be mistakenly used, so strict mode makes it a syntax error:

- -
'use strict';
-var sum = 015 + // !!! syntax error
-          197 +
-          142;
-
-var sumWithOctal = 0o10 + 8;
-console.log(sumWithOctal); // 16
-
- -

Seventh, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a {{jsxref("TypeError")}} is thrown.

- -
(function() {
-'use strict';
-
-false.true = '';         // TypeError
-(14).sailing = 'home';   // TypeError
-'with'.you = 'far away'; // TypeError
-
-})();
- -

Simplifying variable uses

- -

Strict mode simplifies how variable names map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that variable X is stored in that location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform until runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.

- -

First, strict mode prohibits with. The problem with with is that any name inside the block might map either to a property of the object passed to it, or to a variable in surrounding (or even global) scope, at runtime: it's impossible to know which beforehand. Strict mode makes with a syntax error, so there's no chance for a name in a with to refer to an unknown location at runtime:

- -
'use strict';
-var x = 17;
-with (obj) { // !!! syntax error
-  // If this weren't strict mode, would this be var x, or
-  // would it instead be obj.x?  It's impossible in general
-  // to say without running the code, so the name can't be
-  // optimized.
-  x;
-}
-
- -

The simple alternative of assigning the object to a short name variable, then accessing the corresponding property on that variable, stands ready to replace with.

- -

Second, eval of strict mode code does not introduce new variables into the surrounding scope. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable:

- -
var x = 17;
-var evalX = eval("'use strict'; var x = 42; x;");
-console.assert(x === 17);
-console.assert(evalX === 42);
-
- -

If the function eval is invoked by an expression of the form eval(...) in strict mode code, the code will be evaluated as strict mode code. The code may explicitly invoke strict mode, but it's unnecessary to do so.

- -
function strict1(str) {
-  'use strict';
-  return eval(str); // str will be treated as strict mode code
-}
-function strict2(f, str) {
-  'use strict';
-  return f(str); // not eval(...): str is strict if and only
-                 // if it invokes strict mode
-}
-function nonstrict(str) {
-  return eval(str); // str is strict if and only
-                    // if it invokes strict mode
-}
-
-strict1("'Strict mode code!'");
-strict1("'use strict'; 'Strict mode code!'");
-strict2(eval, "'Non-strict code.'");
-strict2(eval, "'use strict'; 'Strict mode code!'");
-nonstrict("'Non-strict code.'");
-nonstrict("'use strict'; 'Strict mode code!'");
-
- -

Thus names in strict mode eval code behave identically to names in strict mode code not being evaluated as the result of eval.

- -

Third, strict mode forbids deleting plain names. delete name in strict mode is a syntax error:

- -
'use strict';
-
-var x;
-delete x; // !!! syntax error
-
-eval('var y; delete y;'); // !!! syntax error
- -

Making eval and arguments simpler

- -

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until a future edition of ECMAScript.

- -

First, the names eval and arguments can't be bound or assigned in language syntax. All these attempts to do so are syntax errors:

- -
'use strict';
-eval = 17;
-arguments++;
-++eval;
-var obj = { set p(arguments) { } };
-var eval;
-try { } catch (arguments) { }
-function x(eval) { }
-function arguments() { }
-var y = function eval() { };
-var f = new Function('arguments', "'use strict'; return 17;");
-
- -

Second, strict mode code doesn't alias properties of arguments objects created within it. In normal code within a function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted). arguments objects for strict mode functions store the original arguments when the function was invoked. arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

- -
function f(a) {
-  'use strict';
-  a = 42;
-  return [a, arguments[0]];
-}
-var pair = f(17);
-console.assert(pair[0] === 42);
-console.assert(pair[1] === 17);
-
- -

Third, arguments.callee is no longer supported. In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws an error when set or retrieved:

- -
'use strict';
-var f = function() { return arguments.callee; };
-f(); // throws a TypeError
-
- -

"Securing" JavaScript

- -

Strict mode makes it easier to write "secure" JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user's private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript's flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has a considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.

- -

First, the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function, this is always an object: either the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined:

- -
'use strict';
-function fun() { return this; }
-console.assert(fun() === undefined);
-console.assert(fun.call(2) === 2);
-console.assert(fun.apply(null) === null);
-console.assert(fun.call(undefined) === undefined);
-console.assert(fun.bind(true)() === true);
-
- -

That means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function.

- -

Second, in strict mode it's no longer possible to "walk" the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. Both extensions are problematic for "secure" JavaScript because they allow "secured" code to access "privileged" functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw when set or retrieved:

- -
function restricted() {
-  'use strict';
-  restricted.caller;    // throws a TypeError
-  restricted.arguments; // throws a TypeError
-}
-function privilegedInvoker() {
-  return restricted();
-}
-privilegedInvoker();
-
- -

Third, arguments for strict mode functions no longer provide access to the corresponding function call's variables. In some old ECMAScript implementations arguments.caller was an object whose properties aliased variables in that function. This is a security hazard because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. For these reasons no recent browsers implement it. Yet because of its historical functionality, arguments.caller for a strict mode function is also a non-deletable property which throws when set or retrieved:

- -
'use strict';
-function fun(a, b) {
-  'use strict';
-  var v = 12;
-  return arguments.caller; // throws a TypeError
-}
-fun(1, 2); // doesn't expose v (or a or b)
-
- -

Paving the way for future ECMAScript versions

- -

Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.

- -

First, in strict mode, a short list of identifiers become reserved keywords. These words are implements, interface, let, package, private, protected, public, static, and yield. In strict mode, then, you can't name or use variables or arguments with these names.

- -
function package(protected) { // !!!
-  'use strict';
-  var implements; // !!!
-
-  interface: // !!!
-  while (true) {
-    break interface; // !!!
-  }
-
-  function private() { } // !!!
-}
-function fun(static) { 'use strict'; } // !!!
-
-
- -

Two Mozilla-specific caveats: First, if your code is JavaScript 1.7 or greater (for example in chrome code or when using the right <script type="">) and is strict mode code, let and yield have the functionality they've had since those keywords were first introduced. But strict mode code on the web, loaded with <script src=""> or <script>...</script>, won't be able to use let/yield as identifiers. Second, while ES5 unconditionally reserves the words class, enum, export, extends, import, and super, before Firefox 5 Mozilla reserved them only in strict mode.

- -

Second, strict mode prohibits function statements, not at the top level of a script or function. In normal mode in browsers, function statements are permitted "everywhere". This is not part of ES5 (or even ES3)! It's an extension with incompatible semantics in different browsers. Note that function statements outside top level are permitted in ES2015.

- -
'use strict';
-if (true) {
-  function f() { } // !!! syntax error
-  f();
-}
-
-for (var i = 0; i < 5; i++) {
-  function f2() { } // !!! syntax error
-  f2();
-}
-
-function baz() { // kosher
-  function eit() { } // also kosher
-}
-
- -

This prohibition isn't strict mode proper because such function statements are an extension of basic ES5. But it is the recommendation of the ECMAScript committee, and browsers will implement it.

- -

Strict mode in browsers

- -

The major browsers now implement strict mode. However, don't blindly depend on it since there still are numerous Browser versions used in the wild that only have partial support for strict mode or do not support it at all (e.g. Internet Explorer below version 10!). Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don't implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented. Finally, make sure to test your code in browsers that do and don't support strict mode. If you test only in browsers that don't support strict mode, you're very likely to have problems in browsers that do, and vice versa.

- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-strict-mode-code', 'Strict Mode Code')}}
- -

See also

- - -- cgit v1.2.3-54-g00ecf