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 | 862 --------------------- files/id/web/javascript/closures/index.html | 346 --------- files/id/web/javascript/data_structures/index.html | 267 ------- .../javascript/guide/grammar_and_types/index.html | 649 ---------------- files/id/web/javascript/guide/index.html | 120 --- .../web/javascript/guide/introduction/index.html | 157 ---- .../guide/loops_and_iteration/index.html | 331 -------- .../javascript/guide/numbers_and_dates/index.html | 377 --------- .../guide/working_with_objects/index.html | 493 ------------ files/id/web/javascript/index.html | 116 --- .../inheritance_and_the_prototype_chain/index.html | 305 -------- .../javascript_technologies_overview/index.html | 88 --- .../web/javascript/language_resources/index.html | 136 ---- .../id/web/javascript/memory_management/index.html | 187 ----- files/id/web/javascript/reference/about/index.html | 86 -- .../reference/classes/constructor/index.html | 162 ---- .../reference/classes/extends/index.html | 112 --- .../id/web/javascript/reference/classes/index.html | 383 --------- .../errors/called_on_incompatible_type/index.html | 69 -- .../id/web/javascript/reference/errors/index.html | 12 - .../errors/invalid_array_length/index.html | 78 -- .../missing_semicolon_before_statement/index.html | 78 -- .../errors/negative_repetition_count/index.html | 45 -- .../reference/errors/not_a_codepoint/index.html | 56 -- .../reference/errors/not_defined/index.html | 66 -- .../errors/property_access_denied/index.html | 47 -- .../reference/errors/too_much_recursion/index.html | 70 -- .../web/javascript/reference/functions/index.html | 596 -------------- .../global_objects/array/concat/index.html | 169 ---- .../global_objects/array/filter/index.html | 244 ------ .../reference/global_objects/array/from/index.html | 248 ------ .../reference/global_objects/array/index.html | 484 ------------ .../global_objects/array/isarray/index.html | 144 ---- .../reference/global_objects/array/join/index.html | 132 ---- .../global_objects/array/length/index.html | 145 ---- .../reference/global_objects/array/of/index.html | 129 --- .../reference/global_objects/array/pop/index.html | 134 ---- .../global_objects/array/reverse/index.html | 127 --- .../global_objects/array/shift/index.html | 129 --- .../global_objects/array/slice/index.html | 152 ---- .../global_objects/array/splice/index.html | 146 ---- .../global_objects/array/unshift/index.html | 135 ---- .../global_objects/array/values/index.html | 120 --- .../global_objects/date/getfullyear/index.html | 88 --- .../reference/global_objects/date/index.html | 261 ------- .../reference/global_objects/date/now/index.html | 124 --- .../global_objects/date/tojson/index.html | 119 --- .../global_objects/date/totimestring/index.html | 125 --- .../reference/global_objects/error/index.html | 231 ------ .../reference/global_objects/error/name/index.html | 119 --- .../global_objects/function/displayname/index.html | 123 --- .../reference/global_objects/function/index.html | 241 ------ .../global_objects/function/length/index.html | 148 ---- .../global_objects/function/name/index.html | 191 ----- .../javascript/reference/global_objects/index.html | 189 ----- .../reference/global_objects/isnan/index.html | 186 ----- .../reference/global_objects/json/index.html | 243 ------ .../reference/global_objects/json/parse/index.html | 171 ---- .../reference/global_objects/map/clear/index.html | 109 --- .../reference/global_objects/map/delete/index.html | 114 --- .../reference/global_objects/map/index.html | 443 ----------- .../reference/global_objects/math/abs/index.html | 145 ---- .../reference/global_objects/math/ceil/index.html | 174 ----- .../reference/global_objects/math/e/index.html | 81 -- .../reference/global_objects/math/floor/index.html | 210 ----- .../reference/global_objects/math/index.html | 213 ----- .../reference/global_objects/math/ln10/index.html | 81 -- .../reference/global_objects/math/max/index.html | 144 ---- .../reference/global_objects/math/min/index.html | 150 ---- .../reference/global_objects/math/pow/index.html | 53 -- .../object/getprototypeof/index.html | 133 ---- .../reference/global_objects/object/index.html | 221 ------ .../global_objects/object/keys/index.html | 197 ----- .../object/preventextensions/index.html | 185 ----- .../global_objects/promise/catch/index.html | 127 --- .../reference/global_objects/promise/index.html | 317 -------- .../global_objects/promise/reject/index.html | 81 -- .../global_objects/promise/resolve/index.html | 140 ---- .../global_objects/promise/then/index.html | 132 ---- .../reference/global_objects/regexp/index.html | 231 ------ .../global_objects/string/charat/index.html | 238 ------ .../global_objects/string/concat/index.html | 134 ---- .../global_objects/string/fromcharcode/index.html | 143 ---- .../global_objects/string/fromcodepoint/index.html | 149 ---- .../reference/global_objects/string/index.html | 371 --------- .../global_objects/string/indexof/index.html | 190 ----- .../global_objects/string/length/index.html | 126 --- .../global_objects/string/link/index.html | 130 ---- .../global_objects/string/split/index.html | 241 ------ .../global_objects/string/tolowercase/index.html | 121 --- .../global_objects/string/tostring/index.html | 118 --- .../global_objects/string/touppercase/index.html | 115 --- .../reference/global_objects/typedarray/index.html | 344 -------- .../global_objects/typedarray/join/index.html | 114 --- files/id/web/javascript/reference/index.html | 48 -- .../reference/lexical_grammar/index.html | 670 ---------------- .../operators/conditional_operator/index.html | 167 ---- .../reference/operators/function/index.html | 154 ---- .../web/javascript/reference/operators/index.html | 269 ------- .../reference/operators/yield/index.html | 109 --- .../reference/statements/class/index.html | 171 ---- .../reference/statements/do...while/index.html | 101 --- .../reference/statements/empty/index.html | 147 ---- .../reference/statements/export/index.html | 171 ---- .../reference/statements/for...in/index.html | 201 ----- .../reference/statements/function/index.html | 233 ------ .../web/javascript/reference/statements/index.html | 139 ---- 107 files changed, 20286 deletions(-) delete mode 100644 files/id/web/javascript/a_re-introduction_to_javascript/index.html delete mode 100644 files/id/web/javascript/closures/index.html delete mode 100644 files/id/web/javascript/data_structures/index.html delete mode 100644 files/id/web/javascript/guide/grammar_and_types/index.html delete mode 100644 files/id/web/javascript/guide/index.html delete mode 100644 files/id/web/javascript/guide/introduction/index.html delete mode 100644 files/id/web/javascript/guide/loops_and_iteration/index.html delete mode 100644 files/id/web/javascript/guide/numbers_and_dates/index.html delete mode 100644 files/id/web/javascript/guide/working_with_objects/index.html delete mode 100644 files/id/web/javascript/index.html delete mode 100644 files/id/web/javascript/inheritance_and_the_prototype_chain/index.html delete mode 100644 files/id/web/javascript/javascript_technologies_overview/index.html delete mode 100644 files/id/web/javascript/language_resources/index.html delete mode 100644 files/id/web/javascript/memory_management/index.html delete mode 100644 files/id/web/javascript/reference/about/index.html delete mode 100644 files/id/web/javascript/reference/classes/constructor/index.html delete mode 100644 files/id/web/javascript/reference/classes/extends/index.html delete mode 100644 files/id/web/javascript/reference/classes/index.html delete mode 100644 files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html delete mode 100644 files/id/web/javascript/reference/errors/index.html delete mode 100644 files/id/web/javascript/reference/errors/invalid_array_length/index.html delete mode 100644 files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/id/web/javascript/reference/errors/negative_repetition_count/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_a_codepoint/index.html delete mode 100644 files/id/web/javascript/reference/errors/not_defined/index.html delete mode 100644 files/id/web/javascript/reference/errors/property_access_denied/index.html delete mode 100644 files/id/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/id/web/javascript/reference/functions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/getfullyear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/now/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/tojson/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/date/totimestring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/error/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/displayname/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/function/name/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/isnan/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/json/parse/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/clear/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/delete/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/abs/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/e/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/floor/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/ln10/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/max/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/min/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/math/pow/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/keys/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/object/preventextensions/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/reject/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/resolve/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/promise/then/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/charat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/concat/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/link/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/split/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tolowercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/tostring/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/string/touppercase/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/index.html delete mode 100644 files/id/web/javascript/reference/global_objects/typedarray/join/index.html delete mode 100644 files/id/web/javascript/reference/index.html delete mode 100644 files/id/web/javascript/reference/lexical_grammar/index.html delete mode 100644 files/id/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/id/web/javascript/reference/operators/function/index.html delete mode 100644 files/id/web/javascript/reference/operators/index.html delete mode 100644 files/id/web/javascript/reference/operators/yield/index.html delete mode 100644 files/id/web/javascript/reference/statements/class/index.html delete mode 100644 files/id/web/javascript/reference/statements/do...while/index.html delete mode 100644 files/id/web/javascript/reference/statements/empty/index.html delete mode 100644 files/id/web/javascript/reference/statements/export/index.html delete mode 100644 files/id/web/javascript/reference/statements/for...in/index.html delete mode 100644 files/id/web/javascript/reference/statements/function/index.html delete mode 100644 files/id/web/javascript/reference/statements/index.html (limited to 'files/id/web/javascript') diff --git a/files/id/web/javascript/a_re-introduction_to_javascript/index.html b/files/id/web/javascript/a_re-introduction_to_javascript/index.html deleted file mode 100644 index 5b7ef3b14e..0000000000 --- a/files/id/web/javascript/a_re-introduction_to_javascript/index.html +++ /dev/null @@ -1,862 +0,0 @@ ---- -title: Sebuah pengenalan ulang pada bahasa JavaScript (tutorial JS) -slug: Web/JavaScript/A_re-introduction_to_JavaScript -translation_of: Web/JavaScript/A_re-introduction_to_JavaScript ---- -
{{jsSidebar}}
- -

Pengantar

- -

Mengapa melakukan pengenalan ulang? Karena bahasa {{Glossary("JavaScript")}} terkenal dengan cap buruk sebagai bahasa pemprograman yang paling sering membuat kesalahpahaman di dunia. Sering kali JavaScript diejek sebagai sebuah mainan (layaknya mobil-mobilan) karena terlihat sederhana, tetapi dibalik kesederhanaannya tersebut, terdapat beberapa fitur yang sangat andal. Saat ini JavaScript digunakan oleh aplikasi-aplikasi terkenal dalam jumlah yang luar biasa banyaknya, memiliki pengetahuan yang mendalam tentang teknologi ini adalah salah satu skill penting bagi para pengembang web atau mobile.

- -

Ada baiknya kita memulai pengenalan ini dengan mengetahui sekilas gambaran sejarah dari bahasa pemograman ini. JavaScript dibuat pada tahun 1995 oleh Brendan Eich ketika dia menjadi seorang insinyur perangkat lunak di Netscape. JavaScript dirilis bersamaan dengan Netscape 2 di permulaan tahun 1996. Awalnya JavaScript dinamakan LiveScript, tetapi diganti menjadi JavaScript karena  memanfaatkan ketenaran bahasa pemograman Java dari Sun Microsystem, walaupun keduanya memiliki sedikit sekali kesamaan. Hal inilah yang menjadi sumber kebingungan sejak saat itu.

- -

Beberapa bulan kemudian, Microsoft merilis JScript yang tertanam di dalam Internet Explore 3. Sebagian besar JScript kompatible dan mirip dengan JavaScript. Beberapa bulan setelahnya Netscape mengajukan JavaScript ke  Ecma International, Organisasi Eropa yang melakukan standarisasi sistem informasi dan komunikasi, yang kemudian menghasilkan edisi pertama dari standar {{Glossary("ECMAScript")}} pada tahun itu. Standar ini memperoleh pembaharuan yang signifikan pada ECMAScript edisi ke-3 pada tahun 1999, dan sejak saat itu standar tersebut tidak terlalu banyak mengalami perubahan. Edisi ke-4 ECMAScript diabaikan dengan alasan perbedaan pandangan terhadap kompleksitas bahasa. Beberapa bagian dari edisi ECMAScript ke-4  membentuk dasar ECMAScript edisi ke-5, yang dipublikasi pada tahun 2009 and edisi ECMAScript ke-6 dirilis pada bulan Juni tahun 2015.

- -
-

Karena lebih familiar, mulai dari sini kita akan mengacu ECMAScript sebagai "JavaScript".

-
- -

Tidak seperti kebanyakan bahasa pemograman, JavaScript tidak mempunyai konsep input atau output (I/O). Didesain untuk dapat dieksekusi sebagai bahasa scripting pada lingkungan pengguna dan mekanisme komunikasi dengan dunia luar diserahkan kepada lingkungan pengguna. Browser adalah lingkungan pengguna yang sangat umum, tetapi Interpreter JavaScript dapat juga ditemukan ditempat lain, termasuk Adobe Acrobat, Adobe Photshop, SVG images, Yahoo Widget engine, lingkungan server seperti Node.js, database NoSQL  seperti Apache CouchDB, komputer tertanam, lingkungan desktop seperti GNOME (salah satu antarmuka yang paling terkenal pada sustem operasi GNU/Linux), dan masih banyak lagi yang lainnya.
-  

- -

Ikhtisar

- -

JavaScript adalah bahasa pemograman dinamis berorientasi objek dengan types dan operator, objek bawaan standar (objek literal),  dan methods. Syntax JavaScript dipengaruhi oleh bahasa Java dan C - sangat banyak struktur dalam bahasa tersebut yang digunakan dalam JavaScript. Perbedaan yang paling mendasar adalah JavaScript tidak mempunyai kelas, melainkan fungsionalitas kelas yang dicapai dengan obyek prototipe (Lebih lanjut tentang ES6 {{jsxref("Classes")}}). Perbedaan utama lainnya adalah fungsi sebagai objek, yaitu fungsi mempunyai kapasitas untuk menahan kode yang dapat dieksekusi dan dilewatkan seperti objek yang lain.

- -

Mari mulai dengan melihat blok pembangun dari bahasa pemograman: types (tipe-tipe data). Program pada JavaScript memanipulasi nilai dan nilai tersebut termasuk ke dalam sebuah tipe. Beberapa tipe dalam JavaScript adalah:
-  

- - - -

...ooo, ada lagi {{jsxref("undefined")}} and {{jsxref("null")}} keduanya mempunyai karakteristik yang sedikit ganjil, {{jsxref("Array")}} merupakan objek spesial, {{jsxref("Date")}} dan {{jsxref("RegExp")}} merupakan objek yang dapat digunakan langsung dan untuk lebih tepatnya, fungsi termasuk dalam objek spesial. Jadi, diagramnya kira-kira seperti ini:

- - - -

Ada beberapa tipe {{jsxref("Error")}} bawaan juga, akan lebih memudahkan jika kita mempelajari terlebih dahulu diagram pertama, bagaimanapun juga kita akan membahas tipe - tipe yang telah dituliskan diatas.

- -

Numbers

- -

Menurut spesifikasi, tipe nomer pada JavaScript menggunakan "format IEEE 754 64-bit double-presisi". Hal ini menyebabkan beberapa konsekuensi, diantaranya tidak adanya tipe integer pada JavaScript. Jadi programmer harus agak teliti dengan operasi aritmatika jika sebelumnya berangkat dari C atau Java.
-
- Perlu juga memperhatikan kasus seperti berikut:

- -
0.1 + 0.2 == 0.30000000000000004
-
- -

Dalam praktiknya, nilai integer diperlakukan sebagai int 32-bit, dan beberapa implementasi bahkan menyimpannya demikian (dalam int 32-bit) kecuali diinstruksikan agar nilai tersebut valid sebagai tipe Number namun tidak dalam integer 32-bit. Hal ini mungkin saja penting untuk operasi yang mementingkan ukuran bit.

- -

Standar operasi aritmatika tersedia, seperti penjumlahan, pengurangan, modulus, dan lain-lain. Ada juga Object bawaan yang kami lupa menyebutkannya di awal disebut {{jsxref("Math")}} yang menyediakan fungsi matematika dan konstan:

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

Anda dapat mengonversi sebuah string ke integer dengan menggunakan fungsi bawaan  {{jsxref("Global_objeks/parseInt", "parseInt()")}}. Basis konversi dapat ditambahkan sebagai argumen kedua (tidak wajib), namun sebaiknya ditambahkan:

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

Pada peramban kuno, string yang diawali dengan "0" diasumsikan sebagai octal (radix 8), namun hal ini tidak lagi menjadi masalah sejak 2013 dan seterusnya. Kecuali Anda sudah yakin mengenai format string-nya, Anda akan mendapatkan hasil mengejutkan pada peramban kuno tersebut:

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

Di sini, kita melihat fungsi {{jsxref("Global_objeks/parseInt", "parseInt()")}} memperlakukan string pertama sebagai oktal karena diawali dengan "0", dan string kedua sebagai hexadecimal karena diawali dengan "0x". Notasi heksadesimal masih ada; hanya oktal yang telah dihapus.

- -

If you want to convert a binary number to an integer, just change the base:

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

Similarly, you can parse floating point numbers using the built-in {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} function. Unlike its {{jsxref("Global_objeks/parseInt", "parseInt()")}} cousin, parseFloat() always uses base 10.

- -

You can also use the unary + operator to convert values to numbers:

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

A special value called {{jsxref("NaN")}} (short for "Not a Number") is returned if the string is non-numeric:

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

NaN is toxic: if you provide it as an input to any mathematical operation the result will also be NaN:

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

You can test for NaN using the built-in {{jsxref("Global_objeks/isNaN", "isNaN()")}} function:

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

JavaScript also has the special values {{jsxref("Infinity")}} and -Infinity:

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

You can test for Infinity, -Infinity and NaN values using the built-in {{jsxref("Global_objeks/isFinite", "isFinite()")}} function:

- -
isFinite(1/0); // false
-isFinite(-Infinity); // false
-isFinite(NaN); // false
-
- -
The {{jsxref("Global_objeks/parseInt", "parseInt()")}} and {{jsxref("Global_objeks/parseFloat", "parseFloat()")}} functions parse a string until they reach a character that isn't valid for the specified number format, then return the number parsed up to that point. However the "+" operator simply converts the string to NaN if there is an invalid character contained within it. Just try parsing the string "10.2abc" with each method by yourself in the console and you'll understand the differences better.
- -

Strings

- -

Strings in JavaScript are sequences of Unicode characters. This should be welcome news to anyone who has had to deal with internationalization. More accurately, they are sequences of UTF-16 code units; each code unit is represented by a 16-bit number. Each Unicode character is represented by either 1 or 2 code units.

- -

If you want to represent a single character, you just use a string consisting of that single character.

- -

To find the length of a string (in code units), access its length property:

- -
"hello".length; // 5
-
- -

There's our first brush with JavaScript objeks! Did we mention that you can use strings like {{jsxref("objek", "objeks", "", 1)}} too? They have {{jsxref("String", "methods", "#Methods", 1)}} as well that allow you to manipulate the string and access information about the string:

- -
"hello".charAt(0); // "h"
-"hello, world".replace("hello", "goodbye"); // "goodbye, world"
-"hello".toUpperCase(); // "HELLO"
-
- -

Other types

- -

JavaScript distinguishes between {{jsxref("null")}}, which is a value that indicates a deliberate non-value (and is only accessible through the null keyword), and {{jsxref("undefined")}}, which is a value of type undefined that indicates an uninitialized value — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant.

- -

JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:

- -
    -
  1. false, 0, empty strings (""), NaN, null, and undefined all become false.
  2. -
  3. All other values become true.
  4. -
- -

You can perform this conversion explicitly using the Boolean() function:

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

However, this is rarely necessary, as JavaScript will silently perform this conversion when it expects a boolean, such as in an if statement (see below.) For this reason, we sometimes speak simply of "true values" and "false values," meaning values that become true and false, respectively, when converted to booleans. Alternatively, such values can be called "truthy" and "falsy", respectively.

- -

Boolean operations such as && (logical and), || (logical or), and ! (logical not) are supported; see below.

- -

Variables

- -

New variables in JavaScript are declared using the var keyword:

- -
var a;
-var name = "simon";
-
- -

If you declare a variable without assigning any value to it, its type is undefined.

- -

An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript Edition 6, let and const declarations allow you to create block-scoped variables.

- -

Operators

- -

JavaScript's numeric operators are +, -, *, / and % — which is the remainder operator (which is not the same as modulo.) Values are assigned using =, and there are also compound assignment statements such as += and -=. These extend out to x = x operator y.

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

You can use ++ and -- to increment and decrement respectively. These can be used as prefix or postfix operators.

- -

The + operator also does string concatenation:

- -
"hello" + " world"; // "hello world"
-
- -

If you add a string to a number (or other value) everything is converted in to a string first. This might catch you up:

- -
"3" + 4 + 5;  // "345"
- 3 + 4 + "5"; // "75"
-
- -

Adding an empty string to something is a useful way of converting it to a string itself.

- -

Comparisons in JavaScript can be made using <, >, <= and >=. These work for both strings and numbers. Equality is a little less straightforward. The double-equals operator performs type coercion if you give it different types, with sometimes interesting results:

- -
123 == "123"; // true
-1 == true; // true
-
- -

To avoid type coercion and make sure your comparisons are always accurate, you should always use the triple-equals operator:

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

There are also != and !== operators.

- -

JavaScript also has bitwise operations. If you want to use them, they're there.

- -

Control structures

- -

JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together if you like:

- -
var name = "kittens";
-if (name == "puppies") {
-  name += "!";
-} else if (name == "kittens") {
-  name += "!!";
-} else {
-  name = "!" + name;
-}
-name == "kittens!!"
-
- -

JavaScript has while loops and do-while loops. The first is good for basic looping; the second for loops where you wish to ensure that the body of the loop is executed at least once:

- -
while (true) {
-  // an infinite loop!
-}
-
-var input;
-do {
-  input = get_input();
-} while (inputIsNotValid(input))
-
- -

JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.

- -
for (var i = 0; i < 5; i++) {
-  // Will execute 5 times
-}
-
- -

The && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. This is useful for checking for null objeks before accessing their attributes:

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

Or for setting default values:

- -
var name = otherName || "default";
-
- -

JavaScript has a ternary operator for conditional expressions:

- -
var allowed = (age > 18) ? "yes" : "no";
-
- -

The switch statement can be used for multiple branches based on a number or string:

- -
switch(action) {
-  case 'draw':
-    drawIt();
-    break;
-  case 'eat':
-    eatIt();
-    break;
-  default:
-    doNothing();
-}
-
- -

If you don't add a break statement, execution will "fall through" to the next level. This is very rarely what you want — in fact it's worth specifically labeling deliberate fallthrough with a comment if you really meant it to aid debugging:

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

The default clause is optional. You can have expressions in both the switch part and the cases if you like; comparisons take place between the two using the === operator:

- -
switch(1 + 3) {
-  case 2 + 2:
-    yay();
-    break;
-  default:
-    neverhappens();
-}
-
- -

objeks

- -

JavaScript objeks can be thought of as simple collections of name-value pairs. As such, they are similar to:

- - - -

The fact that this data structure is so widely used is a testament to its versatility. Since everything (bar core types) in JavaScript is an objek, any JavaScript program naturally involves a great deal of hash table lookups. It's a good thing they're so fast!

- -

The "name" part is a JavaScript string, while the value can be any JavaScript value — including more objeks. This allows you to build data structures of arbitrary complexity.

- -

There are two basic ways to create an empty objek:

- -
var obj = new objek();
-
- -

And:

- -
var obj = {};
-
- -

These are semantically equivalent; the second is called objek literal syntax, and is more convenient. This syntax is also the core of JSON format and should be preferred at all times.

- -

objek literal syntax can be used to initialize an objek in its entirety:

- -
var obj = {
-  name: "Carrot",
-  "for": "Max",
-  details: {
-    color: "orange",
-    size: 12
-  }
-}
-
- -

Attribute access can be chained together:

- -
obj.details.color; // orange
-obj["details"]["size"]; // 12
-
- -

The following example creates an objek prototype, Person, and instance of that prototype, You.

- -
function Person(name, age) {
-  this.name = name;
-  this.age = age;
-}
-
-// Define an objek
-var You = new Person("You", 24);
-// We are creating a new person named "You"
-// (that was the first parameter, and the age..)
-
- -

Once created, an objek's properties can again be accessed in one of two ways:

- -
obj.name = "Simon";
-var name = obj.name;
-
- -

And...

- -
obj["name"] = "Simon";
-var name = obj["name"];
-
- -

These are also semantically equivalent. The second method has the advantage that the name of the property is provided as a string, which means it can be calculated at run-time. However, using this method prevents some JavaScript engine and minifier optimizations being applied. It can also be used to set and get properties with names that are reserved words:

- -
obj.for = "Simon"; // Syntax error, because 'for' is a reserved word
-obj["for"] = "Simon"; // works fine
-
- -
-

Starting in ECMAScript 5, reserved words may be used as objek property names "in the buff". This means that they don't need to be "clothed" in quotes when defining objek literals. See the ES5 Spec.

-
- -

For more on objeks and prototypes see: objek.prototype.

- -

Arrays

- -

Arrays in JavaScript are actually a special type of objek. They work very much like regular objeks (numerical properties can naturally be accessed only using [] syntax) but they have one magic property called 'length'. This is always one more than the highest index in the array.

- -

One way of creating arrays is as follows:

- -
var a = new Array();
-a[0] = "dog";
-a[1] = "cat";
-a[2] = "hen";
-a.length; // 3
-
- -

A more convenient notation is to use an array literal:

- -
var a = ["dog", "cat", "hen"];
-a.length; // 3
-
- -

Note that array.length isn't necessarily the number of items in the array. Consider the following:

- -
var a = ["dog", "cat", "hen"];
-a[100] = "fox";
-a.length; // 101
-
- -

Remember — the length of the array is one more than the highest index.

- -

If you query a non-existent array index, you'll get a value of undefined returned:

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

If you take the above into account, you can iterate over an array using the following:

- -
for (var i = 0; i < a.length; i++) {
-  // Do something with a[i]
-}
-
- -

You can iterate over an array using a for...in loop. Note that if someone added new properties to Array.prototype, they will also be iterated over by this loop.  Therefore this method is "not" recommended.

- -

Another way of iterating over an array that was added with ECMAScript 5 is forEach():

- -
["dog", "cat", "hen"].forEach(function(currentValue, index, array) {
-  // Do something with currentValue or array[index]
-});
-
- -

If you want to append an item to an array simply do it like this:

- -
a.push(item);
- -

Arrays come with a number of methods. See also the full documentation for array methods.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Method nameDescription
a.toString()Returns a string with the toString() of each element separated by commas.
a.toLocaleString()Returns a string with the toLocaleString() of each element separated by commas.
a.concat(item1[, item2[, ...[, itemN]]])Returns a new array with the items added on to it.
a.join(sep)Converts the array to a string — with values delimited by the sep param
a.pop()Removes and returns the last item.
a.push(item1, ..., itemN)Adds one or more items to the end.
a.reverse()Reverses the array.
a.shift()Removes and returns the first item.
a.slice(start[, end])Returns a sub-array.
a.sort([cmpfn])Takes an optional comparison function.
a.splice(start, delcount[, item1[, ...[, itemN]]])Lets you modify an array by deleting a section and replacing it with more items.
a.unshift(item1[, item2[, ...[, itemN]]])Prepends items to the start of the array.
- -

Functions

- -

Along with objeks, functions are the core component in understanding JavaScript. The most basic function couldn't be much simpler:

- -
function add(x, y) {
-  var total = x + y;
-  return total;
-}
-
- -

This demonstrates a basic function. A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

- -

The named parameters turn out to be more like guidelines than anything else. You can call a function without passing the parameters it expects, in which case they will be set to undefined.

- -
add(); // NaN
-// You can't perform addition on undefined
-
- -

You can also pass in more arguments than the function is expecting:

- -
add(2, 3, 4); // 5
-// added the first two; 4 was ignored
-
- -

That may seem a little silly, but functions have access to an additional variable inside their body called arguments, which is an array-like objek holding all of the values passed to the function. Let's re-write the add function to take as many values as we want:

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

That's really not any more useful than writing 2 + 3 + 4 + 5 though. Let's create an averaging function:

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

This is pretty useful, but introduces a new problem. The avg() function takes a comma separated list of arguments — but what if you want to find the average of an array? You could just rewrite the function as follows:

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

But it would be nice to be able to reuse the function that we've already created. Luckily, JavaScript lets you call a function and call it with an arbitrary array of arguments, using the {{jsxref("Function.apply", "apply()")}} method of any function objek.

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

The second argument to apply() is the array to use as arguments; the first will be discussed later on. This emphasizes the fact that functions are objeks too.

- -

JavaScript lets you create anonymous functions.

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

This is semantically equivalent to the function avg() form. It's extremely powerful, as it lets you put a full function definition anywhere that you would normally put an expression. This enables all sorts of clever tricks. Here's a way of "hiding" some local variables — like block scope in C:

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

JavaScript allows you to call functions recursively. This is particularly useful for dealing with tree structures, such as those found in the browser DOM.

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

This highlights a potential problem with anonymous functions: how do you call them recursively if they don't have a name? JavaScript lets you name function expressions for this. You can use named IIFEs (Immediately Invoked Function Expressions) as shown below:

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

The name provided to a function expression as above is only available to the function's own scope. This allows more optimizations to be done by the engine and results in more readable code. The name also shows up in the debugger and some stack traces, which can save you time when debugging.

- -

Note that JavaScript functions are themselves objeks — like everything else in JavaScript — and you can add or change properties on them just like we've seen earlier in the objeks section.

- -

Custom objeks

- -
For a more detailed discussion of objek-oriented programming in JavaScript, see Introduction to objek Oriented JavaScript.
- -

In classic objek Oriented Programming, objeks are collections of data and methods that operate on that data. JavaScript is a prototype-based language that contains no class statement, as you'd find in C++ or Java (this is sometimes confusing for programmers accustomed to languages with a class statement.) Instead, JavaScript uses functions as classes. Let's consider a person objek with first and last name fields. There are two ways in which the name might be displayed: as "first last" or as "last, first". Using the functions and objeks that we've discussed previously, we could display the data like this:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last
-  };
-}
-function personFullName(person) {
-  return person.first + ' ' + person.last;
-}
-function personFullNameReversed(person) {
-  return person.last + ', ' + person.first;
-}
-
-s = makePerson("Simon", "Willison");
-personFullName(s); // "Simon Willison"
-personFullNameReversed(s); // "Willison, Simon"
-
- -

This works, but it's pretty ugly. You end up with dozens of functions in your global namespace. What we really need is a way to attach a function to an objek. Since functions are objeks, this is easy:

- -
function makePerson(first, last) {
-  return {
-    first: first,
-    last: last,
-    fullName: function() {
-      return this.first + ' ' + this.last;
-    },
-    fullNameReversed: function() {
-      return this.last + ', ' + this.first;
-    }
-  };
-}
-
-s = makePerson("Simon", "Willison")
-s.fullName(); // "Simon Willison"
-s.fullNameReversed(); // "Willison, Simon"
-
- -

There's something here we haven't seen before: the this keyword. Used inside a function, this refers to the current objek. What that actually means is specified by the way in which you called that function. If you called it using dot notation or bracket notation on an objek, that objek becomes this. If dot notation wasn't used for the call, this refers to the global objek.

- -

Note that this is a frequent cause of mistakes. For example:

- -
s = makePerson("Simon", "Willison");
-var fullName = s.fullName;
-fullName(); // undefined undefined
-
- -

When we call fullName() alone, without using s.fullName(), this is bound to the global objek. Since there are no global variables called first or last we get undefined for each one.

- -

We can take advantage of the this keyword to improve our makePerson function:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = function() {
-    return this.first + ' ' + this.last;
-  };
-  this.fullNameReversed = function() {
-    return this.last + ', ' + this.first;
-  };
-}
-var s = new Person("Simon", "Willison");
-
- -

We have introduced another keyword: new. new is strongly related to this. It creates a brand new empty objek, and then calls the function specified, with this set to that new objek. Notice though that the function specified with this does not return a value but merely modifies the this objek. It's new that returns the this objek to the calling site. Functions that are designed to be called by new are called constructor functions. Common practice is to capitalize these functions as a reminder to call them with new.

- -

The improved function still has the same pitfall with calling fullName() alone.

- -

Our person objeks are getting better, but there are still some ugly edges to them. Every time we create a person objek we are creating two brand new function objeks within it — wouldn't it be better if this code was shared?

- -
function personFullName() {
-  return this.first + ' ' + this.last;
-}
-function personFullNameReversed() {
-  return this.last + ', ' + this.first;
-}
-function Person(first, last) {
-  this.first = first;
-  this.last = last;
-  this.fullName = personFullName;
-  this.fullNameReversed = personFullNameReversed;
-}
-
- -

That's better: we are creating the method functions only once, and assigning references to them inside the constructor. Can we do any better than that? The answer is yes:

- -
function Person(first, last) {
-  this.first = first;
-  this.last = last;
-}
-Person.prototype.fullName = function() {
-  return this.first + ' ' + this.last;
-};
-Person.prototype.fullNameReversed = function() {
-  return this.last + ', ' + this.first;
-};
-
- -

Person.prototype is an objek shared by all instances of Person. It forms part of a lookup chain (that has a special name, "prototype chain"): any time you attempt to access a property of Person that isn't set, JavaScript will check Person.prototype to see if that property exists there instead. As a result, anything assigned to Person.prototype becomes available to all instances of that constructor via the this objek.

- -

This is an incredibly powerful tool. JavaScript lets you modify something's prototype at any time in your program, which means you can add extra methods to existing objeks at runtime:

- -
s = new Person("Simon", "Willison");
-s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function
-
-Person.prototype.firstNameCaps = function firstNameCaps() {
-  return this.first.toUpperCase()
-};
-s.firstNameCaps(); // "SIMON"
-
- -

Interestingly, you can also add things to the prototype of built-in JavaScript objeks. Let's add a method to String that returns that string in reverse:

- -
var s = "Simon";
-s.reversed(); // TypeError on line 1: s.reversed is not a function
-
-String.prototype.reversed = function reversed() {
-  var r = "";
-  for (var i = this.length - 1; i >= 0; i--) {
-    r += this[i];
-  }
-  return r;
-};
-
-s.reversed(); // nomiS
-
- -

Our new method even works on string literals!

- -
"This can now be reversed".reversed(); // desrever eb won nac sihT
-
- -

As mentioned before, the prototype forms part of a chain. The root of that chain is objek.prototype, whose methods include toString() — it is this method that is called when you try to represent an objek as a string. This is useful for debugging our Person objeks:

- -
var s = new Person("Simon", "Willison");
-s; // [objek objek]
-
-Person.prototype.toString = function() {
-  return '<Person: ' + this.fullName() + '>';
-}
-
-s.toString(); // "<Person: Simon Willison>"
-
- -

Remember how avg.apply() had a null first argument? We can revisit that now. The first argument to apply() is the objek that should be treated as 'this'. For example, here's a trivial implementation of new:

- -
function trivialNew(constructor, ...args) {
-  var o = {}; // Create an objek
-  constructor.apply(o, args);
-  return o;
-}
-
- -

This isn't an exact replica of new as it doesn't set up the prototype chain (it would be difficult to illustrate). This is not something you use very often, but it's useful to know about. In this snippet, ...args (including the ellipsis) is called the "rest arguments" — as the name implies, this contains the rest of the arguments.

- -

Calling

- -
var bill = trivialNew(Person, "William", "Orange");
- -

is therefore almost equivalent to

- -
var bill = new Person("William", "Orange");
- -

apply() has a sister function named call, which again lets you set this but takes an expanded argument list as opposed to an array.

- -
function lastNameCaps() {
-  return this.last.toUpperCase();
-}
-var s = new Person("Simon", "Willison");
-lastNameCaps.call(s);
-// Is the same as:
-s.lastNameCaps = lastNameCaps;
-s.lastNameCaps();
-
- -

Inner functions

- -

JavaScript function declarations are allowed inside other functions. We've seen this once before, with an earlier makePerson() function. An important detail of nested functions in JavaScript is that they can access variables in their parent function's scope:

- -
function betterExampleNeeded() {
-  var a = 1;
-  function oneMoreThanA() {
-    return a + 1;
-  }
-  return oneMoreThanA();
-}
-
- -

This provides a great deal of utility in writing more maintainable code. If a function relies on one or two other functions that are not useful to any other part of your code, you can nest those utility functions inside the function that will be called from elsewhere. This keeps the number of functions that are in the global scope down, which is always a good thing.

- -

This is also a great counter to the lure of global variables. When writing complex code it is often tempting to use global variables to share values between multiple functions — which leads to code that is hard to maintain. Nested functions can share variables in their parent, so you can use that mechanism to couple functions together when it makes sense without polluting your global namespace — "local globals" if you like. This technique should be used with caution, but it's a useful ability to have.

- -

Closures

- -

This leads us to one of the most powerful abstractions that JavaScript has to offer — but also the most potentially confusing. What does this do?

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

The name of the makeAdder() function should give it away: it creates a new 'adder' functions, which when called with one argument adds it to the argument that they were created with.

- -

What's happening here is pretty much the same as was happening with the inner functions earlier on: a function defined inside another function has access to the outer function's variables. The only difference here is that the outer function has returned, and hence common sense would seem to dictate that its local variables no longer exist. But they do still exist — otherwise the adder functions would be unable to work. What's more, there are two different "copies" of makeAdder()'s local variables — one in which a is 5 and one in which a is 20. So the result of those function calls is as follows:

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

Here's what's actually happening. Whenever JavaScript executes a function, a 'scope' objek is created to hold the local variables created within that function. It is initialized with any variables passed in as function parameters. This is similar to the global objek that all global variables and functions live in, but with a couple of important differences: firstly, a brand new scope objek is created every time a function starts executing, and secondly, unlike the global objek (which is accessible as this and in browsers as window) these scope objeks cannot be directly accessed from your JavaScript code. There is no mechanism for iterating over the properties of the current scope objek, for example.

- -

So when makeAdder() is called, a scope objek is created with one property: a, which is the argument passed to the makeAdder() function. makeAdder() then returns a newly created function. Normally JavaScript's garbage collector would clean up the scope objek created for makeAdder() at this point, but the returned function maintains a reference back to that scope objek. As a result, the scope objek will not be garbage collected until there are no more references to the function objek that makeAdder() returned.

- -

Scope objeks form a chain called the scope chain, similar to the prototype chain used by JavaScript's objek system.

- -

A closure is the combination of a function and the scope objek in which it was created. Closures let you save state — as such, they can often be used in place of objeks. You can find several excellent introductions to closures.

diff --git a/files/id/web/javascript/closures/index.html b/files/id/web/javascript/closures/index.html deleted file mode 100644 index 8221ca46e6..0000000000 --- a/files/id/web/javascript/closures/index.html +++ /dev/null @@ -1,346 +0,0 @@ ---- -title: Closures -slug: Web/JavaScript/Closures -translation_of: Web/JavaScript/Closures -original_slug: Web/JavaScript/Panduan/Closures ---- -

Closure adalah fungsi yang merujuk kepada variabel yang mandiri (bebas). 

- -

Dengan kata lain, fungsi yang di definisikan di dalam closure 'mengingat' lingkungan dimana closure ini didefinisikan. 

- -

Lihat contoh berikut:

- -
-
function init() {
-    var name = "Mozilla"; // name adalah sebuah lokal variabel yang dibuat oleh init
-    function displayName() { // displayName() adalah fungsi internal, sebuah closure
-        alert (name); // displayName() menggunakan variabel yang dideklarasikan pada fungsi induknya
-    }
-    displayName();
-}
-init();
-
-
- -

init() membuat sebuah lokal variabel name dan kemudian memanggil fungsi displayName(). displayName() adalah fungsi internal yang didefinisikan didalam init() dan hanya dapat diakses di dalam fungsi tersebut. displayName() tidak memiliki lokal variabelnya sendiri, namun fungsi ini memiliki akses ke variabel diluar fungsinya dan dapat menggunakan variabel name tersebut yang telah di deklarasikan di fungsi induknya.

- -

Jalankan kode dan perhatikan bahwa alert() dapat menampilkan isi dari variabel name, dimana variabel tersebut dideklarasikan pada fungsi induknya. Ini adalah sebuah contoh dari ruang lingkup leksikal (lexical scoping), yang menunjukan bagaimana cara javascript mencari variabel. Di Javascript lokasi dimana variabel tersebut dideklarasikan di dalam source code menentukan dimana variabel itu dapat diakses. Nested functions memiliki akses pada variabel yang dideklarasikan pada ruang lingkup induknya.

- -

Lihat contoh berikut:

- -
function makeFunc() {
-  var name = "Mozilla";
-  function displayName() {
-    alert(name);
-  }
-  return displayName;
-}
-
-var myFunc = makeFunc();
-myFunc();
-
- -

Jika kamu menjalankan kode ini, kode ini akan memiliki efek yang sama seperti contoh sebelumnya init(): teks "Mozilla" akan muncul di JavaScript alert box. Yang membedakan dan menarik adalah fungsi internal displayName() di kembalikan terlebih dahulu ke fungsi di luar sebelum di eksekusi.

- -

Jika dilihat ini agak aneh karena normalnya pada bahasa pemrograman lain, variabel lokal di dalam sebuah fungsi hanya ada saat fungsi tersebut dieksekusi. Sehingga saat makeFunc() selesai dieksekusi, sewajarnya variabel name ini tidak dapat diakses lagi. Namun, karena kode ini masih berjalan normal, ini adalah hal yang berbeda di Javascript.

- -

Alasannya adalah fungsi tersebut telah menjadi closure di javascript. Closure adalah kombinasi dari fungsi dan lingkungan leksikal dimana fungsi itu di deklarasikan. Lingkungan ini terdiri dari lokal variabel yang berada di ruang lingkup yang sama saat closure dibuat. Pada kasus ini, myFunc bereferensi kepada fungsi displayName yang telah dibuat ketika makeFunc dijalankan. Fungsi displayName akan tepat menjaga akses ke lingkungan leksikalnya, dimana variabel name ini aktif. Untuk alasan inilah, ketika myFunc di panggil, variabel name tetap dapat digunakan dan "Mozilla" dikirim ke alert box.

- -

Berikut adalah contoh menarik yang lainnya — fungsi makeAdder :

- -
function makeAdder(x) {
-  return function(y) {
-    return x + y;
-  };
-}
-
-var add5 = makeAdder(5);
-var add10 = makeAdder(10);
-
-console.log(add5(2));  // 7
-console.log(add10(2)); // 12
-
- -

Di contoh ini, kita telah mendefinisikan fungsi makeAdder(x) dengan satu argument x dan mengembalikan sebuah fungsi baru. Fungsi yang dikembalikan membutuhkan satu argumen y, dan mengembalikan jumlah x dan y.

- -

Esensinya, makeAdder adalah fungsi untuk membuat fungsi (function factory) — fungsi ini akan membuat fungsi yang akan menambahkan angka melalui argumen. Pada contoh diatas kita membuat dua fungsi baru — yang satu menambahkan 5 melalui argumentnya dan satu menambahkan 10.

- -

add5 dan add10 keduanya adalah closure. Fungsi ini menggunakan definisi fungsi yang sama, namun menggunakan memori yang berbeda. Di add5 variabel x memiliki nilai 5. sedangkan di add10 variabel x memiliki nilai 10.

- -

Penggunaan Closure

- -

Setelah membaca teorinya muncul pertanyaan —  Apakah closure berguna? Mari kita lihat implikasi dari penggunaan closure. Closure membantu kita mengakses data (pada lingkungannya) dengan fungsi yang mengoperasikan data tersebut. Ini berhubungan dengan object oriented programming, dimana objek obj0ek tersebut membantu kita dalam menghubukan beberapa data (properti objek) dengan satu atau lebih method.

- -

Karena itu, kamu dapat menggunakan closure dimanapun kamu dapat menggunakan objek dengan satu method.

- -

Situasi ini banyak ditemui umumnya pada pengembangan web. Banyak kode yang kita tulis di Javascript berdasarkan event — kita definisikan terlebih dahulu sifat dari event ini, kemudian menempelkannya pada event yang di panggil oleh user (seperti klik atau penekanan tombol). Kode kita secara garis umum adalah sebuah callback: sebuah fungsi yang dijalankan untuk merespon sebuah event.

- -

Berikut adalah contoh: kita ingin menambahkan beberapa tombol di sebuah halaman yang akan merubah ukuran teks. Cara untuk melakukannya adalah dengan menentukan ukuran huruf dari elemen body dalam satuan unit pixel, kemudian menentukan ukuran elemen lain di halaman (seperti header) menggunakan satuan unit em:

- -
body {
-  font-family: Helvetica, Arial, sans-serif;
-  font-size: 12px;
-}
-
-h1 {
-  font-size: 1.5em;
-}
-
-h2 {
-  font-size: 1.2em;
-}
-
- -

Tombol interaktif kita dapat merubah ukuran huruf dari elemen body dan elemen yang lainnya akan menyesuaikan.

- -

Berikut kode Javascript:

- -
function makeSizer(size) {
-  return function() {
-    document.body.style.fontSize = size + 'px';
-  };
-}
-
-var size12 = makeSizer(12);
-var size14 = makeSizer(14);
-var size16 = makeSizer(16);
-
- -

size12, size14, dan size16 adalah fungsi yang akan merubah ukuran teks body ke 12, 14, dan 16 pixel, secara berurutan. Kemudian kita tempelkan fungsi ini ke tombol (pada kasus ini adalah link) sebagai berikut:

- -
document.getElementById('size-12').onclick = size12;
-document.getElementById('size-14').onclick = size14;
-document.getElementById('size-16').onclick = size16;
-
- -
<a href="#" id="size-12">12</a>
-<a href="#" id="size-14">14</a>
-<a href="#" id="size-16">16</a>
-
- -

Lihat pada JSFiddle

- -

Emulating private methods with closures

- -

Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class.

- -

JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.

- -

Here's how to define some public functions that can access private functions and variables, using closures which is also known as the module pattern:

- -
var counter = (function() {
-  var privateCounter = 0;
-  function changeBy(val) {
-    privateCounter += val;
-  }
-  return {
-    increment: function() {
-      changeBy(1);
-    },
-    decrement: function() {
-      changeBy(-1);
-    },
-    value: function() {
-      return privateCounter;
-    }
-  };
-})();
-
-alert(counter.value()); /* Alerts 0 */
-counter.increment();
-counter.increment();
-alert(counter.value()); /* Alerts 2 */
-counter.decrement();
-alert(counter.value()); /* Alerts 1 */
-
- -

There's a lot going on here. In previous examples each closure has had its own environment; here we create a single environment which is shared by three functions: counter.increment, counter.decrement, and counter.value.

- -

The shared environment is created in the body of an anonymous function, which is executed as soon as it has been defined. The environment contains two private items: a variable called privateCounter and a function called changeBy. Neither of these private items can be accessed directly from outside the anonymous function. Instead, they must be accessed by the three public functions that are returned from the anonymous wrapper.

- -

Those three public functions are closures that share the same environment. Thanks to JavaScript's lexical scoping, they each have access to the privateCounter variable and changeBy function.

- -

You'll notice we're defining an anonymous function that creates a counter, and then we call it immediately and assign the result to the counter variable. We could store this function in a separate variable makeCounter and use it to create several counters.

- -
var makeCounter = function() {
-  var privateCounter = 0;
-  function changeBy(val) {
-    privateCounter += val;
-  }
-  return {
-    increment: function() {
-      changeBy(1);
-    },
-    decrement: function() {
-      changeBy(-1);
-    },
-    value: function() {
-      return privateCounter;
-    }
-  }
-};
-
-var counter1 = makeCounter();
-var counter2 = makeCounter();
-alert(counter1.value()); /* Alerts 0 */
-counter1.increment();
-counter1.increment();
-alert(counter1.value()); /* Alerts 2 */
-counter1.decrement();
-alert(counter1.value()); /* Alerts 1 */
-alert(counter2.value()); /* Alerts 0 */
-
- -

Notice how each of the two counters maintains its independence from the other. Its environment during the call of the makeCounter() function is different each time. The closure variable privateCounter contains a different instance each time.

- -

Using closures in this way provides a number of benefits that are normally associated with object oriented programming, in particular data hiding and encapsulation.

- -

Creating closures in loops: A common mistake

- -

Prior to the introduction of the let keyword in JavaScript 1.7, a common problem with closures occurred when they were created inside a loop. Consider the following example:

- -
<p id="help">Helpful notes will appear here</p>
-<p>E-mail: <input type="text" id="email" name="email"></p>
-<p>Name: <input type="text" id="name" name="name"></p>
-<p>Age: <input type="text" id="age" name="age"></p>
-
- -
function showHelp(help) {
-  document.getElementById('help').innerHTML = help;
-}
-
-function setupHelp() {
-  var helpText = [
-      {'id': 'email', 'help': 'Your e-mail address'},
-      {'id': 'name', 'help': 'Your full name'},
-      {'id': 'age', 'help': 'Your age (you must be over 16)'}
-    ];
-
-  for (var i = 0; i < helpText.length; i++) {
-    var item = helpText[i];
-    document.getElementById(item.id).onfocus = function() {
-      showHelp(item.help);
-    }
-  }
-}
-
-setupHelp();
-
- -

Lihat pada JSFiddle

- -

The helpText array defines three helpful hints, each associated with the ID of an input field in the document. The loop cycles through these definitions, hooking up an onfocus event to each one that shows the associated help method.

- -

If you try this code out, you'll see that it doesn't work as expected. No matter what field you focus on, the message about your age will be displayed.

- -

The reason for this is that the functions assigned to onfocus are closures; they consist of the function definition and the captured environment from the setupHelp function's scope. Three closures have been created, but each one shares the same single environment. By the time the onfocus callbacks are executed, the loop has run its course and the item variable (shared by all three closures) has been left pointing to the last entry in the helpText list.

- -

One solution in this case is to use more closures: in particular, to use a function factory as described earlier on:

- -
function showHelp(help) {
-  document.getElementById('help').innerHTML = help;
-}
-
-function makeHelpCallback(help) {
-  return function() {
-    showHelp(help);
-  };
-}
-
-function setupHelp() {
-  var helpText = [
-      {'id': 'email', 'help': 'Your e-mail address'},
-      {'id': 'name', 'help': 'Your full name'},
-      {'id': 'age', 'help': 'Your age (you must be over 16)'}
-    ];
-
-  for (var i = 0; i < helpText.length; i++) {
-    var item = helpText[i];
-    document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
-  }
-}
-
-setupHelp();
-
- -

Lihat pada JSFiddle

- -

This works as expected. Rather than the callbacks all sharing a single environment, the makeHelpCallback function creates a new environment for each one in which help refers to the corresponding string from the helpText array.

- -

Performance considerations

- -

It is unwise to unnecessarily create functions within other functions if closures are not needed for a particular task, as it will negatively affect script performance both in terms of processing speed and memory consumption.

- -

For instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor. The reason is that whenever the constructor is called, the methods would get reassigned (that is, for every object creation).

- -

Consider the following impractical but demonstrative case:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-  this.getName = function() {
-    return this.name;
-  };
-
-  this.getMessage = function() {
-    return this.message;
-  };
-}
-
- -

The previous code does not take advantage of the benefits of closures and thus could instead be formulated:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-}
-MyObject.prototype = {
-  getName: function() {
-    return this.name;
-  },
-  getMessage: function() {
-    return this.message;
-  }
-};
-
- -

However, redefining the prototype is not recommended, so the following example is even better because it appends to the existing prototype:

- -
function MyObject(name, message) {
-  this.name = name.toString();
-  this.message = message.toString();
-}
-MyObject.prototype.getName = function() {
-  return this.name;
-};
-MyObject.prototype.getMessage = function() {
-  return this.message;
-};
-
- -

In the two previous examples, the inherited prototype can be shared by all objects and the method definitions need not occur at every object creation. See Details of the Object Model for more details.

- -

Expression closures

- -

This addition is nothing more than a shorthand for writing simple functions, giving the language something similar to a typical Lambda notation.

- -

JavaScript 1.7 and older:

- -
function(x) { return x * x; }
- -

JavaScript 1.8:

- -
function(x) x * x
- -

This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter.

- -

Examples:

- -

A shorthand for binding event listeners:

- -
 document.addEventListener("click", function() false, true);
-
- -

Using this notation with some of the array functions from JavaScript 1.6:

- -
elems.some(function(elem) elem.type == "text");
diff --git a/files/id/web/javascript/data_structures/index.html b/files/id/web/javascript/data_structures/index.html deleted file mode 100644 index 0fba9dc3a5..0000000000 --- a/files/id/web/javascript/data_structures/index.html +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: JavaScript data types and data structures -slug: Web/JavaScript/Data_structures -tags: - - JavaScript - - Tipe -translation_of: Web/JavaScript/Data_structures ---- -

 {{jsSidebar("More")}}

- -

Semua bahasa pemrograman memiliki struktur data bawaan, namun hal tersebut sering dijumpai berbeda antara satu bahasa dengan bahasa lainya. Artikel ini mencoba untuk membuat daftar struktur data bawaan yang tersedia di JavaScript dan sifat-sifat apa saja yang dimiliki. Struktur data bawaan dapat digunakan untuk membangun struktur data lainnya. Bila memungkinkan, perbandingan dengan bahasa lainya akan diambil.

- -

Dynamic typing

- -

JavaScript adalah salah satu bahasa pemrograman yang tidak mengutamakan tipe data. Tidak perlu mendeklarasikan jenis data dari suatu variabel setiap saat. Tipe data akan dideklarasikan secara otomatis diawal program dijalankan. Dengan kata lain memungkinkan untuk menggunakan nama peubah yang sama dengan jenis data yang berbeda:

- -
var foo = 42;    // foo saat ini adalah angka
-foo     = 'bar'; // foo saat ini adalah string
-foo     = true;  // foo saat ini adalah boolean
-
- -

Tipe Data

- -

Standar ECMAScript terakhir menjelaskan tujuh tipe data:

- - - -

Nilai Primitif

- -

Semua tipe kecuali objek menentukan nilai tetap (nilai, yang tidak dapat diubah). Misalnya dan tidak seperti C, Strings tidak dapat diubah. Di JavaScript, string termasuk sebagai nilai primitif.

- -

Undefined

- -

Variabel yang nilainya tidak ditetapkan (tidak diisi) memiliki nilai undefined. Lihat {{jsxref("undefined")}} dan {{Glossary("Undefined")}} untuk lebih lanjut.

- -

Null

- -

Null hanya memiliki sebuah nilai dan terdiri nilai itu sendiri: null. Lihat {{jsxref("null")}} dan {{Glossary("Null")}} untuk lebih lanjut.

- -

Boolean

- -

Merepresentasikan entitas logika dan hanya memiliki dua nilai atau kemungkinan, yaitu: true dan false.

- -

Number

- -

Berdasarkan standar ECMAScript, dikatakan bahwa hanya ada satu tipe nomor, yaitu double-precision 64-bit binary format IEEE 754 value (nomor diantara -(253 -1) dan (253 -1) ). Tidak ada penomoran bilangan bulat yang spesifik. Sebagai tambahan untuk menampilkan bilangan floating-point (bilangan pecahan float), tipe nomor memiliki tiga simbol, yaitu: +Infinity, -Infinity, dan NaN (Not-a-Number)

- -

Untuk memeriksa nomor paling besar atau paling kecil diantara +/-Infinity diatas, dapat menggunakan konstanta {{jsxref("Number.MAX_VALUE")}} atau {{jsxref("Number.MIN_VALUE")}}. Semenjak standar ECMAScript 2015, untuk memeriksa nilai double-precision floating-point dapat menggunakan {{jsxref("Number.isSafeInteger()")}} yang setara dengan {{jsxref("Number.MAX_SAFE_INTEGER")}} dan {{jsxref("Number.MIN_SAFE_INTEGER")}}. Lebih dari batas tersebut, bilangan bulat di JavaScript tidak aman dan akan digantikan dengan perkiraan double-precision floating-point.

- -

Angka 0 merupakan bilangan bulat integer yang memiliki dua representasi, yaitu +0 dan -0 dan pada kenyataannya tidak berpengaruh dalam perhitungan karena jika keduanya dibandingkan akan bernilai benar: +0 === -0 //-->(true) dan akan diberitahu jika pembagi merupakan nol:

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

Meskipun angka sering hanya mewakili nilainya, JavaScript menyediakan beberapa operator biner (bitwise) yang dapat digunakan untuk bit masking, yaitu mewakili beberapa nilai Boolean dalam sebuah nomor. Namun, ini biasanya dianggap sebagai praktik yang buruk, karena JavaScript menawarkan cara lain untuk mewakili satu set Boolean (seperti array Boolean atau objek dengan nilai Boolean yang ditetapkan untuk properti bernama). Bit masking juga cenderung membuat kode lebih sulit dibaca, dipahami, dan dirawat. Mungkin diperlukan untuk digunakan di lingkungan yang sangat terbatas, seperti saat mencoba mengatasi kompresi atau dalam kasus ekstrim ketika setiap bit di atas jumlah jaringan. Teknik ini hanya harus dipertimbangkan ketika tidak ada cara terakhir yang dapat diambil untuk mengoptimalkan ukuran.

- -

String

- -

Tipe {{jsxref("Global_Objects/String", "String")}} digunakan untuk menampilkan data tulisan (teks). Terdiri dari beberapa bagian karakter yang dibentuk dari bilangan 16-bit unsigned integer. Setiap karakter pada String menempati posisi pada String. Karakter pertama pada string berindeks 0, kemudian 1, lalu 2, ..., hingga karakter terakhir dari String. Panjang String merupakan jumlah karakter pembentuknya.

- -

Berbeda dengan bahasa pemrogramman C, JavaScript string tidak dapat diubah. Dengan kata lain sekali String dibuat, maka tidak mungkin untuk mengubahnya. Namun memungkinkan untuk membuat String baru berdasarkan operasi string sebelumnya. Contoh:

- - - -

Hati-hati pada "stringly-typing" kode!

- -

String dapat digunakan untuk menampilkan data kompleks (rumit). Keuntungan untuk jangka pendek:

- - - -

Dengan adanya konversi, string dapat menampung semua tipe data, dan hentu bukan hal yang baik. Sebagai contoh, dengan separator (pemisah), string dapat meniru list (pada JavaScript disebut sebagai array). Sayangnya saat pemisah digunakan di salahsatu bagian "list" maka strukturnya akan rusak. Escape character menjadi salahsatu cara untuk menangani hal tersebut. Hal tersebut membutuhkan konversi mahal dan hanya menambah beban pemeliharaan.

- -

Gunakan string untuk data teks. Parse string dan gunakan abstraksi yang tepat jika untuk menampilkan data yang rumit.

- -

Symbol

- -

Baru diperkenalkan sejak JavaScript ECMAScript 2015. Simbol memiliki ciri khas (unik) dan nilai primitif tetap (immutable) serta dapat digunakan sebagai kunci dari properti sebuah Objek. Pada beberapa bahasa pemrogramman, Simbol disebut sebagai atom. Untuk lebih jelasnya, lihat pustaka {{Glossary("Symbol")}} dan pembungkus {{jsxref("Symbol")}} objek di JavaScript.

- -

Objek

- -

Pada ilmu komputer, objek adalah nilai pada memori yang dimungkinkan dialamatkan oleh {{Glossary("Identifier", "identifier")}}.

- -

Properties

- -

Pada JavaScript, objek dapat digambarkan sebagai kumpulan properti. Dengan adanya sintaks objek literal, set properti dibatasi; kemudian properti dapat ditambahkan atau dihapus. Nilai dari properti dapat berupa "nilai" atau tipe data lain, termasuk objek itu sendiri, yang memungkinkan untuk membangun struktur data yang rumit. Properti diidentifikasi menggunakan nilai kunci. Kunci dapat berupa String ataupun Simbol.

- -

Terdapat dua tipe objek properti yang memiliki attribut: data property dan accessor property.

- -

Data Property

- -

mengkaitkan kunci dengan nilai dan memiliki beberapa atribut:

- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AttributTipeKeteranganNilai bawaan
[[Value]]Semua jenis JavaScriptNilai yang diterima dengan mengambil akses properti.undefined
[[Writable]]BooleanJika false, maka propeti [[Value]] tidak dapat diubah.false
[[Enumerable]]BooleanJika true, properti dapat terbaca saat for...in loops. Lihat juga Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanJika false, properti tidak dapat dihapus, tidak dapat diubah menjadi aksesor propeti, juga atribut selain [[Value]] dan [[Writable]] tidak dapat diubah.false
- -

 

- - - - - - - - - - - - - - - - - - - - - - - - - -
Atribut usang (as of ECMAScript 3, renamed in ECMAScript 5)
AtributTipeKeterangan
Read-onlyBooleanDiubah di ES5 menjadi atribut [[Writable]].
DontEnumBooleanDiubah di ES5 menjadi atribut [[Enumerable]].
DontDeleteBooleanDiubah di ES5 menjadi atribut [[Configurable]].
- -

 

- -
-

Note: Biasanya atribut digunakan oleh JavaScript engine, sehingga tidak dapat diakses secara langsung (lihat Object.defineProperty()). Itulah mengapa atribut ditulis dengan kurung siku ganda.

-
- -

 

- -

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

- -

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 libraryBagian

- -

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

- -

Determining types using the typeofoperator

- -

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')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
- -

See also

- - - -

 

- -

 

diff --git a/files/id/web/javascript/guide/grammar_and_types/index.html b/files/id/web/javascript/guide/grammar_and_types/index.html deleted file mode 100644 index 78eec69d04..0000000000 --- a/files/id/web/javascript/guide/grammar_and_types/index.html +++ /dev/null @@ -1,649 +0,0 @@ ---- -title: Tata Bahasa dan Tipe -slug: Web/JavaScript/Guide/Grammar_and_types -tags: - - JavaScript - - Panduan -translation_of: Web/JavaScript/Guide/Grammar_and_types -original_slug: Web/JavaScript/Panduan/Values,_variables,_and_literals ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

Pada bagian ini membahas tata bahasa dasar Javascript, deklarasi variabel, tipe data dan literal.

- -

Dasar

- -

Sebagian besar sintak JavaScript terinspirasi dari Java, namun juga dipengaruhi oleh Awk, Perl dan Python.

- -

JavaScript bersifat case-sensitive dan menggunakan set karakter Unicode.

- -

Dalam JavaScript, instruksi disebut {{Glossary ("Statement", "pernyataan")}} dan dipisahkan oleh titik koma (;). Spasi, tab dan karakter baris baru disebut whitespace.Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis (ASI) untuk mengakhiri pernyataan. Namun, dianjurkan untuk selalu menambahkan titik koma untuk mengakhiri pernyataan anda; Itu akan terhindar dari efek samping. Untuk informasi lebih lanjut, lihat referensi rinci tentang tata bahasa eksikal JavaScript.

- -


- Komentar

- -

Sintak komentar pada JavaScript sama dengan C++ dan dalam banyak bahasa pemrograman lainnya:

- -
// komentar satu baris
-
-/* Ini lebih panjang
-   komentar beberapa baris
- */
-
-/* Anda tidak bisa menggunakannya, /* komentar bersarang */ Sintak bermasalah */
- -

Deklarasi

- -

Ada tiga macam deklarasi pada JavaScript.

- -
-
var
-
Mendeklarasikan sebuah variabel, opsional menginisialisasi sebuah nilai.
-
let
-
Mendeklarasikan lingkup-blok, variabel lokal, opsional menginisialisasi sebuah nilai.
-
const
-
Mendeklarasikan sebuah lingkup-blok, baca-saja dinamakan konstanta.
-
- -

Variabel

- -

Anda menggunakan variabel sebagai nama simbolik dalam aplikasi Anda.  Nama variabel, disebut {{Glossary("Identifier", "Pengidentifikasi")}}, sesuai dengan peraturan tertentu.

- -

Pengindetifikasi pada JavaScript harus dimulai dengan huruf, garis bawah (_), atau tanda dolar ($); Karakter selanjutnya bisa berupa digit (0-9). karena JavaScript sensitif huruf (case-sensitive), Huruf termasuk karakter "A" sampai "Z" (huruf besar) dan huruf "a" sampai "z" (huruf kecil) .

- -

Anda dapat menggunakan sebagian besar huruf ISO 8859-1 atau Unicode seperti å dan ü dalam pengidentifikasi (untuk lebih jelasnya lihat postingan blog ini). Anda juga dapat menggunakan urutan rangkaian pelolosan/escape Unicode sebagai karakter dalam pengidentifikasi.

- -

Beberapa contoh nama legal adalah Number_hitstemp99, $credit, dan _name.

- -

Mendeklarasikan variabel

- -

Anda bisa mendeklarasikan sebuah variabel dalam tiga cara:

- - - -

Mengevaluasi variabel

- -

Variabel yang dideklarasikan dengan menggunakan pernyataan  var atau let tanpa penetapan nilai yang ditentukan memiliki nilai undefined.

- -

Upaya untuk mengakses variabel yang tidak dideklarasikan akan menuju kepada pelemparan eksepsi ReferenceError:

- -
var a;
-console.log('Nilai dari a adalah ' + a); // Nilai dari a adalah undefined
-
-console.log('Nilai dari b adalah ' + b); // Nilai dari b adalah undefined
-var b;
-
-console.log('Nilai dari c adalah ' + c); // Tidak tertangkap ReferenceError: c tidak di definisikan
-
-let x;
-console.log('Nilai dari x adalah ' + x); // Nilai dari x adalah undefined
-
-console.log('Nilai dari y adalah ' + y); // Tidak tertangkap ReferenceError: y tidak di definisikan
-let y;
- -

Anda dapat menggunakan undefined untuk menentukan apakah sebuah variabel memiliki nilai. Dalam kode berikut, variabel input tidak diberi nilai, dan pernyataan  if dievaluasi true.

- -
var input;
-if (input === undefined) {
-  lakukanIni();
-} else {
-  lakukanItu();
-}
- -

Nilai  undefined berperilaku sebagai false bila digunakan dalam konteks boolean. Misalnya, kode berikut menjalankan fungsi fungsiSaya karena elemen  myArray undefined:

- -
var myArray = [];
-if (!myArray[0]) fungsiSaya();
- -

Nilai  undefined mengkonversi ke NaN bila digunakan dalam konteks numerik.

- -
var a;
-a + 2;  // Dievaluasi ke NaN
- -

Ketika Anda mengevaluasi sebuah variabel null, nilai null berperilaku seperti 0 dalam konteks numerik dan sebagai false dalam konteks boolean. Sebagai contoh:

- -
var n = null;
-console.log(n * 32); // Akan log 0 ke konsol
- -

Lingkup variabel

- -

Bila Anda mendeklarasikan variabel di luar fungsi apa pun, ini disebut variabel global , karena tersedia pada kode lain dalam dokumen tersebut. Ketika Anda mendeklarasikan sebuah variabel dalam suatu fungsi, itu disebut variabel lokal , karena hanya tersedia di dalam fungsi itu.

- -

JavaScript sebelum ECMAScript 2015 tidak memiliki lingkup pernyataan blok ; Sebaliknya, variabel yang dinyatakan dalam blok bersifat lokal terhadap fungsi (atau lingkup global) yang berada di blok. Misalnya kode berikut akan log 5, karena ruang lingkupnya adalah fungsi (atau konteks global) yang dideklarasikan, bukan bloknya, yang dalam hal ini adalah sebuah pernyataan if.

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

Perilaku ini berubah, saat menggunakan deklarasi let yang diperkenalkan di ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y tidak di definisikan
- -

Hoisting variabel

- -

Hal lain yang tidak biasa tentang variabel dalam JavaScript adalah Anda bisa merujuk ke variabel yang dideklarasikan nanti, tanpa mendapatkan eksepsi. Konsep ini dikenal sebagai hoistingVariabel dalam JavaScript dalam arti "dikibarkan" atau diangkat ke atas fungsi atau pernyataan. Bagaimanapun, variabel yang dikibarkan akan memberikan nilai undefinedJadi, bahkan jika Anda mendeklarasikan dan menginisialisasi setelah Anda menggunakan atau merujuk ke variabel ini, itu akan tetap memberikan undefined.

- -
/**
- * Contoh 1
- */
-console.log(x === undefined); // true
-var x = 3;
-
-/**
- * Contoh 2
- */
-// Akan memberikan nilai undefined
-var myvar = 'my value';
-
-(function() {
-  console.log(myvar); // undefined
-  var myvar = 'local value';
-})();
- -

Contoh di atas akan dinterprestasikan sama dengan:

- -
/**
- * Contoh 1
- */
-var x;
-console.log(x === undefined); // true
-x = 3;
-
-/**
- * Example 2
- */
-var myvar = 'my value';
-
-(function() {
-  var myvar;
-  console.log(myvar); // undefined
-  myvar = 'nilai lokal';
-})();
- -

Karena hoisting, semua pernyataan var dalam suatu fungsi harus ditempatkan sedekat mungkin ke atas fungsi. Praktik terbaik ini meningkatkan kejelasan kode.

- -

Dalam ECMAScript 2015, variabel  let (const) tidak akan hoist ke bagian atas blok. Bagaimanapun, referensi variabel di blok sebelum deklarasi variabel menghasilkan sebuah ReferenceErrorVariabel ini berada dalam "zona mati temporal" dari awal blok sampai deklarasi diproses.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Hoisting fungsi

- -

Untuk fungsi, hanya deklarasi fungsi yang diangkat ke atas dan bukan ekspresi fungsi.

- -
/* Deklarasi fungsi */
-
-foo(); // "bar"
-
-function foo() {
-  console.log('bar');
-}
-
-
-/* Ekspresi fungsi */
-
-baz(); // TypeError: baz adalah bukan fungsi
-
-var baz = function() {
-  console.log('bar2');
-};
- -

Variabel global

- -

Variabel global sebenarnya adalah properti dari objek global . Di halaman web objek global itu window, sehingga Anda bisa mengatur dan mengakses variabel global dengan menggunakan sintaks window.variable

- -

Akibatnya, Anda dapat mengakses variabel global yang dideklarasikan dalam satu window atau frame dari window atau frame lain dengan menentukan nama window atau frame. Misalnya, jika variabel yang disebut phoneNumber dinyatakan dalam dokumen, Anda dapat merujuk variabel ini dari iframe as parent.phoneNumber.

- -

Konstanta

- -

Anda bisa membuat variabel baca-saja, dinamai dengan kata kunci constSintaksis dari pengenal konstanta sama dengan pengenal variabel: ia harus dimulai dengan huruf, garis bawah atau tanda dolar ($) dan dapat berisi karakter abjad, numerik, atau garis bawah.

- -
const PI = 3.14;
- -

Konstanta tidak dapat mengubah nilai melalui penugasan atau dinyatakan ulang saat naskah dijalankan. Ini harus diinisialisasi ke sebuah nilai.

- -

Aturan lingkup untuk konstanta sama dengan variabel lingkup-blok let . Jika kata kunci  const dihilangkan, pengenal dianggap mewakili variabel.

- -

Anda tidak dapat mendeklarasikan konstanta dengan nama yang sama dengan fungsi atau variabel dalam lingkup yang sama. Sebagai contoh:

- -
// INI AKAN MENYEBABKAN ERROR
-function f() {};
-const f = 5;
-
-// INI AKAN MENYEBABKAN ERROR JUGA
-function f() {
-  const g = 5;
-  var g;
-
-  //pernyataan
-}
- -

Namun, properti objek yang ditugaskan pada konstanta tidak terlindungi, jadi pernyataan berikut dijalankan tanpa masalah.

- -
const MY_OBJECT = {'key': 'value'};
-MY_OBJECT.key = 'otherValue';
- -

Struktur dan tipe data

- -

Tipe data

- -

Standar ECMAScript terbaru mendefinisikan tujuh tipe data:

- - - -

Meskipun tipe data ini jumlahnya relatif kecil, namun memungkinkan Anda untuk melakukan fungsi-fungsi yang berguna dengan aplikasi Anda.  {{jsxref("Object", "Objects")}} dan {{jsxref("Function", "functions")}} merupakan unsur fundamental lainnya dalam bahasa ini. Anda bisa memikirkan objek sebagai wadah bernama untuk nilai, dan fungsi sebagai prosedur yang dapat dilakukan aplikasi Anda.

- -

Konversi tipe data

- -

JavaScript adalah bahasa yang diketik secara dinamis. Itu berarti Anda tidak perlu menentukan tipe data variabel saat Anda menyatakannya, dan tipe data akan dikonversi secara otomatis sesuai kebutuhan selama eksekusi skrip. Jadi, misalnya, Anda bisa mendefinisikan variabel sebagai berikut:

- -
var jawaban = 42;
- -

Dan nanti, Anda bisa menetapkan variabel yang sama dengan nilai string, misalnya:

- -
jawaban = 'Thanks for all the fish...';
- -

Karena JavaScript diketik secara dinamis, penugasan ini tidak menyebabkan pesan kesalahan.

- -

Dalam ekspresi yang melibatkan nilai numerik dan string dengan operator +, JavaScript mengubah nilai numerik menjadi string. Misalnya, perhatikan pernyataan berikut:

- -
x = 'Jawabannya adalah ' + 42 // "Jawabannya adalah 42"
-y = 42 + ' Adalah jawabannya' // "42 Adalah jawabannya"
- -

Dalam pernyataan yang melibatkan operator lain, JavaScript tidak mengubah nilai numerik menjadi string. Sebagai contoh:

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

Mengubah string menjadi angka

- -

Dalam kasus yang sebuah nilai mewakili bilangan ada dalam memori sebagai string, ada metode untuk konversi.

- - - -

parseInt Hanya akan memberikan bilangan bulat, jadi penggunaannya berkurang untuk desimal. Selain itu, praktik terbaik untuk parseInt selalu menyertakan parameter radix. Parameter radix digunakan untuk menentukan sistem numerik yang akan digunakan.

- -

Metode alternatif untuk mengambil nomor dari string adalah dengan operator +  (unary plus):

- -
'1.1' + '1.1' = '1.11.1'
-(+'1.1') + (+'1.1') = 2.2
-// Catatan: kurung siku buka tutup ditambahkan untuk kejelasan, tidak diminta.
- -

Literal

- -

Anda menggunakan literal untuk mewakili nilai dalam JavaScript. Ini adalah nilai tetap, bukan variabel, yang Anda berikan secara literal dalam skrip Anda. Bagian ini menjelaskan jenis literal berikut:

- - - -

Literal array

- -

Sebuah literal array adalah daftar dari nol atau lebih ekspresi,  yang masing-masing mewakili elemen array, dilampirkan dalam tanda kurung siku ([]). Bila Anda membuat array menggunakan literal array, ini diinisialisasi dengan nilai yang ditentukan sebagai elemennya, dan panjangnya diatur ke jumlah argumen yang ditentukan.

- -

Contoh berikut membuat array coffees dengan tiga elemen dan panjang tiga:

- -
var coffees = ['French Roast', 'Colombian', 'Kona'];
- -

Catatan: Sebuah literal array  adalah tipe dari object initializer. Lihat Menggunakan Penginisialisasi Objek.

- -

Jika sebuah array dibuat menggunakan literal dalam skrip tingkat-atas, JavaScript menginterpretasikan array setiap kali mengevaluasi ekspresi yang berisi literal array. Selain itu, literal yang digunakan dalam suatu fungsi dibuat setiap kali fungsi dipanggil.

- -

Array literal juga objek ArrayLihat Array dan Koleksi diIndek untuk rincian tentang objek Array.

- -

Ekstra koma dalam literal array

- -

Anda tidak perlu menentukan semua elemen dalam literal array. Jika Anda memasukkan dua koma berturut-turut, array dibuat undefined untuk elemen yang tidak ditentukan. Contoh berikut membuat array fish:

- -
var fish = ['Lion', , 'Angel'];
- -

Array ini memiliki dua elemen dengan nilai dan satu elemen kosong (fish[0] adalah "Lion", fish[1] adalah undefined, dan fish[2] merupakan "Angel").

- -

Jika Anda menyertakan koma di akhir daftar elemen, koma diabaikan. Pada contoh berikut, panjang array adalah tiga. Tidak ada myList[3]Semua koma lainnya dalam daftar menunjukkan elemen baru.

- -

Catatan: Koma diakhir dapat membuat kesalahan pada versi browser lama dan merupakan praktik terbaik untuk menghapusnya.

- -
var myList = ['home', , 'school', ];
- -

Dalam contoh berikut, panjang array adalah empat, dan myList[0]dan myList[2] hilang.

- -
var myList = [ ,'home', , 'school'];
- -

Dalam contoh berikut, panjang array adalah empat, dan myList[1]dan myList[3] hilang. Hanya koma terakhir yang diabaikan.

- -
var myList = ['home', , 'school', , ];
- -

Memahami perilaku ekstra  koma penting untuk memahami JavaScript sebagai bahasa, namun saat menulis kode Anda sendiri: secara eksplisit menyatakan elemen yang hilang sebagai undefined akan meningkatkan kejelasan dan perawatan kode anda.

- -

Literal boolean

- -

Tipe Boolean memiliki dua nilai literal: true dan false.

- -

Jangan membingungkan nilai Boolean primitif true dan false dengan nilai true dan false objek Boolean. Objek Boolean adalah pembungkus di sekitar tipe data Boolean primitif. Lihat {{jsxref("Boolean")}} untuk informasi lebih lanjut.

- -

Integer

- -

Integer dapat dinyatakan dalam desimal (basis 10), heksadesimal (basis 16), oktal (basis 8) dan biner (basis 2).

- - - -

Beberapa contoh literal bilangan bulat adalah:

- -
0, 117 and -345 (desimal, basis 10)
-015, 0001 and -0o77 (oktal, basis 8)
-0x1123, 0x00111 and -0xF1A7 (heksadesimal, "hex" or basis 16)
-0b11, 0b0011 and -0b11 (biner, basis 2)
- -

Untuk informasi lebih lanjut, lihat literatur numerik dalam referensi tata bahasa leksikal .

- -

Literal floating-point

- -

Sebuah literal  floating-point dapat memiliki bagian berikut:

- - - -

Bagian eksponennya adalah "e" atau "E" diikuti oleh bilangan bulat, yang dapat ditandatangani (didahului dengan "+" atau "-"). Literal floating-point harus memiliki setidaknya satu digit dan titik desimal atau "e" (atau "E").

- -

Lebih ringkas lagi, sintaksnya adalah:

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

Sebagai contoh:

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

Literal objek

- -

Literal objek adalah daftar dari nol atau lebih pasangan nama properti dan nilai objek yang terkait, yang dilampirkan dalam kurung kurawal ({}). Anda seharusnya tidak menggunakan literal objek di awal sebuah pernyataan. Ini akan menyebabkan kesalahan atau tidak berperilaku seperti yang Anda harapkan, karena { akan ditafsirkan sebagai awal dari sebuah blok.

- -

Berikut ini adalah contoh dari literal objek. Elemen pertama dari objek car mendefinisikan sebuah properti myCar, dan menetapkan sebuah string baru, " Saturn";  Elemen kedua, properti getCar,  segera diberi hasil pemanggilan function (carTypes("Honda")); elemen ketiga, properti special menggunakan variabel yang ada ( sales).

- -
var sales = 'Toyota';
-
-function carTypes(name) {
-  if (name === 'Honda') {
-    return name;
-  } else {
-    return "Maaf, kami tidak menjual " + name + ".";
-  }
-}
-
-var car = { myCar: 'Saturn', getCar: carTypes('Honda'), special: sales };
-
-console.log(car.myCar);   // Saturn
-console.log(car.getCar);  // Honda
-console.log(car.special); // Toyota
- -

Selain itu, Anda dapat menggunakan literal numerik atau string untuk nama properti atau menyarangkan objek di dalam objek yang lain. Contoh berikut menggunakan opsi ini.

- -
var car = { manyCars: {a: 'Saab', 'b': 'Jeep'}, 7: 'Mazda' };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
- -

Nama properti objek bisa berupa string apapun, termasuk string kosong. Jika nama properti akan menjadi {{Glossary("Identifier","pengidentifikasi")}} JavaScript yang tidak valid atau angka, maka harus dilampirkan dalam tanda petik. Nama properti yang pengidentifikasi tidak valid juga tidak dapat diakses sebagai properti dot (.), namun dapat diakses dan ditetapkan dengan notasi seperti array ("[]").

- -
var namaPropertiTidakBiasa = {
-  '': 'An empty string',
-  '!': 'Bang!'
-}
-console.log(namaPropertiTidakBiasa.'');   // SyntaxError: Unexpected string
-console.log(namaPropertiTidakBiasa['']);  // An empty string
-console.log(namaPropertiTidakBiasa.!);    // SyntaxError: Unexpected token !
-console.log(namaPropertiTidakBiasa['!']); // Bang!
- -

Peningkatan Literal Objek

- -

Di ES2015, literal objek diperluas untuk mendukung pengaturan prototipe pada konstruksi, singkatan untuk  foo: penugasan foo , definisikan metode, pembuatan panggilan super, dan komputasi nama properti dengan ekspresi. Bersamaan dengan itu, ini juga membawa literatur dan deklarasi kelas lebih dekat bersama, dan membiarkan desain berbasis objek mendapatkan keuntungan dari beberapa kemudahan yang sama.

- -
var obj = {
-    // __proto__
-    __proto__: theProtoObj,
-    // Shorthand for ‘handler: penangan’
-    handler,
-    // Metode
-    toString() {
-     // Pangilan super
-     return 'd ' + super.toString();
-    },
-    // Dikalkulasi (dinamis) nama properti
-    [ 'prop_' + (() => 42)() ]: 42
-};
- -

Tolong dicatat:

- -
var foo = {a: 'alpha', 2: 'two'};
-console.log(foo.a);    // alpha
-console.log(foo[2]);   // two
-//console.log(foo.2);  // Error: missing ) after argument list
-//console.log(foo[a]); // Error: a is not defined
-console.log(foo['a']); // alpha
-console.log(foo['2']); // two
- -

Literal RegExp

- -

Sebuah literal regex adalah pola yang dilampirkan diantara garis miring. Berikut ini adalah contoh literal regex.

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

Literal string

- -

Literal string adalah nol atau lebih karakter yang dilampirkan dengan tanda kutip ganda (") atau tunggal ('). String harus dibatasi dengan tanda kutip dari jenis yang sama; Yaitu kedua tanda kutip tunggal atau kedua tanda petik ganda. Berikut ini adalah contoh literal string:

- -
'foo'
-"bar"
-'1234'
-'baris satu \n baris lainnya'
-"Kucing jhon"
- -

Anda dapat memanggil salah satu metode objek String pada nilai literal string-JavaScript secara otomatis mengubah literal string menjadi objek String sementara, memanggil metode tersebut, lalu membuang objek String sementara. Anda juga bisa menggunakan properti String.length dengan literal string:

- -
console.log("Kucing jhon".length)
-// Akan mencetak jumlah simbol dalam string termasuk spasi.
-// Dalam hal ini, 11.
- -

Di ES2015, template literal juga tersedia. Template string memberikan sintaksis gula untuk pembuatan string. Ini mirip dengan fitur interpolasi string di Perl, Python dan lainnya. Secara opsional, tag dapat ditambahkan untuk memungkinkan konstruksi string disesuaikan, menghindari serangan injeksi atau membangun struktur data tingkat tinggi dari konten string.

- -
// Literal dasar kreasi string
-`Dalam JavaScript '\n' adalah sebuah line-feed.`
-
-// String beberapa baris
-`Dalam template string JavaScript dapat berjalan di
- beberapa baris, namun string yang dikutip ganda dan tunggal
- tidak dapat dilakukan.`
-
-// Interpoasi string
-var name = 'Bob', time = 'today';
-`Hello ${name}, how are you ${time}?`
-
-// Membangun prefix permintaan HTTP digunakan untuk menafsirkan penggantian dan konstruksi
-POST`http://foo.org/bar?a=${a}&b=${b}
-     Content-Type: application/json
-     X-Credentials: ${credentials}
-     { "foo": ${foo},
-       "bar": ${bar}}`(myOnReadyStateChangeHandler);
- -

Anda harus menggunakan literal string kecuali Anda secara khusus perlu menggunakan objek String. Lihat {{jsxref("String")}}  untuk rincian tentang objek String.

- -

Menggunakan karakter khusus dalam string

- -

Selain karakter biasa, Anda juga bisa menyertakan karakter khusus dalam string, seperti yang ditunjukkan pada contoh berikut.

- -
'one line \n another line'
- -

Tabel berikut mencantumkan karakter khusus yang dapat Anda gunakan dalam string JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tabel: karakter khusus JavaScript
KarakterBerarti
\0Null Byte
\bbackspase
\fform feed
\nBaris baru
\rCariage return
\tTab
\vTab vertikal
\'Apostrof atau kutipan tunggal
\"Kutipan ganda
\\Karakter backslash
\XXXKarakter dengan pengkodean Latin-1 ditentukan oleh hingga tiga digit oktal XXX antara 0 dan 377. Misalnya, \251 adalah urutan oktal untuk simbol hak cipta.
\xXXKarakter dengan pengkodean Latin-1 yang ditentukan oleh dua digit heksadesimal XX antara 00 dan FF. Misalnya, \xA9 adalah urutan heksadesimal untuk simbol hak cipta.
\uXXXXKarakter Unicode ditentukan oleh empat digit heksadesimal XXXX . Misalnya, \u00A9 adalah urutan Unicode untuk simbol hak cipta. Lihat rangkaian pelolosan Unicode.
\u{XXXXX}Kode Unicode lolos. Misalnya, \u {2F804} sama dengan Unicode sederhana yang lolos \uD87E \uDC04.
- -

Karakter pelolosan

- -

Untuk karakter yang tidak tercantum dalam tabel, tanda garis miring terbalik sebelumnya diabaikan, namun penggunaan ini tidak berlaku lagi dan harus dihindari.

- -

Anda dapat memasukkan tanda petik di dalam string sebelum mendahului dengan garis miring terbalik. Ini dikenal sebagai pelolosan dari tanda petik. Sebagai contoh:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
- -

Hasil dari ini adalah:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
- -

Untuk menyertakan garis miring terbalik di dalam string, Anda harus melepaskan diri dari karakter garis miring terbalik. Misalnya, untuk menetapkan path file c:\temp ke string, gunakan yang berikut ini:

- -
var home = 'c:\\temp';
- -

Anda juga bisa meloloskan dari baris istirahat sebelumnya mendahului mereka dengan garis miring terbalik. Garis miring terbalik dan baris istirahat keduanya terlepas dari nilai string.

- -
var str = 'this string \
-is broken \
-across multiple \
-lines.'
-console.log(str);   // this string is broken across multiplelines.
- -

Meskipun JavaScript tidak memiliki sintaks "heredoc", Anda bisa mendekat dengan menambahkan pelolosan baris istirahat dan baris istirahat pada akhir setiap baris:

- -
var poem =
-'Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo.'
- -

ECMAScript 2015 memperkenalkan tipe literal baru, yaitu  template literal . Hal ini memungkinkan banyak fitur baru termasuk string beberapa baris!

- -

 

- -
var poem =
-`Roses are red,
-Violets are blue.
-Sugar is sweet,
-and so is foo.`
- -

 

- -

Informasi lebih lanjut

- -

Bab ini berfokus pada sintaks dasar untuk deklarasi dan tipe. Untuk mempelajari lebih lanjut tentang konstruksi bahasa JavaScript, lihat juga bab-bab berikut dalam panduan ini:

- - - -

Pada bab berikutnya, kita akan melihat konstruksi aliran kontrol dan penanganan kesalahan.

diff --git a/files/id/web/javascript/guide/index.html b/files/id/web/javascript/guide/index.html deleted file mode 100644 index e1a506b560..0000000000 --- a/files/id/web/javascript/guide/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Panduan JavaScript -slug: Web/JavaScript/Guide -translation_of: Web/JavaScript/Guide -original_slug: Web/JavaScript/Panduan ---- -
{{jsSidebar("JavaScript Guide")}}
- -

Pedoman javasript memberi tahu bagaimana menggunakan JavaScript dan memberikan penjelasan tentang bahasa javascript. Jika anda ingin memulai javascript atau programming secara umum, konsultasikan artikel di Area pembelajaran. Jika anda membutuhkan informasi lengkap tentang fitur silakan lihat  Referensi javaScript.

- -

Bagian

- -

Pedoman ini dibagi menjadi beberapa bagian:

- - - - - - - - - -

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

diff --git a/files/id/web/javascript/guide/introduction/index.html b/files/id/web/javascript/guide/introduction/index.html deleted file mode 100644 index bfe4c9072c..0000000000 --- a/files/id/web/javascript/guide/introduction/index.html +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Perkenalan -slug: Web/JavaScript/Guide/Introduction -tags: - - I10n:priority - - JavaScript - - Pedoman - - Pemula - - Perkenalan -translation_of: Web/JavaScript/Guide/Introduction -original_slug: Web/JavaScript/Panduan/pengenalan ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Bab ini mengenalkan dan membahas konsep yang mendasar di javascript.

- -

Apa yang perlu anda ketahui

- -

Pada pedoman ini kami anggap Anda memiliki pengetahuan dasar dari:

- - - -

Tempat untuk mencari informasi JavaScript 

- -

Dokumentasi JavaScript di MDN menyediakan materi sebagai berikut:

- - - -

Jika Anda baru mengenal JavaScript, mulailah dari area belajar dan Paduan JavaScript. Ketika Anda sudah mendapatkan pemahaman dasarnya, Anda bisa menggunakan Referensi JavaScript untuk melihat lebih detil objek dan statement.

- -

Apa itu JavaScript?

- -

JavaScript adalah bahasa scripting cross-platform yang berorientasi objek yang digunakan untuk membuat bagian interaktif dari halaman-halaman web (misal: animasi kompleks, tombol yang dapat di-klik, menu pop-up, dll). Terdapat juga versi server-side yang lebih lanjut dari JavaScript seperti Node.Js yang mana dapat memberikan Anda fungsionalitas lebih pada sebuah website (seperti kolaborasi realtime di antara beberapa komputer). Di dalam host environment (contoh, sebuah web browser), JavaScript dapat dihubungkan ke objek-objek dari environment tersebut untuk menyediakan kendali programmatis terhadapnya. 

- -

JavaScript memuat satu library standar yang memuat objek-objek, seperti Array, Date, dan Math, juga set inti dari elemen-elemen bahasa ini seperti operator, struktur kontrol, dan statement. Inti dari JavaScript dapat dikembangkan untuk kegunaan yang beragam dengan cara menambahkan  objek-objek tambahan; sebagai contoh:

- - - -

JavaScript dan Java

- -

JavaScript dan Java memang memiliki kemiripan pada beberapa hal, namun pada dasarnya saling berbeda. JavaScript menyerupai Java namum tidak memiliki static typing dan strong type checking. JavaScript mengikuti sebagian besar expresi syntax Java, konvensi penamaan serta konstruksi control-flow dasar, yang mana menjadi alasan untuk mengganti namanya dari LiveScript ke JavaScript.

- -

Berbeda dengan sistem compile-time class Java yang dibangun melalui deklarasi, Javascript mendukung sistem runtime yang berbasis pada sebagian kecil tipe data yang mewakili nilai numerik, Boolean, dan string. Javascript memiliki model objek berbasis prototipe ketimbang model objek berbasis kelas yang lebih umum. Model berbasis prototipe menyediakan inheritance dinamis; yaitu, apa yang diturunkan/diwariskan dapat berbeda pada setiap objek. Javascript juga mendukung fungsi tanpa persyaratan deklaratif khusus. Fungsi bisa berupa properti objek, yang dijalankan sebagai tipe metode yang longgar.

- -

JavaScript merupakan bahasa dengan bentuk yang sangat bebas dibandingkan dengan Java. Anda tidak perlu mendeklarasikan semua variabel, kelas, dan metode. Anda tidak perlu khawatir apakah metode itu public, private, atau protected, dan Anda juga tidak perlu mengimplementasikan interface. Variabel, parameter, dan tipe kembalian fungsi juga tidak ditulis secara eksplisit.

- -

Java merupakan bahasa berbasis kelas yang didesain untuk eksekusi yang cepat dan penulisan yang aman. Penulisan yang aman, misalnya, Anda tidak bisa mengubah integer Java menjadi referensi objek atau mengakses private memori dengan membobol bytecode. Model berbasis kelas Java bermaksud bahwa program secara eksklusif terdiri atas sejumlah kelas beserta metode-metodenya. Pewarisan kelas dan penulisan ketat milik Java umumnya membutuhkan hirarki objek yang juga sangat kekat. Syarat-syarat tersebut menjadikan pemrograman Java lebih kompleks ketimbang pemrograman Javascript.

- -

Sebaliknya, JavaScript mewarisi inti dari baris bahasa yang bertipe dinamis dan lebih sederhana sepeti HyperTalk dan dBASE. Bahasa-bahasa scripting tersebut menawarkan fungsionalitas pemrograman ke pengguna yang lebih luas karena syntax-nya yang lebih mudah, berfokus pada fungsi built-in, dan persyaratan yang minimalis untuk membuat objek.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript dibandingkan Java
JavaScriptJava
Berorientasi objek. Tak ada perbedaan antar tipe objek. Inheritance/ pewarisan melalui mekanisme prototipe, serta properti dan metode bisa ditambahkan kepada objek apapun secara dinamis.Berbasis kelas. Objek dibagi ke dalam kelas dan instansi dengan semua pewarisan melalui hirarki kelas. Kelas dan instansi tidak dapat memiliki properti atau metode yang ditambahkan secara dinamis.
Tipe data variabel tidak dideklarasi (dynamic typing, loosely typed).Tipe data variabel harus dideklarasi (static-typing, strongly typed).
Tidak bisa menulis ke hard disk secara otomatis.Bisa menulis ke hard disk secara otomatis.
- -

Untuk informasi lebih lanjut perbedaan antara JavaScript dan Java, lihat bagian Detil dari model objek.

- -

JavaScript dan spesifikasi ECMAScript

- -

Javascript distandarisasi melalui Ecma International — asosiasi Eropa yang men-standarisasi sistem informasi dan komunikasi  (ECMA merupakan singkatan yang dari European Computer Manufacturers Association) yang mengurusi standarisasi bahasa pemrograman internasional berbasis JavaScript. Versi standarisasi JavaScript ini, yang disebut sebagai ECMAScript, akan berperilaku sama pada setiap aplikasi yang mengikutinya. Perusahaan-perusahaan dapat menggunakan bahasa standar terbuka untuk mengembangkan implementasi JavaScript mereka. Standar ECMAScript didokumentasikan dalam spesifikasi ECMA-262. Kunjungi Terbaru di JavaScript untuk mempelajari lebih lanjut tentang berbagai versi dari JavaScript dan spesifikasi edisi ECMAScript.

- -

Standar ECMA-262 juga disetujui oleh ISO (International Organization for Standardization) sebagai ISO-16262. Anda juga dapat menemukan spesifikasinya di website Ecma International. Spesifikasi ECMAScript tidak memaparkan Document Object Model yang distandarisasi oleh World Wide Web Consortium (W3C) bersama WHATWG (Web Hypertext Application Technology Working Group). DOM mendefinisikan cara dimana dokumen objek HTML diekspos ke script Anda. Untuk mendapatkan pemahaman yang lebih baik tentang berbagai teknologi yang digunakan ketika memrogram menggunakan JavaScript, lihat artikel ikhtisar teknologi JavaScript.

- -

Perbandingan dokumentasi JavaScript dengan spesifikasi ECMAScript

- -

Spesifikasi ECMAScript adalah seperangkat persyaratan untuk menerapkan ECMAScript; berguna jika Anda ingin menerapkan fitur bahasa yang sesuai standar dalam penerapan atau mesin ECMAScript Anda (seperti SpiderMonkey di Firefox, atau V8 di Chrome).

- -

Dokumen ECMAScript tidak dimaksudkan untuk membantu script programmer; gunakanlah dokumentasi JavaScript untuk informasi dalam penulisan script.

- -

Spesifikasi ECMAScript menggunakan terminologi dan syntax yang mungkin asing bagi programmer JavaScript. Meskpun deskripsi dari bahasa tersebut dapat berbeda dengan ECMAScript, bahasanya sendiri tetap sama. JavaScript mendukung semua fungsionalitas yang diuraikan dalam spesifikasi ECMAScript.

- -

Dokumentasi JavaScript menggambarkan aspek bahasa yang sesuai bagi seorang programmer JavaScript.

- -

Memulai Javascript

- -

Memulai JavaScript itu mudah: semua yang dibutuhkan hanyalah Web browser modern untuk menjalankannya. Panduan ini mencakup beberapa fitur JavaScript yang hanya tersedia pada versi terakhir Firefox, sehingga disarankan untuk menggunakan Firefox versi terbaru.

- -

Terdapat dua alat yang dipasang ke dalam Firefox yang berguna dalam bereksperimen dengan JavaScript: Web Console dan Scratchpad.

- -

Web Console

- -

Web Consol / Konsol Web memperlihatkan kepada Anda tentang informasi laman Web yang sedang di-load saat ini, dan juga mencakup commandline / baris perintah yang dapat Anda gunakan untuk mengeksekusi ekspresi JavaScript pada laman saat ini.

- -

Untuk membuka Konsol Web, tekan (Ctrl + Shift + K) pada Windows dan Linux atau tekan (Cmd + Option + K) pada Mac, pilih "Web Console" dari menu "Developer", yang berada di bawah menu "Tools" di Firefox. Konsol akan muncul di bagian bawah jendela browser. Di bagian bawah konsol tersebut adalah command line yang dapat Anda gunakan untuk memasukkan JavaScript, dan outputnya akan muncul pada panel di atasnya.

- -

Konsol tersebut bekerja persis seperti eval: expresi terakhir yang dienter akan dikembalikan. Demi kesederhanaan, bisa dibayangkan jika setiap saat sesuatu dimasukkan ke dalam konsol, ia akan selalu dikelilingi oleh console.log sekitar eval seperti ini.

- -
function greetMe(yourName) {
-  alert('Hello ' + yourName);
-}
-console.log(eval('3 + 5'));
- -

 

- -

Scratchpad

- -

Konsol Web bagus untuk menjalankan satu baris kode JavaScript, meskipun Anda juga dapat menjalankan banyak baris, tetap saja akan terasa kurang nyaman, dan Anda juga tidak bisa menyimpan sampel kode Anda menggunakan Konsol Web. Jadi untuk contoh yang lebih kompleks, Scratchpad adalah solusinya.

- -

Untuk membuka Scratchpad tekan (Shift + F4), pilih "Scratchpad" dari menu "Developer", yang ada di bawah menu pada Firefox. Selanjutnya akan muncul di window yang terpisah dan merupakan editor yang dapat Anda gunakan untuk menulis dan menjalankan JavaScript di browser. Anda juga dapat menyimpan dan membuka kode dari disk.

- -

- -

Hello world

- -

Untuk mulai menulis JavaScript, buka Scratchpad dan tulislah kode JavaScript "Hello world" pertama Anda:

- -
(function(){
-  "use strict";
-  /* Start of your code */
-  function greetMe(yourName) {
-    alert('Hello ' + yourName);
-  }
-
-  greetMe('World');
-  /* End of your code */
-})();
-
- -

Pilih kode diatas dan tekan Ctrl+R untuk melihatnya berjalan di browser Anda! Di laman-laman berikutnya, panduan ini akan memperkenalkan Anda dengan syntax dan fitur-fitur bahasa JavaScript, sehingga Anda dapat menulis aplikasi yang lebih kompleks. Tapi untuk saat ini, ingatlah untuk selalu memasukkan (function(){"use strict"; sebelum kode Anda, dan tambahkan  })(); di akhir kode Anda. Anda akan mempelajari apa artinya itu, tetapi untuk sekarang mereka bisa dianggap melakukan:

- -
    -
  1. Meningkatkan performa secara masif
  2. -
  3. Mencegah semantik ceroboh dalam JavaScript yang menjatuhkan pemula
  4. -
  5. Mencegah code snippets yang dieksekusi dalam konsol untuk berinteraksi satu sama lain (misalnya sesuatu yang dibuat dalam suatu eksekusi konsol digunakan untuk eksekusi konsol yang lain).
  6. -
- -

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

diff --git a/files/id/web/javascript/guide/loops_and_iteration/index.html b/files/id/web/javascript/guide/loops_and_iteration/index.html deleted file mode 100644 index 506b033350..0000000000 --- a/files/id/web/javascript/guide/loops_and_iteration/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Loops and iteration -slug: Web/JavaScript/Guide/Loops_and_iteration -translation_of: Web/JavaScript/Guide/Loops_and_iteration -original_slug: Web/JavaScript/Panduan/Loops_and_iteration ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Control_flow_and_error_handling", "Web/JavaScript/Guide/Functions")}}
- -

Loop menawarkan cara cepat dan mudah untuk melakukan sesuatu secara berulang-ulang. Bab tentang Panduan JavaScript ini memperkenalkan berbagai pernyataan iterasi berbeda yang tersedia untuk JavaScript.

- -

Anda dapat menganggap loop sebagai versi permainan terkomputerisasi di mana Anda menyuruh seseorang untuk mengambil langkah X menuju satu arah lalu langkah Y ke arah yang lain; Sebagai contoh, gagasan "Pergilah lima langkah ke timur" dapat di ekspresikan dengan cara berikut sebagai sebuah loop (pengulangan):

- -
var langkah;
-for (langkah= 0; langkah< 5; langkah++) {
-  // berlari 5 kali, dengan nilai langkah 0 sampai 4.
-  console.log('Berjalan ke timur satu langkah');
-}
-
- -

Ada beberapa jenis loop yang berbeda, namun pada dasarnya semuanya melakukan hal yang sama, mereka mengulangi sebuah aksi beberapa kali (dan sebenarnya memungkinkan bahwa dapat saja menjadi nol). Berbagai mekanisme loop menawarkan berbagai cara untuk menentukan titik awal dan akhir perulangan. Ada berbagai situasi yang lebih mudah dikerjakan oleh sebuah tipe loop dibandingkan tipe (loop) yang lain.

- -

Pernyataan untuk loop yang disediakan dalam JavaScript adalah:

- - - -

for statement

- -

Sebuah {{jsxref("statements/for","for loop")}} mengulang hingga kondisi yang ditentukan evaluasinya menjadi salah/false.  for loop pada Javascript serupa dengan  for loop pada Java dan C. Sebuah statement (pernyataan) for   terlihat sebagai berikut:

- -
for ([initialExpression]; [condition];
-[incrementExpression]) statement
-
- -

Ketika sebuah for loop dieksekusi, Berikut ini akan terjadi:

- -
    -
  1. Ekspresi yang menginisialisasi yaitu initialExpression, Jika ada, maka akan di eksekusi. Ekspresi ini biasanya menginisialisasi satu atau lebih penghitung loop, tetapi sintaksnya memperbolehkan ekspresi dengan tingkat kerumitan apapun. Ekspresi ini juga bisa mendeklarasikan variabel.
  2. -
  3. Ekpresi condition di evaluasi. JIka value dari kondisi adalah true (benar), maka statement loop akan dieksekusi. Jika value dari condition false (salah), for loop akan dihentikan.  Jika ekspresi condition dihilangkan sama sekali, kondisinya diasumsikan benar.
  4. -
  5. Mengeksekusi Statement . Untuk mengeksekusi berbagai pernyataan, gunakanlah sebuah blok pernyataan ({ ... }untuk mengelompokkan pernyataan-pernyataan tersebut.
  6. -
  7. Jika ada, ekspresi baru incrementExpression di eksekusi.
  8. -
  9. Kontrol kembali ke langkah ke-2.
  10. -
- -

Contoh

- -

function (fungsi) berikut memuat sebuah statement for yang menghitung angka dari opsi yang terpilih dalam sebuah daftar scrolling  (sebuah elemen {{HTMLElement("select")}} yang memperbolehkan berbagai pilihan). Statement for mendeklarasikan variable i dan menginisialisasinya ke nol. Ia memeriksa bahwa i lebih kecil dari nomor dari opsi dalam elemen <select> , menampilkan statement if yang berhasil, dan menaikan i satu setelah masing-masing lolos melewati loop.

- -
<form name="selectForm">
-  <p>
-    <label for="musicTypes">Choose some music types, then click the button below:</label>
-    <select id="musicTypes" name="musicTypes" multiple="multiple">
-      <option selected="selected">R&B</option>
-      <option>Jazz</option>
-      <option>Blues</option>
-      <option>New Age</option>
-      <option>Classical</option>
-      <option>Opera</option>
-    </select>
-  </p>
-  <p><input id="btn" type="button" value="How many are selected?" /></p>
-</form>
-
-<script>
-function howMany(selectObject) {
-  var numberSelected = 0;
-  for (var i = 0; i < selectObject.options.length; i++) {
-    if (selectObject.options[i].selected) {
-      numberSelected++;
-    }
-  }
-  return numberSelected;
-}
-
-var btn = document.getElementById('btn');
-btn.addEventListener('click', function() {
-  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
-});
-</script>
-
-
- -

do...while statement

- -

Pernyataan/statement {{jsxref("statements/do...while", "do...while")}} terus di ulangi sampai evaluasi kondisi bernilai false/salah. Sebuah do...while statement terlihat sebagai berikut:

- -
do
-  statement
-while (condition);
-
- -

statement di jalankan lebih dulu sebelum kondisi diperiksa. Untuk menjalankan banyak statements, gunakan statement blok ({ ... }) untuk membuat grup dari statement tersebut. Jika condition bernilai benar, maka statement akan dijalankan kembali. Kondisi diperiksa pada setiap akhir eksekusi. Ketika kondisi bernilai salah, eksekusi berhenti dan kontrol akan melewati pernyataan yang mengikuti do...while.

- -

Contoh

- -

Dalam contoh berikut, perulangan do di iterasi sekali dan di iterasi kembali sampai i tidak lagi kurang dari 5. 

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

while statement

- -

Sebuah statement {{jsxref("statements/while","while")}} di eksekusi pernyataan pernyataannya asalkan memenuhi syarat kondisinya yang bernilai true/benar. Sebuah statement  while terlihat sebagai berikut:

- -
while (condition)
-  statement
-
- -

Jika kondisi bernilai false/salah, statement dengan perulangan berhenti di eksekusi dan kontrol akan melewati statement yang mengikuti perulangan tersebut.

- -

Kondisi terjadi sebelum statement dalam perulangan di eksekusi. Jika kondisi bernilai true/benar, statement di eksekusi dan kondisi di uji kembali. Jika kondisi bernilai false/salah, eksekusi akan berhenti dan konrol lewat untuk statement yang mengikuti while.

- -

Untuk mengeksekusi banyak statement, gunakan blok statement ({ ... }) untuk mengelompokan banyak statement tersebut.

- -

Contoh 1

- -

Beikut perulangan while mengiterasi n selama n kurang dari tiga:

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

Dengan setiap iterasi, perulangan akan menambahkan increments n dan menambahkan nilainya pada  x. Karena itu, x dan n mengambil nilai nilai berikut:

- - - -

Setelah melewati perulangan yang ketiga , kondisinya n < 3 tidak lagi bernilai true/benar, jadi perulangan di hentikan.

- -

Contoh 2

- -

Hindari perulangan tanpa batas. Pastikan kondisi dalam perulangan mendapatkan kondisi yang bernilai false/salah untuk berhenti, jika tidak perulangan tidak akan pernah berhenti. Statements dalam while berikut di eksekusi berulang kali selamanya karena kondisi tidak pernah mendapatkan nilai false/salah:

- -
while (true) {
-  console.log('Hello, world!');
-}
- -

labeled statement

- -

Sebuah {{jsxref("statements/label","label")}} menyediakan sebuah statement dengan pengenal yang memungkinkan Anda merujuknya di tempat lain dalam program Kamu. Untuk contohnya, Kamu dapat menggunakan label untuk mengidentifikasi pengulangan, lalu gunakan statement break atau continue untuk menunjukkan apakah suatu program harus memutuskan loop atau melanjutkan eksekusinya.

- -

Sintak dari statement berlabel terlihat seperti berikut:

- -
label :
-   statement
-
- -

Nilai dai sebuah label dapat berupa identifikasi JavaScript apa pun yang tidak dari kata  kunci yang ada pada javascript. statement
- yang Kamu identifikasi dengan label tersebut dapat berupa statement apa pun.

- -

Contoh

- -

Pada contoh ini, label markLoop mengidentifikasi sebuah perulangan while.

- -
markLoop:
-while (theMark == true) {
-   doSomething();
-}
- -

break statement

- -

Gunakan {{jsxref("statements/break","break")}} statement untuk menghentikan perulangan, switch, atau konjungsi dengan statement yang memakai label.

- - - -

Sintak dari statement break terlihat seperti ini:

- -
break [label];
-
- -

Bentuk pertama sintak mengakhiri perulangan atau switch; Bentuk kedua sintak mengakhiri statement dari spesifik label.

- -

Contoh 1

- -

Contoh berikut mengiterasi melewati elemen-elemen dalam array sampai menemukan indeks elemen  yang bernilai dari theValue:

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

Contoh 2: Breaking pada sebuah label

- -
var x = 0;
-var z = 0;
-labelCancelLoops: while (true) {
-  console.log('Outer loops: ' + x);
-  x += 1;
-  z = 1;
-  while (true) {
-    console.log('Inner loops: ' + z);
-    z += 1;
-    if (z === 10 && x === 10) {
-      break labelCancelLoops;
-    } else if (z === 10) {
-      break;
-    }
-  }
-}
-
- -

continue statement

- -

Statement {{jsxref("statements/continue","continue")}} bisa digunakan untuk memulai lagi statement while, do-while, for, atau label.

- - - -

Sintak statement continue terlihat sebagai berikut:

- -
continue [label];
-
- -

Contoh 1

- -

Contoh berikut menunjukkan sebuah perulangan while dengan sebuah statement continue yang di eksekusi ketika niai dari i adalah tiga  Jadi, n mengambil nilai satu, tiga, tujuh dan dua belas.

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

Contoh 2

- -

Sebuah statement yang berlabel checkiandj berisikan sebuah statement berlabel checkj. Jika ada continue , Programnya akan menghentikan iterasi saat ini dari checkj dan memulai iterasi selanjutnya. Setiap kali continue ditemui, checkj  di iterasi kembali sampai kondisinya bernilai false/salah. Ketika bernilai false/salah, Sisa dari statement checkiandj sudah selesai, dan checkiandj di iterasi kembali sampai kondisi bernilai salah false. Ketika bernilai salah false , program melanjutkan pada statement yang mengikuti checkiandj.

- -

JIka continue dipunyai label dari checkiandj, program akan terus berlanjut ke bagian atas dari statement checkiandj .

- -
checkiandj:
-  while (i < 4) {
-    console.log(i);
-    i += 1;
-    checkj:
-      while (j > 4) {
-        console.log(j);
-        j -= 1;
-        if ((j % 2) == 0) {
-          continue checkj;
-        }
-        console.log(j + ' is odd.');
-      }
-      console.log('i = ' + i);
-      console.log('j = ' + j);
-  }
- -

for...in statement

- -

Statement {{jsxref("statements/for...in","for...in")}} mengiterasi sebuah variabel spesifik diatas properti enumerable dari sebuah objek. Untuk setiap properti yang berbeda, JavaScript mengeksekusi pernyataan pernyataan yang spesifik. Sebuah statement for...in terlihat sebagai berikut:

- -
for (variable in object) {
-  statements
-}
-
- -

Contoh

- -

Function/fungsi berikut mengambil argumentnya dari sebuah objek dan nama objek. Lalu dia di iterasi diatas semua property objek dan mengembalikan sebuah string yang mendaftarkan nama properti dan nilainya.

- -
function dump_props(obj, obj_name) {
-  var result = '';
-  for (var i in obj) {
-    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
-  }
-  result += '<hr>';
-  return result;
-}
-
- -

Untuk sebuah objek car dengan property make dan model, result/hasil akan menjadi:

- -
car.make = Ford
-car.model = Mustang
-
- -

Arrays

- -

Meskipun mungkin menggunakan ini sebagai cara untuk melakukan iterasi di atas elemen {{jsxref("Array")}},statement for...in akan mengembalikan nilai nama property yang di tetapkan pengguna dalam penambahan numerik indek. Jadi lebih baik menggunakan tradisional perulangan {{jsxref("statements/for","for")}} dengan sebuah numerik indek ketika mengiterasi diatas array, karena statement  for...in mengiterasi diatas nama properti yang di tetapkan pengguna pada penambahan elemen array, Jika kamu merubah array, seperti menambahkan properti atau metode. 

- -

for...of statement

- -

Statement {{jsxref("statements/for...of","for...of")}} membuat sebuah iterasi perulangan diatas iterable objects (termasuk {{jsxref("Array")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("functions/arguments","arguments")}} object dan seterusnya), menjalankan hubungan iterasi khusus dengan statement yang akan dieksekusi untuk setiap nilai properti yang berbeda.

- -
for (variable of object) {
-  statement
-}
- -

Contoh berikut menampilkan perbedaan diantara sebuah perulangan for...of dan sebuah perulangan {{jsxref("statements/for...in","for...in")}}. Ketika for...in mengiterasi diatas nama-nama properti, for...of mengiterasi diatas nilai-nilai properti:

- -
let arr = [3, 5, 7];
-arr.foo = 'hello';
-
-for (let i in arr) {
-   console.log(i); // logs "0", "1", "2", "foo"
-}
-
-for (let i of arr) {
-   console.log(i); // logs 3, 5, 7
-}
-
- -

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

diff --git a/files/id/web/javascript/guide/numbers_and_dates/index.html b/files/id/web/javascript/guide/numbers_and_dates/index.html deleted file mode 100644 index 81ff248515..0000000000 --- a/files/id/web/javascript/guide/numbers_and_dates/index.html +++ /dev/null @@ -1,377 +0,0 @@ ---- -title: Numbers and dates -slug: Web/JavaScript/Guide/Numbers_and_dates -translation_of: Web/JavaScript/Guide/Numbers_and_dates -original_slug: Web/JavaScript/Panduan/Numbers_and_dates ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_Operators", "Web/JavaScript/Guide/Text_formatting")}}
- -

Pada Bab ini memperkenalkan cara menggunakan angka dan tanggal pada JavaScript.

- -

Angka

- -

Pada JavaScript, semua angka diimplementasikan kedalam double-precision 64-bit binary format IEEE 754 (mis. angka antara -(253 -1) dan 253 -1). Tidak ada jenis spesifik untuk integer. Selain bisa mewakili angka float, tipe data angka memiliki 3 nilai secara simbolik: +{{jsxref("Infinity")}}, -{{jsxref("Infinity")}}, dan {{jsxref("NaN")}} (bukan sebuah angka). Lihat juga JavaScript tipe data dan struktur untuk konteks dengan tipe data primitif JavaScript yang lain.

- -

Anda dapat menggunakan empat tipe angka literal: desimal, biner, oktal, dan heksadesimal.

- -

Angka Desimal

- -
1234567890
-42
-
-// Perhatikan ketika menggunakan angka berawalan nol:
-
-0888 // 888 diubah menjadi desimal
-0777 // diubah menjadi oktal pada non-strict mode (511 in decimal)
-
- -

Perhatikan bahwa desimal literal dapat dimulai dari nol(0) diikuti angka desimal yang lain, namun jika setiap angka setelah 0 lebih kecil dari 8, angkanya diubah menjadi oktal.

- -

Angka Biner

- -

Sintaks angka biner menggunakan angka nol diikuti dengan huruf kecil atau dengan huruf besar, huruf Latin "B" (0b atau 0B). Jika digit setelah 0b atau bukan 0 atau 1, menurut SyntaxError yang dilemparkan: "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Angka oktal

- -

Angka oktal menggunakan awalan angka nol. Jika digit setelah 0 berada diluar jangkauan 0 hinga 7, angka akan diintrepretasikan sebagai angka desimal.

- -
var n = 0755; // 493
-var m = 0644; // 420
-
- -

Mode ketat pada ECMAScript 5 melarang sintaks oktal. Oktal sintaks bukan bagian dari ECMAScript 5, namun didukung oleh semua peramban dengan cara awalan nomor oktal dengan angka nol: 0644 === 420 dan "\045" === "%". Pada ECMAScript 2015, angka oktal didukung jika diawali dengan 0o, e.g.: 

- -
var a = 0o10; // ES2015: 8
-
- -

Angka Heksadesimal

- -

Sintaks heksadesimal menggunakan awalan nol diikuti dengan huruf kecil atau huruf kapital Latin "X" (0x atau 0X). Jika digit setelah 0x berada diluar jangkauan (0123456789ABCDEF),  menurut SyntaxError yang dilemparkan: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Eksponensial

- -
1E3   // 1000
-2e6   // 2000000
-0.1e2 // 10
- -

Angka object

- -

The built-in {{jsxref("Number")}} objek memiliki properti untuk numerik konstanta, seperti nilai maksimal, bukan-sebuah-angka, dan tak terhingga. Anda tidak dapat mengganti nilai dari properti tersebut dan anda dapat menggunakannya sebagai berikut:

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
-
- -

Anda selalu mengacu pada properti dari objek angka yang telah ditentukan seperti yang ditunjukkan diatas, dan bukan sebagai properti objek angka yang anda tentukan.

- -

Tabel berikut meringkas sifat-sifat nomor object.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Properties of Number
PropertiDeskripsi
{{jsxref("Number.MAX_VALUE")}}Merepresantikan angka maksimal / terbesar
{{jsxref("Number.MIN_VALUE")}}Merepresantikan angka minimal / terkecil
{{jsxref("Number.NaN")}}Nilai spesial "bukan sebuah angka"
{{jsxref("Number.NEGATIVE_INFINITY")}}Nilai spesial negatif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.POSITIVE_INFINITY")}}Nilai spesial positif tak terhingga; dikembalikan pada overflow
{{jsxref("Number.EPSILON")}}Perbedaan antara satu dan nilai terkecil lebih besar dari satu yang dapat direpresentasikan sebagai {{jsxref("Number")}}.
{{jsxref("Number.MIN_SAFE_INTEGER")}}Bilangan bulat aman minimum dalam JavaScript.
{{jsxref("Number.MAX_SAFE_INTEGER")}}Bilangan bulat aman maksimum dalam JavaScript.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Methods of Number
MethodDescription
{{jsxref("Number.parseFloat()")}}Parses a string argument and returns a floating point number.
- Same as the global {{jsxref("parseFloat", "parseFloat()")}} function.
{{jsxref("Number.parseInt()")}}Parses a string argument and returns an integer of the specified radix or base.
- Same as the global {{jsxref("parseInt", "parseInt()")}} function.
{{jsxref("Number.isFinite()")}}Determines whether the passed value is a finite number.
{{jsxref("Number.isInteger()")}}Determines whether the passed value is an integer.
{{jsxref("Number.isNaN()")}}Determines whether the passed value is {{jsxref("Global_Objects/NaN", "NaN")}}. More robust version of the original global {{jsxref("Global_Objects/isNaN", "isNaN()")}}.
{{jsxref("Number.isSafeInteger()")}}Determines whether the provided value is a number that is a safe integer.
- -

Prototipe Angka menyediakan metode-metode untuk menampilkan informasi dari objek angka dalam format bervariasi. Tabel berikut meringkas metode-metode prototipe angka.

- - - - - - - - - - - - - - - - - - - - - - - -
Methods of Number.prototype
MethodDescription
{{jsxref("Number.toExponential", "toExponential()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi eksponensial.
{{jsxref("Number.toFixed", "toFixed()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point.
{{jsxref("Number.toPrecision", "toPrecision()")}}Mengembalikan string yang merepresentasikan nomor dalam notasi fixed-point yang lebih spesifik.
- -

Math object

- -

The built-in {{jsxref("Math")}} objek memiliki properti dan metode-metode untuk konstanta matematika dan fungsi-fungsi. Sebagai contoh, objek matematik PI properti memiliki nilai (3.141...), yang akan anda gunakan dalam aplikasi sebagai

- -
Math.PI
-
- -

Demikian pula, fungsi standard matematika merupakan metode-metode Math. termasuk trigonometri, logaritma, eksponensial, dan fungsi lainnya. Sebagai contoh, jika anda ingin menggunakan fungsi trigonometri sin, anda akan menulis

- -
Math.sin(1.56)
-
- -

Perhatikan bahwa semua metode trigonometri matematika menggunakan argumen dalam radian.

- -

Tabel berikut meringkas metode-metode objek matematik.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Methods of Math
MethodDescription
{{jsxref("Math.abs", "abs()")}}Nilai absolut
{{jsxref("Math.sin", "sin()")}}, {{jsxref("Math.cos", "cos()")}}, {{jsxref("Math.tan", "tan()")}}Fungsi trigonometri standar; dengan argumen dalam radian.
{{jsxref("Math.asin", "asin()")}}, {{jsxref("Math.acos", "acos()")}}, {{jsxref("Math.atan", "atan()")}}, {{jsxref("Math.atan2", "atan2()")}}Fungsi trigonometri terbalik; mengembalikan nilai dalam radian.
{{jsxref("Math.sinh", "sinh()")}}, {{jsxref("Math.cosh", "cosh()")}}, {{jsxref("Math.tanh", "tanh()")}}Fungsi hiperbolik. argumen dalam sudut hiperbolik.
{{jsxref("Math.asinh", "asinh()")}}, {{jsxref("Math.acosh", "acosh()")}}, {{jsxref("Math.atanh", "atanh()")}}Fungsi hiperbolik terbalik. mengembalikan nilai dalam sudut hiperbolik.
-

{{jsxref("Math.pow", "pow()")}}, {{jsxref("Math.exp", "exp()")}}, {{jsxref("Math.expm1", "expm1()")}}, {{jsxref("Math.log10", "log10()")}}, {{jsxref("Math.log1p", "log1p()")}}, {{jsxref("Math.log2", "log2()")}}

-
Fungsi eksponen dan logaritma.
{{jsxref("Math.floor", "floor()")}}, {{jsxref("Math.ceil", "ceil()")}}Mengembalikan angka bulat terkecil/terbesar kurang/lebih dari atau sama dengan pada sebuah argumen.
{{jsxref("Math.min", "min()")}}, {{jsxref("Math.max", "max()")}}Mengembalikan nilai minimum/maksimum sebuah koma terpisah dari angka sebagai argumen.
{{jsxref("Math.random", "random()")}}Megembalikan angka acak antara 0 dan 1.
{{jsxref("Math.round", "round()")}}, {{jsxref("Math.fround", "fround()")}}, {{jsxref("Math.trunc", "trunc()")}},Fungsi pembulatan dan pemotongan.
{{jsxref("Math.sqrt", "sqrt()")}}, {{jsxref("Math.cbrt", "cbrt()")}}, {{jsxref("Math.hypot", "hypot()")}}Akar kuadrat, akar pangkat tiga, akar kuadrat dari jumlah argumen persegi.
{{jsxref("Math.sign", "sign()")}}tanda sebuah angka, mengindikasikan angka apapun merupakan angka positif, negatif, atau nol.
{{jsxref("Math.clz32", "clz32()")}},
- {{jsxref("Math.imul", "imul()")}}
Angka yang dimulai dari nol bit dalam 32-bit.
- Hasil dari C-like 32-bit perkalian dari dua argumen.
- -

Tidak seperti beberapa objek lainnya, anda tidak perlu membuat objek matematika sendiri. anda selalu menggunakan built-in Math object.

- -

Date object

- -

JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

- -

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00, with a Unix Timestamp being the number of seconds since January 1, 1970, 00:00:00.

- -

The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

- -

To create a Date object:

- -
var dateObjectName = new Date([parameters]);
-
- -

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

- -

Calling Date without the new keyword returns a string representing the current date and time.

- -

The parameters in the preceding syntax can be any of the following:

- - - -

Methods of the Date object

- -

The Date object methods for handling dates and times fall into these broad categories:

- - - -

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

- - - -

For example, suppose you define the following date:

- -
var Xmas95 = new Date('December 25, 1995');
-
- -

Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 1995.

- -

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object.

- -

For example, the following code displays the number of days left in the current year:

- -
var today = new Date();
-var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
-endYear.setFullYear(today.getFullYear()); // Set year to this year
-var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
-var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
-var daysLeft = Math.round(daysLeft); //returns days left in the year
-
- -

This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

- -

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate object:

- -
var IPOdate = new Date();
-IPOdate.setTime(Date.parse('Aug 9, 1995'));
-
- -

Example

- -

In the following example, the function JSClock() returns the time in the format of a digital clock.

- -
function JSClock() {
-  var time = new Date();
-  var hour = time.getHours();
-  var minute = time.getMinutes();
-  var second = time.getSeconds();
-  var temp = '' + ((hour > 12) ? hour - 12 : hour);
-  if (hour == 0)
-    temp = '12';
-  temp += ((minute < 10) ? ':0' : ':') + minute;
-  temp += ((second < 10) ? ':0' : ':') + second;
-  temp += (hour >= 12) ? ' P.M.' : ' A.M.';
-  return temp;
-}
-
- -

The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute, and second to hour, minute, and second.

- -

The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 12), otherwise simply hour, unless hour is 0, in which case it becomes 12.

- -

The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

- -

Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater; otherwise, it appends "A.M." to temp.

- -

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

diff --git a/files/id/web/javascript/guide/working_with_objects/index.html b/files/id/web/javascript/guide/working_with_objects/index.html deleted file mode 100644 index 4baf443489..0000000000 --- a/files/id/web/javascript/guide/working_with_objects/index.html +++ /dev/null @@ -1,493 +0,0 @@ ---- -title: Bekerja dengan objek -slug: Web/JavaScript/Guide/Working_with_Objects -tags: - - I10n:priority - - JavaScript - - Konstruktor - - Membandingkan objek - - Objek - - Panduan - - Pemula - - dokumen -translation_of: Web/JavaScript/Guide/Working_with_Objects -original_slug: Web/JavaScript/Panduan/Working_with_Objects ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
- -

JavaScript dirancang berdasarkan paradigma berbasis objek sederhana. Objek adalah kumpulan dari properti, dan properti adalah sepasang hubungan antara nama (atau kunci) dan nilai. Nilai properti bisa berupa fungsi, Dalam hal ini properti itu disebut metode. Selain objek yang sudah di tentukan pada peramban, Kamu bisa menentukan objekmu sendiri. Bab ini menjelaskan cara memakai objek, properti, fungsi, dan metode, serta bagaimana cara membuat objekmu sendiri.

- -

Ikhtisar objek

- -

Objek di JavaScript sama seperti kebanyakan bahasa pemrograman lainnya, bisa dibandingkan dengan objek dalam kehidupan nyata. Konsep objek dalam JavaScript dapat dipahami dengan kehidupan nyata, objek nyata.

- -

Di JavaScript, objek adalah entitas yang mandiri dengan properti dan tipe. Bandingkan dengan cangkir, misalnya. Sebuah cangkir adalah objek dengan banyak properti. Cangkir punya warna, desain, berat, materi bahan, dll. Dengan cara sama, objek JavaScript juga punya banyak properti yang menjelaskan karakteristiknya.

- -

Objek dan properti

- -

Objek JavaScript punya banyak properti yang terkait dengannya. Properti dari objek dapat didefinisikan sebagai variabel yang dilampirkan pada objek itu. Properti dari objek pada dasarnya sama dengan variabel JavaScript biasa, kecuali lampiran pada objek. Properti objek menentukan karakteristik objek itu. Kamu mengakses properti objek dengan sebuah notasi titik sederhana:

- -
objectName.propertyName
-
- -

Seperti semua variabel JavaScript, baik nama objek (bisa jadi variabel normal) maupun nama properti peka terhadap besar huruf. Kamu bisa mendefinisi properti dengan mengassign nilai. Contohnya, ayo buat objek bernama myCar dan dan berikan dia properti bernama make, model, dan year sebagai berikut:

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

Nilai properti objek yang tidak diassign adalah {{jsxref("undefined")}} (dan bukan {{jsxref("null")}}).

- -
myCar.color; // undefined
- -

Properti dari objek JavaScript juga bisa diakses atau diset menggunakan notasi kurung siku (untuk lebih detil lihat aksesor properti). Terkadang objek disebut associative array, karena tiap properti dikaitkan dengan nilai string yang bisa digunakan untuk mengaksesnya. Jadi, contohnya, kamu bisa mengakses properti dari objek myCar seperti berikut:

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

Nama properti objek bisa berupa string dari JavaScript yang valid, atau apapun yang dapat diubah menjadi string, termasuk string kosong. Namun, nama properti apapun yang tidak valid sebagai identitas di JavaScript (contohnya, nama properti yang memiliki spasi atau tanda hubung, atau yang dimulai dengan angka) hanya bisa diakses menggunakan notasi kurung siku. Notasi ini juga sangat berguna ketika nama properti harus ditentukan secara dinamis (ketika nama properti belum ditentukan hingga runtime). Contohnya sebagai berikut:

- -
// empat variabel dibuat dan diberi nilai sekali jalan,
-// dipisahkan oleh koma
-var myObj = new Object(),
-    str = 'myString',
-    rand = Math.random(),
-    obj = new Object();
-
-myObj.type              = 'Syntax titik';
-myObj['date created']   = 'String dengan spasi';
-myObj[str]              = 'Nilai string';
-myObj[rand]             = 'Angka Random';
-myObj[obj]              = 'Objek';
-myObj['']               = 'Bahkan string kosong';
-
-console.log(myObj);
-
- -

Tolong dicatat bahwa semua kunci di dalam notasi kurung siku diubah ke dalam tipe String, karena objek JavaScript hanya bisa punya tipe String sebagai tipe kunci. Contohnya, dalam kode di atas, ketika kunci  obj ditambahkan dalam myObj, JavaScript akan memanggil method obj.toString() , dan menggunakan hasil string ini sebagai kunci baru.

- -

Kamu juga bisa mengakses properti menggunakan nilai string yang disimpan dalam variabel:

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

Kamu bisa menggunakan notasi kurung siku dengan for...in untuk mengiterasi ulang semua kumpulan properti yang terdaftar dari sebuah objek. Untuk mengilustrasikan cara kerjanya, fungsi berikut ini menampilkan properti dari objek ketika kamu memasukkan objek dan nama objek sebagai argumen pada fungsi:

- -
function showProps(obj, objName) {
-  var result = '';
-  for (var i in obj) {
-    // obj.hasOwnProperty() digunakan untuk menyaring properti dari rantai prototipe objek
-    if (obj.hasOwnProperty(i)) {
-      result += objName + '.' + i + ' = ' + obj[i] + '\n';
-    }
-  }
-  return result;
-}
-
- -

Jadi memanggil fungsi showProps(mobilKu, "mobilKu") akan mengembalikan:

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

Mengenumerasi properti dari objek

- -

Mulai ECMAScript 5, ada tiga cara asli untuk mendaftarkan/melintasi properti objek:

- - - -

Sebelum ECMAScript 5, tidak ada cara asli untuk mendaftarkan semua properti-properti dari suatu objek. Namun, ini dapat dicapai dengan fungsi berikut:

- -
function listAllProperties(o) {
-	var objectToInspect;
-	var result = [];
-
-	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
-      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
-	}
-
-	return result;
-}
-
- -

Ini dapat berguna untuk memperlihatkan properti-properti  tersembunyi" (properti-properti dalam rantai prototip yang tidak dapat diakses melalui objek, karena properti lain memiliki nama yang sama di rantai prototip sebelumnya). Mendaftarkan properti-properti yang dapat diakses hanya dapat dilakukan dengan menghapus duplikat di dalam array.

- -

Membuat objek baru

- -

JavaScript mempunyai sejumlah objek yang telah ditetapkan. Selain itu, kamu dapat membuat objek sendiri. Kamu bisa membuat sebuah objek menngunakan sebuah object initializer. Sebagai alternatif, kamu bisa membuat sebuah fungsi konstruktor lalu menginstanisasi sebuah pemanggilan objek bersama dengan operator new.

- -

Menggunakan object initializer

- -

Selain membuat objek menggunakan fungsi konstruktor, kamu bisa membuat objek memakai object initializer. Kadang pemakaian object initializer disamakan dengan pembuatan objek dengan notasi literal. "Object initializer" sama dengan terminologi dalam C++.

- -

Syntax untuk objek yang menggunakan object initializer ialah:

- -
var obj = { property_1:   value_1,   // property_# bisa berupa identifier...
-            2:            value_2,   // atau angka...
-            // ...,
-            'property n': value_n }; // atau string
-
- -

Di mana obj adalah nama objek baru, setiap property_i adalah identifier (baik nama, angka, atau string literal), dan setiap value_i adalah expresi yang nilainya diassign ke property_i.  obj dan assignment adalah opsional, jika kamu tidak butuh rujukan ke objek ini, kamu tak usah mengassign dia ke variabel. (Ingat bahwa kamu harus membungkus literal objek dalam tanda kurung jika objeknya muncul dalam statement diharapkan, supaya bisa membedakan mana literal dan mana statement blok.)

- -

Object initializer adalah expresi, dan setiap object initializer mengembalikan objek baru. Objek baru dibuat saat ia muncul dalam statement yang dieksekusi. Object initializer yang identik membuat objek berbeda yang tidak akan sama bila dibandingkan. Objek dibuat seolah-olah ada panggilan new Object(); yaitu, objek yang dibuat dari expresi literal objek adalah instance dari Object.

- -

Statement berikut membuat objek dan mengassign dia ke variabel x jika dan hanya jika expresi cond benar:

- -
if (cond) var x = {greeting: 'hi there'};
-
- -

Contoh berikut membuat myHonda dengan tiga properti. Ingat bahwa properti engine juga adalah objek yang punya properti sendiri.

- -
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
-
- -

Kamu juga bisa menggunakan object initializer untuk membuat array. Lihat literal array.

- -

Menggunakan fungsi konstruktor

- -

Kamu bisa membuat objek dengan dua langkah alternatif ini:

- -
    -
  1. Definisikan tipe objek dengan menulis fungsi konstruktor. Ada konvensi dengan alasan bagus untuk menggunakan huruf kapital inisial.
  2. -
  3. Membuat instance objek dengan new.
  4. -
- -

Untuk mendefinisi tipe objek, buat fungsi untuk tipe objek tersebut yang menspesifikasi nama, properti, dan metodenya. Misalnya, kamu ingin membuat tipe objek untuk mobil. Kamu ingin jenis objek ini disebut Car, dan kamu ingin punya properti pembuat, model, dan tahun. Untuk melakukan ini, kamu akan menulis fungsi berikut:

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
- -

Perhatikan penggunaan this untuk mengassign nilai ke properti objek berdasarkan nilai yang diteruskan kepada fungsi.

- -

Sekarang kamu bisa membuat objek myCar sebagai berikut:

- -
var mycar = new Car('Eagle', 'Talon TSi', 1993);
- -

Statement ini membuat myCar dan mengassign ia nilai spesifik untuk propertinya. Lalu nilai dari myCar.make ialah string "Eagle", myCar.year ialah integer 1993, dan seterusnya.

- -

Kamu bisa membuat sejumlah objek Car dengan memanggil new. Sebagai contoh.

- -
var kenscar = new Car('Nissan', '300ZX', 1992);
-var vpgscar = new Car('Mazda', 'Miata', 1990);
- -

Objek bisa punya properti yang merupakan objek lain. Misalnya, kamu mendefinisi objek person sebagai berikut:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
- -

dan kemudian menginstantiasi dua objek person baru sebagai berikut:

- -
var rand = new Person('Rand McKinnon', 33, 'M');
-var ken = new Person('Ken Jones', 39, 'M');
- -

Kemudian, kamu bisa menulis ulang definisi Car untuk memasukkan properti owner yang mengambil objek person sebagai berikut:

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-}
- -

Untuk menginstantiasi objek baru, gunakan ini:

- -
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
-var car2 = new Car('Nissan', '300ZX', 1992, ken);
- -

Perhatikan bahwa ketimbang meneruskan nilai string atau integer literal ketika membuat objek baru, statement diatas meneruskan objek rand dan ken sebagai argumen untuk pemilik. Lalu jika kamu mau mencari nama pemilik car2, kamu bisa mengakses properti berikut:

- -
car2.owner.name
-
- -

Ingat bahwa kamu selalu bisa menambah properti ke objek yang sudah dibuat sebelumnya. Contohnya statement

- -
car1.color = 'black';
-
- -

menambah properti color pada car1, dan mengassign nilai "black". Ini tak mempengaruhi objek lain. Untuk menambah properti baru ke semua objek dari tipe yang sama, kamu harus menambah properti pada definisi tipe objek Car.

- -

Menggunakan metode Object.create

- -

Objek bisa juga dibuat menggunakan metode {{jsxref("Object.create()")}}. Metode ini bisa sangat berguna, karena ia memungkinkan kamu memilih prototipe objek untuk objek yang mau kamu buat, tanpa harus mendefinisi fungsi konstruktor.

- -
// Enkapsulasi metode dan properti Animal
-var Animal = {
-  type: 'Invertebrates', // Nilai properti default
-  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
- -

Warisan

- -

Semua objek di javascript diwariskan setidaknya dari satu objek lain. Objek yang diwariskan disebut prototipe, dan properti warisan bisa ditemukan dalam objek prototype dari konstruktor. Lihat Rantai warisan dan prototype untuk informasi lebih lanjut.

- -

Mengindex properti objek

- -

Kamu dapat merujuk ke properti dari objek menggunakan nama propertinya ataupun index urutannya. Jika kamu awalnya mendefinisi properti memakai namanya, kamu harus selalu merujuknya dengan namanya, dan jika kamu awalnya mendefinisikan properti memakai index, kamu harus selalu merujuknya dengan indexnya.

- -

Pembatasan ini berlaku ketika kamu membuat objek dan propertinya dengan fungsi konstruktor (seperti yang kita lakukan sebelumnya dengan jenis objek Car) dan ketika kamu mendefinisi properti individual secara explisit (misalnya, myCar.color = "ref"). Jika kamu awalnya mendefinisi properti objek dengan index, seperti myCar[5] = "25 mpg", maka kamu merujuk ke properti tersebut dengan myCar[5].

- -

Pengecualian dalam aturan ini adalah objek mirip-array pantulan dari HTML, seperti objek mirip-array forms. Kamu selalu dapat merujuk ke objek dalam objek mirip-array ini menggunakan nomor urutan mereka (berdasarkan di mana mereka muncul dalam dokumen) atau nama mereka (jika didefinisi). Misalnya, jika tag <FORM> kedua dalam dokumen punya atribut NAME "myForm", kamu dapat merujuk ke form tersebut sebagai document.forms[1] atau document.forms["myForm"] atau document.forms.myForm.

- -

Mendefinisi properti untuk tipe objek

- -

Kamu dapat menambah properti ke tipe objek yang didefinisi sebelumnya menggunakan properti prototype. Ini mendefinisi properti yang dibagikan semua objek dari tipe yang dispesifikasi, bukan cuma satu instance objek. Kode berikut menambahkan sebuah properti color ke semua objek dari tipe objek Car, dan kemudian mengassign nilai ke properti color dari objek car1.

- -
Car.prototype.color = null;
-car1.color = 'black';
- -

Lihat properti prototipe dari objek Function dalam referensi JavaScript untuk informasi lebih lanjut.

- -

Mendefiniskan metode

- -

Metode ialah fungsi yang terasosiasi dengan objek, atau sederhananya, metode ialah properti dari objek berupa fungsi. Metode didefinisi sebagai cara fungsi nornal didefinisi, kecuali mereka harus diassign sebagai properti objek. Lihat juga definisi metode untuk lebih detil. Contohnya:

- -
objectName.methodname = functionName;
-
-var myObj = {
-  myMethod: function(params) {
-    // ...do something
-  }
-
-  // OR THIS WORKS TOO
-
-  myOtherMethod(params) {
-    // ...do something else
-  }
-};
-
- -

Di mana objectName adalah metode yang sudah ada, methodname ialah nama yang kamu assign ke metode, dan functionName adalah nama fungsi.

- -

Lalu kamu bisa memanggil metode dalam kontex objek sebagai berikut:

- -
object.methodname(params);
-
- -

Kamu bisa mendefinisi metode untuk tipe objek dengan memasukkan sebuah definisi metode dalam fungsi konstruktor objek. Kamu bisa mendefinisi fungsi yang akan memformat dan menampilkan properti objek Car sebelumnya; contohnya,

- -
function displayCar() {
-  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
-  pretty_print(result);
-}
- -

Di mana pretty_print adalah fungsi untuk menampilkan garis horizontal dan string. Perhatikan penggunaan this untuk merujuk ke objek yang punya metode tersebut.

- -

Kamu bisa menjadikan fungsi ini metode Car dengan menambah statement

- -
this.displayCar = displayCar;
- -

ke definisi objek. Jadi definisi penuh dari Car sekarang akan terlihat seperti

- -
function Car(make, model, year, owner) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-  this.owner = owner;
-  this.displayCar = displayCar;
-}
- -

Maka kamu bisa memanggil metode displayCar untuk masing-masig objek sebagai berikut:

- -
car1.displayCar();
-car2.displayCar();
- -

Menggunakan this untuk referensi Objek

- -

JavaScript punya katakunci spesial this, kamu bisa memakainya dalam metode untuk merujuk ke objek saat ini. Misalnya, kamu punya fungsi yang disebut validate yang memvalidasi properti value, yang diberikan objek dan nilai atas dan bawah:

- -
function validate(obj, lowval, hival) {
-  if ((obj.value < lowval) || (obj.value > hival)) {
-    alert('Invalid Value!');
-  }
-}
-
- -

Kemudian kamu bisa panggil validate di penangan event onchange setiap elemen form, gunakan this untuk meneruskan elemen. Seperti contoh berikut:

- -
<input type="text" name="age" size="3"
-  onChange="validate(this, 18, 99)">
-
- -

Secara umum, this merujuk ke pemanggilan objek dalam metode.

- -

Ketika dikombinasikan dengan properti form, this bisa mengacu ke induk objek form saat ini. Dalam contoh berikut, form myForm berisi objek Text dan sebuah tombol. Ketika pengguna mengklik tombol, nilai objek Text diset ke nama form tersebut. Penangan event onclick tombol menggunakan this.form untuk merujuk ke induk form, myForm.

- -
<form name="myForm">
-<p><label>Form name:<input type="text" name="text1" value="Beluga"></label>
-<p><input name="button1" type="button" value="Show Form Name"
-     onclick="this.form.text1.value = this.form.name">
-</p>
-</form>
- -

Mendefinisikan getter dan setter

- -

Getter ialah metode yang mendapat nilai dari properti spesifik. Setter ialah metode yang mengatur nilai properti spesifik. Kamu bisa mendefinisi getter dan setter objek inti apapun yang sudah ditetapkan atau objek yang ditetapkan pengguna yang mendukung penambahan peroperti-properti baru. Syntax untuk mendefinisi getter dan setter menggunakan syntax literal objek.

- -

Berikut ilustrasi cara getter dan setter bisa bekerja untuk objek o yang sudah didefinisi user.

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

Properti objek o adalah:

- - - -

Harap diingat bahwa nama fungsi dari getter dan setter yang didefisini dalam literal objek menggunakan "[gs]et property()" (dibandingkan dengan __define[GS]etter__ ) bukanlah nama getter mereka sendiri, meski syntax [gs]et propertyName(){ } membuatmu berpikir lain. Untuk menamai fungsi dalam getter atau setter menggunakan syntax "[gs]et property()", definiskan fungsi, dengan nama explisit, secara terprogram menggunakan Object.defineProperty (atau pengganti legacy Object.prototype.__defineGetter__).

- -

Kode berikut mengilustrasikan cara getter dan setter bisa memperluas prototipe {{jsxref("Date")}} untuk menambah properti year ke semua instance dari kelas Date yang sudah didefinisi. Ia menggunakan metode kelas Date yang sudah ada, getFullYear dan setFullYear untuk mendukung properti getter dan setter year.

- -

Statement ini mendefinisi getter dan setter untuk properti tahun:

- -
var d = Date.prototype;
-Object.defineProperty(d, 'year', {
-  get: function() { return this.getFullYear(); },
-  set: function(y) { this.setFullYear(y); }
-});
-
- -

Statement ini menggunakan getter dan setter dalam objek Date:

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

Secara pinsip, getter dan setter bisa

- - - -

Ketika mendefiniisi getter dan setter menggunakan object initializer yang harus kamu lakukan adalah memprefix metode getter dengan get dan metode setter dengan set. Tentunya, metode getter tidak boleh mengharapkan parameter, lalu metode setter mengharapkan hanya satu parameter (nilai baru untuk diset). Contohnya:

- -
var o = {
-  a: 7,
-  get b() { return this.a + 1; },
-  set c(x) { this.a = x / 2; }
-};
-
- -

Getter dan setter juga bisa ditambah ke objek kapanpun setelah membuat objek menggunakan metode Object.defineProperties. Parameter pertama metode ini ialah object tempat kamu mendefinisi getter atau setter. Parameter kedua ialah objek yang nama propertinya berupa nama getter atau setter,dan yang nilai propertinya berupa objek yang mendefinisi fungsi getter atau setter. Berikut adalah contoh mendefinisi getter dan setter yang sama yang digunakan dalam contoh sebelumnya:

- -
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; // Menjalankan setter, yang mengassign 10 / 2 (5) ke properti 'a'
-console.log(o.b); // Menjalankan getter, yang menghasilkan a + 1 atau 6
-
- -

Yang manapun dari dua form ini yang dipilih tergantung dari gaya pemrograman dan tugas di tangan. Jika kamu sudah memilih object initializer ketika mendefinisi prototipe kamu mungkin akan sering memilih form pertama. Form ini lebih compact dan natural. Namun, kalau kamu harus menambah getter dan setter nanti — karena kamu tak menulis prototipenya atau object khusus — maka form kedua menjadi satu-satunya solusi. Form kedua mungkin paling baik mewakiliki sifat dinamis JavaScript — tapi ia bisa membuat kode sulit dibaca dan dipahami.

- -

Menghapus properti

- -

Kamu bisa menghapus properti yang bukan warisan menggunakan operator delete. Kode berikut menampilkan cara menghapus properti.

- -
// Membuat objek baru, myobj, dengan dua properti, a dan b.
-var myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// Mengapus properti a, menyisakan myobj hanya dengan properti b.
-delete myobj.a;
-console.log ('a' in myobj); // menghasilkan "false"
-
- -

Kamu juga bisa memakai delete untuk menghapus variabel global jika katakunci var tidak dipakai untuk mendeklarasi variabel itu:

- -
g = 17;
-delete g;
-
- -

Membandingkan objek

- -

Dalam JavaScript objek ialah tipe referensi. Dua objek berbeda tak akan pernah sama, meski mereka punya properti yang sama. Hanya membandingkan referensi objek yang sama dengannya menghasilkan true.

- -
// Dua variabel, dua objek berbeda dengan properti yang sama
-var fruit = {name: 'apple'};
-var fruitbear = {name: 'apple'};
-
-fruit == fruitbear; // mengembalikan false
-fruit === fruitbear; // mengembalikan false
- -
// Dua variabel, objek tunggal
-var fruit = {name: 'apple'};
-var fruitbear = fruit;  // assign referensi objek buah ke fruitbear
-
-// di sini fruit dan fruitbear menunjuk ke objek yang sama
-fruit == fruitbear; // mengembalikan true
-fruit === fruitbear; // mengembalikan true
-
- -
fruit.name = 'grape';
-console.log(fruitbear);    // menghasilkan { name: "grape" } ketimbang { name: "apple" }
-
- -

Untuk informasi lebih tentang operator pembandingan, lihat Operator pembandingan.

- -

Lihat juga

- - - -

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git a/files/id/web/javascript/index.html b/files/id/web/javascript/index.html deleted file mode 100644 index bfc6233ce4..0000000000 --- a/files/id/web/javascript/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: JavaScript -slug: Web/JavaScript -tags: - - JavaScript - - belajar -translation_of: Web/JavaScript ---- -
{{JsSidebar}}
- -

JavaScript (JS) sangat ringan, terinterpretasi, bahasa pemrogramman dengan first-class functions. Umum dikenal sebagai bahasa scripting untuk halaman web, Banyak lingkungan non-browser juga menggunakan javascript, seperti node.js dan Apache CouchDB. JS merupakan prototype-based, multi-paradigm, bahasa scripting dinamis, medukung object-oriented, diperlukan, dan declarative (mis. functional programming) styles. Baca lebih lanjut about JavaScript.

- -

Bagian situs ini didedikasikan untuk bahasa javascript dan bukan bagian yang spesifik dengan halaman web atau lingkungan host lain. Untuk informasi tentang {{Glossary("API","APIs")}} yang spesifik untuk halaman web, Lihat Web APIs dan DOM.

- -

Standar untuk JavaScript adalah ECMAScript. Seperti pada 2012, semua modern browsers mendukung ECMAScript 5.1. Browser lama mendukung setidaknya  ECMAScript 3. Juni 17, 2015, ECMA International mempublikasikan versi major keenam dari ECMAScript, yang secara ofisial disebut ECMAScript 2015, dan umumnya dikaitkan sebagai ECMAScript 6 atau ES6. Sejak ketika standar ECMAScript pada siklus rilis tahunan. Dokumentasi ini mengacu pada draft versi terbaru, saat ini ECMAScript 2018.

- -

Jangan keliru antara JavaScript dengan Bahasa pemrograman java. Keduanya "Java" dan "JavaScript" adalah merek dagang dan merek ini terdaftar oleh Oracle di U.S. dan negara lainnya. Namun, kedua bahasa pemrograman tersebut memiliki sintaks, struktur, dan penggunaan yang berbeda.

- -
-
-

Tutorial

- -

Belajar cara menulis program di javascript dengan paduan dan tutorial.

- -

Untuk Pemula

- -

Pergilah ke topik Area Pembelajaran JavaScript kami jika Anda ingin belajar JavaScript dan belum memiliki pengalaman dari pemrograman JavaScript. Tersedia modul lengkap sebagai berikut:

- -

Langkah pertama JavaScript
-      Jawaban beberapa pertanyaan mendasar seperti "apa itu JavaScript?", "Seperti apa tampilannya?", Dan "apa yang bisa dilakukan?", Bersama mendiskusikan fitur utama JavaScript seperti variabel, string, angka dan array.

- -

Bangunan Blok JavaScript
-     Lanjutan jangkauan dari fitur dasar kunci JavaScript, arahkan perhatian pada jenis blok kode yang biasa ditemukan seperti statement kondisional, loop, fungsi, dan events.

- -

Perkenalan Objek JavaScript
-      Sifat JavaScript yang berorientasi objek penting untuk dipahami jika Anda ingin melangkah lebih jauh dengan pengetahuan Anda tentang bahasanya dan menulis kode yang lebih efisien, oleh karena itu kami menyediakan modul ini untuk membantu Anda.

- -

Pengantar

- -
-
Paduan JavaScript
-
Jika anda baru mengenal javascript, paduan ini akan menuntun anda belajar.
-
Ikhtisar Teknologi JavaScript
-
Pengantar javascript pada lingkungan web browser.
-
Pengantar JavaScript Berbasis Objek
-
Pengantar pada konsep dari bahasa berorientasi object di JavaScript.
-
- -

Menengah

- -
-
Mengenal kembali JavaScript
-
Gambaran bagi mereka yang berfikir mengetahui tentang JavaScript.
-
- -
-
Struktur data JavaScript
-
Gambaran struktur data yang tersedia di JavaScript.
-
Perbandingan kesetaraan dan kesamaan
-
JavaScript  menyediakan tiga operasi perbandingan yang berbeda: perbandingan stric ===, perbandingan loggar menggunakan ==, dan method {{jsxref("Global_Objects/Object/is", "Object.is()")}}.
-
- -

Lanjut

- -
-
Pewarisan dan rantai purwarupa
-
Menjelaskan tentang kesalah-pahaman dan meremehkan yang terjadi pada  pewarisan berbasis purwarupa.
-
Mode Strict
-
Mode strict mendefinisikan bahwa anda tidak dapat menggunakan variabel sebelum menginisialisasinya. Ini bentuk batasan dari varian ECMAScript 5, berguna untuk performa yang lebih cepat dan debuging yang lebih mudah.
-
JavaScript typed arrays
-
JavaScript typed arrays menyediakan mekanisme untuk mengakses data binari mentah(raw).
-
Pengelolaan Memory
-
Siklus memori dan garbage collection di JavaScript.
-
Model konkurensi dan Event Loop
-
JavaScript memiliki model konkurensi berbasis pada "event loop".
-
-
- -
-

Referensi

- -

Jelajahi dokumentasi Referensi javaScript.

- -
-
Standard objects
-
Mencari tahu tentang standarbuilt-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}},{{jsxref("RegExp")}} , {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}} , {{jsxref("WeakSet")}}, dan lainnya.
-
Ekspresi dan operator
-
Belajar tentang cara kerja operator {{jsxref("Operators/instanceof", "instanceof")}},  {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}},  operator precedence, dan banyak lagi.
-
Statemen dan pendeklarasian
-
Belajar cara menggunakan {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, dan statement Javascript lain dan juga kerja keywords.
-
 Fungsi
-
Belajar bagaimana menggunakan fugsi untuk digunakan di aplikasi anda.
-
- -

Alat & sumber

- -

Alat yang dapat membantu anda menulis dan mendebug kode JavaScript.

- -
-
Firefox Developer Tools
-
Scratchpad, Web Console, JavaScript Profiler, Debugger, dan lainnya.
-
Firebug
-
Edit, debug, dan melihat CSS, HTML, juga JavaScript langsung di setiap halaman web.
-
JavaScript Shells
-
JavaScript shell memungkinkan anda untuk mencoba kode snippet JavaScript.
-
TogetherJS
-
Mempermudah kolaborasi.
-
Stack Overflow
-
Bertanya di Stack Overflow dengan tag "JavaScript".
-
Versi JavaScript dan catatan release
-
Jelajahi sejarah fitur JavaScript dan status implementasi.
-
JSFiddle
-
Edit JavaScript, CSS, HTML dan lihat secara langsung. Gunakan sumber dari luar dan berkolaborasi dengan tim anda secara online.
-
-
-
diff --git a/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html deleted file mode 100644 index 851bcbbb21..0000000000 --- a/files/id/web/javascript/inheritance_and_the_prototype_chain/index.html +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: Inheritance dan prototype chain -slug: Web/JavaScript/Inheritance_and_the_prototype_chain -translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain -original_slug: Web/JavaScript/Inheritance_dan_prototype_chain ---- -
{{jsSidebar("Advanced")}}
- -

JavaScript sedikit membingungkan bagi pengembang yang berpengalaman di pemrograman berbasis class (seperti java dan C++), sebagai bahasa dinamis dan tidak mendukung implementasi class lihat( keyword class dikenalkan pada ES2015, namun terkesan berlebihan, JavaScript merupakan bahasa berbasis prototype).

- -

Ketika menggunakan inheritance, JavaScript hanya memiliki satu construct: objek. Setiap objek memiliki sebuah private property ( berkenaan tentang [[Prototype]] ) yang memegang jalinan ke objek lain yang memanggil prototype tersebut. Prototype objek tersebut memiliki prototype sendiri, dan seterusnya hingga objek mencapai prototipe null. Dengan definisi, null tidak lagi memiliki prototype, dan berperan sebagai hubungan terakhir dari prototype chain.

- -

Hampir seluruh objek pada JavaScript merupakan instance dari {{jsxref("Object")}} dimana berada di atas prototype chain.

- -

Meskipun hal ini sering dianggap sebagai salah satu kelemahan JavaScript, model Inheritance prototype sebenarnya lebih hebat daripada model klasiknya. Hal ini, misalnya, cukup sepele untuk membangun model klasik di atas model prototipal.

- -

Inheritance dengan prototype chain

- -

Meng-Inheriting properti

- -

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 assume we have object o, with its own properties a and b:
-// {a: 1, b: 2}
-// o.[[Prototype]] has properties b and c:
-// {b: 3, c: 4}
-// Finally, o.[[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} ---> 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 null, stop searching,
-// no property found, return undefined.
-
- -

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 an own 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 own property 'a' of p
-
- -

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

With the class keyword

- -

ECMAScript 2015 introduced a new set of keywords implementing classes. Although these constructs look like those familiar to developers of class-based languages, they are not the same. JavaScript remains prototype-based. 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 performance, and this may be significant in 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 mis-feature 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.

- -

Example

- -

B shall inherit from A:

- -
function A(a) {
-  this.varA = a;
-}
-
-// What is the purpose of including varA in the prototype when A.prototype.varA will always be shadowed by
-// this.varA, given the definition of function A above?
-A.prototype = {
-  varA: null,  // Shouldn't we strike varA from the prototype as doing nothing?
-      // perhaps intended as an optimization to allocate space in hidden classes?
-      // https://developers.google.com/speed/articles/optimizing-javascript#Initializing-instance-variables
-      // would be valid if varA wasn't being initialized uniquely for each instance
-  doSomething: function() {
-    // ...
-  }
-};
-
-function B(a, b) {
-  A.call(this, a);
-  this.varB = b;
-}
-B.prototype = Object.create(A.prototype, {
-  varB: {
-    value: null,
-    enumerable: true,
-    configurable: true,
-    writable: true
-  },
-  doSomething: {
-    value: function() { // override
-      A.prototype.doSomething.apply(this, arguments); // call super
-      // ...
-    },
-    enumerable: true,
-    configurable: true,
-    writable: true
-  }
-});
-B.prototype.constructor = B;
-
-var b = new B();
-b.doSomething();
-
- -

The important parts are:

- - - -

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/id/web/javascript/javascript_technologies_overview/index.html b/files/id/web/javascript/javascript_technologies_overview/index.html deleted file mode 100644 index c988092b23..0000000000 --- a/files/id/web/javascript/javascript_technologies_overview/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Ikhtisar Teknologi JavaScript -slug: Web/JavaScript/JavaScript_technologies_overview -translation_of: Web/JavaScript/JavaScript_technologies_overview -original_slug: Web/JavaScript/sekilas_teknologi_JavaScript ---- -
{{JsSidebar("Introductory")}}
- -

Pengantar

- -

Jika HTML untuk mengatur struktur dan konten dari halaman web dan CSS untuk menetapkan format dan tampilannya, maka JavaScript digunakan untuk menambah interaksi pada halaman web dan menciptakan aplikasi web yang kaya.

- -

Namun, istilah "JavaScript" seperti yang dikenal pada konteks browser web berisi beberapa elemen yang sangat berbeda. Salah satunya adalah bahasa intinya (ECMAScript), yang lainnya adalah koleksi dari Web APIs, termasuk DOM (Document Object Model).

- -

Bahasa inti (ECMAScript) JavaScript

- -

Bahasa inti dari JavaScript distandarisasi oleh komite ECMA TC39 sebagai bahasa yang bernama ECMAScript.

- -

Bahasa inti ini juga digunakan pada lingkungan non-browser, misalnya node.js.

- -

Apa yang termasuk dalam lingkup ECMAScript?

- -

Diantaranya, ECMAScript menetapkan:

- - - -

Dukungan browser

- -

Pada Oktober 2016, versi terbaru dari sebagian besar browser Web sudah menerapkan ECMAScript 5.1 dan ECMAScript 2015, namun versi yang lebih lama (yang masih digunakan) hanya menerapkan ECMAScript 5.

- -

Masa depan

- -

ECMAScript Edisi ke-6 mayor telah secara resmi disetujui dan diumumkan sebagai standar pada 17 Juni 1015 oleh ECMA General Assembly. Sejak saat itu Edisi ECMAScript diumumkan secara tahunan.

- -

API Internasionalisasi

- -

Spesifikasi API Internasionalisasi ECMAScript merupakan tambahan dari Spesifikasi Bahasa ECMAScript, yang juga distandarisasi oleh Ecma TC39. API internasionalisasi menyediakan kolasi (perbandingan string), format angka, format tanggal dan jam untuk aplikasi JavaScript, memungkinkan aplikasi memilih bahasa dan menyesuaikan fungsi sesuai kebutuhannya. Standar awal telah disetujui pada Desember 2012; status impementasinya dalam browser dicatat di dokumentasi Intl object. Saat ini spesifikasi Internasionalisasi juga disahkan secara tahunan dan browser secara konsisten meningkatkan implementasinya.

- -

API DOM

- -

WebIDL

- -

WebIDL specification memberikan perekat antara teknologi DOM dan ECMAScript.

- -

Inti dari DOM

- -

Document Object Model (DOM) adalah bahasa konvensi independen lintas platform untuk mewakili dan berinteraksi dengan objects dalam dokumen HTML, XHTML dan XML. Objects didalam DOM tree dapat dialamatkan dan dimanipulasi dengan menggunakan methods pada objects. Core Document Object Model yang distandarisasi oleh {{glossary("W3C")}}, menetapkan antarmuka bahasa-agnostik untuk mengabstaraksi dokumen HTML dan XML sebagai objects, dan juga menetapkan mekanisme untuk memanipulasi abstraksi ini. Diantara yang ditetapkan oleh DOM, kita dapat menemukan:

- - - -

Dari sudut pandang ECMAScript, objects yang didefinisikan di spesifikasi DOM disebut "host objects".

- -

HTML DOM

- -

Bahasa markup Web (HTML) yang ditetapkan dari sisi DOM. Seperti dalam konsep abstrak yang dibahas diatas pada Inti DOM, HTML juga didefinisikan sebagai sebuah elemen. The HTML DOM menyertakan properti className pada elemen HTML, or APIs seperti {{ domxref("document.body") }}.

- -

Spesifikasi HTML juga menetapkan batasan pada dokumen; misalnya, ia memerlukan semua elemen anak dari sebuah ul untuk mewakili sebuah daftar tak urut, elemen li untuk mewakili daftar item. Secara umum, ia juga melarang penggunaan elemen dan atribut yang tidak didefinisikan dalam standar.

- -

Ingin mengetahui Document object, Window object, dan elemen DOM lainnya? Baca DOM documentation.

- -

API penting lainnya

- - - -

Dukungan browser

- -

Seperti kata pengembang web yang berpengalaman, DOM berantakan. Dukungan fitur-fitur DOM antar browser bervarasi, terutama disebabkan karena banyak fitur yang penting dari DOM sangat tidak jelas, spesifikasi (jika ada) dan browser web yang berbeda menambahkan fitur yang tidak kompatibel untuk overlapping use cases (misalnya Internet Explorer event model). Pada Juni 2011, W3C dan khususnya WHATWG menetapkan fitur-fitur lama secara rinci untuk meningkatkan interoperabilitas, dan browser pada akhirnya dapat meningkatkan implementasi mereka berdasarkan spesifikasi ini.

- -

Sebuah teknik umum, meskipun mungkin bukan yang paling dapat diandalkan, pendekatan kompatibilitas lintas browser adalah dengan menggunakan pustaka JavaScript, yang menggunakan fitur DOM abstrak untuk menjaga API mereka tetap bekerja di browser yang berbeda. Beberapa framework yang paling banyak digunakan adalah jQuery, prototype, dan YUI.

diff --git a/files/id/web/javascript/language_resources/index.html b/files/id/web/javascript/language_resources/index.html deleted file mode 100644 index bda5fe1f42..0000000000 --- a/files/id/web/javascript/language_resources/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: JavaScript language resources -slug: Web/JavaScript/Language_Resources -tags: - - Advanced - - JavaScript -translation_of: Web/JavaScript/Language_Resources ---- -
{{JsSidebar}}
- -

ECMAScript merupakan bahasa scripting yang membentuk basis dari  JavaScript. ECMAScript di standarisasi oleh organisasi standard ECMA International pada Spesifikasi ECMA-262 dan ECMA-402. Berikut ECMAScript standard yang telah disetujui atau masih dalam pengerjaan:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NamaLinkTanggal rilisDeskripsi
Edisi saat ini
ECMA-262 2017 (ES 8)Working draft, repository2017ECMAScript 2017 (8th Edition), currently work in progress.
ECMA-402 4.0Working draft, repository2017ECMAScript Internationalization API 4.0, currently work in progress.
Obsolete/historical editions
ECMA-262 (ES 1)PDFJune 1997the original ECMAScript standard.
ECMA-262 (ES 2)PDFAugust 1998the second revision of the ECMAScript standard; also ISO standard 16262.
ECMA-262 (ES 3)PDFDecember 1999the third revision of the ECMAScript standard; corresponds to JavaScript 1.5.
- See also the errata
ECMA-262 (ES 5)PDFDecember 2009ECMAScript 5
- See also the ES5 errata and ECMAScript 5 support in Mozilla
ECMA-357PDFJune 2004ECMAScript for XML (E4X).
- See also the E4X errata.
ECMA-357 Edition 2PDFDecember 2005ECMAScript for XML (E4X).
ECMA-262 (ES 5.1)PDF, HTMLJune 2011This version is fully aligned with 3rd edition of the international standard ISO/IEC 16262:2011.
- It includes ES5 errata fixes, no new features.
ECMA-402 1.0PDF, HTMLDecember 2012ECMAScript Internationalization API 1.0.
ECMA-262 2015 (ES 6)PDF, HTMLJune 2015ECMAScript 2015 (6th Edition).
ECMA-402 2.0PDFJune 2015ECMAScript Internationalization API 2.0.
ECMA-262 2016 (ES 7)HTMLJune 2016ECMAScript 2016 (7th Edition). Now feature frozen. To be ratified later this year (June).
ECMA-402 3.0HTMLJune 2016ECMAScript Internationalization API 3.0. To be ratified later this year (June).
- -

Lihat entri Wikipedia ECMAScript untuk info lebih lanjut tentang sejarah ECMAScript.

- -

Anda dapat berpartisipasi atau mengikuti pekerjaan di revisi berikutnya dari spasifikasi bahasa ECMAScript, nama kode "Harmony", dan Spesifikasi ECMAScript Internationalization API melalui public wiki dan es-discuss mailing list tercantum dari ecmascript.org.

- -

Implementasi

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/memory_management/index.html b/files/id/web/javascript/memory_management/index.html deleted file mode 100644 index 90242f72da..0000000000 --- a/files/id/web/javascript/memory_management/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Memory Management -slug: Web/JavaScript/Memory_Management -translation_of: Web/JavaScript/Memory_Management ---- -
{{JsSidebar("Advanced")}}
- -

Introduction

- -

Bahasa-bahasa Level Bawah, seperti C, memiliki manajemen memory level rendah yang primitiv seperti malloc() dan  free(). Pada bagian lain, nilai Javascript dialokasikan ketika sesuatu (objek, string,dll.) dibuat dan secara otomatis dibebaskan ketika tidak digunakan lagi. Proses terakhir disebut garbage collection. "Secara Otomatis" ini adalah sumber kekeliruan dan memberikan kesan developer Javascript (dan Bahasa tingkat tinggi lainnya) bahwa mereka bisa memilih untuk tidak mempedulikan tentang manajemen memory, maka itu adalah suatu kesalahan

- -

Low-level languages, like C, have low-level memory management primitives like malloc() and free(). On the other hand, JavaScript values are allocated when things (objects, strings, etc.) are created and "automatically" freed when they are not used anymore. The latter process is called garbage collection. This "automatically" is a source of confusion and gives JavaScript (and high-level languages) developers the impression they can decide not to care about memory management. This is a mistake.

- -

Siklus hidup sebuah memori

- -

Tanpa memperhatikan bahasa pemograman, siklus hidup memori pada akhirnya selalu sama :

- -
    -
  1. Mengalokasi memori yang kamu gunakan.
  2. -
  3. Menggunakan alokasi memori untuk (baca, tulis).
  4. -
  5. Membebaskan alokasi memori saat tidak digunakan lagi.
  6. -
- -

Bagian pertama dan kedua bersifat ekplisit untuk semua bahasa. Sedangkan untuk bagian terakhir adalah eksplisit untuk bahasa tingkat rendah, tetapi hampir semua bahasa tingkat atas seperti JavaScript juga bersifat implisit.

- -

Allocation in JavaScript

- -

Value initialization

- -

In order not to bother the programmer with allocations, JavaScript does it alongside with declaring values.

- -
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 value,
-// 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 value 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

- -

Most of memory management issues come at this phase. The hardest task here is to find when "the allocated memory is not needed any longer". It often requires for the developer to determine where in the program such piece of memory is not needed anymore and free it.

- -

High-level languages embed a piece of software called "garbage collector" whose job is to track memory allocation and use in order to find when a piece of allocated memory is not needed any longer in which case, it will automatically free it. This process is an approximation since the general problem of knowing whether some piece of memory is needed is undecidable (can't be solved by an algorithm).

- -

Garbage collection

- -

As stated above the general problem of automatically finding whether some memory "is not needed anymore" is undecidable. As a consequence, garbage collections implement a restriction of a solution to the general problem. This section will explain the necessary notions to understand the main garbage collection algorithms and their limitations.

- -

References

- -

The main notion garbage collection algorithms rely on is the notion of reference. Within the context of memory management, an object is said to reference another object if the former has an 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 "object" is extended to something broader than regular JavaScript objects and also contains function scopes (or the global lexical scope).

- -

Reference-counting garbage collection

- -

This is the most naive garbage collection algorithm. This algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it". An object is considered garbage collectable if there is zero reference pointing at this object.

- -

Example

- -
var o = {
-  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 'o' variable.
-// Obviously, none can be garbage-collected
-
-
-var o2 = o; // the 'o2' variable is the second thing that
-            // has a reference to the object
-o = 1;      // now, the object that was originally in 'o' has a unique reference
-            // embodied by the 'o2' variable
-
-var oa = o2.a; // reference to 'a' property of the object.
-               // This object has now 2 references: one as a property,
-               // the other as the 'oa' variable
-
-o2 = "yo"; // The object that was originally in 'o' has now zero
-           // references to it. It can be garbage-collected.
-           // However what was its 'a' property is still referenced by
-           // the 'oa' variable, so it cannot be freed
-
-oa = null; // what was the 'a' property of the object originally in o
-           // has zero references to it. It can be garbage collected.
-
- -

Limitation: cycles

- -

There is a limitation when it comes to cycles. In the following example two objects are created and reference one another – thus creating a cycle. They will not get out of the function scope after the function call, so they are effectively useless and could be freed. However, the reference-counting algorithm considers that since each of both object is referenced at least once and none can be garbage-collected.

- -
function f(){
-  var o = {};
-  var o2 = {};
-  o.a = o2; // o references o2
-  o2.a = o; // o2 references o
-
-  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 lots of data (illustrated in the above example with the "lotsOfData" property), the memory consumed by this data will never be released.

- -

Mark-and-sweep algorithm

- -

This algorithm reduces the definition of "an object is not needed anymore" 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 better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

- -

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 not needed anymore".

- -

Cycles are not a problem anymore

- -

In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.

- -

The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.

- -

Limitation: objects need to be made explicitly unreachable

- -

Although this is marked as a limitation, it is one that is rarely reached in practice which is why no one usually cares that much about garbage collection.

- -

See also

- - diff --git a/files/id/web/javascript/reference/about/index.html b/files/id/web/javascript/reference/about/index.html deleted file mode 100644 index 02c6ef967c..0000000000 --- a/files/id/web/javascript/reference/about/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Mengenai Pustaka Ini -slug: Web/JavaScript/Reference/About -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About ---- -

Apa yang perlu diketahui sebelumnya

- -

Pengalaman menggunakan bahasa pemrograman lainnya dapat menjadi manfaat, meskipun tidak menjadi prasyarat.

- -

JavaScript ditujukan untuk digunakan pada lingkup yang lebih besar, seperti peramban, script server-side, atau sejenisnya. Secara umum, pustaka ini tergantung pada platform tertentu, dan tidak ditujukan hanya untuk peramban.

- -

Untuk tujuan demo, pustakan ini menggunakan fungsi, println. Fungsi tersebut bukanlah bagian dari JavaScript. Namun ia dapat dipetakan terhadap implementasi spesifik pada platform tertentu.

- -

Misal, bila berjalan di peramban, maka fungsi di atas dapat implementasikan sebagai:

- -
-
function println(string) {
-  window.alert(string);
-}
-
- -

 

-
- -

Sejarah JavaScript

- -

Versi terbaru dari peramban berbasis Mozilla mendukung versi terbaru dari JavaScript. Tabel berikut menampilkan daftar dari versi JavaScript yang didukung oleh versi yang berbeda dari peramban berbasis Mozilla.

- -

Peramban yang tidak mendukung versi JavaScript setidaknya versi 1.5 adalah hal yang sangat langka untuk saat ini. JavaScript versi 1.5 sudah dipublikasikan sejak tahun 1999. Bila Anda tertarik untuk mempelajari sejarahnya, silahkan mengunjungi referensi yang terdapat di Wikipedia, ECMAScript.

- -

JavaScript/Browser support history

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
JavaScript (SpiderMonkey) versionMozilla releaseGecko version
JavaScript 1.5Navigator 6.0, Mozilla Application Suite, Firefox 1.0Gecko 0.6x-1.7
JavaScript 1.6Firefox 1.5Gecko 1.8
JavaScript 1.7Firefox 2Gecko 1.8.1
JavaScript 1.8Firefox 3Gecko 1.9
JavaScript 1.8.5Firefox 4Gecko 2.0
JavaScript 1.8.6Firefox 17Gecko 17
- -

Sumber informasi JavaScript

- -

Dokumentasi JavaScript dari fitur bahasa inti (murni ECMAScript, untuk sebagian besar) mencakup:

- - - -

Bila Anda masih baru terhadap JavaScript, mulailah dari pedoman. Bila kemudian Anda sudah merasa memiliki pemahaman yang lebih mendalam, Anda dapat memanfaatkan referensi.

diff --git a/files/id/web/javascript/reference/classes/constructor/index.html b/files/id/web/javascript/reference/classes/constructor/index.html deleted file mode 100644 index 8da1df9428..0000000000 --- a/files/id/web/javascript/reference/classes/constructor/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: constructor -slug: Web/JavaScript/Reference/Classes/constructor -translation_of: Web/JavaScript/Reference/Classes/constructor ---- -
{{jsSidebar("Classes")}}
- -

Metode dengan nama "constructor" adalah metode spesial untuk pembuatan dan penginisialisasian objek yang dibuat dengan kelas.

- -

sintaks

- -
constructor([arguments]) { ... }
- -

Deskripsi

- -

Hanya boleh ada satu metode spesial dengan nama "constructor" dalam sebuah kelas. {{jsxref("SyntaxError")}}  akan dilemparkan jika suatu kelas memiliki lebih dari satu metode konstruktor.

- -

Konstruktor dapat menggunakan kata kunci {{jsxref("Operators/super", "super")}} untuk memanggil konstruktor orang-tua.

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka  kontruktor asali yang akan digunakan.

- -

Contoh

- -

Menggunakan metode constructor

- -

Potongan kode ini diambil dari contoh kelas (demostrasi langsung).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Di sini, akan memanggil konstruktor orang-tua dengan panjang
-    // diberikan untuk panjang dan tinggi Polygon
-    super(length, length);
-    // Catatan: di kelas turunan, super() harus dipanggil sebelum
-    // bisa menggunakan kata kunci 'this'. Meninggalkan pemanggilan ini di awal
-    // akan menyebabkan kesalahan referensi.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Konstruktor asali

- -

Jika metode konstruktor tidak didefinisikan dalam sebuah kelas, maka kontruktor asali yang akan digunakan. Untuk konstruktor asali untuk kelas dasar adalah:

- -
constructor() {}
-
- -

Konstruktor asali untuk kelas turunan adalah:

- -
constructor(...args) {
-  super(...args);
-}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES6')}}Definisi awal
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Default constructors{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Default constructors{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/classes/extends/index.html b/files/id/web/javascript/reference/classes/extends/index.html deleted file mode 100644 index c6def454fe..0000000000 --- a/files/id/web/javascript/reference/classes/extends/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: extends -slug: Web/JavaScript/Reference/Classes/extends -tags: - - ECMAScript 2015 - - JavaScript - - Kelas -translation_of: Web/JavaScript/Reference/Classes/extends ---- -
{{jsSidebar("Classes")}}
- -

Kata kunci extends digunakan pada class declarations atau class expressions untuk membuat sebuah class yang merupakan turunan dari class lain.

- -
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
- - - -

Sintaks

- -
class ChildClass extends ParentClass { ... }
- -

Deskripsi

- -

Kata kunci extends dapat digunakan untuk subclass custom classes dan built-in objects.

- -

.prototype dari suatu ekstensi harus berupa sebuah {{jsxref("Object")}} atau {{jsxref("null")}}.

- -

Contoh

- -

Menggunakan extends

- -

Contoh pertama membuat sebuah class bernama Square dari kelas bernama Polygon. Contoh ini diambil dari live demo (source).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Disini, obyek dari Square memanggil konstruktor dari parent class dengan argumen lengths yang tersedia
-    // untuk width dan height pada Polygon
-    super(length, length);
-    // Catatan: Pada kelas turunan, super() harus dipanggil sebelum Anda
-    // dapat menggunakan 'this'. Pengabaian terhadap hal tersebut akan menyebabkan reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-}
- -

Menggunakan extends dengan built-in objects

- -

Contoh berikut mewarisi built-in {{jsxref("Date")}} object. Contoh ini diambil dari live demo (source).

- -
class myDate extends Date {
-  constructor() {
-    super();
-  }
-
-  getFormattedDate() {
-    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
-  }
-}
- -

Extending (Pewarisan) null

- -

Extending/pewarisan dari {{jsxref("null")}} bekerja layaknya seperti normal class, dengan pengecualian prototype object tidak mewarisi dari {{jsxref("Object.prototype")}}.

- -
class nullExtends extends null {
-  constructor() {}
-}
-
-Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
-
-new nullExtends(); //ReferenceError: this is not defined
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.classes.extends")}}

- -

Cek juga

- - diff --git a/files/id/web/javascript/reference/classes/index.html b/files/id/web/javascript/reference/classes/index.html deleted file mode 100644 index 3a8a71f562..0000000000 --- a/files/id/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Classes - - Constructors - - ECMAScript6 - - Inheritance - - Intermediate - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -

Kelas di JavaScript diperkenalkan pada ECMAScript 6 seperti pemanis dari prototype-based JavaScript yang sudah ada. Syntax dari kelas tidak menggunakan model object-oriented inheritance yang baru. JavaScript kelas menyediakan syntax yang lebih sederhana dan rapi untuk membuat object-object dan mengatasi / dealing dengan turunan / inheritance.

- -

Definisi kelas

- -

Kelas seperti "fungsi istimewa", dan seperti kamu bisa mendeklarasikan ekspresi fungsi (function expressions) dan deklarasi fungsi (function declarations), syntax kelas sendiri mempunyai dua komponen: ekspresi kelas (class expressions) dan deklarasi kelas (class declarations).

- -

Deklarasi Kelas

- -

Salah satu cara untuk mendefinisikan kelas adalah dengan menggunakan class declaration / deklarasi kelas. Untuk mendeklarasikan kelas, kamu bisa menggunakan kata kunci class sebagai contoh class "Polygon" di bawah ini.

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting

- -

Perbedaan penting antara deklarasi fungsi (function declarations) dan deklarasi kelas (class declarations) adalah deklarasi fungsi  {{Glossary("Hoisting", "hoisted")}} dan  deklarasi class tidak. Pertama-tama kamu harus mendeklarasikan kelas dan mengaksesnya, jika tidak maka kode seperti berikut akan menampilkan {{jsxref("ReferenceError")}}:

- -
var p = new Polygon(); // ReferenceError
-
-class Polygon {}
-
- -

Ekspresi Kelas

- -

Ekspresi kelas (class expression) adalah cara lain untuk mendefinisikan sebuah class. Class expression bisa bernama ataupun tidak. Nama yang diberikan berbentuk lokal berada di body class.

- -
// unnamed
-var Polygon = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-// named
-var Polygon = class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
- -

Catatan: Ekspresi kelas (Class expressions) juga mempunyai masalah yang sama terkait hoisting seperti pada Deklarasi kelas (Class declarations).

- -

Tubuh Kelas (class body) and definisi metode

- -

Tubuh atau body sebuah kelas berada didalam kurung {}. Disitu kamu dapat mendefinisikan isi kelas seperti method atau konstruktor.

- -

Strict mode

- -

Body atau bagian badan dari kelas deklarasi dan kelas ekspresi di eksekusi pada strict mode.

- -

Konstruktor

- -

konstruktor adalah metode (method) khusus untuk membuat dan inisialisasi sebuah objek yang dibuat dengan  class. Hanya ada satu metode khusus dengan nama "konstruktor" di kelas. Sebuah {{jsxref("SyntaxError")}} akan tampil jika kelas berisi lebih dari satu method constructor.

- -

Sebuah konstruktor dapat digunakan keyword super untuk memanggil kostruktor dari kelas parent nya.

- -

Prototipe method

- -

Lihat juga definisi method

- -
class Polygon {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Polygon(10, 10);
-
-console.log(square.area);
- -

Metode Statis

- -

Kata kunci statis mendefinisikan metode statis untuk suatu kelas. Metode statis dipanggil tanpa membuat instance kelasnya dan tidak bisa dipanggil ketika kelas tersebut dipakai. Metode statis sering digunakan untuk membuat fungsi utilitas untuk suatu aplikasi.

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

Mem-binding this dengan prototipe dan metode statis

- -

Ketika metode statis atau prototipe dipanggil tanpa objek yang bernilai "this" (atau "this" sebagai boolean, string, angka, tidak terdefinisi atau null), maka nilai "this" akan ditentukan dalam fungsi yang digunakan. Autoboxing tidak akan berjalan. Hal tersebut juga berlaku ketika kita menulis kode dalam mode non-strict.laku akan sama bahkan jika kita menulis kode dalam mode tidak ketat.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // undefined
-
-let eat = Animal.eat;
-eat(); // undefined
- -

Jika kita menulis kode diatas menggunakan fungsi tradisional berdasarkan kelas, maka autoboxing akan berjalan sesuai dengan nilai "this" pada fungsi yang dipanggil.

- -
function Animal() { }
-
-Animal.prototype.speak = function(){
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
-
- -

Sub kelas dengan extends

- -

extends digunakan pada deklarasi kelas atau kelas expresi untuk membuat suatu kelas sebagai turunan dari kelas lain.

- -
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.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Jika terdapat constructor pada sub kelas saat ini, maka pertama dibutuhkan untuk memanggil super() sebelum menggunakan "this".

- -
Seseorang juga dapat mengextend "kelas" berbasis fungsi tradisional:
- -
function Animal (name) {
-  this.name = name;
-}
-
-Animal.prototype.speak = function () {
-  console.log(this.name + ' makes a noise.');
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Perhatikan bahwa kelas tidak dapat di extend pada objek reguler atau biasa (non-constructible) . Jika ingin mewarisi regurel object,  maka dapat menggunakan {{jsxref("Object.setPrototypeOf()")}}:

- -
var Animal = {
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-};
-
-class Dog {
-  constructor(name) {
-    this.name = name;
-  }
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-Object.setPrototypeOf(Dog.prototype, Animal);
-
-var d = new Dog('Mitzie');
-d.speak();
-
- -

Species

- -

Kamu dapat mengembalikan objek {{jsxref("Array")}}  di kelas array yang diturunkan MyArray. Pola spesies memungkinkan Kamu overide konstruktor default.

- -

Contohnya, ketika menggunakan method seperti {{jsxref("Array.map", "map()")}} yang mana mengembalikan konstruktor default, kamu butuh method yang dapat mengembalikan objek parent Array, bukan dari objek MyArray. Simbol {{jsxref("Symbol.species")}} memungkinkan untuk melakukan:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  static get [Symbol.species]() { return Array; }
-}
-
-var a = new MyArray(1,2,3);
-var mapped = a.map(x => x * x);
-
-console.log(mapped instanceof MyArray); // false
-console.log(mapped instanceof Array);   // true
-
- -

Memanggil Kelas Super dengan keyword super

- -

Keyword super digunakan untuk memanggil fungsi pada objek parent nya.

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

- -

Subkelas Abstrak or mix-ins adalah template untuk kelas. Kelas berbasis  ECMAScript hanya dapat memiliki satu superclass (Kelas super), jadi inheritence berganda dari kelas tool sebagai contohnya, itu tidak memungkinkan. Fungsionalitas harus disediakan oleh superclass.

- -

Sebuah fungsi dengan superclass sebagai inputanya dan sukelas as input and a subclass extend superclass sebagai output dapat mengimplemtasikan pada  ECMAScript sebagai berikut:

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
- -

Kompatibilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatNo}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoMobile(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.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html b/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html deleted file mode 100644 index 4fab8e8ca2..0000000000 --- a/files/id/web/javascript/reference/errors/called_on_incompatible_type/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: X.prototype.y called on incompatible type -slug: Web/JavaScript/Reference/Errors/Called_on_incompatible_type -tags: - - Error - - JavaScript - - TypeError -translation_of: Web/JavaScript/Reference/Errors/Called_on_incompatible_type ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: 'this' is not a Set object (EdgE)
-TypeError: Function.prototype.toString called on incompatible object (Firefox)
-TypeError: Function.prototype.bind called on incompatible target (Firefox)
-TypeError: Method Set.prototype.add called on incompatible receiver undefined (Chrome)
-TypeError: Bind must be called on a function (Chrome)
-
- -

Tipe error

- -

{{jsxref("TypeError")}}

- -

Apa yang salah?

- -

Ketika error ini dilempar, suatu fungsi (dari objek yang diberikan), dipanggil dengan this tidak berkorespondensi ke tipe yang diharapkan fungsi tersebut.

- -

Isu ini bisa terbit ketika menggunakan metode {{jsxref("Function.prototype.call()")}} atau {{jsxref("Function.prototype.apply()")}}, dan menyediakan argumen this yang tak punya tipe yang diharapkan.

- -

Isu ini juga bisa terjadi ketika menyediakan fungsi yang disimpan sebagai properti suatu objek sebagai argumen fungsi lain. Dalam hal ini, objek yang menyimpan fungsi tersebut takkan menjadi target this target dari fungsi itu ketika dipanggil oleh fungsi lain. Untuk mengatasi isu ini, kamu harus menyediakan lambda yang membuat panggilan, ataupun menggunakan fungsi {{jsxref("Function.prototype.bind()")}} untuk memaksa argumen this ke objek yang diharapkan.

- -

Contoh

- -

Kasus tak valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add);
-// mySet.add adalah fungsi, tapi "mySet" tidak dikaptur sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(myFun.bind);
-// myFun.bind adalah fungsi, tapi "myFun" tidak dikaptur sebagai this.
-
-
- -

Kasus valid

- -
var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add.bind(mySet));
-// Ini berjalan karena mengikat "mySet" sebagai this.
-
-var myFun = function () {
-  console.log(this);
-};
-['bar', 'baz'].forEach(x => myFun.bind(x));
-// Ini berjalan menggunakan fungsi "bind". Ia membuat lambda yang meneruskan argumen.
-
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/index.html b/files/id/web/javascript/reference/errors/index.html deleted file mode 100644 index 68e7cce3df..0000000000 --- a/files/id/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Referensi error JavaScript -slug: Web/JavaScript/Reference/Errors -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Error, error dimana - mana.

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

diff --git a/files/id/web/javascript/reference/errors/invalid_array_length/index.html b/files/id/web/javascript/reference/errors/invalid_array_length/index.html deleted file mode 100644 index 3b7fd4e78e..0000000000 --- a/files/id/web/javascript/reference/errors/invalid_array_length/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'RangeError: invalid array length' -slug: Web/JavaScript/Reference/Errors/Invalid_array_length -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
RangeError: Array length must be a finite positive integer (Edge)
-RangeError: invalid array length (Firefox)
-RangeError: Invalid array length (Chrome)
-RangeError: Invalid array buffer length (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Panjang array tak valid bisa muncul di situasi berikut:

- - - -

Kenapa panjang Array dan ArrayBuffer dibatasi? Properti length dari Array atau ArrayBuffer diwakili dengan satu unsigned 32-bit integer, yang hanya menyimpan nilai dalam kisaran dari 0 hingga 232-1.

- -

Jika kamu membuat satu Array, menggunakan constructor, kamu mungkin mau memakai notasi literal saja, karena argumen pertama diinterpretasi sebagai panjang Array.

- -

Sebaliknya, kamu mungkin mau mengelam panjangnya sebelum mengeset properti panjangnya, atau memakainya sebagai argumen konstructor.

- -

Contoh

- -

Kasus tak valid

- -
new Array(Math.pow(2, 40))
-new Array(-1)
-new ArrayBuffer(Math.pow(2, 32))
-new ArrayBuffer(-1)
-
-let a = [];
-a.length = a.length - 1;         // set -1 to the length property
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = b.length + 1;         // set 2^32 to the length property
-
- -

Kasus valid

- -
[ Math.pow(2, 40) ]                     // [ 1099511627776 ]
-[ -1 ]                                  // [ -1 ]
-new ArrayBuffer(Math.pow(2, 32) - 1)
-new ArrayBuffer(0)
-
-let a = [];
-a.length = Math.max(0, a.length - 1);
-
-let b = new Array(Math.pow(2, 32) - 1);
-b.length = Math.min(0xffffffff, b.length + 1);
-
-// 0xffffffff is the hexadecimal notation for 2^32 - 1
-// which can also be written as (-1 >>> 0)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 32be54e5ce..0000000000 --- a/files/id/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: 'SyntaxError: missing ; before statement' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
SyntaxError: Expected ';' (Edge)
-SyntaxError: missing ; before statement (Firefox)
-
- -

Tipe error

- -

{{jsxref("SyntaxError")}}.

- -

Apa yang Salah?

- -

Ada titik koma (;) yang hilang di suatu tempat. JavaScript statements harus diakhiri dengan semicolon. Beberapa dari mereka dipengaruhi oleh automatic semicolon insertion (ASI), tetapi dalam hal ini anda perlu memberikan titik koma, sehingga JavaScript dapat mem-parse kode sumber dengan benar.

- -

Namun, seringkali, kesalahan ini hanya merupakan konsekuensi dari kesalahan lain, seperti tidak menempatkan string dengan benar, atau menggunakan var secara salah. Ada mungkin juga memiliki terlalu banyak tanda kurung di suatu tempat. Hati-hati memeriksa sintaks ketika kesalahan ini dilemparkan.

- -

Contoh

- -

Unescaped strings

- -

Kesalahan ini dapat terjadi dengan mudah ketika tidak melepaskan string dengan benar dan engine JavaScript is expecting the end of your string already. Sebagai contoh:

- -
var foo = 'Tom's bar';
-// SyntaxError: missing ; before statement
- -

Anda dapat menggunakan double quotes, atau menggunakan tanda kutip dengan menambahkan backslash

- -
var foo = "Tom's bar";
-var foo = 'Tom\'s bar';
-
- -

Declaring properties with var

- -

Anda tidak dapat mendeklarasikan property dari sebuah objek atau larik(array) dengan deklarasi var.

- -
var obj = {};
-var obj.foo = 'hi'; // SyntaxError missing ; before statement
-
-var array = [];
-var array[0] = 'there'; // SyntaxError missing ; before statement
-
- -

Sebagai gantinya, hapus kata kunci var:

- -
var obj = {};
-obj.foo = 'hi';
-
-var array = [];
-array[0] = 'there';
-
- -

Kata kunci yang buruk

- -

Jika ada berasal dari bahasa pemrograman yang lain, itu juga umum untuk menggunakan kata kunci yang tidak berarti sama atau tidak memiliki arti sama sekali di JavaScript:

- -
def print(info){
-  console.log(info);
-}; // SyntaxError missing ; before statement
- -

Sebagai gantinya, gunakan function daripada menggunakan kata kunci def:

- -
function print(info){
-  console.log(info);
-};
- -

See also

- - diff --git a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html b/files/id/web/javascript/reference/errors/negative_repetition_count/index.html deleted file mode 100644 index 0ea4bec83a..0000000000 --- a/files/id/web/javascript/reference/errors/negative_repetition_count/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: 'RangeError: repeat count must be non-negative' -slug: Web/JavaScript/Reference/Errors/Negative_repetition_count -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Negative_repetition_count ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: argument out of range
-RangeError: repeat count must be non-negative (Firefox)
-RangeError: Invalid count value (Chrome)
-
- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

Metode {{jsxref("String.prototype.repeat()")}} telah digunakan. Ia punya parameter count mengindikasikan jumlah pengulangan string. Ia harus bernilai antara 0 dan kurang dari positif {{jsxref("Infinity")}} dan tidak boleh angka negatif. Kisarannya nilai yang diperbolehkan bisa dijelaskan seperti ini: [0, +∞).

- -

Contoh

- -

Kasus tak valid

- -
'abc'.repeat(-1); // RangeError 
- -

Kasus valid

- -
'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (count will be converted to integer)
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html b/files/id/web/javascript/reference/errors/not_a_codepoint/index.html deleted file mode 100644 index d3d8b2f934..0000000000 --- a/files/id/web/javascript/reference/errors/not_a_codepoint/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: 'RangeError: argument is not a valid code point' -slug: Web/JavaScript/Reference/Errors/Not_a_codepoint -tags: - - Errors - - JavaScript - - RangeError -translation_of: Web/JavaScript/Reference/Errors/Not_a_codepoint ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
RangeError: Invalid code point {0} (Edge)
-RangeError: {0} is not a valid code point (Firefox)
-RangeError: Invalid code point {0} (Chrome)
-
- -

 

- -

Tipe error

- -

{{jsxref("RangeError")}}

- -

Apa yang salah?

- -

{{jsxref("String.fromCodePoint()")}} throws this error when passed {{jsxref("NaN")}} values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111).

- -

Satu poin kode ialah satu nilai dalam codespace Unicode; yaitu, kisaran integer dari 0 hingga 0x10FFFF.

- -

Contoh

- -

Kasus tak nvalid

- -
String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
- -

Kasus valid

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/not_defined/index.html b/files/id/web/javascript/reference/errors/not_defined/index.html deleted file mode 100644 index d0dc93a0c6..0000000000 --- a/files/id/web/javascript/reference/errors/not_defined/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: 'ReferenceError: "x" is not defined' -slug: Web/JavaScript/Reference/Errors/Not_defined -translation_of: Web/JavaScript/Reference/Errors/Not_defined ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
ReferenceError: "x" is not defined
-
- -

Type Error

- -

{{jsxref("ReferenceError")}}.

- -

Mengapa salah?

- -

Tidak ditemukannya referensi variabel dimanapun. Variabel ini perlu dideklarasikan, atau anda pastikan lagi bahwa ada di dalam script atau {{Glossary("scope")}} anda.

- -
-

Note: Ketika memanggil sebuah library (seperti jQuery), pastikan memanggilnya terlebih dahulu tanda "$" sebelum mengakses variabel library. Gunakan tag {{HTMLElement("script")}} untuk memanggil library sebelum menggunakannya pada kode anda.

-
- -

Contoh

- -

Variable tidak dideklarasikan

- -
foo.substring(1); // ReferenceError: foo is not defined
-
- -

Variabel "foo" tidak ditemukan dimanapun. Variabel tersebut diperlukan oleh beberapa string, agar metode {{jsxref("String.prototype.substring()")}} dapat bekerja.

- -
var foo = 'bar';
-foo.substring(1); // "ar"
- -

Ruang lingkup salah

- -

Sebuah variabel harus tersedia dalam kontek eksekusi saat ini . Variabel yang berada di dalam sebuah fungsi tidak dapat diakses dari luar fungsi, sebab sebuah variabel mepunyai batasan pada cakupan wilayah sebuah fungsi

- -
function numbers() {
-  var num1 = 2,
-      num2 = 3;
-  return num1 + num2;
-}
-
-console.log(num1); // ReferenceError num1 is not defined.
- -

Dengan demikian sebuah fungsi dapat mengakses semua variabel dan fungsi lainnya yang didefinisikan di dalam cakupan dimana ia didefinisikan. Dengan kata lain, sebiah fungsi yang didefinisikan di cakupan global dapat mengakses semua variabel yang didefinisian secara global pula.

- -
var num1 = 2,
-    num2 = 3;
-
-function numbers() {
-  return num1 + num2;
-}
-
-console.log(numbers()); // 5
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/property_access_denied/index.html b/files/id/web/javascript/reference/errors/property_access_denied/index.html deleted file mode 100644 index 6cbece3868..0000000000 --- a/files/id/web/javascript/reference/errors/property_access_denied/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: 'Error: Permission denied to access property "x"' -slug: Web/JavaScript/Reference/Errors/Property_access_denied -tags: - - Error - - Errors - - JavaScript - - Keamanan -translation_of: Web/JavaScript/Reference/Errors/Property_access_denied ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Permission denied to access property "x"
-
- -

Tipe error

- -

{{jsxref("Error")}}.

- -

Apa kesalahannya?

- -

Ada usaha pengaksesan objeck yang kamu belum punya ijinnya. Sepertinya elemen {{HTMLElement("iframe")}} diload dari domain berbeda yang kebijakan same-origin policynya kamu langgar.

- -

Contoh

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe>
-    <script>
-      onload = function() {
-        console.log(frames[0].document);
-        // Error: Permission denied to access property "document"
-      }
-    </script>
-  </head>
-  <body></body>
-</html>
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/errors/too_much_recursion/index.html b/files/id/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 4c35bcfc83..0000000000 --- a/files/id/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: 'InternalError: too much recursion' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -tags: - - Errors - - InternalError - - JavaScript -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion ---- -
{{jsSidebar("Errors")}}
- -

Pesan

- -
Error: Out of stack space (Edge)
-InternalError: too much recursion (Firefox)
-RangeError: Maximum call stack size exceeded (Chrome)
-
- -

Tipe error

- -

{{jsxref("InternalError")}}.

- -

Apa yang salah?

- -

Fungsi yang memanggil dirinya sendiri disebut fungsi rekursif. Sekali satu kondisi telah ketemu, fungsi itu berhenti memanggil dirinya. Ini disebut base case.

- -

Dalam beberapa cara, rekursi analog dengan loop. Keduanya mengeksekusi kode yang sama berulang kali, dan keduanya membutuhkan satu kondisi (untuk mencegah loop tak-terbatas, atau lebih tepatnya, rekursi tak-terbatas dalam hal ini). Ketika panggilan fungsi terlalu banyak, atau tak ada base case dalam fungsi, JavaScript akan melempar error ini.

- -

Contoh

- -

Fungsi rekursif ini berjalan 10 kali, per kondisi exit.

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
- -

Mengeset kondisi ini ke nilai extrem sangat tinggi, tak akan jalan:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

Fungsi rekursif ini tak punya base case. Jika tak kondisi exit, function akan memanggil dirinya sendiri terus-terusan.

- -
function loop(x) {
- // The base case is missing
-
-loop(x + 1); // Recursive call
-}
-
-loop(0);
-
-// InternalError: too much recursion
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/functions/index.html b/files/id/web/javascript/reference/functions/index.html deleted file mode 100644 index adb0d13f05..0000000000 --- a/files/id/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.
-
- -
-
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.
-
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 benefits of creating a named function expression is that in case we encountered 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.
-
- -
-
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.
-
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 representing 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/id/web/javascript/reference/global_objects/array/concat/index.html b/files/id/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index c6a25609db..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -tags: - - Array -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Method concat() mengembalikan sebuah array baru yang terdiri dari array yang dipanggil kemudian digabung dengan array dan/atau nilai yang ditambahkan pada argumen.

- -

Syntax

- -
var array_baru = array_lama.concat(value1[, value2[, ...[, valueN]]])
- -

Parameter

- -
-
valueN
-
Array dan/atau nilai untuk digabung menjadi array baru. Untuk detailnya lihat deskripsi dibawah.
-
- -

Deskripsi

- -

concat menciptakan array baru yang terdiri dari unsur - unsur dalam object yang disebut, berdasarkan urutannya, setiap argumen, elemen dari argumen tersebut(Jika argumen adalah array) atau argumennya sendiri (jika argumennya bukan array).

- -

concat tidak mengubah this atau beberapa array yang tersedia sebagai argumen melainkan mengembalikan shallow copy yang berisi salinan dari elemen yang sama digabung dengan array yang asli. Elemen dari array asli disalin ke array baru sebagai berikut:

- - - -
-

Catatan: Concatenating array/nilai akan membiarkan aslinya tidak tersentuh. Selanjutnya, setiap operasi pada array baru tidak akan mempengaruhi array yang asli, begitupun sebaliknya.

-
- -

Contoh

- -

Menggabungkan dua Array

- -

Berikut kode untuk menggabunggkan dua array:

- -
var huruf = ['a', 'b', 'c'],
-    angka = [1, 2, 3];
-
-var hurufAngka = huruf.concat(angka);
-
-console.log(hurufAngka); // Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Menggabungkan tiga array

- -

Berikut kode untuk mengabungkan tiga array:

- -
var angka1 = [1, 2, 3],
-    angka2 = [4, 5, 6],
-    angka3 = [7, 8, 9];
-
-var angkaBaru = angka1.concat(angka2, angka3);
-
-console.log(angkaBaru); // Hasil: [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Menggabungkan nilai ke sebuah array

- -

Berikut kode untuk menggabungkan tiga nilai ke sebuah array :

- -
var huruf = ['a', 'b', 'c'];
-
-var hurufAngka = huruf.concat(1, [2, 3]);
-
-console.log(hurufAngka);
-// Hasil: ['a', 'b', 'c', 1, 2, 3]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial 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')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/filter/index.html b/files/id/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 5c23313268..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -tags: - - Array - - ECMAScript 5 - - JavaScript - - Metode - - Referensi - - polyfill - - purwarupa -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Fungsi filter() membuat array baru berisi elemen yang lolos pengecekan di dalam fungsi anonim yang dikirim sebagai parameter.

- -
var words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-var longWords = words.filter(function(word){
-  return word.length > 6;
-});
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Versi ES6

- -
const words = ["spray", "limit", "elite", "exuberant", "destruction", "present"];
-
-let longWords = words.filter(word => word.length > 6);
-
-// Filtered array longWords is ["exuberant", "destruction", "present"]
-
- -

Sintaksis

- -
var newArray = arr.filter(callback[, thisArg])
- -

Parameter-parameter

- -
-
callback
-
Fungsi berupa tes untuk mengecek elemen yang ada di dalam array. Kembalikan nilai true untuk meloloskan element, false untuk tidak lolos, dan dapat memiliki tiga argumen:
-
-
-
element
-
Elemen saat ini yang sedang diproses.
-
index
-
Nilai indeks (posisi) dari elemen yang sedang diproses.
-
array
-
Array yang memanggil fungsi filter.
-
-
-
thisArg {{Optional_inline}}
-
Opsional. Objek yang akan digunakan sebagai this saat mengeksekusi callback.
-
- -

Nilai balikan

- -

Array baru yang berisi elemen lolos pengecekan.

- -

Deskripsi

- -

filter() akan memanggil fungsi callback sekali untuk tiap elemen di dalam array, dan membuat array baru dari semua nilai yang dianggap true dari hasil yang dikembalikan callbackcallback hanya dipanggil untuk indeks dari array yang berisi sebuah nilai; fungsi tidak akan dipanggil untuk indeks yang telah dihapus atau belum diisi nilai tertentu. Elemen array yang tidak lolos tes callback akan dilewati dan tidak dimasukkan ke dalam array baru.

- -

callback dapat dipanggil dengan tiga argumen:

- -
    -
  1. nilai dari elemen
  2. -
  3. indeks dari elemen
  4. -
  5. objek array yang diproses
  6. -
- -

Jika parameter thisArg tersedia juga saat memanggil filter, itu akan digunakan sebagai nilai this di dalam callback.  Jika tidak disediakan, maka undefined yang digunakan sebagai nilai this. Nilai this yang dapat digunakan dalam callback ditentukan dari aturan umum penentuan this dalam fungsi.

- -

filter() tidak mengubah array yang memanggil fungsi ini.

- -

Kumpulan elemen yang akan diproses oleh filter() ditentukan sebelum pemanggilan pertama callback. Elemen yang ditambahkan ke array setelah pemanggilanfilter() dimulai tidak akan diproses oleh callback. Jika elemen yang sudah ada dalam array berubah, atau dihapus, nilai yang digunakan dalam callback adalah nilai pada saat filter() menggunakannya; elemen yang dihapus tidak akan diproses.

- -

Contoh

- -

Menyaring semua nilai kecil

- -

Contoh berikut ini menggunakan filter() untuk membuat array yang menyaring semua nilai di bawah 10.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Menyaring entri invalid dari JSON

- -

Contoh berikut ini menggunakan filter() untuk membuat json tersaring berisi semua elemen id berupa angka bukan nol.

- -
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)) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Filtered Array
-// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Number of Invalid Entries = ', invalidEntries);
-// Number of Invalid Entries = 4
-
- -

Pencarian dalam array

- -

Contoh berikut menggunakan filter() untuk menyaring isi array berdasarkan kriteria pencarian

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

Implementasi ES2015

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

- -

filter() ditambahkan ke standar ECMA-262 baru pada edisi ke-5; sehingga fungsi ini mungkin tidak terdapat pada semua implementasi standar. Anda dapat mengatasi hal ini dengan menambahkan kode berikut pada awalan skrip Anda, memungkinkan penggunaan filter() di implementasi ECMA-262 yang belum mendukung. Algoritma ini persis sepadan dengan yang dispesifikasikan dalam ECMA-262, edisi ke-5, dengan asumsi fn.call dievaluasi ke nilai asli dari {{jsxref("Function.prototype.bind()")}}, dan {{jsxref("Array.prototype.push()")}} memiliki nilai aslinya.

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

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
- - -

{{Compat("javascript.builtins.Array.filter")}}

-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/from/index.html b/files/id/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index 7845da9755..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Method Array.from() membuat sebuah instansi Array dari sebuah array-like atau objek iterable.

- -

Di ES6, sintaks class memungkinkan untuk subclassing diantaranya built-in dan user defined classes; hasilnya , method statik class-side seperti Array.from  "diwariskan" oleh subclasses dari Array dan membuat instansi baru dari subclass, bukan Array.

- -

Sintaks

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Parameter

- -
-
arrayLike
-
 Array-like atau objek iterable untuk diubah menjadi array.
-
mapFn
-
Opsional. Fungsi Map untuk memanggil setiap elemen array.
-
thisArg
-
Opsional. Nilai untuk digunakan this ketika mengeksekusi mapFn.
-
- -

Deskripsi

- -

Array.from() memungkinkan anda membuat Arrays dari:

- - - -

Array.from() memiliki parameter opsional mapFn, yang memungkinkan anda untuk mengeksekusi fungsi {{jsxref("Array.prototype.map", "map")}} pada setiap elemen array (atau objek subclass) yang akan dibuat. Jelasnya, Array.from(obj, mapFn, thisArg) sama dengan Array.from(obj).map(mapFn, thisArg), kecuali dengan tidak membuat array menengah. Ini sangat penting untuk setiap subclass array, seperti typed arrays, selama array menengah akan memiliki nilai yang terpisah agar bisa masuk ke tipe yang sesuai.

- -

Properti length dari method from() adalah 1.

- -

Contoh

- -
// Array-like object (arguments) to Array
-function f() {
-  return Array.from(arguments);
-}
-
-f(1, 2, 3);
-// [1, 2, 3]
-
-
-// Any iterable object...
-// Set
-var s = new Set(["foo", window]);
-Array.from(s);
-// ["foo", window]
-
-
-// Map
-var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-
-// String
-Array.from("foo");
-// ["f", "o", "o"]
-
-
-// Using an arrow function as the map function to
-// manipulate the elements
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Generate a sequence of numbers
-Array.from({length: 5}, (v, k) => k);
-// [0, 1, 2, 3, 4]
-
-
- -

Polyfill

- -

Array.from telah di masukkan di standar ECMA-262 pada edisi ke-6; karena itu mungkin tidak bisa digunakan pada implementasi standar lain. Anda bisa menyiasatinya dengan menambahkan kode berikut ke awal script, memungkinkan penggunaan Array.from pada implementasi yang aslinya tidak mendukung.  Algoritma ini sama dengan yang di spesifikasikan di ECMA-262, edisi ke-6, dengan saumsi Object dan TypeError memiliki nilai tersendiri dan callback.call mengevaluasi nilai valur dari {{jsxref("Function.prototype.call")}}. Selain itu, sejak iterable tidak dapat di polyfill, implementasi ini tidak mendukung generik iterable seperti yang didefinisikan di edisi ke-6 di ECMA-262.

- -
// Production steps of ECMA-262, Edition 6, 22.1.2.1
-// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
-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;
-    };
-  }());
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.from', 'Array.from')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("45")}}{{CompatGeckoDesktop("32")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}9.0
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/index.html b/files/id/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 2b052487c4..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,484 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - Global Objects - - JavaScript - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Objek JavaScript Array merupakan objek global yang berguna membangun himpunan; dimana merupakan objek level tinggi dan (seperti) daftar.

- -

Membuat sebuah Array

- -
var fruits = ["Apple", "Banana"];
-
-console.log(fruits.length);
-// 2
-
- -

Akses (index) kedalam sebuah item Array

- -
var first = fruits[0];
-// Apple
-
-var last = fruits[fruits.length - 1];
-// Banana
-
- -

Perulangan pada Array

- -
fruits.forEach(function (item, index, array) {
-  console.log(item, index);
-});
-// Apple 0
-// Banana 1
-
- -

Menambahkan elemen pada bagian akhir sebuah Array

- -
var newLength = fruits.push("Orange");
-// ["Apple", "Banana", "Orange"]
-
- -

Menghapus elemen di akhir sebuah Array

- -
var last = fruits.pop(); // remove Orange (from the end)
-// ["Apple", "Banana"];
-
- -

Menghapus elemen di awal sebuah Array

- -
var first = fruits.shift(); // remove Apple from the front
-// ["Banana"];
-
- -

Menambahkan elemen di bagian awal sebuah Array

- -
var newLength = fruits.unshift("Strawberry") // add to the front
-// ["Strawberry", "Banana"];
-
- -

Mencari (nomor) index elemen pada sebuah Array

- -
fruits.push("Mango");
-// ["Strawberry", "Banana", "Mango"]
-
-var pos = fruits.indexOf("Banana");
-// 1
-
- -

Menghapus elemen berdasar posisi index

- -
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
-// ["Strawberry", "Mango"]
-
- -

Menduplikat sebuah Array

- -
var shallowCopy = fruits.slice(); // this is how to make a copy
-// ["Strawberry", "Mango"]
-
- -

Syntax

- -
[element0, element1, ..., elementN]
-new Array(element0, element1[, ...[, elementN]])
-new Array(arrayLength)
- -
-
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below).Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
-
arrayLength
-
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number. If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
-
- -

Description

- -

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

- -

Some people think that you shouldn't use an array as an associative array. In any case, 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.

- -

Accessing array elements

- -

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.

- -
var arr = ['this is the first element', 'this is the second element'];
-console.log(arr[0]);              // logs 'this is the first element'
-console.log(arr[1]);              // logs 'this is the second element'
-console.log(arr[arr.length - 1]); // logs 'this is the second element'
-
- -

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:

- -
console.log(arr.0); // a syntax error
-
- -

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0);   // a syntax error
-console.log(years[0]);  // works properly
-
- -
renderer.3d.setTexture(model, 'character.png');     // a syntax error
-renderer['3d'].setTexture(model, 'character.png');  // works properly
-
- -

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] is coerced into a string by the JavaScript engine 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 could be 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(but it can be accessed by dot notation in firefox 40.0a2 at least):

- -
var promise = {
-  'var'  : 'text',
-  'array': [1, 2, 3, 4]
-};
-
-console.log(promise['array']);
-
- -

Relationship between length and numerical properties

- -

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

- -
var fruits = [];
-fruits.push('banana', 'apple', 'peach');
-
-console.log(fruits.length); // 3
-
- -

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

- -
fruits[5] = 'mango';
-console.log(fruits[5]); // 'mango'
-console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
-console.log(fruits.length); // 6
-
- -

Increasing the {{jsxref("Array.length", "length")}}.

- -
fruits.length = 10;
-console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
-console.log(fruits.length); // 10
-
- -

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

- -
fruits.length = 2;
-console.log(Object.keys(fruits)); // ['0', '1']
-console.log(fruits.length); // 2
-
- -

This is explained further on the {{jsxref("Array.length")}} page.

- -

Creating an array using the result of a match

- -

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

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

The properties and elements returned from this match are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.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
- -

Properties

- -
-
Array.length
-
The Array constructor's length property whose value is 1.
-
{{jsxref("Array.@@species", "get Array[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Array.prototype")}}
-
Allows the addition of properties to all array objects.
-
- -

Methods

- -
-
{{jsxref("Array.from()")}}
-
Creates a new Array instance from an array-like or iterable object.
-
{{jsxref("Array.isArray()")}}
-
Returns true if a variable is an array, if not false.
-
{{jsxref("Array.of()")}}
-
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
-
- -

Array instances

- -

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

- -

Properties

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
- -

Methods

- -

Mutator methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
- -

Accessor methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
- -

Iteration methods

- -
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
- -

Array generic methods

- -
-

Array generics are non-standard, deprecated and will get removed near future. Note that you can not rely on them cross-browser. However, there is a shim available on GitHub.

-
- -

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)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

- -
if (Array.every(str, isLetter)) {
-  console.log("The string '" + str + "' contains only letters!");
-}
-
- -

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

- -

These are 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', 'find', 'findIndex', 'entries', 'keys',
-      'values', 'copyWithin', 'includes'
-    ],
-    methodCount = methods.length,
-    assignArrayGeneric = function(methodName) {
-      if (!Array[methodName]) {
-        var method = Array.prototype[methodName];
-        if (typeof method === 'function') {
-          Array[methodName] = function() {
-            return method.call.apply(method, arguments);
-          };
-        }
-      }
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignArrayGeneric(methods[i]);
-  }
-}());
-
- -

Examples

- -

Creating an array

- -

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

- -
var msgArray = [];
-msgArray[0] = 'Hello';
-msgArray[99] = 'world';
-
-if (msgArray.length === 100) {
-  console.log('The length is 100.');
-}
-
- -

Creating a two-dimensional array

- -

The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

- -
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'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Move King's Pawn forward 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
-
- -

Here is the output:

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

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}}New method added: {{jsxref("Array.prototype.includes()")}}
- -

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/id/web/javascript/reference/global_objects/array/isarray/index.html b/files/id/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index 152b6cdfd0..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript5 - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Method Array.isArray() mengembalikan nilai true jika objek adalah array, false jika bukan.

- -

Sintaks

- -
Array.isArray(obj)
- -

Parameter

- -
-
obj
-
Objek yang di cek.
-
- -

Deskripsi

- -

Baca artikel “Determining with absolute accuracy whether or not a JavaScript object is an array” untuk detailnya.

- -

Contoh

- -
// semuanya mengembalikan nilai true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Sekedar fakta : Array.prototype sendiri adalah array:
-Array.isArray(Array.prototype);
-
-// semua mengembalikan nilai false
-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 });
-
- -

Polyfill

- -

Jalankan kode berikut sebelum kode lain untuk membuat method Array.isArray() jika secara native tidak tersedia.

- -
if (!Array.isArray) {
-  Array.isArray = function(arg) {
-    return Object.prototype.toString.call(arg) === '[object Array]';
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/join/index.html b/files/id/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 8ddd3bb8ed..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - Array - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari sebuah array menjadi sebuah string.

- -

Syntax

- -
str = arr.join([separator = ','])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan string untuk memisahkan setiap elemen array. separator dapat di konersi ke string jika diperlukan. Jika dihilangkan, elemen array akan dipisahkan dengan koma, jika separator adalah string kosong, semua elemen digabungkan tanpa karakter pemisah.
-
- -

Deskripsi

- -

mengonversi string dari semua elemen array dengan menggabungkannya menjadi sebuah string. Jika elemen bernilai undefined atau null, akan dikonversi menjadi string kosong.

- -

Contoh

- -

Penggabungan array menggunakan empat cara yang berbeda

- -

Berikut merupakan contoh membuat array, dengan tiga elemen, kemudian menggabungkan array dengan empa cara berbeda : menggunakan separator default, koma dan spasi, plus dan string kosong.

- -
var a = ['Angin', 'Air', 'Api'];
-var variabel1 = a.join();      // Memberikan nilai 'Angin,Air,Api' pada variabel1
-var variabel2 = a.join(', ');  // Memberikan nilai 'Angin, Air, Api' pada variabel2
-var variabel3 = a.join(' + '); // Memberikan nilai 'Angin + Air + Api' pada variabel3
-var variabel4 = a.join('');    // Memberikan nilai 'AnginAirApi' pada variabel4
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/length/index.html b/files/id/web/javascript/reference/global_objects/array/length/index.html deleted file mode 100644 index 6e8e9e3ae8..0000000000 --- a/files/id/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: - - Array - - JavaScript - - Property - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Array/length ---- -
{{JSRef}}
- -

Properti array length merangkai atau mengembalikan angka dari sejumlah elemen pada array. berupa unsigned, 32-bit integer yang selalu lebih besar dari indeks array terbesar atau index array terakhir.

- -
var items = ["sepatu", "kaos", "baju", "sweater"];
-items.length;
-
-// index terakhir "sweater" 3
-// returns 4
- -

Deskripsi

- -

Nilai properti length berupa integer positif dan nilainya lebih kecil dari 2 sampai 2 pangkat 32 (232).

- -

Anda bisa merangkai properti length untuk memotong array kapanpun. Ketika anda memperpanjang array dengan mengubah properti length, nomor dari elemen sebenarnya tidak bertambah; contoh, jika anda merangkai length ke 3 ketika saat ini adalah 2, array tetap berisi 2 element. Dengan begitu, properti length tidak selalu menunjukkan jumlah angka dari nilai yang didefinisikan pada array. Lihat juga Hubungan antara length dan properti numerik.

- -

{{js_property_attributes(1, 0, 0)}}

- -

Contoh

- -

Iterasi pada array

- -

Pada contoh, numbers array diiterasikan melalui nilai properti array length. Nilai setiap elemen kemudian dikalikan.

- -
var numbers = [1, 2, 3, 4, 5];
-var length = numbers.length;
-for (var i = 0; i < length; i++) {
-  numbers[i] *= 2;
-}
-// numbers is now [2, 4, 6, 8, 10]
-
- -

Memendekan array

- -

Pada contoh memendekkan array numbers ke panjang array 3 jika panjang array sebenarnya lebih besar dari 3.

- -
var numbers = [1,2,3,4,5];
-
-if (numbers.length > 3) {
-  numbers.length = 3;
-}
-
-console.log(numbers); // [1, 2, 3]
-console.log(numbers.length); // 3
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{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')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/of/index.html b/files/id/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index 49ca553133..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -tags: - - Array - - JavaScript - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Method Array.of() membuat instansi Array baru denganjumlah variabel argumen.

- -

Perbedaan antara Array.of() dan konstruktor Array pada penanganan argumen integer: Array.of(42) membuat sebuah array dengan sebuah elemen, 42, sedang Array(42) membuat array dengan 42 element, yang masing - masing undefined.

- -

Sintaks

- -
Array.of(element0[, element1[, ...[, elementN]]])
- -

Parameter

- -
-
elementN
-
Element yang digunakan untuk membuat array.
-
- -

Deskripsi

- -

Fungsi ini merupakan bagian dari ECMAScript 6 standard. Untuk informasi lengkap lihat Array.of and Array.from proposal dan Array.of polyfill.

- -

Contoh

- -
Array.of(1);         // [1]
-Array.of(1, 2, 3);   // [1, 2, 3]
-Array.of(undefined); // [undefined]
-
- -

Polyfill

- -

Menjalankan kode berikut sebelum kode lain membuat Array.of() jika secara native tidak tersedia.

- -
if (!Array.of) {
-  Array.of = function() {
-    return Array.prototype.slice.call(arguments);
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.of', 'Array.of')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(45)}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39)}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/pop/index.html b/files/id/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index f8dc9f0523..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - Array - - JavaScript - - Method - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Method pop() menghapus elemen terakhir dari array dan mengembalikan elemen tersebut.

- -

Syntaks

- -
arr.pop()
- -

Deskripsi

- -

Method pop menghapus elemen terakhir pada array dan mengembalikan nilai ke pemanggil.

- -

pop adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek yang menyerupai array. Objek yang tidak memiliki properti length mencerminkan akhir dari urutan, properti numerik yang berbasis zero mungkin tidak memiliki makna yang berarti.

- -

jika anda menggunakan pop() pada array yang kosong, akan mengembalikan nilai {{jsxref("undefined")}}.

- -

Contoh

- -

Menghapus elemen terakhir pada array

- -

Kode berikut membuat array myFish yang memiliki empat elemen, kemudian menghapus elemen teakhirnya.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-console.log(myFish); // ['angel', 'clown', 'mandarin', 'sturgeon']
-
-var popped = myFish.pop();
-
-console.log(myFish); // ['angel', 'clown', 'mandarin' ]
-
-console.log(popped); // 'sturgeon'
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/reverse/index.html b/files/id/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index dca16b463e..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - Array - - Method -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Method reverse() membalikkan urutan array elemen. Elemen array pertama menjadi terakhir dan sebaliknya.

- -

Sintaks

- -
arr.reverse()
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method reverse mengubah urutan elemen objek array, memutasi array, dan mengembalikan referensi ke array.

- -

Contoh

- -

Membalikan elemen di dalam array

- -

Pada contoh membuat array myArray dengan tiga elemen,  kemudian membalikkan array.

- -
var myArray = ['one', 'two', 'three'];
-myArray.reverse();
-
-console.log(myArray) // ['three', 'two', 'one']
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/shift/index.html b/files/id/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index ac20d5cd60..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

method shift() menghapus elemen pertama pada array dan mengembalikan elemen tersebut. Method ini mengubah panjang (jumlah elemen) array.

- -

Sintaks

- -
arr.shift()
- -

Deskripsi

- -

Method shift menghapus elemen pada index 0 dan menggeser nilai index setelahnya, kemudian mengembalikan nilai yang dihapus. Jika properti {{jsxref("Array.length", "length")}} bernilai 0, maka akan mengembalikan nilai {{jsxref("undefined")}}.

- -

shift adalah desain generic; method ini dapat berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} pada objek yag menyerupai array. Objek yang tidak memiliki properti length akan dianggap terakhir dalam urutan, properti numerik berbasis zero mungkin tidak memiliki makna yang berarti.

- -

Contoh

- -

Menghapus Elemen dari sebuah Array

- -

Kode berikut menampilkan array myFish sebelum dan sesudah menghapus elemen pertama. Juga menampilkan elemen yang dihapus:

- -
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
-
-console.log('myFish sebelum: ' + myFish);
-// myFish sebelum: angel,clown,mandarin,surgeon
-
-var shifted = myFish.shift();
-
-console.log('myFish sesudah: ' + myFish);
-// myFish sesudah: clown,mandarin,surgeon
-
-console.log('Elemen yang dihapus: ' + shifted);
-// Elemen yang dihapus: angel
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{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')}} 
- -

Kompabiltas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/slice/index.html b/files/id/web/javascript/reference/global_objects/array/slice/index.html deleted file mode 100644 index 44f018ba65..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/slice/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Array.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/Array/slice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---- -
{{JSRef}}
- -

Method slice() mengembalikan sebuah salinan dangkal dari sebagian array menjadi sebuah objek array baru yang dimulai dari start sampai end (end tidak termasuk) dimana start dan end merupakan index dari  item yang ada di  array tersebut. Tidak merubah array asli.

- -
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
- - - -

Sintaks

- -
arr.slice([start[, end]])
-
- -

Parameter

- -
-
start {{optional_inline}}
-
Indeks berbasis nol untuk memulai ekstraksi.
-

- Indeks negatif dapat digunakan, menunjukkan offset dari akhir urutan.. slice(-2) mengekstrak dua elemen terakhir dari urutan.
-
Jika start tidak terdefinisi, slice memulai dari indeks ke 0.
-
Jika start lebih besar dari indeks urutan, array kosong akan dikembalikan.
-
end {{optional_inline}}
-
Indeks berbasis nol untuk mengakhiri ekstraksi. slice mengekstrak hingga tapi tidak termasuk end. Sebagai contoh, slice(1,4) mengekstrak elemen kedua menuju elemen ke-empat (indeks elemen 1, 2, dan 3).
-
-

Indeks negatif bisa digunakan,
- menunjukkan offset dari akhir urutan. slice(2,-1) mengekstrak elemen ketiga menuju elemen kedua-ke-terakhir dalam urutan.

-
-
Jika end dihillangkan, slice mengekstrak melalui akhir dari urutan (arr.length).
-
Jika end lebih besar dari panjang urutan, slice mengkstrak melalui akhir urutan (arr.length).
-
- -

Return value

- -

Array baru berisi elemen yang diekstrak.

- -

Deskripsi

- -

slice does not alter the original array. It returns a shallow copy of elements from the original array. Elements of the original array are copied into the returned array as follows:

- - - -

If a new element is added to either array, the other array is not affected.

- -

Contoh

- -

Return a portion of an existing array

- -
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-let citrus = fruits.slice(1, 3)
-
-// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus contains ['Orange','Lemon']
-
- -

Using slice

- -

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

- -
// Using slice, create newCar from myCar.
-let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
-let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
-let newCar = myCar.slice(0, 2)
-
-// Display the values of myCar, newCar, and the color of myHonda
-//  referenced from both arrays.
-console.log('myCar = ' + JSON.stringify(myCar))
-console.log('newCar = ' + JSON.stringify(newCar))
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
-// Change the color of myHonda.
-myHonda.color = 'purple'
-console.log('The new color of my Honda is ' + myHonda.color)
-
-// Display the color of myHonda referenced from both arrays.
-console.log('myCar[0].color = ' + myCar[0].color)
-console.log('newCar[0].color = ' + newCar[0].color)
-
- -

This script writes:

- -
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
-         'cherry condition', 'purchased 1997']
-newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
-myCar[0].color = red
-newCar[0].color = red
-The new color of my Honda is purple
-myCar[0].color = purple
-newCar[0].color = purple
-
- -

Array-like objects

- -

slice method can also be called to convert Array-like objects/collections to a new Array. You just {{jsxref("Function.prototype.bind", "bind")}} the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

- -
function list() {
-  return Array.prototype.slice.call(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
-
- -

Binding can be done with the {{jsxref("Function.prototype.call", "call()")}} method of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call.

- -

Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

- -
let unboundSlice = Array.prototype.slice
-let slice = Function.prototype.call.bind(unboundSlice)
-
-function list() {
-  return slice(arguments)
-}
-
-let list1 = list(1, 2, 3) // [1, 2, 3]
- -

Spesifikasi

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}
- -

Kompatibilitas Peramban

- - - -

{{Compat("javascript.builtins.Array.slice")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/splice/index.html b/files/id/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a0c7c1cb86..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -tags: - - Indonesia -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Metode splice() mengubah konten dari array dengan menghapus elemen yang ada dan/atau menambah elemen baru.

- -
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
- -

Syntax

- -
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
-
- -

Parameters

- -
-
start
-
Indeks di mana untuk mulai mengubah array (dengan asal 0). Jika lebih besar dari panjang array, indeks awal sebenarnya akan diatur ke panjang array. Jika negatif, akan mulai banyak elemen dari akhir array (dengan asal -1) dan akan diset ke 0 jika nilai absolut lebih besar dari panjang array.
-
deleteCount {{optional_inline}}
-
Sebuah integer yang menunjukkan jumlah elemen array lama yang akan dihapus.
-
Jika deleteCount dihilangkan, atau jika nilainya lebih besar dari array.length - start (yaitu, jika lebih besar dari jumlah elemen yang tersisa dalam array, mulai dari start), maka semua elemen dari start sampai akhir dari array akan dihapus.
-
Jika deleteCount adalah 0 atau negatif, tidak ada elemen yang dihapus. Dalam kasus ini, Anda harus menentukan setidaknya satu elemen baru (lihat di bawah).
-
item1, item2, ... {{optional_inline}}
-
Elemen yang ditambahkan ke array, dimulai pada indeks awal. Jika kamu tidak menentukan elemen apapun, splice() hanya akan menghapus elemen-elemen dari array.
-
- -

Return value

- -

Array berisi elemen yang dihapus. Jika hanya satu elemen yang dihapus, array dari satu elemen dikembalikan. Jika tidak ada elemen yang dihapus, sebuah array kosong akan dikembalikan.

- -

Deskripsi

- -

Jika anda menentukan elemen yang berbeda untuk disisipkan daripada nomor yang anda hapus, array akan memiliki panjang yang berbeda ketika kamu memanggilnya nanti.

- -

Contoh

- -

Remove 0 elements from index 2, and insert "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed is [], no elements removed
-
- -

Remove 1 element from index 3

- -
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(3, 1);
-
-// removed is ["mandarin"]
-// myFish is ["angel", "clown", "drum", "sturgeon"]
-
- -

Remove 1 element from index 2, and insert "trumpet"

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var removed = myFish.splice(2, 1, 'trumpet');
-
-// myFish is ["angel", "clown", "trumpet", "sturgeon"]
-// removed is ["drum"]
- -

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// removed is ["angel", "clown"]
- -

Remove 2 elements from index 2

- -
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(myFish.length - 3, 2);
-
-// myFish is ["parrot", "anemone", "sturgeon"]
-// removed is ["blue", "trumpet"]
- -

Remove 1 element from index -2

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(-2, 1);
-
-// myFish is ["angel", "clown", "sturgeon"]
-// removed is ["mandarin"]
- -

Remove all elements after index 2 (incl.)

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2);
-
-// myFish is ["angel", "clown"]
-// removed is ["mandarin", "sturgeon"]
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{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')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Array.splice")}}

-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/array/unshift/index.html b/files/id/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index 4df2069f54..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

Method unshift() menambahkan satu atau lebih elemen ke indek awal array dan mengembalikan jumlah index array yang baru.

- -

Sintaks

- -
arr.unshift([element1[, ...[, elementN]]])
- -

Parameter

- -
-
elementN
-
Elemen yang akan di tambahkan di awal array.
-
- -

Returns

- -

Properti {{jsxref("Array.length", "length")}} baru dari objek teratas dimana method di panggil.

- -

Deskripsi

- -

Method unshift menambahkan nilai yang diberikan ke awal objek array.

- -

unshift biasanya generic; method ini bisa berupa {{jsxref("Function.call", "called", "", 1)}} atau {{jsxref("Function.apply", "applied", "", 1)}} ke objek menyerupai array. Objek yang tidak memiliki properti length mencerminkan dari serangkaian urutan, properti numerik berbasis zero kemungkinan tidak berperilaku dengan cara yang berarti.

- -

Contoh

- -
var arr = [1, 2];
-
-arr.unshift(0); // result of call is 3, the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // = 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-3]);
-// arr is [[-3], -2, -1, 0, 1, 2]
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{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')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/array/values/index.html b/files/id/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index dd77cc65a5..0000000000 --- a/files/id/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

Method values() mengembalikan objek Array Iterator baru yang berisi nilai setiap index pada array.

- -

Sintaks

- -
arr.values()
- -

Contoh

- -

Iterasi menggunakan for...of loop

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-// your browser must support for..of loop
-// and let-scoped variables in for loops
-for (let letter of eArr) {
-  console.log(letter);
-}
-
- -

Iterasi alternatif

- -
var arr = ['w', 'y', 'k', 'o', 'p'];
-var eArr = arr.values();
-console.log(eArr.next().value); // w
-console.log(eArr.next().value); // y
-console.log(eArr.next().value); // k
-console.log(eArr.next().value); // o
-console.log(eArr.next().value); // p
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("51")}}{{CompatGeckoDesktop(48)}}{{CompatNo}}{{CompatNo}}9
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("51")}}{{CompatGeckoMobile(48)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html b/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html deleted file mode 100644 index 08e657aeec..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/getfullyear/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Date.prototype.getFullYear() -slug: Web/JavaScript/Reference/Global_Objects/Date/getFullYear -tags: - - Date - - JavaScript - - Metode - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/getFullYear ---- -
{{JSRef}}
- -

Metode getFullYear() mengembanlikan tahun dari tanggal yang dispesifikasi, mengikuti waktu lokal.

- -

Gunakan metode ini ketimbang metode {{jsxref("Date.prototype.getYear()", "getYear()")}}.

- -
{{EmbedInteractiveExample("pages/js/date-getfullyear.html")}}
- - - -

Syntax

- -
dateObj.getFullYear()
- -

Nilai kembali

- -

Angka yang berkorespondensi ke tahuny dari tanggal yang diberikan, mengikuti waktu lokal.

- -

Deskripsi

- -

Nilai yang dikembalikan oleh getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 1995. Use this function to make sure a year is compliant with years after 2000.

- -

Contoh

- -

Menggunakan getFullYear()

- -

Contoh ini menggassign nilai empat-digit dari tahun saat ini ke variabel year.

- -
var today = new Date();
-var year = today.getFullYear();
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasi di JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.9.5.10', 'Date.prototype.getFullYear')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.getfullyear', 'Date.prototype.getFullYear')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- - - -

{{Compat("javascript.builtins.Date.getFullYear")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/index.html b/files/id/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 1fc6272dcf..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Date -slug: Web/JavaScript/Reference/Global_Objects/Date -tags: - - Date - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Date ---- -
{{JSRef}}
- -

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

- -

Syntax

- -
new Date();
-new Date(value);
-new Date(dateString);
-new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
-
- -
-

Note: JavaScript Date objects can only be instantiated by calling JavaScript Date as a constructor: calling it as a regular function (i.e. without the {{jsxref("Operators/new", "new")}} operator) will return a string rather than a Date object; unlike other JavaScript object types, JavaScript Date objects have no literal syntax.

-
- -

Parameters

- -
-

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

-
- -
-

Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) with the same arguments.

-
- -
-
value
-
Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch).
-
dateString
-
String value representing a date. The string should be in a format recognized by the {{jsxref("Date.parse()")}} method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601). -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
-
-
year
-
Integer value representing the year. Values from 0 to 99 map to the years 1900 to 1999. See the {{anch("Example:_Two_digit_years_map_to_1900_-_1999", "example below")}}.
-
month
-
Integer value representing the month, beginning with 0 for January to 11 for December.
-
day
-
Optional. Integer value representing the day of the month.
-
hour
-
Optional. Integer value representing the hour of the day.
-
minute
-
Optional. Integer value representing the minute segment of a time.
-
second
-
Optional. Integer value representing the second segment of a time.
-
millisecond
-
Optional. Integer value representing the millisecond segment of a time.
-
- -

Description

- - - -

Properties

- -
-
{{jsxref("Date.prototype")}}
-
Allows the addition of properties to a JavaScript Date object.
-
Date.length
-
The value of Date.length is 7. This is the number of arguments handled by the constructor.
-
- -

Methods

- -
-
{{jsxref("Date.now()")}}
-
Returns the numeric value corresponding to the current time - the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
-
{{jsxref("Date.parse()")}}
-
Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00, UTC. -
-

Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

-
-
-
{{jsxref("Date.UTC()")}}
-
Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC.
-
- -

JavaScript Date instances

- -

All Date instances inherit from {{jsxref("Date.prototype")}}. The prototype object of the Date constructor can be modified to affect all Date instances.

- -

Date.prototype Methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', 'Methods')}}
- -

Examples

- -

Several ways to create a Date object

- -

The following examples show several ways to create JavaScript dates:

- -
-

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

-
- -
var today = new Date();
-var birthday = new Date('December 17, 1995 03:24:00');
-var birthday = new Date('1995-12-17T03:24:00');
-var birthday = new Date(1995, 11, 17);
-var birthday = new Date(1995, 11, 17, 3, 24, 0);
-
- -

Two digit years map to 1900 - 1999

- -

In order to create and get dates between the years 0 and 99 the {{jsxref("Date.prototype.setFullYear()")}} and {{jsxref("Date.prototype.getFullYear()")}} methods should be used.

- -
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-// Deprecated method, 98 maps to 1998 here as well
-date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
-
-date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
-
- -

Calculating elapsed time

- -

The following examples show how to determine the elapsed time between two JavaScript dates in millisconds.

- -

Due to the differing lengths of days (due to daylight saving changeover), months and years, expressing elapsed time in units greater than hours, minutes and seconds requires addressing a number of issues and should be thoroughly researched before being attempted.

- -
// using Date objects
-var start = Date.now();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = Date.now();
-var elapsed = end - start; // elapsed time in milliseconds
-
- -
// using built-in methods
-var start = new Date();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = new Date();
-var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
-
- -
// to test a function and get back its return
-function printElapsedTime(fTest) {
-  var nStartTime = Date.now(),
-      vReturn = fTest(),
-      nEndTime = Date.now();
-
-  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
-  return vReturn;
-}
-
-yourFunctionReturn = printElapsedTime(yourFunction);
-
- -
-

Note: In browsers that support the {{domxref("window.performance", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.

-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Some browsers can have issues when parsing dates: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

- -

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/id/web/javascript/reference/global_objects/date/now/index.html b/files/id/web/javascript/reference/global_objects/date/now/index.html deleted file mode 100644 index 43760a275b..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/now/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Date.now() -slug: Web/JavaScript/Reference/Global_Objects/Date/now -tags: - - Date - - JavaScript - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/now ---- -
{{JSRef}}
- -

Method Date.now() mengembalikan jumlah milisekon sejak 1 Januari 1970 00:00:00 UTC.

- -

Sintaks

- -
var timeInMs = Date.now();
- -

Parameter

- -

None.

- -

Deskripsi

- -

Method now() mengembalikan nilaimillisekon sejak 1 January 1970 00:00:00 UTC hingga sekarang sebagai {{jsxref("Number")}}.

- -

Karena now() adalah method static dari {{jsxref("Date")}}, anda bisa menggunakannya sebagai Date.now().

- -

Polyfill

- -

Method ini di bakukan pada ECMA-262 5th edition. Mesin yang belum diupdate untuk mendukung method ini bisa menggunkan shim berikut:

- -
if (!Date.now) {
-  Date.now = function now() {
-    return new Date().getTime();
-  };
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/tojson/index.html b/files/id/web/javascript/reference/global_objects/date/tojson/index.html deleted file mode 100644 index cb951d5fa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/tojson/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Date.prototype.toJSON() -slug: Web/JavaScript/Reference/Global_Objects/Date/toJSON -tags: - - Date - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toJSON ---- -
{{JSRef}}
- -

Method toJSON() mengembalikan string berdasarkan pada object {{jsxref("Date")}}.

- -

Syntax

- -
dateObj.toJSON()
- -

Deskripsi

- -

{{jsxref("Date")}} mengacu pada titik waktu tertentu. Memanggil toJSON() mengembalikan nilai ke string (menggunakan {{jsxref("Date.prototype.toISOString()", "toISOString()")}}) berdasarkan nilai pada object {{jsxref("Date")}}. Method ini biasanya ditujukan, secara default, guna menserialisasi object {{jsxref("Date")}} saat serialisasi {{Glossary("JSON")}}.

- -

Contoh

- -

Penggunaan toJSON()

- -
var jsonDate = (new Date()).toJSON();
-var backToDate = new Date(jsonDate);
-
-console.log(jsonDate); //2015-10-26T07:46:36.611Z
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.9.5.44', 'Date.prototype.toJSON')}}{{Spec2('ES5.1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.8.5.
{{SpecName('ES6', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.tojson', 'Date.prototype.toJSON')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html b/files/id/web/javascript/reference/global_objects/date/totimestring/index.html deleted file mode 100644 index 90ebd23e68..0000000000 --- a/files/id/web/javascript/reference/global_objects/date/totimestring/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Date.prototype.toTimeString() -slug: Web/JavaScript/Reference/Global_Objects/Date/toTimeString -tags: - - Date - - JavaScript - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Date/toTimeString ---- -
{{JSRef}}
- -

Method toTimeString() mengembalikan satuan waktu dari objek {{jsxref("Date")}} object dalam format yang dapat dibaca manusia.

- -

Sintaks

- -
dateObj.toTimeString()
- -

Deskripsi

- -

Instansi {{jsxref("Date")}} menunjuk pada titik waktu spesifik. Dengan memanggil {{jsxref("Date.prototype.toString()", "toString()")}} akan mengembalikan format tanggal dalam bentuk yang mudah dibaca manuasia dengan format tanggal English (Amerika). Di SpiderMonkey, Bagian tanggal terdiri dari (hari, bulan, dan tahun) di ikuti dengan waktu (Jam, menit, detik, dan waktu bagian). Terkadang kita hanya membutuhan bagian waktu dalam bentuk string; hal tersebut bisa di capai dengan menggunakan metod toTimeString().

- -

Method toTimeString() sangatlah berguna karena berdasarkan engine (compiliant engine) yang di implementasikan ECMA-262 mungkin string yang diperoleh akan berbeda dari {{jsxref("Date.prototype.toString()", "toString()")}} untuk objek {{jsxref("Date")}}, dengan format tergantung dari implementasi; pendekatan bagian string sederhana kemungkinan tidak sama untuk engine yang berbeda.

- -

Contoh

- -

Dasar penggunaan of toTimeString()

- -
var d = new Date(1993, 6, 28, 14, 39, 7);
-
-console.log(d.toString());     // logs Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
-console.log(d.toTimeString()); // logs 14:39:07 GMT-0600 (PDT)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.9.5.4', 'Date.prototype.toTimeString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.prototype.totimestring', 'Date.prototype.toTimeString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/error/index.html b/files/id/web/javascript/reference/global_objects/error/index.html deleted file mode 100644 index c0fc3cec6f..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Error -slug: Web/JavaScript/Reference/Global_Objects/Error -tags: - - Error - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Error ---- -
{{JSRef}}
- -

Konstruktor Error membuat sebuah objek error. Misal objek Error di lontarkan ketika terjadi runtime error. Objek Error juga dapat digunakan sebagai objek dasar dengan pengecualian yang ditentukan pengguna. Berikut untuk standard jenis built-in error.

- -

Sintaks

- -
new Error([message[, fileName[, lineNumber]]])
- -

Parameter

- -
-
message
-
Optional. Human-readable description of the error.
-
fileName {{non-standard_inline}}
-
Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
-
lineNumber {{non-standard_inline}}
-
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
-
- -

Description

- -

Runtime errors result in new Error objects being created and thrown.

- -

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

- -

Error types

- -

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

- -
-
{{jsxref("EvalError")}}
-
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("InternalError")}} {{non-standard_inline}}
-
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
-
{{jsxref("RangeError")}}
-
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
-
{{jsxref("ReferenceError")}}
-
Creates an instance representing an error that occurs when de-referencing an invalid reference.
-
{{jsxref("SyntaxError")}}
-
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("TypeError")}}
-
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
-
{{jsxref("URIError")}}
-
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.
-
- -

Properties

- -
-
{{jsxref("Error.prototype")}}
-
Allows the addition of properties to Error instances.
-
- -

Methods

- -

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

- -

Error instances

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
- -

Properties

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}
- -

Methods

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}
- -

Examples

- -

Throwing a generic error

- -

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

- -
try {
-  throw new Error('Whoops!');
-} catch (e) {
-  console.log(e.name + ': ' + e.message);
-}
-
- -

Handling a specific error

- -

You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:

- -
try {
-  foo.bar();
-} catch (e) {
-  if (e instanceof EvalError) {
-    console.log(e.name + ': ' + e.message);
-  } else if (e instanceof RangeError) {
-    console.log(e.name + ': ' + e.message);
-  }
-  // ... etc
-}
-
- -

Custom Error Types

- -

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

- -
-

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

-
- -

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

- -
// Create a new object, that prototypically inherits from the Error constructor
-function MyError(message) {
-  this.name = 'MyError';
-  this.message = message || 'Default Message';
-  this.stack = (new Error()).stack;
-}
-MyError.prototype = Object.create(Error.prototype);
-MyError.prototype.constructor = MyError;
-
-try {
-  throw new MyError();
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'Default Message'
-}
-
-try {
-  throw new MyError('custom message');
-} catch (e) {
-  console.log(e.name);     // 'MyError'
-  console.log(e.message);  // 'custom message'
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{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/id/web/javascript/reference/global_objects/error/name/index.html b/files/id/web/javascript/reference/global_objects/error/name/index.html deleted file mode 100644 index 6644fff80a..0000000000 --- a/files/id/web/javascript/reference/global_objects/error/name/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Error.prototype.name -slug: Web/JavaScript/Reference/Global_Objects/Error/name -tags: - - Error - - JavaScript - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Error/name ---- -
{{JSRef}}
- -

Properti name menyatakan nama dari jenis error. Nilai awalnya adalah "Error".

- -

Deskripsi

- -

Secara default, misalnya {{jsxref("Error")}} diberi nama "Error". Properti name, sebagai tambahan utuk properti {{jsxref("Error.prototype.message", "message")}}, digunakan oleh method {{jsxref("Error.prototype.toString()")}} untuk membuat sebuah pernyataan dalam bentuk string yang menyatakan error.

- -

Contoh

- -

Menggunakan custom error

- -
var e = new Error('Inputan tidak lengkap'); // e.name nilainya 'Error'
-
-e.name = 'ParseError';
-throw e;
-// e.toString() akan mengembalikan 'ParseError: Inputan tidak lengkap'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.4.2', 'Error.prototype.name')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error.prototype.name', 'Error.prototype.name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/displayname/index.html b/files/id/web/javascript/reference/global_objects/function/displayname/index.html deleted file mode 100644 index 952014983b..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/displayname/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Function.displayName -slug: Web/JavaScript/Reference/Global_Objects/Function/displayName -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/displayName ---- -
{{JSRef}} {{non-standard_header}}
- -

Properti function.displayName mengembalikan nama fungsi.

- -

Deskripsi

- -

Ketika didefinisikan, properti displayName mengembalikan nama dari sebuah fungsi:

- -
function doSomething() {}
-
-console.log(doSomething.displayName); // "undefined"
-
-var popup = function(content) { console.log(content); };
-
-popup.displayName = 'Show Popup';
-
-console.log(popup.displayName); // "Show Popup"
-
- -

Anda bisa mendefinisikan sebuah fungsi dengan sebuah display nama di {{jsxref("Functions", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function() {}
-};
-
-object.someMethod.displayName = 'someMethod';
-
-console.log(object.someMethod.displayName); // logs "someMethod"
-
-try { someMethod } catch(e) { console.log(e); }
-// ReferenceError: someMethod is not defined
-
- -

Anda bisa merubah  displayName dari sebuah fungsi secara dinamis:

- -
var object = {
-  // anonymous
-  someMethod: function(value) {
-    this.displayName = 'someMethod (' + value + ')';
-  }
-};
-
-console.log(object.someMethod.displayName); // "undefined"
-
-object.someMethod('123')
-console.log(object.someMethod.displayName); // "someMethod (123)"
-
- -

Contoh

- -

Biasanya lebih banyak digunakan dengan console dan profiler melalui {{jsxref("Function.name", "func.name")}} untuk menampilkan nama function.

- -

Dengan menuliskan kode berikut, maka seharusnya akan menampilkan "function My Function()":

- -
var a = function() {};
-a.displayName = 'My Function';
-
-a; // "function My Function()"
- -

Spesifikasi

- -

Bukan bagian dari spesifikasi.

- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(13)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
diff --git a/files/id/web/javascript/reference/global_objects/function/index.html b/files/id/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index 49d1c1a114..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Konstruktor Function membuat sebuah objek Function baru. Di Javascript setiap fungsi adalah sebuah objek Function.

- -

Sintaks

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Parameter

- -
-
arg1, arg2, ... argN
-
Nama yang akan digunakan oleh fungsi sebagai nama formal argumen. Masing-masing harus berupa string yang sesuai dengan identifier JavaScript yang valid atau daftar string dipisahkan dengan koma; contohnya "x", "theValue", atau "a,b".
-
functionBody
-
String berisi sintaks JavaScript yang terdiri dari definisi fungsi.
-
- -

Deskripsi

- -

Objek  Function yang dibuat dengan konstruktor Function diuraikan ketika fungsi dibuat. Hal tersebut kurang efisien dibandingkan dengan mendeklarasikan fungsi dengan function expression atau function statement dan memanggilnya dengan kode Anda, karena fungsi-fungsi tersebut diuraikan dengan sisa kode.

- -

Semua argumen yang diteruskan ke fungsi diperlakukan sebagai nama identifier parameter dalam fungsi yang akan dibuat, dalam urutan yang dilewatkan.

- -
-

Catatan: Fungsi dibuat dengan konstruktor Function  jangan membuat penutup pada konteks kreasi mereka; Mereka selalu dibuat dalam ruang lingkup global. Saat menjalankannya, mereka hanya bisa mengakses variabel lokal mereka sendiri dan variabel global, bukan variabel dari ruang lingkup dimana konstruktor Function dipanggil. Berbeda dari menggunakan {{jsxref("eval")}} dengan kode untuk fungsi ekspresi.

-
- -

memanggil konstruktor Function sebagai sebuah fungsi (tanpa menggunakan operatur baru) mempunyai efek yang sama seperti memanggilnya sebagai konstruktor

- -

Properti dan Method Function

- -

Objek Function global tidak memiliki method atau properti sendiri. Namun, fungsi itu sendiri mewarisi beberapa method dan properti melalui prototipe dari {{jsxref("Function.prototype")}}.

- -

Objek prototipe Function

- -

Properti

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
- -

Method

- -
{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
- -

Function instances

- -

Function instances mewarisi method dan properti dari {{jsxref("Function.prototype")}}. Seperti halnya semua konstruktor, Anda dapat mengubah objek prototipe konstruktor untuk membuat perubahan pada semua Function instances.

- -

Contoh

- -

Menentukan arguman dengan konstruktor Function

- -

Dibawah ini kode untuk membuat sebuah objek Function yang menggunakan dua argumen.

- -
// Contoh dapat dijalankan langsung di konsol JavaScript Anda
-
-// Buat fungsi yang mengambil dua argumen dan mengembalikan jumlah argumen tersebut
-var adder = new Function('a', 'b', 'return a + b');
-
-// Memanggil fungsi
-adder(2, 6);
-// > 8
-
- -

Argumen "a" dan "b" adalah nama argumen formal yang digunakan pada function body "return a + b".

- -

Pintasan rekursif untuk memofikasi DOM secara masif

- -

Membuat fungsi dengan konstruktor Function adalah salah satu cara dinamis untuk membuat objek baru dengan beberapa kode yang dapat dieksekusi ke dalam lingkup global dari suatu fungsi. Contoh berikut (pintasan rekursif untuk memodifikasi DOM secara masif) tidak dimungkinkan tanpa permintaan konstruktor Function untuk setiap kueri baru jika Anda ingin menghindari penutup tiap fungsi.

- -
<!doctype html>
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
-<title>MDN Example - a recursive shortcut to massively modify the DOM</title>
-<script type="text/javascript">
-var domQuery = (function() {
-  var aDOMFunc = [
-    Element.prototype.removeAttribute,
-    Element.prototype.setAttribute,
-    CSSStyleDeclaration.prototype.removeProperty,
-    CSSStyleDeclaration.prototype.setProperty
-  ];
-
-  function setSomething(bStyle, sProp, sVal) {
-    var bSet = Boolean(sVal), fAction = aDOMFunc[bSet | bStyle << 1],
-        aArgs = Array.prototype.slice.call(arguments, 1, bSet ? 3 : 2),
-        aNodeList = bStyle ? this.cssNodes : this.nodes;
-
-    if (bSet && bStyle) { aArgs.push(''); }
-    for (
-      var nItem = 0, nLen = this.nodes.length;
-      nItem < nLen;
-      fAction.apply(aNodeList[nItem++], aArgs)
-    );
-    this.follow = setSomething.caller;
-    return this;
-  }
-
-  function setStyles(sProp, sVal) { return setSomething.call(this, true, sProp, sVal); }
-  function setAttribs(sProp, sVal) { return setSomething.call(this, false, sProp, sVal); }
-  function getSelectors() { return this.selectors; };
-  function getNodes() { return this.nodes; };
-
-  return (function(sSelectors) {
-    var oQuery = new Function('return arguments.callee.follow.apply(arguments.callee, arguments);');
-    oQuery.selectors = sSelectors;
-    oQuery.nodes = document.querySelectorAll(sSelectors);
-    oQuery.cssNodes = Array.prototype.map.call(oQuery.nodes, function(oInlineCSS) { return oInlineCSS.style; });
-    oQuery.attributes = setAttribs;
-    oQuery.inlineStyle = setStyles;
-    oQuery.follow = getNodes;
-    oQuery.toString = getSelectors;
-    oQuery.valueOf = getNodes;
-    return oQuery;
-  });
-})();
-</script>
-</head>
-
-<body>
-
-<div class="testClass">Lorem ipsum</div>
-<p>Some text</p>
-<div class="testClass">dolor sit amet</div>
-
-<script type="text/javascript">
-domQuery('.testClass')
-  .attributes('lang', 'en')('title', 'Risus abundat in ore stultorum')
-  .inlineStyle('background-color', 'black')('color', 'white')('width', '100px')('height', '50px');
-</script>
-</body>
-
-</html>
-
- -

Spesifikasi

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

Kesesuaian Browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/length/index.html b/files/id/web/javascript/reference/global_objects/function/length/index.html deleted file mode 100644 index 901c11b336..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/length/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Function.length -slug: Web/JavaScript/Reference/Global_Objects/Function/length -tags: - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/length ---- -
{{JSRef}}
- -

Properti length menentukan jumlah argumen yang diharapkan oleh fungsi.

- -
{{js_property_attributes(0,0,1)}}
- -

Deskripsi

- -

length merupakan properti dari objek fungsi, dan mengindikasikan berapa banyak argumen yang diharapkan fungsi, mis. jumlah parameter formal. Jumlah ini mengesampingkan {{jsxref("rest_parameters", "rest parameter", "", 1)}}. Sebaliknya, {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} adalah lokal untuk fungsi dan memberikan jumlah argumen sebenarnya ke fungsi.

- -

Properti data dari constructor Function

- -

Construktor {{jsxref("Function")}} sendiri adalah objek {{jsxref("Function")}}. data properti length bernilai 1. Properti atribut: Writable: false, Enumerable: false, Configurable: true.

- -

Properti dari Function prototype object

- -

Panjang properti dari prototype objek {{jsxref("Function")}} bernilai 0.

- -

Contoh

- -
console.log(Function.length); /* 1 */
-
-console.log((function()        {}).length); /* 0 */
-console.log((function(a)       {}).length); /* 1 */
-console.log((function(a, b)    {}).length); /* 2 etc. */
-
-console.log((function(...args) {}).length);
-// 0, rest parameter is not counted
-
-console.log((function(a, b = 1, c) {}).length);
-// 1, only parameters before the first one with
-// a default value is counted
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}The configurable attribute of this property is now true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/function/name/index.html b/files/id/web/javascript/reference/global_objects/function/name/index.html deleted file mode 100644 index 1a35d62020..0000000000 --- a/files/id/web/javascript/reference/global_objects/function/name/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: Function.name -slug: Web/JavaScript/Reference/Global_Objects/Function/name -tags: - - ECMAScript6 - - Function - - JavaScript - - Property -translation_of: Web/JavaScript/Reference/Global_Objects/Function/name ---- -
{{JSRef}}
- -

Properti function.name mengembalikan nama fungsi.

- -
{{js_property_attributes(0,0,1)}}
- -
Perlu di ingat bahwa ini di dalam non-standard, implementasi pre-ES6 atribut configurable juga false.
- -

Deskripsi

- -

Properti name property mengembalikan nama sebuah fungsi , atau (sebelum implementasi ES6) string kosong untuk anonymous functions:

- -
function doSomething() {}
-
-console.log(doSomething.name); // logs "doSomething"
-
- -

Fungsi di buat menggunakan sintaks new Function(...) atau hanya Function(...) memiliki properti name di set empty string. Pada contoh anonymous functions dibuat, sehingga name mengembalikan empty string:

- -
var f = function() {};
-var object = {
-  someMethod: function() {}
-};
-
-console.log(f.name == ''); // true
-console.log(object.someMethod.name == ''); // also true
-
- -

Browser yang mengimplementasikan fungsi ES6 mengambil nama dari anonymous function dari posisi syntactic-nya. Contoh:

- -
var f = function() {};
-console.log(f.name); // "f"
- -

Anda bisa mendefinisikan sebuah fungsi dengan nama di {{jsxref("Operators/Function", "function expression", "", 1)}}:

- -
var object = {
-  someMethod: function object_someMethod() {}
-};
-console.log(object.someMethod.name); // logs "object_someMethod"
-
-try { object_someMethod } catch(e) { console.log(e); }
-// ReferenceError: object_someMethod is not defined
-
- -

Anda tidak bisa mengubah nama fungsi, Properti ini hanya bisa dibaca:

- -
var object = {
-  // anonymous
-  someMethod: function() {}
-};
-
-object.someMethod.name = 'someMethod';
-console.log(object.someMethod.name); // empty string, someMethod is anonymous
-
- -

Untuk mengubah, anda perlu menggunakan {{jsxref("Object.defineProperty()")}}.

- -

Contoh

- -

Anda bisa menggunakan obj.constructor.name untuk memeriksa "class" dari sebuah objek:

- -
function a() {}
-
-var b = new a();
-
-console.log(b.constructor.name); // logs "a"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-name', 'name')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-name', 'name')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(33.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatChrome(43.0)}}{{CompatGeckoDesktop(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(38)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Inferred names on anonymous functions{{CompatNo}}{{CompatChrome(51.0)}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(51.0)}}
-
- -

[1] See {{bug(883377)}}.

diff --git a/files/id/web/javascript/reference/global_objects/index.html b/files/id/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 5259bde5b8..0000000000 --- a/files/id/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Global Objek -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Pada bagian ini membahas standar javascript, objek built-in, Termasuk didalamnya method dan properti.

- -
-

Istilah "Global Objek" (atau standar objek built-in)disini bukan berarti Global Objek. Disini global objek di artikan sebagai objek pada scope global (tapi hanya jika ECMAScript 5 mode strict tidak digunakan; pada kasus ini mengembalikan {{jsxref("undefined")}}).  Global objek sendiri bisa di akses menggunakan operator {{jsxref("Operators/this", "this")}} pada lingkup global. Bahkan, lingkup global terdiri dari properti pada global objek, termasuk peoperti yang diwariskan, jika ada.

- -

Objek lain di lingkup global salah satunya dibuat oleh user script atau disediakan oleh aplikasi host. Objek host tersedia di konteks browser, didokumentasi di Referensi API. Untuk informasi lengkap tentang perbedaan antara DOM dan inti JavaScript, lihat Gambaran teknologi javaScript.

- -

Objek standar berdasarkan kategori

- -

Properti nilai

- -

Properti global ini mengembalikan nilai simple; tidak memiliki properti ataupun method.

- - - -

Properti fungsi

- -

Fungsi global—fungsi yang di panggil secara global bukan pada objek — langsung mengembalikan nilai ke pemenggil.

- - - -

Fundamental objek

- -

Ini merupakan fundamental, objek dasar berdasarkan pada semua objek lain yang didasarkan. Ini termasuk objek yang mewakili objek umum, fungsi dan error.

- - - -

Nomor dan tanggal

- -

Objek dasar yang mewakili angka, tanggal dan kalkulasi matematik.

- - - -

Pengolah teks

- -

Objek yang mewakili string dan dukungan untuk memanipulasinya.

- - - -

Koleksi Index

- -

Objek ini mewakili koleksi data berdasarkan nilai index. Ini termasuk (jenis) array dan konstruksi mirip array (array-like).

- - - -

Koleksi keyed

- -

Objek ini merupakan koleksi yang menggunakan key; mengandung unsur yang iterable di urutan penyisipan.

- - - -

Koleksi vektor

- -

{{Glossary("SIMD")}} tipe data vector adalah objek dimana data diatur arahnya.

- - - -

Data terstruktur

- -

Objek ini mewakili dan berinteraksi dengan buffer data terstruktur dan data yang dikodekan menggunakan JavaScript Object Notation (JSON).

- - - -

Kontrol objek abstraksi 

- - - -

Refleksi (Pantulan)

- - - -

Internasionalisasi

- -

Penambahan inti ECMAScript untuk fungsi bahasa-sensitif.

- - - -

Objek Non-standar

- - - -

Lainnya

- - -
- -

 

diff --git a/files/id/web/javascript/reference/global_objects/isnan/index.html b/files/id/web/javascript/reference/global_objects/isnan/index.html deleted file mode 100644 index b7a6774528..0000000000 --- a/files/id/web/javascript/reference/global_objects/isnan/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: isNaN() -slug: Web/JavaScript/Reference/Global_Objects/isNaN -translation_of: Web/JavaScript/Reference/Global_Objects/isNaN ---- -
{{jsSidebar("Objects")}}
- -

Fungsi isNaN() menentukan apakah nilai adalah sebuah {{jsxref("NaN")}} atau bukan. Catatan: pemaksaan pada fungsi isNaN memiliki aturan yang menarik. Anda mungkin ingin menggunakan {{jsxref("Number.isNaN()")}}, seperti yang didefinisikan dalam ECMAScript 2015.

- -

Syntax

- -
isNaN(value)
- -

Parameters

- -
-
value
-
Nilai yang akan di uji.
-
- -

Return value

- -

true Jika nilai yang di uji adalah {{jsxref("NaN")}}; jika tidak, false.

- -

Deskripsi

- -

Kebutuhan akan fungsi isNaN

- -

Mungkin tidak seperti nilai lainnya dalam javascript, Ini tidak memungkinkan untuk mengandalkan operator persamaan (== dan ===) untuk menentukan bahwa nilai adalah {{jsxref("NaN")}} atau bukan, karena NaN == NaN dan NaN === NaN mengevaluasi ke false. Oleh karena itu, diperlukan adanya fungsi isNaN.

- -

Asal Mula Nilai NaN

- -

NilaiNaN dihasilkan saat operasi aritmatika menghasilkan nilai undefined atau unrepresentable. Nilai tersebut tidak harus mewakili kondisi overflowNaN juga dihasilkan dari percobaan pemaksaan ke nilai numerik dari nilai non-numerik yang tidak memiliki nilai numerik primitif yang tersedia.

- -

Misalnya, membagi nol dengan nol menghasilkan sebuah NaN — namun membagi angka lain dengan nol tidak menghasilkan sebuah NaN.

- -

Perilaku Khusus yang membingungkan

- -

Karena versi paling awal dari spesifikasi fungsi isNaN , perilaku untuk argumen non-numerik menjadi membingungkan. Ketika argumen ke fungsi isNaN bukan bertipe Number, Nilainya akan dipaksakan terlebih dahulu ke tipe Number. Nilai yang dihasilkan kemudian diuji untuk menentukan apakah itu {{jsxref("NaN")}}. Jadi untuk non-angka yang jika dipaksakan pada hasil numerik menghasilkan nilai numerik non-NaN (terutama string kosong dan primitif boolean, yang jika dipaksakan memberi nilai numerik nol atau satu), nilai pengembalian "false" mungkin tidak terduga; String kosong, misalnya, pastinya "not a number". Kebingungan itu berawal dari kenyataan bahwa istilah "not a number", memiliki arti khusus untuk angka yang diwakili sebagai nilai floating-point IEEE-754. Fungsi harus diinterpretasikan sebagai penjawab pertanyaan, "apakah nilai ini, jika dipaksakan pada nilai numerik, nilai IEEE-754 'Not A Number'?"

- -

Versi terbaru dari ECMAScript (ES2015) berisi fungsi {{jsxref("Number.isNaN()")}}. Number.isNaN(x) akan menjadi cara yang andal untuk menguji apakah x adalah NaN atau bukan. Bahkan dengan Number.isNaN, namun arti NaN tetap merupakan makna numerik yang tepat, dan bukan sekadar, "not a number". Sebagai alternatif, untuk ketidakhadiran Number.isNaN, ekspresi (x != x) adalah cara yang lebih dapat diandalkan untuk menguji apakah variabel x adalah NaN atau bukan, karena hasilnya tidak sesuai dengan false positive yang membuat isNaN tidak dapat diandalkan.

- -

Anda bisa memikirkan isNaN sebagai:

- -
var isNaN = function(value) {
-    return Number.isNaN(Number(value));
-}
- -

Contoh

- -
isNaN(NaN);       // true
-isNaN(undefined); // true
-isNaN({});        // true
-
-isNaN(true);      // false
-isNaN(null);      // false
-isNaN(37);        // false
-
-// strings
-isNaN('37');      // false: "37" dikonversi ke nomor 37 yang mana bukan NaN
-isNaN('37.37');   // false: "37.37" dikonversi ke nomor 37.37 yang mana bukan NaN
-isNaN('123ABC');  // true:  parseInt("123ABC") adalah 123 namun Number("123ABC") adalah NaN
-isNaN('');        // false: string kosing dikonversi ke 0 yang mana bukan NaN
-isNaN(' ');       // false: string dengan spasi dikonversi ke 0 yang mana bukan NaN
-
-// dates
-isNaN(new Date());                // false
-isNaN(new Date().toString());     // true
-
-// Ini adalah false positif dan alasan mengapa NaN tidak sepenuhnya dapat diandalkan
-isNaN('blabla');   // true: "blabla" dikonversi ke nomor.
-                   // Parsing ini sebagai nomor gagal dan mengembalikan NaN
-
- -

Berguna dalam perilaku khusus

- -

Ada cara penggunaan yang lebih berorientasi untuk memikirkan isNaN isNaN(): Jika isNaN(x) mengembalikan false, anda bisa menggunakan x dalam ekspresi aritmatika tidak membuat ekspresi mengembalikan NaN. Jika itu mengembalikantrue, x akan membuat setiap ekspresi aritmatika mengembalikan NaN. Ini berarti bahwa dalam JavaScript, isNaN(x) == true setara dengan x - 0 mengembalikan NaN (meskipun di JavaScript x - 0 == NaN selalu mengembalikan false, jadi anda tidak bisa mengujinya). Sebenarnya, isNaN(x), isNaN(x - 0), isNaN(Number(x)), Number.isNaN(x - 0), dan Number.isNaN(Number(x)) selalu kembali sama dan di JavaScriptisNaN(x) hanya bentuk sesingkat mungkin untuk mengungkapkan masing-masing istilah ini.

- -

Anda dapat menggunakan ini, misalnya, untuk menguji apakah sebuah argumen terhadap suatu fungsi secara aritmatika dapat diolah (dapat digunakan "seperti" angka), atau jika tidak dan Anda harus memberikan nilai default atau yang lainnya. Dengan cara ini Anda dapat memiliki fungsi yang memanfaatkan fleksibilitas penuh JavaScript yang disediakan oleh nilai konversi secara implisit bergantung pada konteks.

- -

Contoh

- -
function increment(x) {
-  if (isNaN(x)) x = 0;
-  return x + 1;
-}
-
-// Efek yang sama dengan Number.isNaN():
-function increment(x) {
-  if (Number.isNaN(Number(x))) x = 0;
-  return x + 1;
-}
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x)selalu salah, meski x memang bukan sebuah
-// nomor, namun bisa digunakan seperti itu dalam ekspresi
-// aritmatika
-increment('');            // 1: "" dikonversi ke 0
-increment(new String());  // 1: Objek String yang mewakili string kosong dikonversi menjadi 0
-increment([]);            // 1: [] dikonversi ke 0
-increment(new Array());   // 1: Objek array yang mewakili sebuah array kosong dikonversi menjadi 0
-increment('0');           // 1: "0" dikonversi ke 0
-increment('1');           // 2: "1" dikonversi ke 1
-increment('0.1');         // 1.1: "0.1" dikonversi ke 0.1
-increment('Infinity');    // Infinity: "Infinity" dikonversi ke Infinity
-increment(null);          // 1: null dikonversi ke 0
-increment(false);         // 1: false dikonversi ke 0
-increment(true);          // 2: true dikonversi ke 1
-increment(new Date());    // mengembalikan tanggal/waktu sekarang dalam milidetik ditambah 1
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu false dan x memang angka
-increment(-1);            // 0
-increment(-0.1);          // 0.9
-increment(0);             // 1
-increment(1);             // 2
-increment(2);             // 3
-// ... dan seterusnya ...
-increment(Infinity);      // Infinity
-
-// Dalam kasus berikut untuk argumen fungsi x,
-// isNaN(x) selalu true dan x benar-benar bukan angka,
-// sehingga fungsi tersebut menggantikannya dengan 0 dan mengembalikan 1
-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) selalu sama dengan isNaN(Number(x)),
-// namun kehadirannya x adalah wajib disini!
-isNaN(x) == isNaN(Number(x)); // true untuk setiap nilai x, termasuk x == undefined,
-                              // karena isNaN(undefined) == true dan Number(undefined) mengembalikan NaN,
-                              // namun ...
-isNaN() == isNaN(Number());   // false, karena isNaN() == true dan Number() == 0
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.isNaN")}}

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/index.html b/files/id/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index 4f07030358..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,243 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

Didalam object JSON terdapat banyak method untuk memparse JavaScript Object Notation ({{glossary("JSON")}}) dan mengkonversi nilai ke JSON. Hal ini tidak dapat di gunakan atau dibangun, dan selain dari kedua sifat method tersebut tidak memiliki fungsi tersendiri.

- -

Deskripsi

- -

JavaScript Object Notation

- -

JSON merupakan sebuah syntax untuk menserialisasi objects, array, angka, string, boolean, dan {{jsxref("null")}}. Hal ini dilihat berdasarkan pada syntax  javascript. Akan tetapi terpisah dari dari hal tersebut: beberapa javascript bukanlah JSON, dan beberapa JSON juga tidak dapat dikatakan sebagai Javascript. Lihat juga JSON: The JavaScript subset that isn't.

- - - - - - - - - - - - - - - - - - - - - - - -
Perbedaan JavaScript dan JSON
Type pada JavaScriptPerbedaan dengan JSON
Object dan ArrayNama properti harus menggunakan string double quotes; tidak diakhiri dengan koma.
AngkaTidak diawali dengan nol; desimal harus di ikuti setidaknya satu digit.
String -

Hanya beberapa karakter tertentu yang menggunakan escape; Kontrol karakter tertentu tidak diperbolehkan; Pemisah baris Unicode (U+2028) dan pemisah paragraf (U+2029) dapat digunakan; string harus menggunakan double-quoted. Lihat contoh dimana {{jsxref("JSON.parse()")}} bisa digunakan dan {{jsxref("SyntaxError")}} dilemparkan ketika mengevaluasi kode sebagai javascript:

- -
-var kode = '"\u2028\u2029"';
-JSON.parse(kode); // bisa digunakan.
-eval(kode); // gagal!
-
-
- -

Syntax JSON lengkapnya sebagai berikut:

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

Whitespace yang tidak signifikan dapat digunakan dimanasaja kecuali didalam JSONNumber (angka tidak dipisahkan dengan whitespace) atau JSONString (dimana ditafsirkan sebagai karakter yang sesuai dalam string; atau akan menyebabkan kesalahan). Karakter Tab (U+0009), carriage return (U+000D), line feed (U+000A), dan karakter spasi (U+0020) merupakan karakter whitespace yang valid.

- -

Method

- -
-
{{jsxref("JSON.parse()")}}
-
Memparse string sebagai JSON, biasanya mengubah nilai yang diberikan beserta sifatnya, dan mengembalikan nilai.
-
{{jsxref("JSON.stringify()")}}
-
Mengembalikan string JSON berdasarkan nilai spesifik, biasanya termasuk beberapa properti tertentu saja atau mengganti nilai properti secara user-defined.
-
- -

Polyfill

- -

Object JSON tidak didukung oleh browser lawas. Anda bisa menyiasatinya dengan memasukkan kode berikut di awal skrip Anda, memungkinkan penggunaan JSON objek dalam implementasi yang secara native tidak mendukung Object JSON (seperti Internet Explorer 6).

- -

Algoritma berikut adalah tiruan dari objek JSON asli:

- -
if (!window.JSON) {
-  window.JSON = {
-    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
-    stringify: (function () {
-      var toString = Object.prototype.toString;
-      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) {
-              if (value.hasOwnProperty(k))
-                tmp.push(stringify(k) + ': ' + stringify(value[k]));
-            }
-            return '{' + tmp.join(', ') + '}';
-          }
-        }
-        return '"' + value.toString().replace(escRE, escFunc) + '"';
-      };
-    })()
-  };
-}
-
- -

Lebih kompleks dari polyfills yang banyak dikenal untuk object JSON adalah JSON2 dan JSON3.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/json/parse/index.html b/files/id/web/javascript/reference/global_objects/json/parse/index.html deleted file mode 100644 index 5eb3f60424..0000000000 --- a/files/id/web/javascript/reference/global_objects/json/parse/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: JSON.parse() -slug: Web/JavaScript/Reference/Global_Objects/JSON/parse -tags: - - ECMAScript5 - - JSON - - Method - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse ---- -
{{JSRef}}
- -

Method JSON.parse() memparse string ke JSON, biasanya mengubah nilai yang dihasilkan oleh parsing.

- -

Sintaks

- -
JSON.parse(text[, reviver])
- -

Parameters

- -
-
text
-
String yang akan di parse ke JSON. Lihat objek {{jsxref("JSON")}} untuk deskripsi lengkap sintaks JSON.
-
reviver {{optional_inline}}
-
Jika sebuah fungsi, mendeskripsikan bagaimana nilai asli dihasilkan oleh parsing berubah, sebelum dikembalikan.
-
- -

Pemulangan

- -

Mengembalikan {{jsxref("Object")}} sesuai dengan teks JSON yang diberikan.

- -

Lontaran

- -

Melontarkan pengecualian {{jsxref("SyntaxError")}} jika string yang di parse tidak sesuai JSON.

- -

Contoh

- -

Menggunakan JSON.parse()

- -
JSON.parse('{}');              // {}
-JSON.parse('true');            // true
-JSON.parse('"foo"');           // "foo"
-JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
-JSON.parse('null');            // null
-
- -

Menggunakan parameter reviver

- -

Jika reviver telah ditentukan, nilai dihitung dengan parsing transformed sebelum dikembalikan. Khususnya, nilai yang terhitung, dan semua propertinya (dimulai dari properti yang paling bersarang dan berlanjut ke nilai asli), secara individu dijalankan melalui reviver, yang di panggil dengan objek yang berada di dalam properti yang akan diproses sebagai this dan dengan nama properti sebagai string dan nilai properti sebagai argumen. jika fungsi reviver mengembalikan {{jsxref("undefined")}} (tidak mengembalikan nilai, contoh, jika eksekusi gagal di akhir fungsi), properti akan dihapus dari objek. Jika tidak, properti akan didefinisikan ulang sebagai sebuah nilai kembali.

- -

reviver dipanggil dengan string kosong dan nilai paling atas mengizinkan tranformsi dari nilai paling atas. Jadi untuk menangani kasus ini dengan baik, biasanya dengan mengembalikan nilai yang diberikan, atau JSON.parse() akan mengembalikan {{jsxref("undefined")}}.

- -
JSON.parse('{"p": 5}', function(k, v) {
-  if (k === '') { return v; } // if topmost value, return it,
-  return v * 2;               // else return v * 2.
-});                           // { p: 10 }
-
-JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
-  console.log(k); // log the current property name, the last is "".
-  return v;       // return the unchanged property value.
-});
-
-// 1
-// 2
-// 4
-// 6
-// 5
-// 3
-// ""
-
- -

JSON.parse() tidak mengizinkan trailing koma

- -
// both will throw a SyntaxError
-JSON.parse('[1, 2, 3, 4, ]');
-JSON.parse('{"foo" : 1, }');
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Gecko-specific notes

- -

Pada Gecko 29 {{geckoRelease("29")}}, string JSON yang gagal akan menampilkan pesan kesalahan yang lebih rinci tentang error dalam memparse. Hal ini sangat berguna ketika mendebug data JSON yang besar.

- -
JSON.parse('[1, 2, 3, 4,]');
-// SyntaxError: JSON.parse: unexpected character at
-// line 1 column 13 of the JSON data
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/clear/index.html b/files/id/web/javascript/reference/global_objects/map/clear/index.html deleted file mode 100644 index 2869835e02..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/clear/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Map.prototype.clear() -slug: Web/JavaScript/Reference/Global_Objects/Map/clear -translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear ---- -
{{JSRef}}
- -

Method clear() menghapus semua elemen yang ada pada objek Map.

- -

Sintaks

- -
myMap.clear();
- -

Contoh

- -

Menggunakan method clear

- -
var myMap = new Map();
-myMap.set("bar", "baz");
-myMap.set(1, "foo");
-
-myMap.size;       // 2
-myMap.has("bar"); // true
-
-myMap.clear();
-
-myMap.size;       // 0
-myMap.has("bar")  // false
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("19.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasart{{CompatNo}}38{{CompatGeckoMobile("19.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/delete/index.html b/files/id/web/javascript/reference/global_objects/map/delete/index.html deleted file mode 100644 index ad9d1922b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/delete/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Map.prototype.delete() -slug: Web/JavaScript/Reference/Global_Objects/Map/delete -translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete ---- -
{{JSRef}}
- -

Method  delete() menghapus elemen yang ditentukan dari objek Map.

- -

Sintaks

- -
myMap.delete(key);
- -

Parameter

- -
-
key
-
Diperlukan. Kunci dari elemen untuk menghapusnya dari objek Map.
-
- -

Return value

- -

Mengembalikan nilai true jika elemen yang ada di dalam objek Map ada dan telah dihapus, atau false jika elemen tidak ada.

- -

Contoh

- -

Menggunakan method delete

- -
var myMap = new Map();
-myMap.set("bar", "foo");
-
-myMap.delete("bar"); // Returns true. Berhasil dihapus.
-myMap.has("bar");    // Returns false. Elemen "bar" sudah tidak tersedia.
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar38{{CompatGeckoDesktop("13.0")}}11257.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatNo}}38{{CompatGeckoMobile("13.0")}}{{CompatNo}}{{CompatNo}}8
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/map/index.html b/files/id/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 9e4a93cfa0..0000000000 --- a/files/id/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,443 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ECMAScript6 - - JavaScript - - Map - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

The Map object is a simple key/value map. 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
-
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair is added to the new Map. null is 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.

- -

Key equality

- -

Key equality is based on the "same-value" 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 earlier versions of the ECMAScript 6 draft -0 and +0 were considered distinct (even though -0 === +0), this has been changed in later versions and has been adapted in Gecko 29 {{geckoRelease("29")}} ({{bug("952870")}}) and a recent nightly Chrome.

- -

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 between Objects and Maps that make using a Map better:

- - - -

This does not mean you should use Maps everywhere, objects still are used in most cases. Map instances are only useful for collections, and you should consider adapting your code where you have previously used objects for such. Objects shall be used as records, with fields and methods.
- If you're still not sure which one to use, ask yourself the following questions:

- - - -

Those all are signs that you want a Map for a collection. If in contrast you have a fixed amount of keys, operate on them individually, and distinguish between their usage, then you want an object.

- -

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);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// Will show 2 logs; first with "0" and second with "1"
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// Will show 2 logs; first with "zero" and second with "one"
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + " = " + value);
-}
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Iterating Maps with forEach()

- -

Maps can be iterated using the forEach() method:

- -
myMap.forEach(function(value, key) {
-  console.log(key + " = " + value);
-}, myMap)
-// 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 spread operator to transform a map into a 2D key-value Array.
-console.log(uneval([...myMap])); // Will show you exactly the same Array as kvArray
-
-// Or use the spread operator on the keys or values iterator to get
-// an array of only the keys or values
-console.log(uneval([...myMap.keys()])); // Will show ["key1", "key2"]
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-map-objects', 'Map')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support -

{{ CompatChrome(38) }} [1]

-
{{ CompatGeckoDesktop("13") }}11257.1
Constructor argument: new Map(iterable){{ CompatChrome(38) }}{{ CompatGeckoDesktop("13") }}{{CompatNo}}25{{CompatNo}}
iterable{{ CompatChrome(38) }}{{ CompatGeckoDesktop("17") }}{{CompatNo}}257.1
Map.clear(){{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("19")}}11257.1
Map.keys(), Map.values(), Map.entries(){{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("20")}}{{CompatNo}}257.1
Map.forEach(){{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("25")}}11257.1
Key equality for -0 and 0{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoDesktop("29")}}{{CompatNo}}25{{CompatNo}}
Constructor argument: new Map(null){{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{ CompatGeckoDesktop("42") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatChrome(38) }} [1]{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}8
Constructor argument: new Map(iterable){{CompatNo}}{{ CompatChrome(38) }}{{ CompatGeckoMobile("13") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
iterable{{CompatNo}}{{CompatNo}}{{ CompatGeckoMobile("17") }}{{CompatNo}}{{CompatNo}}8
Map.clear(){{CompatNo}}{{ CompatChrome(31) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("19")}}{{CompatNo}}{{CompatNo}}8
Map.keys(), Map.values(), Map.entries(){{CompatNo}}{{ CompatChrome(37) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("20")}}{{CompatNo}}{{CompatNo}}8
Map.forEach(){{CompatNo}}{{ CompatChrome(36) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}8
Key equality for -0 and 0{{CompatNo}}{{ CompatChrome(34) }}
- {{ CompatChrome(38) }}
{{CompatGeckoMobile("29")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Constructor argument: new Map(null){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Monkey-patched set() in Constructor{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("37")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map[@@species]{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Map() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("42")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Starting with Chrome 31, the feature was available behind a preference. In chrome://flags, activate the entry “Enable Experimental JavaScript”.

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/math/abs/index.html b/files/id/web/javascript/reference/global_objects/math/abs/index.html deleted file mode 100644 index c15b00b315..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -tags: - - Math - - abs - - math abs -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -
{{JSRef}}
- -

Fungsi Math.abs() mengembalikan nilai mutlak dari sebuah bilangan, yakni

- -

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ -x & \text{if} \quad x < 0 \end{cases}

- -

Sintak

- -
Math.abs(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Nilai mutlak dari bilangan yang diberikan.

- -

Deskripsi

- -

Karena abs() merupakan sebuah metode statis dari Math, anda harus menggunakannya/menulisnya sebagai berikut Math.abs(), Bukan sebagai metode dari sebuah object Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Prilaku dari Math.abs()

- -

Mengabaikan objek kosong, sebuah array dengan lebih dari satu anggota, sebuah string non-numerik atau {{jsxref("undefined")}}/variabel kosong dikembalikan{{jsxref("NaN")}}. Mengabaikan {{jsxref("null")}}, sebuah string kosong atau sebuah array kosong akan menghasilkan 0.

- -
Math.abs('-1');     // 1
-Math.abs(-2);       // 2
-Math.abs(null);     // 0
-Math.abs('');       // 0
-Math.abs([]);       // 0
-Math.abs([2]);      // 2
-Math.abs([1,2]);    // NaN
-Math.abs({});       // NaN
-Math.abs('string'); // NaN
-Math.abs();         // NaN
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/ceil/index.html b/files/id/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index cba010ffdb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -tags: - - JavaScript - - Math - - Metode - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

Fungsi Math.ceil() adalah memberikan nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Catatan: Nilai kembalian Math.ceil(null) adalah integer 0 dan tidak memberikan kesalahan NaN.

- -
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
- - - -

Sintaks

- -
Math.ceil(x)
- -

Parameter

- -
-
x
-
Sebuah angka.
-
- -

Nilai kembali

- -

Nilai integer lebih-besar-dari terkecil atau sama-dengan (pembulatan ke atas) nilai yang ditentukan.

- -

Deskripsi

- -

Karena ceil() adalah sebuah metode statis dari Math, Anda harus selalu menggunakan sebagai Math.ceil(), bukan sebagai metode dari object  Math yang Anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.ceil()

- -

Berikut adalah contoh penggunaan dari Math.ceil().

- -
Math.ceil(.95);    // 1
-Math.ceil(4);      // 4
-Math.ceil(7.004);  // 8
-Math.ceil(-0.95);  // -0
-Math.ceil(-4);     // -4
-Math.ceil(-7.004); // -7
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah angka.
-   *
-   * @param {String}  type  Tipe dari penyesuaian.
-   * @param {Number}  value Angka.
-   * @param {Integer} exp   Eksponen (10 logaritma basis penyesuaian).
-   * @returns {Number} Nilai yang di sesuaikan.
-   */
-  function decimalAdjust(type, value, exp) {
-    // jika exp adalah undefined atau nol...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // Jika nilai adalah bukan sebuah angka atau bilangan integer...
-    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-      return NaN;
-    }
-    // Shift
-    value = value.toString().split('e');
-    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-    // Shift back
-    value = value.toString().split('e');
-    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-  }
-
-  // Decimal round
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Decimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Decimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomen
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas peramban

- -
- -
- -

{{Compat("javascript.builtins.Math.ceil")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/global_objects/math/e/index.html b/files/id/web/javascript/reference/global_objects/math/e/index.html deleted file mode 100644 index 79e9f21f4a..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/e/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.E -slug: Web/JavaScript/Reference/Global_Objects/Math/E -translation_of: Web/JavaScript/Reference/Global_Objects/Math/E ---- -
{{JSRef}}
- -

Properti Math.E mewakili dasar logaritma alami, e,  mendekati 2.718.

- -

Math.E=e2.718\mathtt{\mi{Math.E}} = e \approx 2.718

- -
{{EmbedInteractiveExample("pages/js/math-e.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena E adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.E, daripada sebagai sebuah properti dari objek matematika yang saudara buat. (Math bukan sebuah konstruktor).

- -

Contoh

- -

Menggunakan Math.E

- -

Fungsi berikut menampilkan nilai e:

- -
function getNapier() {
-  return Math.E;
-}
-
-getNapier(); // 2.718281828459045
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}} -

definisi inisial. Diimplementasikan dalam  JavaScript 1.0.

-
{{SpecName('ES5.1', '#sec-15.8.1.1', 'Math.E')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.e', 'Math.E')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.e', 'Math.E')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.E")}}

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/floor/index.html b/files/id/web/javascript/reference/global_objects/math/floor/index.html deleted file mode 100644 index ecd6e89cdd..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -tags: - - Math - - math floor - - pembulatan - - pembulatan bilangan - - pembulatan kebawah javascript -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -
{{JSRef}}
- -

Fungsi Math.floor() mengembalikan bilangan bulat terbesar yang kurang dari atau sama dengan bilangan yang diberikan.

- -

Sintaks

- -
Math.floor(x)
- -

Parameter

- -
-
x
-
Sebuah bilangan.
-
- -

Nilai kembali

- -

Sebuah bilangan yang merepresentasikan bilangan bulat terbesar yang kurang dari atau sama dengan nilai yang diberikan

- -

Deskripsi

- -

Karena floor() adalah sebuah metode statis dari Math, sintaks yang harus anda gunakan adalah Math.floor(), bukan sebagai metode dari obyek Math yang anda buat (Math bukanlah sebuah konstruktor).

- -

Contoh

- -

Penggunaan Math.floor()

- -
Math.floor( 45.95); //  45
-Math.floor( 45.05); //  45
-Math.floor(  4   ); //   4
-Math.floor(-45.05); // -46
-Math.floor(-45.95); // -46
-
- -

Penyesuaian desimal

- -
// Closure
-(function() {
-  /**
-   * Penyesuaian desimal dari sebuah bilangan.
-   *
-   * @param {String}  type  Jenis penyesuaian.
-   * @param {Number}  value Nomor.
-   * @param {Integer} exp   Eksponen (10 logaritma dari penyesuaian dasar).
-   * @returns {Number} Nilai yang disesuaikan.
-   */
-  function decimalAdjust(jenis, nilai, eks) {
-    // Jika eks adalah undefined(belum didefinisikan) atau kosong...
-    if (typeof eks === 'undefined' || +eks === 0) {
-      return Math[jenis](nilai);
-    }
-    nilai = +nilai;
-    eks= +eks;
-    // Jika nilai bukan sebuah angka atau eks bukan sebuah bilangan integer...
-    if (isNaN(nilai) || !(typeof eks === 'number' && eks % 1 === 0)) {
-      return NaN;
-    }
-    // Pengalihan
-    nilai = nilai.toString().split('e');
-    nilai = Math[jenis](+(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] - eks) : -eks)));
-    // pengalihan kembali
-    nilai = nilai.toString().split('e');
-    return +(nilai[0] + 'e' + (nilai[1] ? (+nilai[1] + eks) : eks));
-  }
-
-  // Desimal bulat
-  if (!Math.round10) {
-    Math.round10 = function(nilai, eks) {
-      return decimalAdjust('round', nilai, eks);
-    };
-  }
-  // Desimal floor
-  if (!Math.floor10) {
-    Math.floor10 = function(nilai, eks) {
-      return decimalAdjust('floor', nilai, eks);
-    };
-  }
-  // Desimal ceil
-  if (!Math.ceil10) {
-    Math.ceil10 = function(nilai, eks) {
-      return decimalAdjust('ceil', nilai, eks);
-    };
-  }
-})();
-
-// Round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan pada JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/index.html b/files/id/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index 4d9bb6a9bb..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math merupakan objek built-in yang memiliki properti dan method untuk perhitungan konstan dan fungsi. bukan Fungsi Objek.

- -

Description

- -

Tidak seperti global objects lain, Math bukanlah constructor. Semua properti dan method dari Math adalah 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.

- -

Properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm 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 circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Method

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that a lot of the math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{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 a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{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 a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm of 1 + x (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{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 to the exponent power, that is, baseexponent.
-
{{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 a number 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 a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integral part of the number x, removing any fractional digits.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{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/id/web/javascript/reference/global_objects/math/ln10/index.html b/files/id/web/javascript/reference/global_objects/math/ln10/index.html deleted file mode 100644 index 04e4fe5468..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/ln10/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Math.LN10 -slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 -translation_of: Web/JavaScript/Reference/Global_Objects/Math/LN10 ---- -
{{JSRef}}
- -

Properti Math.LN10 mewakili logaritma alami dari 10, mendekati 2.302:

- -

Math.LN10=ln(10)2.302\mathtt{\mi{Math.LN10}} = \ln(10) \approx 2.302

- -
{{EmbedInteractiveExample("pages/js/math-ln10.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Deskripsi

- -

Karena LN10 adalah sebuah properti matematika statis, saudara selalu menggunakannya sebagai Math.LN10, daripada sebagai sebuah properti objek matematika yang saudara buat (Math bukan sebuah konstruktor).

- -

Contoh

- -

-

Menggunakan Math.LN10

-

- -

Fungsi berikut menampilkan log alami dari 10:

- -
function getNatLog10() {
-  return Math.LN10;
-}
-
-getNatLog10(); // 2.302585092994046
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecisifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi inisial. Diimplementasikan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.1.2', 'Math.LN10')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ln10', 'Math.LN10')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- - - -

{{Compat("javascript.builtins.Math.LN10")}}

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/max/index.html b/files/id/web/javascript/reference/global_objects/math/max/index.html deleted file mode 100644 index aeb1b207ce..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/max/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Math.max() -slug: Web/JavaScript/Reference/Global_Objects/Math/max -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/max ---- -
{{JSRef}}
- -

Fungsi Math.max() mengembalikan nilai terbesar dari zero atau lebih besar.

- -

Sintaks

- -
Math.max([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena max() merupakan method static dari Math, anda perlu menggunakan Math.max(), daripada sebagai method dari objek Math yang anda buat (Math bukan constructor).

- -

Jika tidak diberi argumen, hasilnya akan -{{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak dapat dikonversi ke angka, maka hasilnya {{jsxref("NaN")}}.

- -

Contoh

- -

Penggunaan Math.max()

- -
Math.max(10, 20);   //  20
-Math.max(-10, -20); // -10
-Math.max(-10, 20);  //  20
-
- -

Pada contoh menggunakan fungsi {{jsxref("Function.prototype.apply()")}} untuk mencari nilai elemen maksimum pada sebuah numeric array. getMaxOfArray([1, 2, 3]) sama halnya dengan Math.max(1, 2, 3), tapi anda bisa menggunakan getMaxOfArray() pada programmatikal pembuatan array untuk semua ukuran.

- -
function getMaxOfArray(numArray) {
-  return Math.max.apply(null, numArray);
-}
-
- -

Atau dengan {{jsxref("Operators/Spread_operator", "spread operator")}} baru, mencari nilai terbesar menjadi lebih mudah.

- -
var arr = [1, 2, 3];
-var max = Math.max(...arr);
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/min/index.html b/files/id/web/javascript/reference/global_objects/math/min/index.html deleted file mode 100644 index eb557f36bf..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/min/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Math.min() -slug: Web/JavaScript/Reference/Global_Objects/Math/min -tags: - - JavaScript - - Math - - Method - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Math/min ---- -
{{JSRef}}
- -

Function Math.min() mengembalikan nilai terkecil dari zero atau lebih kecil.

- -

Sintaks

- -
Math.min([value1[, value2[, ...]]])
- -

Parameter

- -
-
value1, value2, ...
-
Nomor.
-
- -

Deskripsi

- -

Karena min() merupakan static method dari Math, anda perlu menggunakan  Math.min(), daripada sebagai method dari objek Math yang anda buat (Math bukanlah konstruktor).

- -

Jika tidak diberi argumen, hasilnya adalah {{jsxref("Infinity")}}.

- -

Jika setidaknya satu argumen tidak bisa di konversi ke angka, maka hasilnya{{jsxref("NaN")}}.

- -

Contoh

- -

Menggunakan Math.min()

- -

Mencari nilai terkecil diantara x dan y dan menyimpannya di variabel z:

- -
var x = 10, y = -20;
-var z = Math.min(x, y);
-
- -

Mengambil nilai dengan Math.min()

- -

Math.min() biasa digunakan untuk mengambil nilai yang terkecil atau sama berdasarkan batasan yang ada. contoh sebagai berikut.

- -
var x = f(foo);
-
-if (x > boundary) {
-  x = boundary;
-}
-
- -

bisa ditulis sebagai berikut

- -
var x = Math.min(f(foo), boundary);
-
- -

{{jsxref("Math.max()")}} bisa digunakan sama halnya denga mengambil nilai pada setiap batasan.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.12', 'Math.min')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.min', 'Math.min')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.min', 'Math.min')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/math/pow/index.html b/files/id/web/javascript/reference/global_objects/math/pow/index.html deleted file mode 100644 index 878fde0e04..0000000000 --- a/files/id/web/javascript/reference/global_objects/math/pow/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: Math.pow -slug: Web/JavaScript/Reference/Global_Objects/Math/pow -translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow ---- -

Ringkasan

-

Mengembalikan bilangan terhadap Pangkat exponent,  yaitu, bilanganeksponen.

- - - - - - - - - - - - - - - - -
Method dari Math
Diimplementasikan padaJavaScript 1.0
Edisi ECMAScriptECMAScript 1st Edition
-

Sintaks

-
Math.pow(bilangan, eksponen) 
-

Parameter

-
-
- bilangan
-
- Bilangan pokok.
-
- eksponen
-
- Eksponen yang digunakan untuk memangkatkan bilangan pokok.
-
-

Deskripsi

-

Karena pow adalah sebuah static method dari Math, anda senantiasa menggunakannya sebagai Math.pow(), daripada sebagai sebuah method dari sebuah Objek Math yang anda buat.

-

Contoh

-

Contoh: Penggunaan Math.pow

-
function raisePower(x,y) {
-   return Math.pow(x,y)
-}
-

Jika x adalah 7 dan y adalah 2, raisePower mengembalikan 49 (7 dipangkatkan 2).

-

Lihat juga

- diff --git a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html deleted file mode 100644 index 6ac06ec718..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/getprototypeof/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Object.getPrototypeOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf ---- -
{{JSRef}}
- -

Metode Object.getPrototypeOf() mengembalikan nilai prototipe dari obyek yang disebutkan (misalnya,  nilai dari properti internal [[Prototype]]).

- -

Sintaks

- -
Object.getPrototypeOf(obj)
- -

Parameter

- -
-
obj
-
Obyek yang memiliki prototipe.
-
- -

Nilai kembali

- -

Prototipe dari obyek yang diberikan. Jika tidak ada property yang ditemukan, {{jsxref("null")}} yang akan dikembalikan.

- -

Contoh

- -
var proto = {};
-var obj = Object.create(proto);
-Object.getPrototypeOf(obj) === proto; // true
-
- -

Catatan

- -

Dalam ES5, akan melemparkan eksepsi {{jsxref("TypeError")}} jika parameter obj parameter bukanlah sebuah obyek. Dalam ES6, parameter akan dipaksa menjadi {{jsxref("Object")}}.

- -
Object.getPrototypeOf("foo");
-// TypeError: "foo" is not an object (ES5 code)
-Object.getPrototypeOf("foo");
-// String.prototype                  (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Definisi awal.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas perambah

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Catatan khusus Opera

- -

Meskipun Opera dengan versi yang lebih lama belum mendukung Object.getPrototypeOf(), Opera mendukung properti non-standar {{jsxref("Object.proto", "__proto__")}} sejak Opera 10.50.

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/index.html b/files/id/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index cc79ab6890..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,221 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

Konstruktor Object membuat sebuah pembungkus objek.

- -

Sintaks

- -
// Persiapan literasi objek
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Panggil konstruktor
-new Object([value])
- -

Parameter

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pasangan dari nama (strings) dan nilai dimana nama dipisahkan dari nilai menggunakan titik dua (colon).
-
value
-
Nilai bebas.
-
- -

Keterangan

- -

Konstruktor Object membuat sebuah pembungkus objek dari nilai yang diberikan. Jika nilainya {{jsxref("null")}} atau {{jsxref("undefined")}}, maka akan menghasilkan dan mengembalikan objek kosong. Sebaliknya, akan mengembalikan sebuah objek dari Type yang bergantung pada nilai yang diberikan. Jika nilai adalah objek, maka nilai akan langsung dikembalikan.

- -

Ketika memanggil konteks non-constructor, Object berperilaku seperti layaknya new Object().

- -

Lihat juga object initializer / literal syntax.

- -

Properti dari konstruktor Object

- -
-
Object.length
-
Bernilai 1.
-
{{jsxref("Object.prototype")}}
-
Memungkinkan untuk menambahkan properti ke semua objek dari type Object.
-
- -

Method dari konstruktor Object

- -
-
{{jsxref("Object.assign()")}}
-
Membuat objek baru dengan menyalin nilai dari semua properti enumerable dari satu atau lebih sumber ke sebuah objek target.
-
{{jsxref("Object.create()")}}
-
Membuat objek baru dengan prototype dan properti objek tertentu.
-
{{jsxref("Object.defineProperty()")}}
-
Menambahkan nama properti berdasarkan deskripsi yang diberikan oleh descriptor pada sebuah objek.
-
{{jsxref("Object.defineProperties()")}}
-
Menambahkan nama properti yang dideskripsikan descriptors pada sebuah object.
-
{{jsxref("Object.entries()")}} {{experimental_inline}}
-
Mengembalikan sebuah array dari enumerable objek dengan  pasangan properti [key, value].
-
{{jsxref("Object.freeze()")}}
-
Membekukan objek: kode lain tidak dapat dihapus atau diubah oleh semua properti.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Mengembalikan sebuah properti descriptor untuk nama propeti pada sebuah object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Mengembalikan array berisi nama dari semua objek yang diberikan own enumerable dan properti non-enumerable.
-
{{jsxref("Object.getOwnPropertySymbols()")}}
-
Mengembalikan sebuah array dari semua properti simbol yang ditemukan secara langsung atas objek yang diberikan.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Mengembalikan prototype dari objek tertentu.
-
{{jsxref("Object.is()")}}
-
Membandingkan dua nilai yang berbeda (mis. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Menentukan apakah memperluas objek di perbolehkan.
-
{{jsxref("Object.isFrozen()")}}
-
Menentukan apakah objek telah beku.
-
{{jsxref("Object.isSealed()")}}
-
Menentukan apakah objek adalah sealed.
-
{{jsxref("Object.keys()")}}
-
Menegembalikan array berisi nama dari semua objek properti own enumerable.
-
{{jsxref("Object.preventExtensions()")}}
-
Mencegah ekstensi dari sebuah objek.
-
{{jsxref("Object.seal()")}}
-
Mencegah kode lain dari penghapusan properti dari sebuah objek.
-
{{jsxref("Object.setPrototypeOf()")}}
-
Mengatur prototype (mis., internal properti [[Prototype]])
-
{{jsxref("Object.values()")}} {{experimental_inline}}
-
Mengembalikan array dari objek nilai own enumerable.
-
- -

Perumpamaan Object dan Object prototype objek

- -

Pada JavaScript, semua objek diturunkan dari Object; dan semua objek mewarisi method dan property dari {{jsxref("Object.prototype")}}, meskipun hal tersebut telah di-override (diganti). Sebagai contoh, prototipe konstruktor lain mengesampingkan properti konstruktor dan menyediakan metode toString() yang spesifik. Perubahan ke objek prototipe Object disebarkan ke semua objek kecuali properti dan metode yang telah diubah sebelumnya diganti di sepanjang rantai prototipe.

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Properties') }}
- -

Method

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Methods') }}
- -

Contoh

- -

Using Object given undefined and null types

- -

Dibawah ini adalah contoh menyimpan objek kosong pada variabel o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Using Object to create Boolean objects

- -

Dibawah ini adalah contoh menyimpan objek {{jsxref("Boolean")}} pada variabel o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Rincian Teknis

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diterapkan di JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}-
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} -

Penambahan Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is

-
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Penambahan Object.entries, Object.values, dan Object.getOwnPropertyDescriptors.
- -

Kesesuaian browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/object/keys/index.html b/files/id/web/javascript/reference/global_objects/object/keys/index.html deleted file mode 100644 index cc1c7dc1a9..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/keys/index.html +++ /dev/null @@ -1,197 +0,0 @@ ---- -title: Object.keys() -slug: Web/JavaScript/Reference/Global_Objects/Object/keys -translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys ---- -
{{JSRef}}
- -

Object.keys() Metode mengembalikan array dari objek yang diberikan sendiri enumerable properti, dalam urutan yang sama seperti yang disediakan oleh loop {{jsxref("Statements/for...in", "for...in")}} (perbedaan adalah bahwa sebuah loop for-in enumerates properti dalam mata rantai prototipe juga).

- -

Syntax

- -
Object.keys(obj)
- -

Parameters

- -
-
obj
-
Objek yang propertinya sendiri enumerable yang harus dikembalikan.
-
- -

Description

- -

Object.keys() mengembalikan array yang elemen string yang sesuai dengan properti enumerable yang ditemukan langsung pada objek. Urutan properti adalah sama dengan yang diberikan oleh perulangan / looping melalui properti dari objek secara manual.

- -

Examples

- -
var arr = ['a', 'b', 'c'];
-console.log(Object.keys(arr)); // console: ['0', '1', '2']
-
-// array like object
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.keys(obj)); // console: ['0', '1', '2']
-
-// array like object with random key ordering
-var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
-console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
-
-// getFoo is property which isn't enumerable
-var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
-my_obj.foo = 1;
-
-console.log(Object.keys(my_obj)); // console: ['foo']
-
- -

Jika Anda ingin semua properti, bahkan tidak enumerables, lihat {{jsxref("Object.getOwnPropertyNames()")}}.

- -

Notes

- -

Dalam ES5, jika argumen untuk metode ini bukan merupakan objek (primitive), maka akan menyebabkan {{jsxref("TypeError")}}. Dalam ES6, argumen tidak-objek akan dipaksa untuk sebuah objek.

- -
Object.keys("foo");
-// TypeError: "foo" is not an object (ES5 code)
-
-Object.keys("foo");
-// ["0", "1", "2"]                   (ES6 code)
-
- -

Polyfill

- -

Untuk menambahkan kompatibel Object.keys dukungan dalam lingkungan yang lebih tua yang tidak native mendukung itu, copy potongan berikut:

- -
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
-if (!Object.keys) {
-  Object.keys = (function() {
-    'use strict';
-    var hasOwnProperty = Object.prototype.hasOwnProperty,
-        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
-        dontEnums = [
-          'toString',
-          'toLocaleString',
-          'valueOf',
-          'hasOwnProperty',
-          'isPrototypeOf',
-          'propertyIsEnumerable',
-          'constructor'
-        ],
-        dontEnumsLength = dontEnums.length;
-
-    return function(obj) {
-      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
-        throw new TypeError('Object.keys called on non-object');
-      }
-
-      var result = [], prop, i;
-
-      for (prop in obj) {
-        if (hasOwnProperty.call(obj, prop)) {
-          result.push(prop);
-        }
-      }
-
-      if (hasDontEnumBug) {
-        for (i = 0; i < dontEnumsLength; i++) {
-          if (hasOwnProperty.call(obj, dontEnums[i])) {
-            result.push(dontEnums[i]);
-          }
-        }
-      }
-      return result;
-    };
-  }());
-}
-
- -

Harap dicatat bahwa kode di atas termasuk kunci non-enumerable di  IE7 (dan mungkin IE8), ketika lewat di sebuah objek dari berbagai window.

- -

Untuk Browser sederhana Polyfill, lihat Javascript - Object.keys Browser Compatibility.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html deleted file mode 100644 index 3899fef48f..0000000000 --- a/files/id/web/javascript/reference/global_objects/object/preventextensions/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Object.preventExtensions() -slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions -translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions ---- -
{{JSRef}}
- -

Metode Object.preventExtensions() mencegah properti-properti baru untuk ditambahkan pada sebuah obyek (mencegah ekstensi di masa depan pada sebuah obyek).

- -

Sintaks

- -
Object.preventExtensions(obj)
- -

Parameter

- -
-
obj
-
Obyek yang akan dibuat menjadi non-ekstensibel.
-
- -

Pengembalian nilai

- -

Obyek yang telah dibuat non-ekstensibel.

- -

Deskripsi

- -

 

- -

Sebuah obyek disebut ekstensibel jika properti baru dapat ditambahkan ke dalamnya . Object.preventExtensions() menandai suatu obyek untuk menjadi tidak ekstensibel, sehingga tidak akan pernah memiliki properti diluar properti-properti yang dimiliki sebelum ditandai sebagai non-ekstensibel. Perhatikan bahwa properti-properti obyek non-ekstensibel, secara umum, masih dapat dihapus. Mencoba untuk menambah properti baru ke obyek non-ekstensibel akan gagal, baik secara diam-diam atau dengan melemparkan {{jsxref("TypeError")}} (paling umum, tetapi tidak secara eksklusif,  ketika berada di {{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}}).

- -

Object.preventExtensions() hanya mencegah penambahan properti sendiri . Sifat masih bisa ditambahkan ke prototipe obyek. Namun, memanggil Object.preventExtensions() pada obyek juga akan mencegah ekstensi / penambahan properti {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}}.

- -

Jika ada cara untuk mengubah suatu obyek ekstensibel untuk satu non-ekstensibel, tidak ada cara untuk melakukan yang sebaliknya di ECMAScript 5 .

- -

Contoh

- -
// Object.preventExtensions returns the object being made non-extensible.
-var obj = {};
-var obj2 = Object.preventExtensions(obj);
-obj === obj2; // true
-
-// Objects are extensible by default.
-var empty = {};
-Object.isExtensible(empty); // === true
-
-// ...but that can be changed.
-Object.preventExtensions(empty);
-Object.isExtensible(empty); // === false
-
-// Object.defineProperty throws when adding a new property to a non-extensible object.
-var nonExtensible = { removable: true };
-Object.preventExtensions(nonExtensible);
-Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
-
-// In strict mode, attempting to add new properties to a non-extensible object throws a TypeError.
-function fail() {
-  'use strict';
-  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
-}
-fail();
-
-// EXTENSION (only works in engines supporting __proto__
-// (which is deprecated. Use Object.getPrototypeOf instead)):
-// A non-extensible object's prototype is immutable.
-var fixed = Object.preventExtensions({});
-fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
-
- -

Catatan

- -

Pada ES5, jika argumen pada fungsi metode ini adalah bukan sebuah obyek (sebuah tipe data primitif), maka hal itu akan menyebabkan {{jsxref("TypeError")}}. Pada ES6, sebuah argumen non-obyek akan diperlakukan seperti obyek tersebut obyek biasa yang non-ekstensibel, dan langsung mengembalikan nilai. 

- -
Object.preventExtensions(1);
-// TypeError: 1 is not an object (ES5 code)
-
-Object.preventExtensions(1);
-// 1                             (ES6 code)
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Definisi awal. Terimplementasi pada JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
- -

Browser kompatibilitas

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/catch/index.html b/files/id/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index f2d5e38e8f..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -tags: - - ECMAScript6 - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

Method catch() mengembalikan Promise dan hanya setuju jika kasusnya gagal. Sama halnya dengan memenggil method {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}.

- -

Sintaks

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Parameter

- -
-
onRejected
-
 {{jsxref("Function")}} dipanggil ketika Promise ditolak. Fungsi ini memiliki satu argumen, alasan penolakan.
-
- -

Deskripsi

- -

Method catch sangat berguna untuk menangani error di gabungan promis anda.

- -

Contoh

- -

Penggunaan method catch

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw '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');
-});
-
-// 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');
-});
-
-
- -

Promis tidak dapat mendeteksi error pada asynchronous callback

- -
var p1 = new Promise(function(resolve, reject) {
-  throw 'Uh-oh!';
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw 'Uncaught Exception!';
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.catch")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/index.html b/files/id/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 240915ba23..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Promise - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

- -

Syntax

- -
new Promise( /* executor */ function(resolve, reject) { ... } );
- -

Parameters

- -
-
executor
-
A function that will be passed to other functions via the arguments resolve and reject. The executor function is executed immediately by the Promise implementation which provides the resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions are bound to the promise and calling them fulfills or rejects the promise, respectively. The executor is expected to initiate some asynchronous work and then, once that completes, call either the resolve or reject function to resolve the promise's final value or else reject it if an error occurred.
-
- -

Description

- -

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

- -

A Promise is in one of these states:

- - - -

A pending promise can become either fulfilled with a value, or rejected with a reason (error). When either of these happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)

- -

As the {{jsxref("Promise.then", "Promise.prototype.then()")}} and {{jsxref("Promise.catch", "Promise.prototype.catch()")}} methods return promises, they can be chained—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.

-
- -

Properties

- -
-
Promise.length
-
Length property whose value is 1 (number of constructor arguments).
-
{{jsxref("Promise.prototype")}}
-
Represents the prototype for the Promise constructor.
-
- -

Methods

- -
-
{{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)")}}
-
Returns a Promise object that is rejected with the given reason.
-
- -
-
{{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

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

- -

Examples

- -

Creating a Promise

- - - -

This small example shows the mechanism of a Promise. The testPromise() method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will resolve, using {{domxref("window.setTimeout()")}}, to the promise count (number starting from 1) 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 a numeric count of this promise, starting from 1 (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/>');
-}
- - - -

This example is executed when clicking the button. You need a browser supporting Promise. By clicking several times the button in a short amount of time, you'll even see the different promises being fulfilled one after the other.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

Example using new XMLHttpRequest()

- -

Creating a Promise

- -

This example shows the implementation of a method which uses a Promise to report the success or failure of an {{domxref("XMLHttpRequest")}}.

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

Loading an image with XHR

- -

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

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

 

- -
- - -

{{Compat("javascript.builtins.Promise")}}

-
- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/reject/index.html b/files/id/web/javascript/reference/global_objects/promise/reject/index.html deleted file mode 100644 index 180fcc5571..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/reject/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Promise.reject() -slug: Web/JavaScript/Reference/Global_Objects/Promise/reject -tags: - - ECMAScript6 - - Method - - Promise - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject ---- -
{{JSRef}}
- -

Method Promise.reject(reason) mengembalikan objek Promise yang ditolak dengan alasan yang diberikan.

- -

Sintaks

- -
Promise.reject(reason);
- -

Parameter

- -
-
reason
-
Alasan kenapa Promise ditolak.
-
- -

Deskripsi

- -

Fungsi static Promise.reject mengembalikan Promise yang ditolak. Untuk keperluan debugging dan seleksi penankapan error, sangat berguna untuk membuat reason pada instanceof {{jsxref("Error")}}.

- -

Contoh

- -

Penggunaan mthod static Promise.reject()

- -
Promise.reject("Testing static reject").then(function(reason) {
-  // not called
-}, function(reason) {
-  console.log(reason); // "Testing static reject"
-});
-
-Promise.reject(new Error("fail")).then(function(error) {
-  // not called
-}, function(error) {
-  console.log(error); // Stacktrace
-});
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.reject")}}

- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html b/files/id/web/javascript/reference/global_objects/promise/resolve/index.html deleted file mode 100644 index d958ab4d52..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/resolve/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Promise.resolve() -slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve ---- -
{{JSRef}}
- -

Method Promise.resolve(value) mengembalikan objek {{jsxref("Promise.then")}} yang diselesaikan dengan nilai yang diberikan. jika nilainya thenable (mis. memiliki {{jsxref("Promise.then", "\"then\" method")}}), promise yang dikembalikan akan "mengikuti" thenable-nya, menggunakan keadaan ini; sebaliknya promise akan dikembalikan sesuai nilai yang terpenuhi.

- -

Sintaks

- -
Promise.resolve(value);
-Promise.resolve(promise);
-Promise.resolve(thenable);
-
- -

Parameter

- -
-
value
-
Argumen untuk diselesaikan oleh Promise. Dapat juga sebuah Promise atau thenable untuk diselesaikan.
-
- -

Deskripsi

- -

Fungsi statis Promise.resolve mengembalikan Promise yang terselesaikan.

- -

Contoh

- -

Penggunaan method static Promise.resolve

- -
Promise.resolve("Success").then(function(value) {
-  console.log(value); // "Success"
-}, function(value) {
-  // not called
-});
-
- -

Penyelesaian pada array

- -
var p = Promise.resolve([1,2,3]);
-p.then(function(v) {
-  console.log(v[0]); // 1
-});
-
- -

Penyelesaian pada Promise lain

- -
var original = Promise.resolve(true);
-var cast = Promise.resolve(original);
-cast.then(function(v) {
-  console.log(v); // true
-});
-
- -

Penyelesaian thenables dan throwing Errors

- -
// Resolving a thenable object
-var p1 = Promise.resolve({
-  then: function(onFulfill, onReject) { onFulfill("fulfilled!"); }
-});
-console.log(p1 instanceof Promise) // true, object casted to a Promise
-
-p1.then(function(v) {
-    console.log(v); // "fulfilled!"
-  }, function(e) {
-    // not called
-});
-
-// Thenable throws before callback
-// Promise rejects
-var thenable = { then: function(resolve) {
-  throw new TypeError("Throwing");
-  resolve("Resolving");
-}};
-
-var p2 = Promise.resolve(thenable);
-p2.then(function(v) {
-  // not called
-}, function(e) {
-  console.log(e); // TypeError: Throwing
-});
-
-// Thenable throws after callback
-// Promise resolves
-var thenable = { then: function(resolve) {
-  resolve("Resolving");
-  throw new TypeError("Throwing");
-}};
-
-var p3 = Promise.resolve(thenable);
-p3.then(function(v) {
-  console.log(v); // "Resolving"
-}, function(e) {
-  // not called
-});
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

 

- - - -

{{Compat("javascript.builtins.Promise.resolve")}}

- -

 

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/promise/then/index.html b/files/id/web/javascript/reference/global_objects/promise/then/index.html deleted file mode 100644 index 5a1e275c8c..0000000000 --- a/files/id/web/javascript/reference/global_objects/promise/then/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Promise.prototype.then() -slug: Web/JavaScript/Reference/Global_Objects/Promise/then -tags: - - ECMAScript6 - - JavaScript - - Method - - Promise - - Prototype - - Referensi -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then ---- -
{{JSRef}}
- -

Method then() mengembalikan {{domxref("Promise")}}. Menggunakan dua argumen: fungsi callback untuk kasus sukses dan gagal pada Promise.

- -

Sintaks

- -
p.then(onFulfilled, onRejected);
-
-p.then(function(value) {
-   // fulfillment
-  }, function(reason) {
-  // rejection
-});
-
- -

Parameter

- -
-
onFulfilled
-
{{jsxref("Function")}} dipanggil ketika Promise dipenuhi. Fungsi ini memiliki satu argumen, value pemenuhan.
-
onRejected
-
{{jsxref("Function")}} dipangil ketika Promise ditolak. fungsi ini memiliki satau argumen, alasan penolakan.
-
- -

Deskripsi

- -

Kedua method then dan {{jsxref("Promise.prototype.catch()")}} megembalikan promis, juga dapat dirantaikan — operasi yang disebut composition.

- -

Contoh

- -

Meggunakan method then

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve("Success!");
-  // or
-  // reject ("Error!");
-});
-
-p1.then(function(value) {
-  console.log(value); // Success!
-}, function(reason) {
-  console.log(reason); // Error!
-});
-
- -

Perantaian

- -

Karena method then mengembalikan Promise, anda bisa merantaikan pemanggilan then.

- -
var p2 = new Promise(function(resolve, reject) {
-  resolve(1);
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-  return value + 1;
-}).then(function(value) {
-  console.log(value); // 2
-});
-
-p2.then(function(value) {
-  console.log(value); // 1
-});
-
- -

Anda juga bisa menggunakan perantaian untuk melaksanakan satu fungsi dengan sebuah Promise berbasis API diatas fungsi lainnya.

- -
function fetch_current_data() {
-  // The fetch() API returns a Promise.  This function
-  // exposes a similar API, except the fulfillment
-  // value of this function's Promise has had more
-  // work done on it.
-  return fetch("current-data.json").then((response) => {
-    if (response.headers.get("content-type") != "application/json") {
-      throw new TypeError();
-    }
-    var j = response.json();
-    // maybe do something with j
-    return j; // fulfillment value given to user of
-              // fetch_current_data().then()
-  });
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- - - -

{{Compat("javascript.builtins.Promise.then")}}

- -

 

- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/regexp/index.html b/files/id/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 8bd6dce4b9..0000000000 --- a/files/id/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}

The RegExpobjek digunakan untuk pencocokan teks dengan pola.

- -

Untuk pengantar ekspresi reguler, baca bab Ekspresi Reguler di Panduan JavaScript .

- -

Deskripsi

- -

Notasi dan konstruktor literal

- -

Ada dua cara untuk membuat RegExpobjek: notasi literal dan konstruktor .

- - - -

Tiga ekspresi berikut membuat ekspresi reguler yang sama:

- -
/ab+c/i
-new RegExp(/ab+c/, 'i') // literal notation
-new RegExp('ab+c', 'i') // constructor
-
- -

Notasi literal menghasilkan kompilasi dari ekspresi reguler ketika ekspresi dievaluasi. Gunakan notasi literal ketika ekspresi reguler akan tetap konstan. Misalnya, jika Anda menggunakan notasi literal untuk membuat ekspresi reguler yang digunakan dalam satu lingkaran, ekspresi reguler tidak akan dikompilasi ulang pada setiap iterasi.

- -

Konstruktor objek ekspresi reguler — misalnya, new RegExp('ab+c')—menghasilkan kompilasi runtime dari ekspresi reguler. Gunakan fungsi konstruktor ketika Anda tahu pola ekspresi reguler akan berubah, atau Anda tidak tahu pola dan mendapatkannya dari sumber lain, seperti input pengguna.

- -

Bendera dalam konstruktor

- -

Dimulai dengan ECMAScript 6, new RegExp(/ab+c/, 'i')tidak lagi melempar a TypeError"can't supply flags when constructing one RegExp from another") ketika argumen pertama adalah a RegExpdan flagsargumen kedua hadir. Sebagai RegExpgantinya, argumen baru dibuat.

- -

Saat menggunakan fungsi konstruktor, aturan pelolosan string normal (mendahului karakter khusus \ketika disertakan dalam string) diperlukan.

- -

Misalnya, yang berikut ini setara:

- -
let re = /\w+/
-let re = new RegExp('\\w+')
-
- -

Properti Reg-suka seperti Perl

- -

Perhatikan bahwa beberapa RegExpproperti memiliki nama panjang dan pendek (seperti Perl). Kedua nama selalu merujuk pada nilai yang sama. (Perl adalah bahasa pemrograman tempat JavaScript memodelkan ekspresi regulernya.). Lihat juga properti yang sudah usang RegExp.

- -

Konstruktor

- -
-
RegExp()
-
Menciptakan RegExpobjek baru .
-
- -

Sifat statis

- -
-
get RegExp[@@species]
-
The constructor function that is used to create derived objects.
-
RegExp.lastIndex
-
The index at which to start the next match.
-
- -

Instance properties

- -
-
RegExp.prototype.flags
-
A string that contains the flags of the RegExp object.
-
RegExp.prototype.dotAll
-
Whether . matches newlines or not.
-
RegExp.prototype.global
-
Whether to test the regular expression against all possible matches in a string, or only against the first.
-
RegExp.prototype.ignoreCase
-
Whether to ignore case while attempting a match in a string.
-
RegExp.prototype.multiline
-
Whether or not to search in strings across multiple lines.
-
RegExp.prototype.source
-
The text of the pattern.
-
RegExp.prototype.sticky
-
Whether or not the search is sticky.
-
RegExp.prototype.unicode
-
Whether or not Unicode features are enabled.
-
- -

Instance methods

- -
-
RegExp.prototype.compile()
-
(Re-)compiles a regular expression during execution of a script.
-
RegExp.prototype.exec()
-
Executes a search for a match in its string parameter.
-
RegExp.prototype.test()
-
Tests for a match in its string parameter.
-
RegExp.prototype.toString()
-
Returns a string representing the specified object. Overrides the Object.prototype.toString() method.
-
RegExp.prototype[@@match]()
-
Performs match to given string and returns match result.
-
RegExp.prototype[@@matchAll]()
-
Returns all matches of the regular expression against a string.
-
RegExp.prototype[@@replace]()
-
Replaces matches in given string with new substring.
-
RegExp.prototype[@@search]()
-
Searches the match in given string and returns the index the pattern found in the string.
-
RegExp.prototype[@@split]()
-
Splits given string into an array by separating the string into substring.
-
- -

Examples

- -

Using a regular expression to change data format

- -

The following script uses the replace() method of the 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.

- -
let re = /(\w+)\s(\w+)/
-let str = 'John Smith'
-let 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.

- -
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
-let 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

- -
let 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 RegExp.prototype.lastIndex.

- -
let str = '#foo#'
-let 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)
- -

The difference between the sticky flag and the global flag

- -

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

- -
re = /\d/y;
-while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
-
-// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
-// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
-// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
-//   ... and no more match.
- -

With the global flag g, all 6 digits would be matched, not just 3.

- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, a to zA to Z0 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.

- -
let text = 'Образец text на русском языке'
-let regex = /[\u0400-\u04FF]+/g
-
-let match = regex.exec(text)
-console.log(match[0])        // logs 'Образец'
-console.log(regex.lastIndex) // logs '7'
-
-let match2 = regex.exec(text)
-console.log(match2[0])       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex) // logs '15'
-
-// and so on
-
- -

The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.

- -

Extracting sub-domain name from URL

- -
let url = 'http://xxx.domain.com'
-console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
-
- -

Instead of using regular expressions for parsing URLs, it is usually better to use the browsers built-in URL parser by using the URL API.

- -

Specifications

- - - - - - - - - - - - -
Specification
ECMAScript (ECMA-262)
- The definition of 'RegExp' in that specification.
- -

Browser compatibility

- -

{{Compat("javascript.builtins.RegExp")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/charat/index.html b/files/id/web/javascript/reference/global_objects/string/charat/index.html deleted file mode 100644 index e464f2bd4c..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/charat/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: String.prototype.charAt() -slug: Web/JavaScript/Reference/Global_Objects/String/charAt -translation_of: Web/JavaScript/Reference/Global_Objects/String/charAt ---- -
{{JSRef}}
- -

Method charAt() pada Objek {{jsxref("String")}} mengembalikan string baru yang berisi kode lokasi single UTF-16 pada offset yang ditentukan ke dalam string.

- -
{{EmbedInteractiveExample("pages/js/string-charat.html", "shorter")}}
- - - -

Syntax

- -
let character = str.charAt(index)
- -

Parameter

- -
-
index
-
Sebuah integer antara 0 sampai str.length - 1. Bila nilai index bukan dalam bentuk integer atau index tidak ditentukan, maka nilai index akan bernilai 0, sehingga karakter pertama varibel str akan dikembalikan/ di-return.
-
- -

Nilai Return

- -

Sebuah string yang merepresentasikan sebuah karakter pada indeks tertentu. Jika index indeks berada di luar range, maka charAt()  akan me-return string kosong.

- -

Deskripsi

- -

Karakter dalam sebuah string diberi indeks dari kiri ke kanan. Indeks karakter pertama adalah 0, dan index karakter terakhir dalam string — misal nama stringnya stringName, adalah stringName.length - 1. Jika indeks yang anda berikan diluar range ini, maka JavaScript akan me-return string kosong.

- -

Jika tidak ada indeks yang tertera pada charAt(), maka nilai defaultnya adalah 0.

- -

Contoh

- -

Menampilkan karakter pada lokasi yang berbeda pada sebuah string

- -

Contoh berikut menunjukan karakter di lokasi berbeda pada string "Brave new world":

- -
var anyString = 'Brave new world';
-console.log("The character at index 0   is '" + anyString.charAt()   + "'");
-// Tidak ada angka yang tertera pada charAt(), maka digunakan nilai 0 sebagai default
-
-console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
-console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
-console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
-console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
-console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
-console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
-
- -

Baris kode di atas menghasilkan output sebagai berikut:

- -
The character at index 0   is 'B'
-
-The character at index 0   is 'B'
-The character at index 1   is 'r'
-The character at index 2   is 'a'
-The character at index 3   is 'v'
-The character at index 4   is 'e'
-The character at index 999 is ''
-
- -

Mendapatkan seluruh karakter

- -

Berikut ini adalah cara untuk memastikan bahwa melalui loop string selalu memberikan karakter utuh, meskipun string berisi karakter yang tidak ada dalam Bidang Multilingual Dasar.

- -
var str = 'A \uD87E\uDC04 Z'; // Kita bisa menggunakan karakter non-BMP
-for (var i = 0, chr; i < str.length; i++) {
-  if ((chr = getWholeChar(str, i)) === false) {
-    continue;
-  }
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning a variable to represent the
-  // individual character
-
-  console.log(chr);
-}
-
-function getWholeChar(str, i) {
-  var code = str.charCodeAt(i);
-
-  if (Number.isNaN(code)) {
-    return ''; // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return str.charAt(i);
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate';
-    }
-    var next = str.charCodeAt(i + 1);
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate';
-      }
-      return str.charAt(i) + str.charAt(i + 1);
-  }
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  var prev = str.charCodeAt(i - 1);
-
-  // (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate';
-  }
-  // We can pass over low surrogates now as the second component
-  // in a pair which we have already processed
-  return false;
-}
-
- -

Pada environment ECMAScript 2016 yang memungkinkan assignment yang rusak, Berikut ini merupakan alternatif yang lebih ringkas dan fleksibel karena perulangan dilakukan penmabahan secara otomatis pada variabel increment/ penambahannya (jika karakter menjaminnya sebagai pasangan pengganti).

- -
let str = 'A\uD87E\uDC04Z'  // Kita juga dapat menggunakan karakter non-BMP
-for (let i = 0, chr; i < str.length; i++) {
-  [chr, i] = getWholeCharAndI(str, i)
-
-  // Adapt this line at the top of each loop, passing in the whole string and
-  // the current iteration and returning an array with the individual character
-  // and 'i' value (only changed if a surrogate pair)
-
-  console.log(chr)
-}
-
-function getWholeCharAndI(str, i) {
-  let code = str.charCodeAt(i)
-
-  if (Number.isNaN(code)) {
-    return ''  // Posisi tidak ditemukan
-  }
-  if (code < 0xD800 || code > 0xDFFF) {
-    return [str.charAt(i), i]  // Karakter normal, keeping 'i' the same
-  }
-
-  // High surrogate (could change last hex to 0xDB7F to treat high private
-  // surrogates as single characters)
-  if (0xD800 <= code && code <= 0xDBFF) {
-    if (str.length <= (i + 1)) {
-      throw 'High surrogate without following low surrogate'
-    }
-    let next = str.charCodeAt(i + 1)
-      if (0xDC00 > next || next > 0xDFFF) {
-        throw 'High surrogate without following low surrogate'
-      }
-      return [str.charAt(i) + str.charAt(i + 1), i + 1]
-  }
-
-  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
-  if (i === 0) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  let prev = str.charCodeAt(i - 1)
-
-  // (could change last hex to 0xDB7F to treat high private surrogates
-  // as single characters)
-  if (0xD800 > prev || prev > 0xDBFF) {
-    throw 'Low surrogate without preceding high surrogate'
-  }
-
-  // Return the next character instead (and increment)
-  return [str.charAt(i + 1), i + 1]
-}
-
- -

Memperbaiki charAt() untuk mendukung karakter non-Basic-Multilingual-Plane (BMP)

- -

Pada contoh sebelumnya mungkin lebih berguna untuk program yang mendukung karakter non-BMP (karena tidak mengharuskan pemanggil untuk mengetahui dimana karakter non-BMP mungkin muncul), jika memang diinginkan, dalam memilih karakter dengan index, untuk memperlakukan pasangan pengganti dalam string sebagai karakter tunggal yang mereka wakili, dapat menggunakan yang berikut ini:

- -
function fixedCharAt(str, idx) {
-  let ret = ''
-  str += ''
-  let end = str.length
-
-  let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
-  while ((surrogatePairs.exec(str)) != null) {
-    let lastIdx = surrogatePairs.lastIndex
-    if (lastIdx - 2 < idx) {
-      idx++
-    } else {
-      break
-    }
-  }
-
-  if (idx >= end || idx < 0) {
-    return ''
-  }
-
-  ret += str.charAt(idx)
-
-  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
-    // Go one further, since one of the "characters" is part of a surrogate pair
-    ret += str.charAt(idx + 1)
-  }
-  return ret
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.charat', 'String.prototype.charAt')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.charAt")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/concat/index.html b/files/id/web/javascript/reference/global_objects/string/concat/index.html deleted file mode 100644 index 0ba2b2a156..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/concat/index.html +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: String.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/String/concat -tags: - - JavaScript - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/concat ---- -
{{JSRef}}
- -

Method concat() menggabungkan dua teks atau lebih menjadi sebuah string baru.

- -

Syntax

- -
str.concat(string2, string3[, ..., stringN])
- -

Parameter

- -
-
string2...stringN
-
String untuk menggabungkan string.
-
- -

Deskripsi

- -

Fungsi concat() menggabungkan teks dari satu atau lebih string dan mengembalikanya menjadi sebuah string. Perubahan pada salah satu teks tidak mempengaruhi string lainnya.

- -

Contoh

- -

Penggunaan concat()

- -

Untuk menggabungkan string menjadi sebuah string baru seperti pada contoh dibawah.

- -
var halo = 'Halo, ';
-console.log(halo.concat('Didik', ' semoga hari ini menyenangkan.'));
-
-/* Halo, Didik semoga hari ini menyenangkan. */
-
- -

Performa

- -

Sangat disarankan untuk menggunakan {{jsxref("Operators/Assignment_Operators", "assignment operators", "", 1)}} (+, +=) pada method concat(). lihat test performa berikut ini.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.6', 'String.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.concat', 'String.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome untuk AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html deleted file mode 100644 index 786e32883e..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcharcode/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: String.fromCharCode() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCharCode -tags: - - JavaScript - - Method - - Metode - - Reference - - Referensi - - String - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode ---- -
{{JSRef}}
- -

Metode statis String.fromCharCode() mengembalikan sebuah string yang dibuat dari barisan nilai Unicode tertentu.

- -

Sintak

- -
String.fromCharCode(num1[, ...[, numN]])
- -

Parameter

- -
-
num1, ..., numN
-
Barisan dari angka-angka yang merupakan nilai Unicode.Jangkauannya antara 0 sampai dengan 65535(0xFFFF).Nomor yang lebih besar dari 0xFFFF dipotong.Tidak ada cek validasi yang dilakukan.   
-
- -

Nilai kembalian

- -

Sebuah string yang di dalamnya terdapat karakter-karakter sesuai nilai Unicode dari barisan angka yang diberikan.

- -

Deskripsi

- -

Metode ini mengembalikan sebuah string dan bukan objek {{jsxref("String")}}.

- -

Karena fromCharCode() merupakan metode statis dari {{jsxref("String")}}, Anda selalu bisa menggunakannya sebagai String.fromCharCode(), daripada sebagai metode dari objek {{jsxref("String")}} yang Anda buat.

- -

Contoh

- -

Menggunakan fromCharCode()

- -

Contoh di bawah ini mengembalikan string "ABC".

- -
String.fromCharCode(65, 66, 67);  // "ABC"
-
- -

Membuatnya bekerja dengan nilai yang lebih tinggi

- -

Meskipu nilai Unicode yang umum dapat digambarkan dengan satu angka 16-bit (seperti yang diharapkan pada awal mula standarisasi JavaScript) dan fromCharCode() dapat digunakan untuk mengembalikan sebuah karakter dari nilai yang paling umum (misal. nilai UCS-2 yang merupakan bagian dari UTF-16 dengan karakter yang paling umum digunakan). Untuk menghadapi SEMUA nilai Unicode yang sah (hingga 21 bit), fromCharCode() sendiri tidak dapat menghadapinya. Semenjak nilai code point karakter yang lebih tinggi menggunakan dua angka "pengganti"  (dengan nilai yang lebih rendah) untuk membuat sebuah karakter tunggal, {{jsxref("String.fromCodePoint()")}} (bagian dari draf ES6) dapat digunakan untuk menggunakan sepasang angka tersebut, sehingga dapat menampilkan karakter dengan nilai yang lebih tinggi.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi awal. Diimplementasikan dalam JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.3.2', 'StringfromCharCode')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.fromcharcodes', 'String.fromCharCode')}}{{Spec2('ESDraft')}}
- -

Kompabilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html b/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html deleted file mode 100644 index dc4024f941..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/fromcodepoint/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: String.fromCodePoint() -slug: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint -tags: - - ECMAScript 2015 - - JavaScript - - Metode - - Referensi - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCodePoint ---- -
{{JSRef}}
- -

Metode String.fromCodePoint() mengembalikan string yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -
{{EmbedInteractiveExample("pages/js/string-fromcodepoint.html")}}
- - - -

Syntax

- -
String.fromCodePoint(num1[, ...[, numN]])
- -

Parameters

- -
-
num1, ..., numN
-
Urutan Poin Kode
-
- -

Return value

- -

String yang dibuat dengan menggunakan urutan titik kode yang ditentukan.

- -

Exceptions

- - - -

Description

- -

Metode ini mengembalikan string dan bukan sebuah objek. {{jsxref("String")}} .

- -

Karena fromCodePoint() adalah metode statik dari {{jsxref("String")}}, dan anda selalu menggunakannya sebagai String.fromCodePoint(), alih-alih sebagai sebuah metode yang anda buat {{jsxref("String")}}

- -

Examples

- -

Using fromCodePoint()

- -
String.fromCodePoint(42);       // "*"
-String.fromCodePoint(65, 90);   // "AZ"
-String.fromCodePoint(0x404);    // "\u0404"
-String.fromCodePoint(0x2F804);  // "\uD87E\uDC04"
-String.fromCodePoint(194564);   // "\uD87E\uDC04"
-String.fromCodePoint(0x1D306, 0x61, 0x1D307) // "\uD834\uDF06a\uD834\uDF07"
-
-String.fromCodePoint('_');      // RangeError
-String.fromCodePoint(Infinity); // RangeError
-String.fromCodePoint(-1);       // RangeError
-String.fromCodePoint(3.14);     // RangeError
-String.fromCodePoint(3e-2);     // RangeError
-String.fromCodePoint(NaN);      // RangeError
-
- -
// String.fromCharCode() sendiri tidak bisa mendapatkan karakter pada titik kode tinggi seperti itu
-// Disisi lain, dapat juga mengembalikan karakter 4-byte dan juga
-// yang biasa 2-byte (i.e., dapat mengembalikan satu karakter yang sebenarnya sudah dimiliki
-// string 2 daripada 1!)
-console.log(String.fromCodePoint(0x2F804)); // atau 194564 dalam bilangan desimal
-
- -

Polyfill

- -

Metode String.fromCodePoint telah ditambahkan ke ECMAScript 2015 dan mungkin belum didukung di semua browser web atau lingkungannya. Gunakan kode dibawah ini untuk polyfill:

- -
if (!String.fromCodePoint) (function(stringFromCharCode) {
-    var fromCodePoint = function(_) {
-      var codeUnits = [], codeLen = 0, result = "";
-      for (var index=0, len = arguments.length; index !== len; ++index) {
-        var codePoint = +arguments[index];
-        // correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
-        // The surrounding `!(...)` is required to correctly handle `NaN` cases
-        // The (codePoint>>>0) === codePoint clause handles decimals and negatives
-        if (!(codePoint < 0x10FFFF && (codePoint>>>0) === codePoint))
-          throw RangeError("Invalid code point: " + codePoint);
-        if (codePoint <= 0xFFFF) { // BMP code point
-          codeLen = codeUnits.push(codePoint);
-        } else { // Astral code point; split in surrogate halves
-          // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
-          codePoint -= 0x10000;
-          codeLen = codeUnits.push(
-            (codePoint >> 10) + 0xD800,  // highSurrogate
-            (codePoint % 0x400) + 0xDC00 // lowSurrogate
-          );
-        }
-        if (codeLen >= 0x3fff) {
-          result += stringFromCharCode.apply(null, codeUnits);
-          codeUnits.length = 0;
-        }
-      }
-      return result + stringFromCharCode.apply(null, codeUnits);
-    };
-    try { // IE 8 only supports `Object.defineProperty` on DOM elements
-      Object.defineProperty(String, "fromCodePoint", {
-        "value": fromCodePoint, "configurable": true, "writable": true
-      });
-    } catch(e) {
-      String.fromCodePoint = fromCodePoint;
-    }
-}(String.fromCharCode));
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ES2015')}}Definisi Awal
{{SpecName('ESDraft', '#sec-string.fromcodepoint', 'String.fromCodePoint')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.fromCodePoint")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/string/index.html b/files/id/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 35f78502d5..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,371 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - Reference - - Referensi - - Referensı(2) - - Référence(2) - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef("Global_Objects", "String")}}
- -

Ringkasan

- -

Objek global String adalah sebuah pembangun untuk string, atau sebuah rangkaian dari karakter.

- -

Sintak

- -

String secara harfiah berbentuk:

- -
'string text'
-"string text"
-"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
-
- -

Sejak ECMAScript 6 String secara harfiah dapat juga menjadi Template Strings:

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -

Selain karakter biasa yang dapat dicetak, karakter spesial dapat disandikan dengan notasi lepas:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KodeKeluaran
\0karakter NUL
\'petik satu
\"petik dua
\\garis miring
\nbaris baru
\rcarriage return
\vtab vertikal
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXkarakter Latin-1
- -

Atau, menggunakan objek global String langsung:

- -
String(benda)
-new String(benda)
-
- -

Parameter

- -
-
benda
-
Apapun yang akan diubah ke string.
-
- -

Deskripsi

- -

String berguna untuk membawa data yang dapat diitampilkan dalam bentuk teks. Beberapa operasi yang paling sering digunakan dalam string adalah untuk memeriksa {{jsxref("String.length", "panjangnya")}}, untuk membuat dan menggabungkannya dengan operator string + dan +=, mengecek adanya atau lokasi dari substring dengan metode {{jsxref("String.prototype.indexOf()", "indexOf()")}}, atau mendapatkan substring dengan metode {{jsxref("String.prototype.substring()", "substring()")}}.

- -

Akses karakter

- -

Ada dua cara untuk mengakses sebuah karakter dalam string. Cara yang pertama adalah metode {{jsxref("String.prototype.charAt()", "charAt()")}}:

- -
return 'cat'.charAt(1); // mengembalikan "a"
-
- -

Cara yang lain (diperkenalkan dalam ECMAScript 5) adalah menganggap string sebagai objek mirip-susunan, di mana setiap karakter disesuaikan dengan indeks angka:

- -
return 'cat'[1]; // mengembalikan "a"
-
- -

Untuk akses karakter dengan menggunakan notasi kurung, mencoba untuk menghapus atau menetapkan nilai ke propertinya tidak akan berhasil. Properti yang terlibat tidak dapat ditulis maupun diubah. (Lihat {{jsxref("Object.defineProperty()")}} untuk informasi lebih.)

- -

Membandingkan string

- -

Pengembang C mempunyai fungsi strcmp() untuk membandingkan string. Dalam JavaScript, Anda cukup menggunakan operas kurang dari dan lebih dari:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // benar
-  print(a + ' kurang dari ' + b);
-} else if (a > b) {
-  print(a + ' lebih dari ' + b);
-} else {
-  print(a + ' sama dengan ' + b);
-}
-
- -

Hasil yang serupa dapat didapatkan dengan metode {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} yang diwariskan oleh benda String.

- -

Perbedaan antara string primitif dan objek String

- -

Ingat bahwa JavaScript membedakan nilai antara objek String dan string primitif. (Serupa dengan {{jsxref("Global_Objects/Boolean", "Boolean")}} dan {{jsxref("Global_Objects/Number", "Angka")}}.)

- -

String yang harfiah (ditandai dengan petik satu atau dua) dan string yang dikembalikan dari panggilan String dalam sebuah konteks non-pembangun (misal, tanpa menggunakan kata kunci {{jsxref("Operators/new", "new")}}) adalah string primitif. JavaScript secara otomatis mengubah primitif ke objek String, jadi mungkin untuk menggunakan metode objek String untuk string primitif. Dalam konteks di mana sebuah metode dipanggil pada string primitif atau sebuah pembacaan properti terjadi, JavaScript akan secara otomatis membungkus string primitif dan memanggil metode tersebut atau melakukan pembacaan properti.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // "string"
-console.log(typeof s_obj);  // "object"
-
- -

String primitif dan objek String juga memberikan hasil berbeda saat menggunakan {{jsxref("Global_Objects/eval", "eval()")}}. Primitif melewati eval sebagai kode sumber; Objek String dianggap semua objek lain, dengan mengembalikan objek tersebut. Sebagai contoh:

- -
var s1 = '2 + 2';             // membuat sebuah string primitif
-var s2 = new String('2 + 2'); // membuat sebuah objek String
-console.log(eval(s1));        // mengembalikan angka 4
-console.log(eval(s2));        // mengembalikan string "2 + 2"
-
- -

Untuk itu, kode mungkin berhenti saat menemui objek String saat mengharapkan string primitif, meskipun secara umum pembuat tidak perlu khawatir tentang perbedaannya.

- -

Sebuah objek String dapat selalu diubah menjadi kawan primitifnya dengan metode {{jsxref("String.prototype.valueOf()", "valueOf()")}}.

- -
console.log(eval(s2.valueOf())); // mengembalikan angka 4
-
- -
Catatan: Untuk kemungkinan lain ke string dalam JavaScript, mohon baca artikel tentang StringView — a C-like representation of strings based on typed arrays (bahasa Inggris).
- -

Properti

- -
-
{{jsxref("String.prototype")}}
-
Membolehkan penambahan properti ke sebuahobjek String.
-
- -
{{jsOverrides("Function", "Properties", "prototype")}}
- -

Metode

- -
-
{{jsxref("String.fromCharCode()")}}
-
Mengembalikan sebuah string yang dibuat dengan menggunakan nilai urutan Unicode.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Mengembalikan sebuah string dibuat dengan menggunakan urutan code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Mengembalikan sebuah string yang dibuat dari sebuah templat string mentah.
-
- -
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint", "raw")}}
- -

Metode umum String

- -

Metode benda String juga terdapat dalam Firefox sejak JavaScript 1.6 (meskipun bukan bagian dari standar ECMAScript) salam objek String untuk menerapkan metode String ke objek lain:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

{{jsxref("Global_Objects/Array", "Metode umum", "#Metode_umum_Array", 1)}} juga terdapat dalam metode {{jsxref("Global_Objects/Array", "Array")}}.

- -

Berikut ini sebuah pengisi untuk memberikan dukungan ke peramban yang tidak mendukung:

- -
/*globals define*/
-// Menganggap semua metode String telah ada
-(function() {
-  'use strict';
-
-  var i,
-    methods = [
-      'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
-      'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
-      'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
-      'toLocaleUpperCase', 'localeCompare', 'match', 'search',
-      'replace', 'split', 'substr', 'concat', 'slice'
-    ],
-    methodCount = methods.length,
-    assignStringGeneric = function(methodName) {
-      var method = String.prototype[methodName];
-      String[methodName] = function(arg1) {
-        return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
-      };
-    };
-
-  for (i = 0; i < methodCount; i++) {
-    assignStringGeneric(methods[i]);
-  }
-}());
-
- -

Benda String

- -

Properti

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properti')}}
- -

Metode

- -

Metode yang tidak terkait dengan HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_yang_tidak_terkait_dengan_HTML')}}
- -

Metode pembungkus HTML

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Metode_pembungkus_HTML')}}
- -

Contoh

- -

Contoh: Pengubahan String

- -

Ini mungkin untuk menggunakan String sebagai alternatif "lebih aman" dari {{jsxref("String.prototype.toString()", "toString()")}}, meskipun masih dapat secara normal memanggil toString(), ini juga bekerja untuk {{jsxref("Global_Objects/null", "null")}} dan {{jsxref("Global_Objects/undefined", "undefined")}}. Sebagai contoh:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
ECMAScript 1st Edition.StandardDefinisi pertama.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
- -

Kompatibilitas peramban

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome("0.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatGeckoDesktop("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("40")}}{{CompatUnknown()}}{{CompatUnknown()}}{{CompatUnknown()}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/indexof/index.html b/files/id/web/javascript/reference/global_objects/string/indexof/index.html deleted file mode 100644 index 3b7f7d0965..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/indexof/index.html +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: String.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/String/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf ---- -
{{JSRef}}
- -

indexOf() method mengembalikan sebuah index saat memanggil objek  {{jsxref("String")}} pertama kali dengan value yang di tentukan, bermula dari pencarian pada fromIndex. Dan pencarian ini akan mengembalikan index dari karakter pada String,  dan akan mengembalikan -1 ketika pencarian indexOf ini tak menemukan karakter yang cocok/ value yang sesuai.

- -

Syntax

- -
str.indexOf(searchValue[, fromIndex])
- -

Parameters

- -
-
searchValue
-
Sebuah string yang me-representasikan dari nilai yang ingin di cari.
-
fromIndex {{optional_inline}}
-
Index bermulai dari awal hingga bergerak ke depan sepanjang string. Index bisa berupa bilangan bulat atau apa pun. Nilai standarnya adalah 0, jadi seluruh index dari array akan dicari. Jika fromIndex < 0 seluruh string dicari. Jika fromIndex >= str.length, string tidak dicari dan -1 sebagai kembaliannya. Kecuali kalau searchValue adalah string kosong, maka str.length sebagai kembaliannya.
-
- -

Deskripsi

- -

Karakter dalam sebuah string di indeks berurutan dari kiri ke kanan. Index pada karakter pertama yaitu 0, dan index pada karakter terakhir dalam sebuah String di sebut stringName is stringName.length - 1.

- -
'Blue Whale'.indexOf('Blue');     // mengembalikan  0
-'Blue Whale'.indexOf('Blute');    // mengembalikan -1
-'Blue Whale'.indexOf('Whale', 0); // mengembalikan  5
-'Blue Whale'.indexOf('Whale', 5); // mengembalikan  5
-'Blue Whale'.indexOf('', 9);      // mengembalikan  9
-'Blue Whale'.indexOf('', 10);     // mengembalikan 10
-'Blue Whale'.indexOf('', 11);     // mengembalikan 10
-
- -

Case-sensitivity

- -

The indexOf() method sangat case sensitive. Sebagai contoh, expression berikut ini mengembalikan -1:

- -
'Blue Whale'.indexOf('blue'); // mengembalikan -1
-
- -

Checking occurrences/ Memeriksa suatu kejadian

- -

Catat bahwa  '0' tak bernilai true dan '-1' bukan bernilali false. Oleh karena-nya, ketika memeriksa apakah sebuah String  Therefore, when checking if a specific string exists within another string the correct way to check would be:

- -
'Blue Whale'.indexOf('Blue') !== -1; // true
-'Blue Whale'.indexOf('Bloe') !== -1; // false
-
- -

Examples

- -

Using indexOf() and lastIndexOf()

- -

The following example uses indexOf() and {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} to locate values in the string "Brave new world".

- -
var anyString = 'Brave new world';
-
-console.log('The index of the first w from the beginning is ' + anyString.indexOf('w'));
-// logs 8
-console.log('The index of the last w from the beginning is ' + anyString.lastIndexOf('w'));
-// logs 10
-
-console.log('The index of "new" from the beginning is ' + anyString.indexOf('new'));
-// logs 6
-console.log('The index of "new" from the end is ' + anyString.lastIndexOf('new'));
-// logs 6
-
- -

indexOf() and case-sensitivity

- -

The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first {{domxref("console.log()")}} method displays 19. But because the indexOf() method is case sensitive, the string "cheddar" is not found in myCapString, so the second console.log() method displays -1.

- -
var myString    = 'brie, pepper jack, cheddar';
-var myCapString = 'Brie, Pepper Jack, Cheddar';
-
-console.log('myString.indexOf("cheddar") is ' + myString.indexOf('cheddar'));
-// logs 19
-console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf('cheddar'));
-// logs -1
-
- -

Using indexOf() to count occurrences of a letter in a string

- -

The following example sets count to the number of occurrences of the letter e in the string str:

- -
var str = 'To be, or not to be, that is the question.';
-var count = 0;
-var pos = str.indexOf('e');
-
-while (pos !== -1) {
-  count++;
-  pos = str.indexOf('e', pos + 1);
-}
-
-console.log(count); // displays 4
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{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/id/web/javascript/reference/global_objects/string/length/index.html b/files/id/web/javascript/reference/global_objects/string/length/index.html deleted file mode 100644 index 6975d8b7d3..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: String.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -
{{JSRef}}
- -

Properti length mewakili panjang string.

- -

Syntax

- -
str.length
- -

Deskripsi

- -

Properti ini mengembalikan jumlah unit kode dalam string. {{interwiki("wikipedia", "UTF-16")}}, Format string yang digunakan oleh javascript, Menggunakan 16-bit unit kode tunggal untuk mewakili karakter yang paling umum, tapi perlu menggunakan dua unit kode untuk unit karakter tertentu, sehingga dapat terjadi kemungkinan nilai yang dikembalikan oleh ​​​length tidak sesuai dengan jumlah karakter pada string.

- -

Untuk string kosong, jumlahnya 0.

- -

Properti static String.length mengembalikan nilai 1.

- -

Contoh

- -

Penggunaan Dasar

- -
var x = 'Mozilla';
-var kosong = '';
-
-console.log('Mozilla memiliki ' + x.length + ' unit kode');
-/* "Mozilla memiliki 7 unit kode" */
-
-console.log('String kosong memiliki jumlah unit kode ' + kosong.length);
-/* "String kosong memiliki jumlah unit kode 0" */
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definisi Inisial. Diimplementasikan dalam JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/link/index.html b/files/id/web/javascript/reference/global_objects/string/link/index.html deleted file mode 100644 index 914eff9955..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/link/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: String.prototype.link() -slug: Web/JavaScript/Reference/Global_Objects/String/link -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/link ---- -
{{JSRef}}
- -

Method link() membuat sebuah string seperti halnya kode untuk sebuah elemen HTML {{HTMLElement("a")}} untuk digunakan sebagai link hypertext ke URL lain.

- -

Sintaks

- -
str.link(url)
- -

Parameters

- -
-
url
-
String yang menentukan atribut href dai tag <a>; harus merupakan URL yang valid (relative ataupun absolute), dengan setiap karakter & harus ditulis &amp;, dan setiap karakter " harus ditulis &quot;.
-
- -

Deskripsi

- -

Menggunakan method link() untuk membuat snippet HTML untuk sebuah link hypertext. Mengembalikan string  yang kemudian dapat di tambahkan ke dokumen html menggunakan {{domxref("document.write()")}} atau {{domxref("element.innerHTML")}}.

- -

Link yang dibuat menggunakan method link() akan menjadi elemen di array links dari sebuah objek document. Lihat juga {{domxref("document.links")}}.

- -

Contoh

- -

Penggunaan link()

- -

Pada contoh berikut menampilkan kata "MDN" sebagai sebuah link hypertext yang mengembalikan pengguna ke halaman Mozilla Developer Network.

- -
var hotText = 'MDN';
-var URL = 'https://developer.mozilla.org/';
-
-console.log('Klik untuk kembali ke ' + hotText.link(URL));
-// Klik untuk kembali ke <a href="https://developer.mozilla.org/">MDN</a>
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ES6')}}Initial definition. Implemented in JavaScript 1.0. Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
{{SpecName('ESDraft', '#sec-string.prototype.link', 'String.prototype.link')}}{{Spec2('ESDraft')}}Defined in the (normative) Annex B for Additional ECMAScript Features for Web Browsers.
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Catatan Gecko-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/split/index.html b/files/id/web/javascript/reference/global_objects/string/split/index.html deleted file mode 100644 index 21f19d353f..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/split/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: String.prototype.split() -slug: Web/JavaScript/Reference/Global_Objects/String/split -tags: - - JavaScript - - Method - - Prototype - - Reference - - Regular Expressions - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/split ---- -
{{JSRef}}
- -

Method split() membagi sebuah objek {{jsxref("String")}} ke sebuah array string dengan memisahkannya menjadi substring.

- -

Sintaks

- -
str.split([separator[, limit]])
- -

Parameter

- -
-
separator
-
Opsional. Menentukan karakter yang digunakan untuk memisahkan string. separator dapat berupa string atau sebuah {{jsxref("Global_Objects/RegExp", "regular expression", "", 1)}}. Jika separator dihilangkan / tidak digunakan, array yang dikembalikan akan terdiri dari satu elemen yang berisi seluruh string. Jika separator dikosongkan atau empty string, str akan dikonversikan sebagai sebuah array dari karakter.
-
limit
-
-

Opsional. Nilai integer yang digunakan untuk menentukan jumlah batas yang dapat ditemukan. Method split() tetap membagi pada setiap kecocokan pada separator, sampai jumlah pembagi item sama dengan limit atau string jatuh lebih pendek dari separator.

-
-
- -

Deskripsi

- -

Method split() mengembalikan array baru.

- -

Saat ditemukan, separator akan dihapus dari string dan substrings akan di kembalikan ke dalam array. Jika separator tidak ditemukan atau di hilangkan, array terdiri satu elemen array yang terdiri dari keseluruhan string. Jika separator merupakan empty string, str dikonversi menjadi sebuah array karakter.

- -

Jika separator adalah ekspesi reguler yang terdapat tanda kurung , maka setiap kali separator cocok, hasilnya (termasuk hasil yang tidak didefinisikan) dari penangkap tanda kurung akan di sambungkan ke dalam output array. Namun, tidak semua browser mendukung kemampuan ini.

- -

{{Note("Ketika string kosong, method split() mengembalikan array berisi satu string kosong, dari pada array kosong. Jika string dan separator keduanya string kosong, array kosong akan dikembalikan.")}}

- -

Contoh

- -

Penggunaan split()

- -

Contoh berikut menjelaskan fungsi yang membagi string ke dalam sebuah array string menggunakan separator tertentu. Setelah memisahkan string , fungsi menampilkan pesan yang menunjukan string asli (sebelum dibagi), separator yang digunakan, jumlah elemen pada array, dan elemen array secara individual.

- -
function splitString(stringToSplit, separator) {
-  var arrayOfStrings = stringToSplit.split(separator);
-
-  console.log('The original string is: "' + stringToSplit + '"');
-  console.log('The separator is: "' + separator + '"');
-  console.log('The array has ' + arrayOfStrings.length + ' elements: ' + arrayOfStrings.join(' / '));
-}
-
-var tempestString = 'Oh brave new world that has such people in it.';
-var monthString = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec';
-
-var space = ' ';
-var comma = ',';
-
-splitString(tempestString, space);
-splitString(tempestString);
-splitString(monthString, comma);
-
- -

Contoh ini menghasilkan output berikut:

- -
The original string is: "Oh brave new world that has such people in it."
-The separator is: " "
-The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it.
-
-The original string is: "Oh brave new world that has such people in it."
-The separator is: "undefined"
-The array has 1 elements: Oh brave new world that has such people in it.
-
-The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
-The separator is: ","
-The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec
-
- -

Menghapus spasi dari string

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi diikuti semikolon, dan di ikuti 0 atau lebih spasi dan, saat ditemukan, menghapus spasi dari string. nameList merupakan array yang dikembalikan dari hasil split().

- -
var names = 'Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ';
-
-console.log(names);
-
-var re = /\s*;\s*/;
-var nameList = names.split(re);
-
-console.log(nameList);
-
- -

Dua baris log ini; log baris pertama string asli, dan log baris kedua array yang dihasilkan.

- -
Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
-[ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand " ]
-
- -

Mengembalikan batas jumlah pembagi

- -

Pada contoh berikut, split() mencari 0 atau lebih spasi didalam string dan mengembalikan 3 pembagian pertama yang ditemukan.

- -
var myString = 'Hello World. How are you doing?';
-var splits = myString.split(' ', 3);
-
-console.log(splits);
-
- -

Script ini akan menampilkan seperti berikut:

- -
Hello,World.,How
-
- -

Tanda kurung

- -

Jika separator terdapat tanda kurung, hasil yang cocok akan dikembalikan ke dalam array.

- -
var myString = 'Hello 1 word. Sentence number 2.';
-var splits = myString.split(/(\d)/);
-
-console.log(splits);
-
- -

Script tersebut menampilkan seperti berikut:

- -
[ 'Hello ', '1', ' word. Sentence number ', '2', '.' ]
-
- -

Membalikkan String menggunakan split()

- -
var str = 'asdfghjkl';
-var strReverse = str.split('').reverse().join(''); // 'lkjhgfdsa'
-// split() returns an array on which reverse() and join() can be applied
-
- -

Bonus: Gunakan operator {{jsxref("Operators/Comparison_Operators", "===", "#Identity_strict_equality_(===)")}} untuk mengetahui apakah string asli adalah palindrome.

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.14', 'String.prototype.split')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.split', 'String.prototype.split')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
- - - - - - - -
Dukungan dasar 
-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html deleted file mode 100644 index 69fdfd1bec..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tolowercase/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.toLowerCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase ---- -
{{JSRef}}
- -

Method toLowerCase() mengembalikan nilai string yang dipanggil yang telah dikonversi ke lowercase (huruf kecil).

- -

Sintaks

- -
str.toLowerCase()
- -

Deskripsi

- -

Method toLowerCase() mengembaikan nilai dari string yang telah dikonversi ke lowercase. toLowerCase() tidak berdampak pada nilai string pada variabel str itu sendiri.

- -

Contoh

- -

Penggunaan toLowerCase()

- -
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/tostring/index.html b/files/id/web/javascript/reference/global_objects/string/tostring/index.html deleted file mode 100644 index dba9c9f792..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/tostring/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/String/toString -translation_of: Web/JavaScript/Reference/Global_Objects/String/toString ---- -
{{JSRef}}
- -

Method toString() mengembalikan sebuah string berdasarkan objek spesifik.

- -

Sintaks

- -
str.toString()
- -

Deskripsi

- -

Objek {{jsxref("String")}} akan menimpa method toString() dari objek {{jsxref("Object")}}; bukan turunan {{jsxref("Object.prototype.toString()")}}. Untuk objek {{jsxref("String")}}, method toString() mengembalikan sebuah string berdasarkan objek dan seperti halnya pada method {{jsxref("String.prototype.valueOf()")}}.

- -

Contoh

- -

Penggunaan toString()

- -

Pada contoh menampilkan nilai string dari sebuah objek {{jsxref("String")}}:

- -
var x = new String('Halo Dunia');
-
-console.log(x.toString()); // logs 'Halo Dunia'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.5.4.2', 'String.prototype.toString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.tostring', 'String.prototype.toString')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html b/files/id/web/javascript/reference/global_objects/string/touppercase/index.html deleted file mode 100644 index bf8182a590..0000000000 --- a/files/id/web/javascript/reference/global_objects/string/touppercase/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: String.prototype.toUpperCase() -slug: Web/JavaScript/Reference/Global_Objects/String/toUpperCase -translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase ---- -
{{JSRef}}
- -

Method toUpperCase() mengembalikan nilai string pemanggil dikonversi ke huruf besar.

- -

Sintaks

- -
str.toUpperCase()
- -

Deskripsi

- -

Method toUpperCase() mengembalikan nilai string diconversikan ke huruf besar. toUpperCase() tidak mempengaruhi nilai string itu sendiri.

- -

Contoh

- -

Penggunaan toUpperCase()

- -
console.log('alphabet'.toUpperCase()); // 'ALPHABET'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.18', 'String.prototype.toUpperCase')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.touppercase', 'String.prototype.toUpperCase')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas browser

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

Lihat Pula

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/index.html b/files/id/web/javascript/reference/global_objects/typedarray/index.html deleted file mode 100644 index e0b8d942c1..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/index.html +++ /dev/null @@ -1,344 +0,0 @@ ---- -title: TypedArray -slug: Web/JavaScript/Reference/Global_Objects/TypedArray -tags: - - JavaScript - - NeedsTranslation - - TopicStub - - TypedArray - - TypedArrays -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray ---- -
{{JSRef}}
- -

A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray, nor is there a directly visible TypedArray constructor.  Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type.

- -

Syntax

- -
new TypedArray(length);
-new TypedArray(typedArray);
-new TypedArray(object);
-new TypedArray(buffer [, byteOffset [, length]]);
-
-where TypedArray() is one of:
-
-Int8Array();
-Uint8Array();
-Uint8ClampedArray();
-Int16Array();
-Uint16Array();
-Int32Array();
-Uint32Array();
-Float32Array();
-Float64Array();
-
- -

Parameters

- -
-
length
-
When called with a length argument, a typed array containing length zeroes is created.
-
typedArray
-
When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.
-
object
-
When called with an object argument, a new typed array is created as if by the TypedArray.from() method.
-
buffer, byteOffset, length
-
When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view.  If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.
-
- -

Description

- -

ECMAScript 6 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors.  This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property.  It is only directly accessible through Object.getPrototypeOf(Int8Array.prototype) and similar.  All TypedArrays constructors inherit common properties from the %TypedArray% constructor function.  Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

- -

The %TypedArray% constructor on its own is not particularly useful.  Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing.  There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

- -

Property access

- -

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.

- -
// Setting and getting using standard array syntax
-var int16 = new Int16Array(2);
-int16[0] = 42;
-console.log(int16[0]); // 42
-
-// Indexed properties on prototypes are not consulted (Fx 25)
-Int8Array.prototype[20] = "foo";
-(new Int8Array(32))[20]; // 0
-// even when out of bound
-Int8Array.prototype[20] = "foo";
-(new Int8Array(8))[20]; // undefined
-// or with negative integers
-Int8Array.prototype[-1] = "foo";
-(new Int8Array(8))[-1]; // undefined
-
-// Named properties are allowed, though (Fx 30)
-Int8Array.prototype.foo = "bar";
-(new Int8Array(32)).foo; // "bar"
- -

TypedArray objects

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}18-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}18-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}18-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}432-bit IEEE floating point numberunrestricted floatfloat
{{jsxref("Float64Array")}}864-bit IEEE floating point numberunrestricted doubledouble
- -

Properties

- -
-
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
-
Returns a number value of the element size for the different typed array objects.
-
TypedArray.length
-
Length property whose value is 3.
-
{{jsxref("TypedArray.name")}}
-
Returns the string value of the constructor name. E.g "Int8Array".
-
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("TypedArray.prototype")}}
-
Prototype for the TypedArray objects.
-
- -

Methods

- -
-
{{jsxref("TypedArray.from()")}}
-
Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
-
{{jsxref("TypedArray.of()")}}
-
Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
-
- -

TypedArray prototype

- -

All TypedArrays inherit from {{jsxref("TypedArray.prototype")}}.

- -

Properties

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Properties')}}

- -

Methods

- -

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Methods')}}

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Defined as TypedArray and ArrayBufferView interface with typed array view types. Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that new is required.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatGeckoDesktop("2")}}1011.65.1
Indexed properties not consulting prototype{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Named properties{{CompatVersionUnknown}}{{CompatGeckoDesktop("30")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support4.0{{CompatVersionUnknown}}{{ CompatGeckoMobile("2") }}1011.64.2{{CompatVersionUnknown}}
Indexed properties not consulting prototype{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{ CompatGeckoMobile("25") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} [1]
Named properties{{CompatUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("30") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
new is required{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("44") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] -1 and similar are not considered as indexed properties and therefore return the value of the prototype property.

- -

Compatibility notes

- -

Starting with ECMAScript 2015 (ES6), TypedArray constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a TypedArray constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

- -
var dv = Int8Array([1, 2, 3]);
-// TypeError: calling a builtin Int8Array constructor
-// without new is forbidden
- -
var dv = new Int8Array([1, 2, 3]);
- -

See also

- - diff --git a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html b/files/id/web/javascript/reference/global_objects/typedarray/join/index.html deleted file mode 100644 index 84f328ae1b..0000000000 --- a/files/id/web/javascript/reference/global_objects/typedarray/join/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: TypedArray.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/TypedArray/join -tags: - - ECMAScript6 - - JavaScript - - Method - - Prototype - - TypedArray -translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/join ---- -
{{JSRef}}
- -

Method join() menggabungkan semua elemen dari array menjadi sebuah string. Alogaritma method ini memiliki kesamaan dengan {{jsxref("Array.prototype.join()")}}. TypedArray di sini merupakan salah datu typed array types.

- -

Sintaks

- -
typedarray.join([separator = ',']);
- -

Parameter

- -
-
separator
-
Opsional. Menentukan sebuah string untuk memisahkan setiap elemen. Separator perlu di konversi ke string jika dianggap penting. Jika dikosongkan, elemen array akan dipisahkan dengan tanda koma (",").
-
- -

Contoh

- -
var uint8 = new Uint8Array([1,2,3]);
-uint8.join();      // '1,2,3'
-uint8.join(' / '); // '1 / 2 / 3'
-uint8.join('');    // '123'
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-%typedarray%.prototype.join', 'TypedArray.prototype.join')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("37")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/index.html b/files/id/web/javascript/reference/index.html deleted file mode 100644 index 261b76a5b5..0000000000 --- a/files/id/web/javascript/reference/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Referensi JavaScript -slug: Web/JavaScript/Reference -tags: - - JavaScript -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

Laman ini merupakan bagian dari sesi JavaScript pada MDN yang berfungsi sebagai acuan mengenai bahasa pemrograman JavaScript. Pelajari lebih lanjut perihal acuan ini.

- -

Objek Global

- -

Bagian ini mendokumentasikan semua object standar built-in JavaScript, beserta method dan propertinya.

- -
{{page('/id/docs/Web/JavaScript/Reference/Global_Objects', 'Standard_objects_by_category')}}
- -

Pernyataan

- -

Bagian ini mendekumentasikan semua pernyataan dan deklarasi  JavaScript.

- -
{{page('/id/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Ungkapan dan operator

- -

Bagian ini mendokumentasikan semua ungkapan dan operator JavaScript .

- -
{{page('/id/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Fungsi

- -

Bagian ini mendokumentasikan tentang Fungsi JavaScrip dan penggunaanya untuk pengembangan aplikasi anda.

- - - -

Acuan tambahan

- - diff --git a/files/id/web/javascript/reference/lexical_grammar/index.html b/files/id/web/javascript/reference/lexical_grammar/index.html deleted file mode 100644 index 83e5696ccd..0000000000 --- a/files/id/web/javascript/reference/lexical_grammar/index.html +++ /dev/null @@ -1,670 +0,0 @@ ---- -title: Lexical grammar -slug: Web/JavaScript/Reference/Lexical_grammar -translation_of: Web/JavaScript/Reference/Lexical_grammar ---- -
{{JsSidebar("More")}}
- -

Halaman ini menjelaskan tata bahasa leksikal JavaScript. Teks sumber skrip JavaScript dipindai dari kiri ke kanan dan diubah menjadi urutan elemen masukan yang merupakan token, karakter kontrol, terminator baris, komentar atau whitespace. ECMAScript juga mendefinisikan kata kunci dan literal tertentu dan memiliki aturan untuk penyisipan titik koma secara otomatis untuk mengakhiri pernyataan.

- -

Karakter-karakter kontrol

- -

Karakter kontrol tidak memiliki representasi visual namun digunakan untuk mengendalikan interpretasi teks.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter kontrol format unicode
KodeNamaSingkatanDeskripsi
U+200CZero width non-joiner<ZWNJ>Ditempatkan di antara karakter untuk mencegah terhubung ke ligatur dalam bahasa tertentu (Wikipedia).
U+200DZero width joiner<ZWJ>Ditempatkan di antara karakter yang biasanya tidak terhubung agar karakter dapat dirender menggunakan bentuknya yang terhubung dalam bahasa tertentu. (Wikipedia).
U+FEFFByte order mark<BOM>Digunakan pada awal skrip untuk menandainya sebagai Unicode dan urutan byte teks (Wikipedia).
- -

White space

- -

Karakter whitespace meningkatkan keterbacaan teks sumber dan memisahkan token-token. Karakter ini biasanya tidak diperlukan untuk fungsionalitas kode. Alat minifikasi sering digunakan untuk membuang whitespace agar mengurangi jumlah data yang perlu ditransfer.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter whitespace
KodeNamaSingkatanDeskripsi -

Rangkaian pelolosan/Escape

-
U+0009Tabulasi karakter<HT>Tabulasi horisontal\t
U+000BTabulasi baris<VT>Tabulasi vertikal\v
U+000CForm feed<FF>Karakter kontrol pemecah halaman (Wikipedia).\f
U+0020Space<SP>Spasi normal 
U+00A0No-break space<NBSP>Spasi normal, tetapi tidak ada petunjuk dimana baris terputus. 
OthersOther Unicode space characters<USP>Spasi di Unicode on Wikipedia 
- -

Terminator baris

- -

Selain karakter whitespace, karakter terminator baris digunakan untuk meningkatkan keterbacaan teks sumber. Namun, dalam beberapa kasus, terminator baris dapat mempengaruhi eksekusi kode JavaScript karena ada beberapa tempat di mana mereka dilarang. Terminator baris juga mempengaruhi proses penyisipan titik koma otomatis. Terminator baris dicocokkan dengan kelas \s dalam regular expressions.

- -

Hanya kode Unicode berikut yang diperlakukan sebagai terminator baris di ECMAScript, karakter pemecah baris lainnya diperlakukan sebagai whitespace (misalnya, Next Line, NEL, U+0085 dianggap sebagai whitespace).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Karakter-karakter terminator baris
KodeNamaSingkatanDeskripsiRangkaian pelolosan/escape 
U+000ALine Feed<LF>Karakter baris baru di sistem UNIX.\n
U+000DCarriage Return<CR>Karakter baris baru di Commodore dan sistem Mac awal.\r
U+2028Line Separator<LS>Wikipedia 
U+2029Paragraph Separator<PS>Wikipedia 
- -

Komentar

- -

Komentar digunakan untuk menambahkan petunjuk, catatan, saran, atau peringatan ke kode JavaScript. Hal ini dapat mempermudah membaca dan memahami. Mereka juga dapat digunakan untuk menonaktifkan kode agar tidak dieksekusi; Ini juga dapat menjadi alat debugging yang berharga.

- -

JavaScript memiliki dua cara untuk memberi komentar pada kodenya.

- -

Cara pertama adalah komentar //; Ini membuat semua teks yang mengikutinya pada baris yang sama menjadi sebuah komentar. Sebagai contoh:

- -
function komentar() {
-  // Ini adalah komentar JavaScript satu baris
-  console.log('Hello world!');
-}
-komentar();
-
- -

Cara kedua adalah komentar gaya  /* */ , yang jauh lebih fleksibel.

- -

Misalnya, Anda bisa menggunakannya dalam satu baris:

- -
function komentar() {
-  /* Ini adalah komentar JavaScript satu baris */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa membuat komentar beberapa baris, seperti ini:

- -
function komentar() {
-  /* Komentar ini merentang dalam beberapa baris. Perhatikan
-     bahwa kita tidak perlu mengakhir komentar sebelum selesai. */
-  console.log('Hello world!');
-}
-komentar();
- -

Anda juga bisa menggunakannya di tengah baris, jika Anda mau, meskipun ini bisa membuat kode Anda lebih sulit dibaca sehingga harus digunakan dengan hati-hati:

- -
function komentar(x) {
-  console.log('Hello ' + x /* menysipkan nilai dari x */ + ' !');
-}
-comment('world');
- -

Selain itu, Anda bisa menggunakannya untuk menonaktifkan kode agar tidak berjalan, dengan membungkus kode dalam komentar, seperti ini:

- -
function comment() {
-  /* console.log('Hello world!'); */
-}
-comment();
- -

Dalam hal ini, pemaggilan console.log() tidak pernah dikeluarkan, karena itu ada di dalam komentar. Sejumlah baris kode dapat dinonaktifkan dengan cara ini.

- -

Kata kunci

- -

Reserved keywords as of ECMAScript 2015

- - - -

Kata kunci akan datang yang dicadangkan

- -

Berikut ini disediakan sebagai kata kunci akan datang menurut spesifikasi ECMAScript. Mereka tidak memiliki fungsi khusus saat ini, namun mungkin pada beberapa waktu mendatang, sehingga tidak dapat digunakan sebagai pengidentifikasi.

- -

Selalu dicadangkan:

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode mode strict "ketat":

- - - -

Berikut ini hanya dicadangkan saat ditemukan dalam kode modul:

- - - -

Kata kunci standart lama yang masih dingunakan hingga sekarang

- -

Berikut adalah dicadankan sebagai kata kunci akan datang pada spesifikasi ECMAScript usang (ECMAScript 1 s/d 3).

- - - -

Selain itu literal-literal null, true, dan false tidak dapat digunakan sebagai pengidentifikasi didalam ECMAScript.

- -

Penggunaan kata dicadangkan

- -

Kata yang dicadangkan sebenarnya hanya berlaku untuk pengidentifikasi (vs. IdentifierNames ). Seperti yang dijelaskan di es5.github.com/#A.1, ini semua adalah IdentifierNames yang tidak mengecualikan ReservedWords .

- -
a.import
-a['import']
-a = { import: 'test' }.
-
- -

Di sisi lain, hal-hal berikut ini ilegal karena ini adalah pengidentifikasi, yaitu IdentifierName tanpa kata-kata yang dicadangkan. Pengidentifikasi digunakan untuk FunctionDeclaration dan FunctionExpression.

- -
function import() {} // Illegal.
- -

Literal

- -

Literal null

- -

Lihat juga null untuk informasi lebih lanjut.

- -
null
- -

Literal Boolean

- -

Lihat juga Boolean untuk informasi lebih lanjut.

- -
true
-false
- -

Literal numerik

- -

Decimal

- -
1234567890
-42
-
-// Waspada saat mengunakan nol dimuka:
-0888 // 888 diuraikan sebagai desimal
-0777 // diuraikan sebagai oktal, 511 dalam desimal
-
- -

Perhatikan bahwa literal desimal dapat dimulai dengan angka nol ( 0 ) diikuti oleh digit desimal lainnya, namun jika semua digit setelah angka 0 teratas lebih kecil dari 8, angka tersebut diartikan sebagai angka oktal. Ini tidak akan melempar JavaScript, lihat {{bug(957513)}}. Lihat juga halaman tentang parseInt().

- -

Biner

- -

Sintaksis bilangan biner menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "B" ( 0b atau 0B ). Karena sintaksis ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0b tidak 0 atau 1, SyntaxError berikut dilempar: "Missing binary digits after 0b".

- -
var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
-var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
-var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
- -

Oktal

- -

Sintaksis bilangan oktal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "O" ( 0o atau 0O). Karena sintaks ini baru di ECMAScript 2015, lihat tabel kompatibilitas browser, di bawah ini. Jika digit setelah 0o berada di luar kisaran (01234567), SyntaxError berikut dilempar: "Missing octal digits after 0o".

- -
var n = 0O755; // 493
-var m = 0o644; // 420
-
-// Juga dimungkinkan hanya menggunakan nol dimuka (lihat tentang desimal diatas)
-0755
-0644
-
- -

Heksadesimal

- -

Sintaksis bilangan heksadesimal menggunakan nol dimuka diikuti huruf kecil atau huruf besar Latin "X" ( 0x atau 0X). Jika digit setelah 0x berada di luar rentang (0123456789ABCDEF), SyntaxError berikut dilempar: "Identifier starts immediately after numeric literal".

- -
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
-0x123456789ABCDEF   // 81985529216486900
-0XA                 // 10
-
- -

Literal objek

- -

Lihat juga Objek and Penginisialisasi objek untuk informasi lebih lanjut.

- -
var o = { a: 'foo', b: 'bar', c: 42 };
-
-// notasi singkat. baru di ES2015
-var a = 'foo', b = 'bar', c = 42;
-var o = {a, b, c};
-
-// bukannya
-var o = { a: a, b: b, c: c };
-
- -

Literal array

- -

Lihat juga Array untuk informasi lebih lanjut.

- -
[1954, 1974, 1990, 2014]
- -

Literal string

- -
'foo'
-"bar"
- -

Rangkaian pelolosan/escape heksadesimal

- -
'\xA9' // "©"
-
- -

Rangkaian pelolosan/escape Unicode

- -

Rangkaian pelolosan Unicode memerlukan setidaknya empat karakter diawali \u.

- -
'\u00A9' // "©"
- -

Penerapan point kode Unicode

- -

Baru di ECMAScript 2015. Dengan pelolosan kode Unicode, tiap karakter dapat diloloskan menggunakan bilangan hexadesimal jadi dimungkinkan untuk menggunkan kode Unicode sampai 0x10FFFF. Dengan pelolosan Unicode sederhana terkadang lebih dibutuhkan untuk menulis bagian pengganti secara terpisah untuk mencapai tujuan yang sama.

- -

Lihat juga String.fromCodePoint() atau String.prototype.codePointAt().

- -
'\u{2F804}'
-
-// ekuivalen dengan pelolosan Unicode sederhana
-'\uD87E\uDC04'
- -

Literal regular expression

- -

Lihat juga RegExp untuk informasi lebih lanjut.

- -
/ab+c/g
-
-// Suatu literal "kosong" regular expression
-// diperlukan grup bukan penangkap
-// untuk menghindarkan ambiguitas denga komentar satu baris
-/(?:)/
- -

Literal template

- -

Lihat juga template strings untuk informasi lebih lanjut.

- -
`string text`
-
-`string text baris 1
- string text baris 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
- -

Penyisipan titik koma otomatis

- -

Beberapa pernyataan JavaScript harus diakhiri dengan titik koma an oleh karena itu dipengaruhi oleh penyisipan otomatis semicolon (ASI):

- - - -

Spesifikasi ECMAScript menyebutkan tiga aturan penyisipan titik koma.

- -

1.  Titik koma disisipkan sebelumnya, bila terminator baris or "}" diteramukan yang tidak diizinkan oleh tata bahasa.

- -
{ 1 2 } 3
-
-// di transformasikan ke ASI kedalam
-
-{ 1 2 ;} 3;
- -

2.  Titik koma disisipkan di bagian akhir, saat akhir aliran input token terdeteksi dan parser tidak dapat mengurai aliran input tunggal aliran sebagai program yang lengkap.

- -

Disini ++ tidak diperlakukan sebagai operator postfix yang menerapkan variabel b, karena terminator baris terjadi antara b dan ++.

- -
a = b
-++c
-
-// di transformasikan ke ASI kedalam
-
-a = b;
-++c;
-
- -

3. Titik koma disisipkan pada akhirnya, ketika sebuah pernyataan dengan produksi terbatas dalam tata bahasa diikuti oleh terminator baris. Pernyataan-pernyataan ini dengan aturan "tidak diperlukan terminator baris" adalah:

- - - -
return
-a + b
-
-// di transformasikan ke ASI kedalam
-
-return;
-a + b;
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2("ES1")}}Definisi awal.
{{SpecName('ES5.1', '#sec-7', 'Lexical Conventions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ES6')}} -

Ditambahkan: Literal Bilangan Biner dan Octal, pelolosan kode Unicode, Templates

-
{{SpecName('ESDraft', '#sec-ecmascript-language-lexical-grammar', 'Lexical Grammar')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatChrome(41)}}12{{CompatGeckoDesktop(25)}}{{CompatUnknown}}{{CompatOpera(28)}}{{CompatSafari(9)}}
Pelolosan kode Unicode (\u{}){{CompatChrome(44)}}12{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatOpera(31)}}{{CompatSafari(9)}}
Notasi singkat untuk literal objek{{CompatChrome(43)}}12{{CompatGeckoDesktop(33)}}{{CompatNo}}{{CompatChrome(30)}}{{CompatSafari(9)}}
Literal template{{CompatChrome(41)}}12{{CompatGeckoDesktop(34)}}{{CompatNo}}{{CompatOpera(28)}}{{CompatSafari(9)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Literal numerik biner dan oktal (0b dan 0o){{CompatUnknown}}41{{CompatGeckomobile(33)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Pelolosan kode Unicode (\u{}){{CompatUnknown}}{{CompatUnknown}}{{CompatGeckomobile(40)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Notasi singkat untuk literal objek{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(33)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Literal template{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(34)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Firefox-specific notes

- - - -

See also

- - diff --git a/files/id/web/javascript/reference/operators/conditional_operator/index.html b/files/id/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 1a64158acb..0000000000 --- a/files/id/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Operasional Kondisi (ternary) -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator ---- -
{{jsSidebar("Operators")}}
- -

Operasianal kondisional (ternary) adalah satu-satunya operator yang hanya membutuhkan tiga operator. Operator ini sering digunakan sebagai jalan pintas untuk `if` statement.

- -

Syntax

- -
condition ? expr1 : expr2 
- -

Parameters

- -
-
condition (atau conditions)
-
Sebuah ekspresi akan menguji apakah menghasilkan true atau false.
-
- -
-
expr1, expr2
-
Ekspresi yang akan dilakukan setelah kondisi terpenuhi.
-
- -

Description

- -

Jika condition menghasilkan true, maka operator ini akan menghasilkan/mengembalikan nilai dari expr1; dan jika sebaliknya, ini akan menghasilkan/mengembalikan nilai dari expr2. Sebagai contoh, untuk menampilkan pesan yang berbeda berdasarkan nilai dari variabel isMember, anda bisa menggunakan contoh kode berikut:

- -
var isMember = true;
-'The fee is ' + (isMember ? '$2.00' : '$10.00'); //$2.00
-
- -

Anda juga dapat mendefinisikan sebuah variabel secara langsung:

- -
var elvisLives = Math.PI > 4 ? 'Yep' : 'Nope';
- -

Anda juga bisa menggunakan operator ternary secara jamak (catatan: conditional operator adalah associative yang lebih baik):

- -
var firstCheck = false, secondCheck = false, access = firstCheck ? 'Access denied' : secondCheck ? 'Access denied' : 'Access granted';
-console.log(access); // logs "Access granted"
- -

Anda juga dapat menggunakan pengondisian jamak seperti pengondisian jamak pada statement IF pada umumnya:

- -
var condition1 = true,
-    condition2 = false,
-    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
-
-console.log(access); // logs "true false"
-
- -

 

- -

Note: The parentheses are not required, and do not affect the functionality. They are there to help visualize how the outcome is processed.

- -

You can also use ternary evaluations in free space in order to do different operations:

- -
var stop = false, age = 16;
-
-age > 18 ? location.assign('continue.html') : stop = true;
-
- -

You can also do more than one single operation per case, separating them with a comma, and enclosing them in parenthesis:

- -
var stop = false, age = 23;
-
-age > 18 ? (
-    alert('OK, you can go.'),
-    location.assign('continue.html')
-) : (
-    stop = true,
-    alert('Sorry, you are much too young!')
-);
-
- -

You can also do more than one operation during the assignation of a value. In this case, the last comma-separated value of the parenthesis will be the value to be assigned.

- -
var age = 16;
-
-var url = age > 18 ? (
-    alert('OK, you can go.'),
-    // alert returns "undefined", but it will be ignored because
-    // isn't the last comma-separated value of the parenthesis
-    'continue.html' // the value to be assigned if age > 18
-) : (
-    alert('You are much too young!'),
-    alert('Sorry :-('),
-    // etc. etc.
-    'stop.html' // the value to be assigned if !(age > 18)
-);
-
-location.assign(url); // "stop.html"
- -

Returning Ternary Statements

- -

The ternary operator lends itself well to function returns that would otherwise require an if/else statement.

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else { return value2 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1 : value2
-}
- -

A good way to spot that the ternary will be a suitable replacement for an if/else statement is when the return keyword is used multiple times and is the only expression inside of the if block.

- -

By breaking the ternary onto multiple lines and making use of extra whitespace, the ternary operator can be used to very cleanly replace a lengthy series of if/else statements. This provides a syntactically light way of expressing the same logic:

- -
var func1 = function( .. ) {
-  if (condition1) { return value1 }
-  else if (condition2) { return value2 }
-  else if (condition3) { return value3 }
-  else { return value4 }
-}
-
-var func2 = function( .. ) {
-  return condition1 ? value1
-       : condition2 ? value2
-       : condition3 ? value3
-       :              value4
-}
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.conditional")}}

- -

See also

- - diff --git a/files/id/web/javascript/reference/operators/function/index.html b/files/id/web/javascript/reference/operators/function/index.html deleted file mode 100644 index 7fa9564333..0000000000 --- a/files/id/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: ungkapan fungsi -slug: Web/JavaScript/Reference/Operators/function -tags: - - Fungsi - - JavaScript - - Operator - - Ungkapan Utama -translation_of: Web/JavaScript/Reference/Operators/function -original_slug: Web/JavaScript/Reference/Operators/fungsi ---- -
{{jsSidebar("Operators")}}
- -
Kata kunci fungsi digunakan untuk mendefinisikan fungsi dalam sebuah ungkapan.
- -
 
- -

Sintaksis

- -
function [nama]([param1[, param2[, ..., paramN]]]) {
-   pernyataan
-}
- -

Parameters

- -
-
nama
-
Bisa dihilangkan apabila fungsi merupaka fungsi anonim. Nama fungsi bersifat lokal, relatif terhadap tubuh fungsi.
-
paramN
-
Nama argumen yang akan diumpankan kepada fungsi.
-
pernyataan
-
Pernyataan yang menyusun tubuh fungsi.
-
- -

Deskripsi

- -

Sintaksis ungkapan fungsi nyaris sama apabila dibandingkan dengan sintaksis pernyataan fungsi(lihat pernyataan fungsi untuk lebih jelasnya). Perbedaan utama antara ungkapan fungsi dengan pernyataan fungsi ialah; ungkapan fungsi memperbolehkan nama fungsi untuk tidak digunakan/dihilangkan apabila ungkapan fungsi tersebut merupakan fungsi anonim. Ungkapan fungsi dapat digunakan sebagai IIFE (immediately Invoked Function Expression), sebuah fungsi yang otomatis dijalankan apabila didefinisikan. Untuk informasi lebih lanjut, lihat juga bab tentang fungsi.

- -

Contoh

- -

Dibawah ini merupakan contoh definisi sebuah fungsi tanpa nama yang kemudian ditugaskan kedalam variabel x:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

Ungkapan fungsi bernama (Named function expression)

- -

Apabila sebuah fungsi hendak dipanggil dari dalam tubuh fungsi itu sendiri, pergunakanlah ungkapan fungsi bernama. Nama fungsi bersifat lokal relatif terhadap tubuh fungsi. Manfaat penggunaan ungkapan fungsi bernama ialah menghindarkan penggunaan properti non-standar arguments.callee.

- -
var math = {
-  'factorial': function factorial(n) {
-    if (n <= 1)
-      return 1;
-    return n * factorial(n - 1);
-  }
-};
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Definisi awal. Diterapkan pada JavaScript 1.5.
- -

Kesesuaian Perambah (Browser)

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan Mendasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/operators/index.html b/files/id/web/javascript/reference/operators/index.html deleted file mode 100644 index ef3afeb763..0000000000 --- a/files/id/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,269 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

This chapter documents all the JavaScript language operators, expressions and keywords.

- -

Ekspresi and operator sesuai kategori

- -

Untuk daftar isi sesuai Alfabet, silahkan lihat sisi sebelah kiri artikel ini.

- -

Primary expressions

- -

Basic keywords and general expressions in JavaScript.

- -

Keyword-keyword dasar dan ekspersi-ekspresi umum di javascript

- -
-
{{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.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array literal syntax.
-
{{jsxref("Global_Objects/Object", "{}")}}
-
Object 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.

-
-
- -

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/id/web/javascript/reference/operators/yield/index.html b/files/id/web/javascript/reference/operators/yield/index.html deleted file mode 100644 index 366f2aaa38..0000000000 --- a/files/id/web/javascript/reference/operators/yield/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: yield -slug: Web/JavaScript/Reference/Operators/yield -translation_of: Web/JavaScript/Reference/Operators/yield ---- -
{{jsSidebar("Operators")}}
- -

Keyword yield digunakan untuk menghentikan sementara dan melanjutkan sebuah fungsi generator ({{jsxref("Statements/function*", "function*")}} atau legacy generator function).

- -

Sintak

- -
[rv] = yield [expression];
- -
-
expression
-
Mendefeniskan nilai yang akan dikembalikan melalui iterator protocol. Apabila diabaikan, maka undefined akan dikembalikan.
-
rv
-
-

Mengembalikan nilai opsional yang diberikan pada generator method next() untuk melanjutkan eksekusinya.

-
-
- -

Deskripsi

- -

Keyword yield menghentikan secara sementara eksekusi dari fungsi generator dan nilai setelah keyword yield dikembalikan pada pemanggil generator tersebut. yield bisa juga disebut sebagai versi generator dari keywordreturn.

- -

Keyword yield sebenarnya mengembalikan sebuah obyek IteratorResult dengan dua properti, value dan done. Propertivalue adalah hasi dari evaluasi ekspresi yield, dan done yang false, mengindikasikan bahwa fungsi generator tersebut belum selesai sepenuhnya.

- -

Sekali berhenti pada ekspresi yield , eksekusi dari code generator tersebut akan terus dihentikan sampai generator method next() dipanggil. Setiap kali method generator next() dipanggil, generator melanjutkan eksekusi dan berjalan hingga mencapai salah satu dari kondisi berikut ini :

- - - -

JIka sebuah nilai opsional diberikan pada generator method next(), nilai tersebut menjadi nilai yang dikembalikan oleh operasi yield dari generator pada saat itu.

- -

Di antara kode generator, operatoryield -nya, dan kemampuan untuk menentukan sebua nilai awal baru dengan memberikannya pada {{jsxref("Generator.prototype.next()")}}, generator menawarkan power dan kontrol yang luar biasa.

- -

Contoh

- -

Kode berikut merupakan deklarasi dari sebuah contoh fungsi generator.

- -
function* countAppleSales () {
-  var saleList = [3, 7, 5];
-  for (var i = 0; i < saleList.length; i++) {
-    yield saleList[i];
-  }
-}
- -

Setelah sebuah fungsi generator didefenisikan, maka fungsi tersebut dapat digunakan untuk menghasilkan sebuah iterator seperti berikut.

- -
var appleStore = countAppleSales(); // Generator { }
-console.log(appleStore.next()); // { value: 3, done: false }
-console.log(appleStore.next()); // { value: 7, done: false }
-console.log(appleStore.next()); // { value: 5, done: false }
-console.log(appleStore.next()); // { value: undefined, done: true }
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}}
- -

Kompatabilitas Browser

- - - -

{{Compat("javascript.operators.yield")}}

- -

Catatan Firefox-specific

- - - -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/class/index.html b/files/id/web/javascript/reference/statements/class/index.html deleted file mode 100644 index 6ca35e9c71..0000000000 --- a/files/id/web/javascript/reference/statements/class/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: class -slug: Web/JavaScript/Reference/Statements/class -tags: - - Classes - - Declaration - - ECMAScript6 - - Referensi -translation_of: Web/JavaScript/Reference/Statements/class ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi class digunakan untuk membuat class baru dengan nama menggunakan turunan berbasis prototype.

- -
-

Anda juga bisa mendefinisikan kelas menggunakan{{jsxref("Operators/class", "class expression", "", 1)}}.

-
- -

Sintaks

- -
class name [extends] {
-  // class body
-}
-
- -

Deskripsi

- -

Seperti halnya dengan ekspresi class,  pembentuk (body) class dari deklarasi class di jalankan pada strict mode.

- -

Deklarasi class bukanlah {{Glossary("Hoisting", "hoisted")}} (Tidak seperti function declarations).

- -

Contoh

- -

Dasar deklarasi class

- -

Pada contoh, hal pertama yang kita lakukan adalah mendefinisikan class dengan nama Polygon, kemudian membentangkannya ( extend ) untuk membuat class bernama Square. Perlu diperhatikan bahwa super(), digunakan pada constructor, hanya dapat digunakan di konstruktor dan harus dipanggil setelah keyword 'this' dapat digunakan.

- -
class Polygon {
-  constructor(height, width) {
-    this.name = 'Polygon';
-    this.height = height;
-    this.width = width;
-  }
-}
-
-class Square extends Polygon {
-  constructor(length) {
-    super(length, length);
-    this.name = 'Square';
-  }
-}
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Array subclassing{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}    
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FiturAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Dukungan dasar{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
Array subclassing{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
Allowed in sloppy mode{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
-
- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/do...while/index.html b/files/id/web/javascript/reference/statements/do...while/index.html deleted file mode 100644 index 01c518ad84..0000000000 --- a/files/id/web/javascript/reference/statements/do...while/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: do...while -slug: Web/JavaScript/Reference/Statements/do...while -tags: - - JavaScript - - Referensi -translation_of: Web/JavaScript/Reference/Statements/do...while ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan do...while digunakan untuk membuat perulangan yang mengeksekusi penyataan tertentu hingga kondisi pemeriksaan penyataan tersebut bernilai false. Kondisi akan diperiksa setelah pernyataan dieksekusi/dijalankan dengan hasil penyataan tersebut yang dijalankan sekurangnya sekali.

- -
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
- - - -

Sintaks

- -
do
-   penyataan
-while (kondisi);
-
- -
-
penyataan
-
Sebuah penyataan yang dieksekusi setidaknya sekali dan akan kembali dieksekusi setiap kali kondisi pemeriksaan bernial true. Untuk mengeksekusi lebih dari satu penyataan di dalam perulangan, gunakan pernyataan {{jsxref("Statements/block", "block")}}  ({ ... }) untuk mengelompokkan penyataan.
-
- -
-
kondisi
-
Sebuah ekspresi yang periksa setelah perulangan. Bila kondisi periksa bernilai true, maka pernyataan akan kembali dieksekusi. Bila kondisi periksa bernilai false, maka kendali akan melewati do...while dan meneruskan ke pernyataan selanjutnya.
-
- -

Contoh

- -

Penggunaan do...while

- -

Pada contoh berikut, perulangan do...while diiterasikan setidaknya sekali dan kembali di iterasikan sampai nilai i tidak kurang dari 5.

- -

Kode HTML

- -
<div id="example"></div>
- -

Kode JavaScript

- -
var result = '';
-var i = 0;
-do {
-   i += 1;
-   result += i + ' ';
-} while (i < 5);
-document.getElementById('example').innerHTML = result;
- -

Hasil

- -

{{ EmbedLiveSample('Examples') }}

- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas Peramban

- - - -

{{Compat("javascript.statements.do_while")}}

- -

Lihat pula

- - diff --git a/files/id/web/javascript/reference/statements/empty/index.html b/files/id/web/javascript/reference/statements/empty/index.html deleted file mode 100644 index 26b2bf8d20..0000000000 --- a/files/id/web/javascript/reference/statements/empty/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: empty -slug: Web/JavaScript/Reference/Statements/Empty -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/Empty ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan empty digunakan untuk menyediakan statement kosong, walaupun begitu sintaks JavaScript tetap menghitungnya sebagai sebuah Pernyataan.

- -

Sintak

- -
;
-
- -

Deskripsi

- -

Statemen atau penyataan kosong hanya berupa semicolon (;) menunjukkan bahawa tidak ada statement untuk dijalankan, meskipun jika sintak JavaScript membutuhkan salah satunya. Sifat kebalikan, dimana anda ingin menggunakan lebih dari satu statemen, namun javascript hanya memperbolehkan sebuah statemen kosong, anda bisa menggunakan block statement; yang merupakan gabungan dari beberapa statement menjadi satu.

- -

Contoh

- -

Statement kosong terkadang digunakan pada perulangan. Lihat pada contoh dengan body berisi sebuah statement kosong:

- -
var arr = [1, 2, 3];
-
-// Assign all array values to 0
-for (i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
-
-console.log(arr)
-// [0, 0, 0]
-
- -

Catatan: Ini merupakan ide yang bagus dengan menggunakan komentar pada penggunaan statement kosong, karena ini tidak benar - benar jelas seperti halnya penggunaan semicolon (;) pada umumnya. Contoh berikut bisa dikatakan merupakan penggunaan yang tidak disengaja:

- -
if (condition);       // Perhatian, "if" tidak menjalankan apapun!
-   killTheUniverse()  // Jadi ini akan selalu di jalankan!!!
-
- -

Contoh lain: Statemen if...else tanpa tanda kurung keriting ({}). Jika three bernilai true, tidak akan terjadi apapun, four tidak begitu penting, dan juga fungsi launchRocket() pada kasus else tidak akan dijalankan.

- -
if (one)
-  doOne();
-else if (two)
-  doTwo();
-else if (three)
-  ; // nothing here
-else if (four)
-  doFour();
-else
-  launchRocket();
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ESDraft', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-empty-statement', 'Empty statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.3', 'Empty statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.3', 'Empty statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

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

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/export/index.html b/files/id/web/javascript/reference/statements/export/index.html deleted file mode 100644 index 1f6d26b71d..0000000000 --- a/files/id/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: export -slug: Web/JavaScript/Reference/Statements/export -translation_of: Web/JavaScript/Reference/Statements/export ---- -
{{jsSidebar("Statements")}}
- -

export statement digunakan untuk meng-ekspor fungsi, objects atau primitives dari file yang di berikan (atau module).

- -
-

Catatan: Fitur ini tidak di implementasikan di browser secara bawaan untuk saat ini. ini hanya diimplementasikan di beberapa transpilers, seperti Traceur CompilerBabel atau Rollup.

-
- -

Syntax

- -
export { name1, name2, …, nameN };
-export { variable1 as name1, variable2 as name2, …, nameN };
-export let name1, name2, …, nameN; // also var
-export let name1 = …, name2 = …, …, nameN; // also var, const
-
-export default expression;
-export default function (…) { … } // also class, function*
-export default function name1(…) { … } // also class, function*
-export { name1 as default, … };
-
-export * from …;
-export { name1, name2, …, nameN } from …;
-export { import1 as name1, import2 as name2, …, nameN } from …;
- -
-
nameN
-
- -

Identitas yang akan diekspor ( sehingga dapat di impor via import di lain skrip).

- -

Deskripsi

- -

Ada dua jenis tipe yang berbeda-beda dari export, masing-masing sesuai dengan salah satu sintaks di atas:

- - - -

Named exports berguna untuk mengekspor beberapa nilai. Selama import, satu akan menggunakan nama yang sama untuk mengacu pada nilai yang sesuai.

- -

Mengenai default export, hanya ada satu default export per modul. default export bisa menjadi fungsi, class, objek atau yang lainya. Nilai ini dianggap sebagai  "Pokok" pengeluaran nilai karena akan menjadi sederhana untuk di import.

- -

Contoh

- -

Menggunakan named exports

- -

dalam modul, kita bisa menggunakan kode berikut:

- -
// module "my-module.js"
-export function cube(x) {
-  return x * x * x;
-}
-const foo = Math.PI + Math.SQRT2;
-export { foo };
-
- -

Cara ini, di dalam script lain  (cf. import), kita bisa memiliki:

- -
import { cube, foo } from 'my-module';
-console.log(cube(3)); // 27
-console.log(foo);    // 4.555806215962888
- -

Menggunakan default export

- -

Jika kita ingin mengekspor nilai tunggal atau memiliki nilai fallback untuk modul kita, kita bisa menggunakan default export:

- -
// module "my-module.js"
-export default function cube(x) {
-  return x * x * x;
-}
-
- -

Kemudian, di lain skrip, akan lebih mudah untuk mengimpor export default :

- -
import cube from 'my-module';
-console.log(cube(3)); // 27
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusComment
{{SpecName('ES6', '#sec-exports', 'Exports')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
- -

Kompatibilitas browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/for...in/index.html b/files/id/web/javascript/reference/statements/for...in/index.html deleted file mode 100644 index 0162c204ee..0000000000 --- a/files/id/web/javascript/reference/statements/for...in/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: for...in -slug: Web/JavaScript/Reference/Statements/for...in -tags: - - JavaScript - - Statement -translation_of: Web/JavaScript/Reference/Statements/for...in ---- -
{{jsSidebar("Statements")}}
- -

Pernyataan for...in mengulang setiap properti enumerable dari sebuah objek, dalam urutan sembarang. Untuk setiap properti yang berbeda, pernyataan dapat dieksekusi.

- -

Sintak

- -
for (variable in object) {...
-}
- -
-
variable
-
Sebuah nama properti yang berbeda ditugaskan untuk variabel pada setiap iterasi.
-
object
-
Objek yang propertinya enumerable yang diiterasi.
-
- -

Deskripsi

- -

Perulangan for...in hanya mengiterasi pada properti enumerable. Objek yang dibuat dari built-in konstruktor seperti Array dan Object telah mewarisi properti non-enumerable dari Object.prototype dan String.prototype, seperti {{jsxref("String")}}'s {{jsxref("String.indexOf", "indexOf()")}} metode atau {{jsxref("Object")}}'s {{jsxref("Object.toString", "toString()")}} metode. Perulangan akan iterate atas semua properti enumerable dari objek itu sendiri dan mereka objek mewarisi dari prototipe konstruktor ini (properti lebih dekat ke objek di properti mata rantai prototipe menggantikan prototipe' properti).

- -

Penghapusan, penambahan atau perubahan pada properti

- -

Perulangan for...in mengiterasi properti suatu objek dalam urutan sembarang (lihat {{jsxref("Operators/delete", "delete")}} Operator untuk lebih lanjut tentang mengapa salah satu tidak dapat bergantung pada keteraturan tampak dari iterasi, setidaknya dalam pengaturan lintas-browser). Jika properti yang diubah dalam satu iterasi dan kemudian mengunjungi di lain waktu, nilainya dalam lingkaran adalah nilai pada waktu kemudian. Sebuah properti yang dihapus sebelum telah dikunjungi tidak akan dikunjungi nanti. Sifat ditambahkan ke objek dimana iterasi terjadi baik dapat dikunjungi atau dihilangkan dari iterasi. Secara umum yang terbaik adalah tidak untuk menambah, mengubah atau menghapus properti dari objek selama iterasi, selain properti saat ini sedang mengunjungi. Tidak ada jaminan apakah properti menambahkan akan dikunjungi, apakah properti dimodifikasi (selain yang saat ini) akan dikunjungi sebelum atau setelah dimodifikasi, atau apakah properti dihapus akan dikunjungi sebelum dihapus.

- -

Iterasi Array dan for...in

- -
-

Catatan: for...in tidak perlu digunakan untuk mengiterasi sebuah {{jsxref("Array")}} dimana urutan indeksnya sangat penting.

-
- -

Index array hanyalah properti enumerable dengan nama integer dan tidak sama dengan properti Objek pada umumnya. Disini tidak akan menjamin jika for...in akan mengembalikan indek pada urutan tertentu.  Pernyataan for...in akan mengembalikan semua properti enumerable, termasuk didalamnya dengan nama non–integer dan serta turunannya.

- -

Karena urutan iterasi merupakan implementation-dependent, pengiterasian pada array mungkin tidak membaca elemen pada urutan yang urut. Karena itu lebih baik menggunakan perulangan {{jsxref("Statements/for", "for")}} dengan menggunakan nomor indek (atau {{jsxref("Array.prototype.forEach()")}} atau {{jsxref("Statements/for...of", "for...of")}} loop) ketika mengiterasi array dimana urutan akses sangat penting.

- -

Iterasi hanya pada properti sendiri

- -

Jika anda hanya ingin mempertimbangkan properti yang melekat pada objek itu sendri, dan bukan prototypes-nya, gunakan {{jsxref("Object.getOwnPropertyNames", "getOwnPropertyNames()")}} atau lakukan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}} cek ({{jsxref("Object.prototype.propertyIsEnumerable", "propertyIsEnumerable")}} juga dapat digunakan). Alternatifnya, jika anda tahu disana tidak ada campur tangan kode luar , anda dapat memperpanjang built-in prototypes dengan metode cek.

- -

Contoh

- -

Pada fungsi berikut menggunakan sebuah objek argumen. kemudian mengiterasi pada semua properti enumerable pada objek tersebut dan mengembalikan string dari nama properti dan nilainya.

- -
var obj = {a:1, b:2, c:3};
-
-for (var prop in obj) {
-  console.log("obj." + prop + " = " + obj[prop]);
-}
-
-// Output:
-// "obj.a = 1"
-// "obj.b = 2"
-// "obj.c = 3"
- -

Fungsi berikut mengiterasi menggunakan {{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}: properti turunannya tidak akan di tampilkan.

- -
var triangle = {a:1, b:2, c:3};
-
-function ColoredTriangle() {
-  this.color = "red";
-}
-
-ColoredTriangle.prototype = triangle;
-
-var obj = new ColoredTriangle();
-
-for (var prop in obj) {
-  if( obj.hasOwnProperty( prop ) ) {
-    console.log("obj." + prop + " = " + obj[prop]);
-  }
-}
-
-// Output:
-// "obj.color = red"
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpesifikasiStatusKomentar
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-for-in-and-for-of-statements', 'for...in statement')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-12.6.4', 'for...in statement')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-12.6.3', 'for...in statement')}}{{Spec2('ES1')}}Initial definition.
- -

Kompabilitas Browser

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FiturChromeFirefox (Gecko)Internet ExplorerOperaSafari
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FiturAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Dukungan dasar{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Kompabilitas: Ekspresi Initializer

- -

Pada SpiderMonkey 40 {{geckoRelease(40)}} atau sebelumnya, bisa menggunakan ekspersi initializer (i=0) pada perulangan for...in :

- -
var obj = {a:1, b:2, c:3};
-for(var i=0 in obj) {
-  console.log(obj[i]);
-}
-// 1
-// 2
-// 3
-
- -

Perilaku non-standard ini sekarang diabaikan pada versi 40 dan selanjutnya akan disajikan dengan {{jsxref("SyntaxError")}} ("for-in loop head declarations may not have initializers") Peringatan pada konsole ({{bug(748550)}} dan {{bug(1164741)}}).

- -

Pada mesin lain seperti v8 (Chrome), Chakra (IE/Edge), dan JSC (WebKit/Safari) juga telah menyelidiki untuk menghapus perilaku non standar tersebut.

- -

Lihat Juga

- - diff --git a/files/id/web/javascript/reference/statements/function/index.html b/files/id/web/javascript/reference/statements/function/index.html deleted file mode 100644 index bd6b665d2e..0000000000 --- a/files/id/web/javascript/reference/statements/function/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: Deklarasi Fungsi -slug: Web/JavaScript/Reference/Statements/function -tags: - - JavaScript - - Pernyataan - - Statement -translation_of: Web/JavaScript/Reference/Statements/function -original_slug: Web/JavaScript/Reference/Statements/fungsi ---- -
{{jsSidebar("Statements")}}
- -

Deklarasi fungsi mendefinisikan sebuah fungsi dengan parameter-parameter yang ditentukan.

- -

Fungsi juga dapat didefinisikan menggukanan konstruktor {{jsxref("Function")}} dan {{jsxref("Operators/function", "function expression")}}.

- -

Sintak

- -
function name([param,[, param,[..., param]]]) {
-   [statements]
-}
-
- -
-
name
-
Nama dari fungsi.
-
- -
-
param
-
Nama dari argumen yang akan dilewatkan kepada fungsi. Jumlah maksimal dari argumen berbeda-beda di setiap mesin.
-
- -
-
statements
-
Statemen-statemen yang membentuk tubuh dari sebuah fungsi.
-
- -

Deskripsi

- -

Sebuah fungsi yang diciptakan dengan deklarasi fungsi adalah sebuah objek Function dan memiliki semua properti, method-method dan tingkah laku dari objek Function. Lihat {{jsxref("Function")}} untuk informasi mendetail tentang fungsi-fungsi.

- -

Sebuah fungsi juga dapat diciptakan menggunakan sebuah ekspresi (lihat  {{jsxref("Operators/function", "function expression")}}).

- -

Secara default, fungsi mengembalikan nilai undefined. Untuk mengembalikan nilai lain, fungsi tersebut harus memiliki sebuah {{jsxref("Statements/return", "return")}} statement yang menentukan nilai untuk dikembalikan.

- -

Fungsi yang dibuat secara kondisional

- -

Fungsi dapat dideklarasikan secara kondisional, yaitu sebuah statement fungsi dapat disarangkan di dalam sebuah statement if. Kebanyakan aplikasi perambah selain Mozilla akan memperlakukan deklarasi kondisional seperti itu sebagai sebuah deklarasi non kondisional dan menciptakan fungsi tersebut meskipun kondisi bernilai benar atau salah, lihat artikel berikut untuk ikhtisar. Untuk alasan tersebut, deklarasi kondisional seharusnya tidak digunakan -- untuk pembuatakan kondisional gunakan ekspresi fungsi sebagai gantinya.

- -

Pengangkatan deklarasi fungsi

- -

Deklarasi fungsi di javaScript mengangkat definisi fungsi. Kamu dapat menggunakan fungsi sebelum kamu mendeklarasikan fungsi tersebut.

- -
hoisted(); // logs "foo"
-
-function hoisted() {
-  console.log('foo');
-}
-
- -

Dicatat bahwa {{jsxref("Operators/function", "function expressions")}} tidak terangkat:

- -
notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Contoh

- -

Menggunakan fungsi

- -

Kode berikut mendeklarasikan sebuah fungsi yang mengembalikan jumlah total penjualan ketika diberikan angka dari unit-unit yang terjual dari produk a, b, dan c.

- -
function calc_sales(units_a, units_b, units_c) {
-   return units_a * 79 + units_b * 129 + units_c * 699;
-}
-
- -

Spesifikasi

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-13', 'Function definition')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Kompabilitas Perambah

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatChrome(49.0)}}{{CompatUnknown}}    
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Allowed in sloppy mode{{CompatNo}} -

{{CompatChrome(49.0)}}

-
{{CompatUnknown}}     -

{{CompatChrome(49.0)}}

-
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

Lihat juga

- - diff --git a/files/id/web/javascript/reference/statements/index.html b/files/id/web/javascript/reference/statements/index.html deleted file mode 100644 index 08840f4e1a..0000000000 --- a/files/id/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Statements -slug: Web/JavaScript/Reference/Statements -tags: - - JavaScript - - Referensi - - Statement -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

Aplikasi JavaScript terdiri dari statemen dengan sebuah sintaks tertentu. Sebuah statement dapat terdiri lebih dari satu baris. Setiap statement dapat berupa sebaris kode jika di pisahkan dengan semikolon ( ; ). Bukan merupakan keyword, tapi sekumpulan keyword.

- -

Statemen dan deklarasi berdasarkan kategori

- -

Untuk daftar berdasarkan alfabet lihat pada sidebar sebelah kiri.

- -

Control flow

- -
-
{{jsxref("Statements/block", "Block")}}
-
Sebuah block statemen digunakan untuk mengelompokkan zero ( 0 ) atau lebih statement. Block ini dibatasi menggunakan kurung kurawal.
-
{{jsxref("Statements/break", "break")}}
-
Membatasi  loop, switch, atau label statement dan transfer kontrol program pada statement berdasakan statemen akhir.
-
{{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.
-
- -

Deklarasi

- -
-
{{jsxref("Statements/var", "var")}}
-
Mendeklarasikan variabel, biasanya menginisialisasi ke sebuah nilai.
-
{{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.
-
- -

Fungsi dan class

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

- - -- cgit v1.2.3-54-g00ecf