aboutsummaryrefslogtreecommitdiff
path: root/files/ru/conflicting/web/javascript/guide/index.html
blob: aa546fe55998aa1e26e558344f0c7f45084aef46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
---
title: Predefined Core Objects
slug: conflicting/Web/JavaScript/Guide
translation_of: Web/JavaScript/Guide
translation_of_original: Web/JavaScript/Guide/Predefined_Core_Objects
original_slug: Web/JavaScript/Guide/Predefined_Core_Objects
---
<p>Эта глава описывает предопределённые объекты в стандартном JavaScript: <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Math</code>, <code>Number</code>, <code>RegExp</code>, и <code>String</code>.</p>

<h2 id="Объект_Array">Объект Array</h2>

<p>В JavaScript массив как тип данных отсутствует. Тем не менее, вы можете использовать предопределённый объект <code>Array</code> и его методы, чтобы работать с массивами в ваших приложениях. Объект <code>Array</code> содержит различные методы для манипуляций с массивами, такими как объединение, обращение и сортировка. У него есть свойство для определения длины массива и другие свойства для работы с регулярными выражениями.</p>

<p><em>Массив</em> - это упорядоченный набор значений, обращаться к которым можно с помощью имени и индекса. Например, можно создать массив <code>emp</code>, который содержит имена сотрудников фирмы, проиндексированные номерами. Тогда <code>emp[1]</code> будет соответствовать сотруднику номер один, <code>emp[2]</code> сотруднику номер два и так далее.</p>

<h3 id="Создание_объекта_Array">Создание объекта Array</h3>

<p>Следующие инструкции создают эквивалентные массивы:</p>

<div style="margin-right: 270px;">
<pre class="brush: js">var arr = new Array(element0, element1, ..., elementN);
var arr = Array(element0, element1, ..., elementN);
var arr = [element0, element1, ..., elementN];
</pre>
</div>

<p><code>element0, element1, ..., elementN</code> это список значений во вновь создаваемом массиве. Когда эти значения заданы, массив инициализирует ими свои элементы. Длина массива определяется по числу аргументов и сохраняется в свойстве <code>length </code>(длина).</p>

<p>Синтаксис с квадратными скобками называется "литералом массива" (array literal) или "инициализатором массива" (array initializer). Такая запись короче других и используется чаще. Подробности смотрите в <a href="/en-US/docs/JavaScript/Guide/Values,_Variables,_and_Literals#Array_Literals" title="en-US/docs/JavaScript/Guide/Values, Variables, and Literals#Array Literals">Array Literals</a>.</p>

<p>Создать массив ненулевой длины, но без элементов, можно одним из следующих способов:</p>

<pre class="brush: js">var arr = new Array(arrayLength);
var arr = Array(arrayLength);

// This has exactly the same effect
var arr = [];
arr.length = arrayLength;
</pre>

<p>Обратите внимание: в приведённом выше коде <code>arrayLength</code> должен быть значением типа <code>Number</code>, то есть числом, иначе будет создан массив с одним элементом (переданным конструктору значением). Вызов <code>arr.length</code> возвратит <code>arrayLength</code>, хотя на самом деле элемент содержит пустые (неопределённые, undefined) элементы. Итерация по массиву циклом for...in не возвратит никаких элементов.</p>

<p>Массивы можно не только определить как и переменные, но и присвоить существующему объекту как свойство:</p>

<pre class="brush: js">var obj = {};
// ...
obj.prop = [element0, element1, ..., elementN];

// OR
var obj = {prop: [element0, element1, ...., elementN]}
</pre>

<p>Если же вы хотите создать одноэлементный массив, содержащий число, придётся использовать запись с квадратными скобками, так как когда конструктору Array() передаётся одно-единственное число, оно трактуется как длина массива, а не как хранимый элемент.</p>

<pre><code>var arr = [42];
var arr = Array(42); // Creates an array with no element, but with arr.length set to 42

// The above code is equivalent to
var arr = [];
arr.length = 42;
</code>
</pre>

<p>Вызов <code>Array(N)</code> приводит к <code>RangeError</code>, если <code>N</code> не является целым числом, чья дробная часть не равна нулю. Следующий пример иллюстрирует это поведение.</p>

<pre>var arr = Array(9.3);  // RangeError: Invalid array length
</pre>

<p>Если ваш код должен создавать массивы с отдельными элементами произвольного типа, безопаснее использовать литералы массива. Или, создайте пустой массив, прежде чем добавлять элементы к нему.</p>

<h3 id="Заполнение_массива">Заполнение массива</h3>

<p>You can populate an array by assigning values to its elements. For example,</p>

<pre class="brush: js">var emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";
</pre>

<p><strong>Note:</strong> if you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.</p>

<pre> var arr = [];
arr[3.4] = "Oranges";
console.log(arr.length);                // 0
console.log(arr.hasOwnProperty(3.4));   // true
</pre>

<p>You can also populate an array when you create it:</p>

<pre class="brush: js">var myArray = new Array("Hello", myVar, 3.14159);
var myArray = ["Mango", "Apple", "Orange"]
</pre>

<h3 id="Referring_to_Array_Elements">Referring to Array Elements</h3>

<p>You refer to an array's elements by using the element's ordinal number. For example, suppose you define the following array:</p>

<pre class="brush: js">var myArray = ["Wind", "Rain", "Fire"];
</pre>

<p>You then refer to the first element of the array as <code>myArray[0]</code> and the second element of the array as <code>myArray[1]</code>. The index of the elements begins with zero.</p>

<p><strong>Note:</strong> the array operator (square brackets) is also used for accessing the array's properties (arrays are also objects in JavaScript). For example,</p>

<pre> var arr = ["one", "two", "three"];
arr[2];  // three
arr["length"];  // 3
</pre>

<h3 id="Understanding_length">Understanding length</h3>

<p>At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name. The <code>length</code> property is special; it always returns the index of the last element plus one (in following example Dusty is indexed at 30 so cats.length returns 30 + 1). Remember, Javascript Array indexes are 0-based: they start at 0, not 1. This means that the <code><code>length</code></code> property will be one more than the highest index stored in the array:</p>

<pre class="brush: js">var cats = [];
cats[30] = ['Dusty'];
print(cats.length); // 31
</pre>

<p>You can also assign to the <code>length</code> property. Writing a value that is shorter than the number of stored items truncates the array; writing 0 empties it entirely:</p>

<pre class="brush: js">var cats = ['Dusty', 'Misty', 'Twiggy'];
console.log(cats.length); // 3

cats.length = 2;
console.log(cats); // prints "Dusty,Misty" - Twiggy has been removed

cats.length = 0;
console.log(cats); // prints nothing; the cats array is empty

cats.length = 3;
console.log(cats); // [undefined, undefined, undefined]
</pre>

<h3 id="Iterating_over_arrays">Iterating over arrays</h3>

<p>A common operation is to iterate over the values of an array, processing each one in some way. The simplest way to do this is as follows:</p>

<pre class="brush: js">var colors = ['red', 'green', 'blue'];
for (var i = 0; i &lt; colors.length; i++) {
  console.log(colors[i]);
}
</pre>

<p>If you know that none of the elements in your array evaluate to <code>false</code> in a boolean context — if your array consists only of <a href="/en-US/docs/DOM" title="en-US/docs/DOM">DOM</a> nodes, for example, you can use a more efficient idiom:</p>

<pre class="brush: js">var divs = document.getElementsByTagName('div');
for (var i = 0, div; div = divs[i]; i++) {
  /* Process div in some way */
}
</pre>

<p>This avoids the overhead of checking the length of the array, and ensures that the <code>div</code> variable is reassigned to the current item each time around the loop for added convenience.</p>

<p>The <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach"><code>forEach()</code></a> method, introduced in JavaScript 1.6, provides another way of iterating over an array:</p>

<pre class="brush: js">var colors = ['red', 'green', 'blue'];
colors.forEach(function(color) {
  console.log(color);
});
</pre>

<p>The function passed to <code>forEach</code> is executed once for every item in the array, with the array item passed as the argument to the function. Unassigned values are not iterated in a <code>forEach</code> loop.</p>

<p>Note that the elements of array omitted when the array is defined are not listed when iterating by <code>forEach, </code>but are listed when <code>undefined</code> has been manually assigned to the element:</p>

<pre class="brush: js">var array = ['first', 'second', , 'fourth'];

// returns ['first', 'second', 'fourth'];
array.forEach(function(element) {
  console.log(element);
})

if(array[2] === undefined) { console.log('array[2] is undefined'); } // true

var array = ['first', 'second', undefined, 'fourth'];

// returns ['first', 'second', undefined, 'fourth'];
array.forEach(function(element) {
  console.log(element);
})</pre>

<p>Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in loops because normal elements and all enumerable properties will be listed.</p>

<h3 id="Array_Methods">Array Methods</h3>

<p>The <code>Array</code> object has the following methods:</p>

<ul>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/concat" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/concat"><code>concat()</code></a> joins two arrays and returns a new array.

  <pre class="brush: js">var myArray = new Array("1", "2", "3");
myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"]
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/join" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/join"><code>join(deliminator = ",")</code></a> joins all elements of an array into a string.
  <pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire");
var list = myArray.join(" - "); // list is "Wind - Rain - Fire"
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/push"><code>push()</code></a> adds one or more elements to the end of an array and returns the resulting length of the array.
  <pre class="brush: js">var myArray = new Array("1", "2");
myArray.push("3"); // myArray is now ["1", "2", "3"]
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/pop" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/pop"><code>pop()</code></a> removes the last element from an array and returns that element.
  <pre class="brush: js">var myArray = new Array("1", "2", "3");
var last = myArray.pop(); // myArray is now ["1", "2"], last = "3"
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/shift"><code>shift()</code></a> removes the first element from an array and returns that element.
  <pre class="brush: js">var myArray = new Array ("1", "2", "3");
var first = myArray.shift(); // myArray is now ["2", "3"], first is "1"
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/unshift" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/unshift"><code>unshift()</code></a> adds one or more elements to the front of an array and returns the new length of the array.
  <pre class="brush: js">var myArray = new Array ("1", "2", "3");
myArray.unshift("4", "5"); // myArray becomes ["4", "5", "1", "2", "3"]</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/slice"><code>slice(start_index, upto_index)</code></a> extracts a section of an array and returns a new array.
  <pre class="brush: js">var myArray = new Array ("a", "b", "c", "d", "e");
myArray = myArray.slice(1, 4); /* starts at index 1 and extracts all elements
  until index 3, returning [ "b", "c", "d"] */
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/splice"><code>splice(index, count_to_remove, addelement1, addelement2, ...)</code></a> removes elements from an array and (optionally) replaces them.
  <pre class="brush: js">var myArray = new Array ("1", "2", "3", "4", "5");
myArray.splice(1, 3, "a", "b", "c", "d"); // myArray is now ["1", "a", "b", "c", "d", "5"]
  // This code started at index one (or where the "2" was), removed 3 elements there,
  // and then inserted all consecutive elements in its place.
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/reverse" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/reverse"><code>reverse()</code></a> transposes the elements of an array: the first array element becomes the last and the last becomes the first.
  <pre class="brush: js">var myArray = new Array ("1", "2", "3");
myArray.reverse(); // transposes the array so that myArray = [ "3", "2", "1" ]
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/sort"><code>sort()</code></a> sorts the elements of an array.
  <pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire");
myArray.sort(); // sorts the array so that myArrray = [ "Fire", "Rain", "Wind" ]
</pre>

  <p><code>sort()</code> can also take a callback function to determine how array elements are compared. The function compares two values and returns one of three values:</p>

  <ul>
   <li>if <code>a</code> is less than <code>b</code> by the sorting system, return -1 (or any negative number)</li>
   <li>if <code>a</code> is greater than <code>b</code> by the sorting system, return 1 (or any positive number)</li>
   <li>if <code>a</code> and <code>b</code> are considered equivalent, return 0.</li>
  </ul>

  <p>For instance, the following will sort by the last letter of an array:</p>

  <pre class="brush: js">var sortFn = function(a, b){
  if (a[a.length - 1] &lt; b[b.length - 1]) return -1;
  if (a[a.length - 1] &gt; b[b.length - 1]) return 1;
  if (a[a.length - 1] == b[b.length - 1]) return 0;
}
myArray.sort(sortFn); // sorts the array so that myArray = ["Wind","Fire","Rain"]</pre>
 </li>
</ul>

<p>Compatibility code for older browsers can be found for each of these functions on the individual pages. Native browser support for these features in various browsers can be found<a class="external" href="http://www.robertnyman.com/javascript/" title="http://www.robertnyman.com/javascript/"> here.</a></p>

<ul>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/indexOf"><code>indexOf(searchElement[, fromIndex])</code></a> searches the array for <code>searchElement</code> and returns the index of the first match.

  <pre class="brush: js">var a = ['a', 'b', 'a', 'b', 'a'];
alert(a.indexOf('b')); // Alerts 1
// Now try again, starting from after the last match
alert(a.indexOf('b', 2)); // Alerts 3
alert(a.indexOf('z')); // Alerts -1, because 'z' was not found
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/lastIndexOf"><code>lastIndexOf(searchElement[, fromIndex])</code></a> works like <code>indexOf</code>, but starts at the end and searches backwards.
  <pre class="brush: js">var a = ['a', 'b', 'c', 'd', 'a', 'b'];
alert(a.lastIndexOf('b')); // Alerts 5
// Now try again, starting from before the last match
alert(a.lastIndexOf('b', 4)); // Alerts 1
alert(a.lastIndexOf('z')); // Alerts -1
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/forEach"><code>forEach(callback[, thisObject])</code></a> executes <code>callback</code> on every array item.
  <pre class="brush: js">var a = ['a', 'b', 'c'];
a.forEach(alert); // Alerts each item in turn
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/map" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/map"><code>map(callback[, thisObject])</code></a> returns a new array of the return value from executing <code>callback</code> on every array item.
  <pre class="brush: js">var a1 = ['a', 'b', 'c'];
var a2 = a1.map(function(item) { return item.toUpperCase(); });
alert(a2); // Alerts A,B,C
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/filter"><code>filter(callback[, thisObject])</code></a> returns a new array containing the items for which callback returned true.
  <pre class="brush: js">var a1 = ['a', 10, 'b', 20, 'c', 30];
var a2 = a1.filter(function(item) { return typeof item == 'number'; });
alert(a2); // Alerts 10,20,30
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/every" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/every"><code>every(callback[, thisObject])</code></a> returns true if <code>callback</code> returns true for every item in the array.
  <pre class="brush: js">function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
alert(a1.every(isNumber)); // Alerts true
var a2 = [1, '2', 3];
alert(a2.every(isNumber)); // Alerts false
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/some" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/some"><code>some(callback[, thisObject])</code></a> returns true if <code>callback</code> returns true for at least one item in the array.
  <pre class="brush: js">function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
alert(a1.some(isNumber)); // Alerts true
var a2 = [1, '2', 3];
alert(a2.some(isNumber)); // Alerts true
var a3 = ['1', '2', '3'];
alert(a3.some(isNumber)); // Alerts false
</pre>
 </li>
</ul>

<p>The methods above that take a callback are known as <em>iterative methods</em>, because they iterate over the entire array in some fashion. Each one takes an optional second argument called <code>thisObject</code>. If provided, <code>thisObject</code> becomes the value of the <code>this</code> keyword inside the body of the callback function. If not provided, as with other cases where a function is invoked outside of an explicit object context, <code>this</code> will refer to the global object (<a href="/en-US/docs/DOM/window" title="en-US/docs/DOM/window"><code>window</code></a>).</p>

<p>The callback function is actually called with three arguments. The first is the value of the current item, the second is its array index, and the third is a reference to the array itself. JavaScript functions ignore any arguments that are not named in the parameter list so it is safe to provide a callback function that only takes a single argument, such as <code>alert</code>.</p>

<ul>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/reduce"><code>reduce(callback[, initialValue])</code></a> applies <code>callback(firstValue, secondValue)</code> to reduce the list of items down to a single value.

  <pre class="brush: js">var a = [10, 20, 30];
var total = a.reduce(function(first, second) { return first + second; }, 0);
alert(total) // Alerts 60
</pre>
 </li>
 <li><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/ReduceRight" title="en-US/docs/JavaScript/Reference/Global
    Objects/Array/reduceRight"><code>reduceRight(callback[, initialValue])</code></a> works like <code>reduce()</code>, but starts with the last element.</li>
</ul>

<p><code>reduce</code> and <code>reduceRight</code> are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.</p>

<h3 id="Multi-Dimensional_Arrays">Multi-Dimensional Arrays</h3>

<p>Arrays can be nested, meaning that an array can contain another array as an element. Using this characteristic of JavaScript arrays, multi-dimensional arrays can be created.</p>

<p>The following code creates a two-dimensional array.</p>

<pre class="brush: js">var a = new Array(4);
for (i = 0; i &lt; 4; i++) {
  a[i] = new Array(4);
  for (j = 0; j &lt; 4; j++) {
    a[i][j] = "[" + i + "," + j + "]";
  }
}
</pre>

<p>This example creates an array with the following rows:</p>

<pre>Row 0: [0,0] [0,1] [0,2] [0,3]
Row 1: [1,0] [1,1] [1,2] [1,3]
Row 2: [2,0] [2,1] [2,2] [2,3]
Row 3: [3,0] [3,1] [3,2] [3,3]
</pre>

<h3 id="Arrays_and_Regular_Expressions">Arrays and Regular Expressions</h3>

<p>When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of <a href="/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec" title="en-US/docs/JavaScript/Reference/Global Objects/RegExp/exec"><code>RegExp.exec()</code></a>, <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="en-US/docs/JavaScript/Reference/Global Objects/String/match"><code>String.match()</code></a>, and <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="en-US/docs/JavaScript/Reference/Global
Objects/String/split"><code>String.split()</code></a>. For information on using arrays with regular expressions, see <a href="/en-US/docs/JavaScript/Guide/Regular_Expressions" title="en-US/docs/JavaScript/Guide/Regular Expressions">Regular Expressions</a>.</p>

<h3 id="Working_with_Array-like_objects">Working with Array-like objects</h3>

<p>Some JavaScript objects, such as the <a href="/en-US/docs/DOM/NodeList" title="en-US/docs/DOM/NodeList"><code>NodeList</code></a> returned by <a href="/en-US/docs/DOM/document.getElementsByTagName" title="en-US/docs/DOM/document.getElementsByTagName"><code>document.getElementsByTagName()</code></a> or the <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments" title="en-US/docs/JavaScript/Reference/Functions and
function
scope/arguments"><code>arguments</code></a> object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The <code>arguments</code> object provides a <a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length" title="en-US/docs/JavaScript/Reference/Functions
and function
scope/arguments/length"><code>length</code></a> attribute but does not implement the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach" title="en-US/docs/JavaScript/Reference/Global Objects/Array/forEach"><code>forEach()</code></a> method, for example.</p>

<p>Array generics, introduced in JavaScript 1.6, provide a way of running <code>Array</code> methods against other array-like objects. Each standard array method has a corresponding method on the <code>Array</code> object itself; for example:</p>

<pre class="brush: js"> function alertArguments() {
   Array.forEach(arguments, function(item) {
     alert(item);
   });
 }
</pre>

<p>These generic methods can be emulated more verbosely in older versions of JavaScript using the call method provided by JavaScript function objects:</p>

<pre class="brush: js"> Array.prototype.forEach.call(arguments, function(item) {
   alert(item);
 });
</pre>

<p>Array generic methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:</p>

<pre class="brush: js">Array.forEach("a string", function(chr) {
   alert(chr);
});</pre>

<p>Here are some further examples of applying array methods to strings, also taking advantage of <a href="/en-US/docs/JavaScript/New_in_JavaScript/1.8#Expression_closures" title="en-US/docs/New_in_JavaScript_1.8#Expression_closures">JavaScript 1.8 expression closures</a>:</p>

<pre class="brush: js">var str = 'abcdef';
var consonantsOnlyStr = Array.filter(str, function (c) !(/[aeiou]/i).test(c)).join(''); // 'bcdf'
var vowelsPresent = Array.some(str, function (c) (/[aeiou]/i).test(c)); // true
var allVowels = Array.every(str, function (c) (/[aeiou]/i).test(c)); // false
var interpolatedZeros = Array.map(str, function (c) c+'0').join(''); // 'a0b0c0d0e0f0'
var numerologicalValue = Array.reduce(str, function (c, c2) c+c2.toLowerCase().charCodeAt()-96, 0);
// 21 (reduce() since JS v1.8)
</pre>

<p>Note that <code>filter</code> and <code>map</code> do not automatically return the characters back into being members of a string in the return result; an array is returned, so we must use <code>join</code> to return back to a string.</p>

<h3 id="Array_comprehensions">Array comprehensions</h3>

<p>Introduced in JavaScript 1.7, array comprehensions provide a useful shortcut for constructing a new array based on the contents of another. Comprehensions can often be used in place of calls to <code>map()</code> and <code>filter()</code>, or as a way of combining the two.</p>

<p>The following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.</p>

<pre class="brush: js">var numbers = [1, 2, 3, 4];
var doubled = [i * 2 for (i of numbers)];
alert(doubled); // Alerts 2,4,6,8
</pre>

<p>This is equivalent to the following <code>map()</code> operation:</p>

<pre class="brush: js">var doubled = numbers.map(function(i){return i * 2;});
</pre>

<p>Comprehensions can also be used to select items that match a particular expression. Here is a comprehension which selects only even numbers:</p>

<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30];
var evens = [i for (i of numbers) if (i % 2 === 0)];
alert(evens); // Alerts 2,22,30
</pre>

<p><code>filter()</code> can be used for the same purpose:</p>

<pre class="brush: js">var evens = numbers.filter(function(i){return i % 2 === 0;});
</pre>

<p><code>map()</code> and <code>filter()</code> style operations can be combined into a single array comprehension. Here is one that filters just the even numbers, then creates an array containing their doubles:</p>

<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30];
var doubledEvens = [i * 2 for (i of numbers) if (i % 2 === 0)];
alert(doubledEvens); // Alerts 4,44,60
</pre>

<p>The square brackets of an array comprehension introduce an implicit block for scoping purposes. New variables (such as i in the example) are treated as if they had been declared using <a href="/en-US/docs/JavaScript/Reference/Statements/let" title="/en-US/docs/JavaScript/Reference/Statements/let"><code>let</code></a>. This means that they will not be available outside of the comprehension.</p>

<p>The input to an array comprehension does not itself need to be an array; <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators" title="en-US/docs/JavaScript/Guide/Iterators and Generators">iterators and generators</a> can also be used.</p>

<p>Even strings may be used as input; to achieve the filter and map actions (under Array-like objects) above:</p>

<pre class="brush: js">var str = 'abcdef';
var consonantsOnlyStr = [c for (c of str) if (!(/[aeiouAEIOU]/).test(c))  ].join(''); // 'bcdf'
var interpolatedZeros = [c+'0' for (c of str) ].join(''); // 'a0b0c0d0e0f0'
</pre>

<p>Again, the input form is not preserved, so we have to use <code>join()</code> to revert back to a string.</p>

<h2 id="Boolean_Object">Boolean Object</h2>

<p>The <code>Boolean</code> object is a wrapper around the primitive Boolean data type. Use the following syntax to create a <code>Boolean</code> object:</p>

<pre class="brush: js">var booleanObjectName = new Boolean(value);
</pre>

<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the <code>Boolean</code> object. Any object whose value is not <code>undefined</code> , <code>null</code>, <code>0</code>, <code>NaN</code>, or the empty string, including a <code>Boolean</code> object whose value is false, evaluates to true when passed to a conditional statement. See <a href="/en-US/docs/JavaScript/Guide/Statements#if...else_Statement" title="en-US/docs/JavaScript/Guide/Statements#if...else Statement">if...else Statement</a> for more information.</p>

<h2 id="Date_Object">Date Object</h2>

<p>JavaScript does not have a date data type. However, you can use the <code>Date</code> object and its methods to work with dates and times in your applications. The <code>Date</code> object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.</p>

<p>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.</p>

<p>The <code>Date</code> object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.</p>

<p>To create a <code>Date</code> object:</p>

<pre class="brush: js">var dateObjectName = new Date([parameters]);
</pre>

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

<p>Calling <code>Date</code> without the <code>new</code> keyword simply converts the provided date to a string representation.</p>

<p>The <code>parameters</code> in the preceding syntax can be any of the following:</p>

<ul>
 <li>Nothing: creates today's date and time. For example, <code>today = new Date();</code>.</li>
 <li>A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, <code>var Xmas95 = new Date("December 25, 1995 13:30:00")</code>. If you omit hours, minutes, or seconds, the value will be set to zero.</li>
 <li>A set of integer values for year, month, and day. For example, <code>var Xmas95 = new Date(1995, 11, 25)</code>.</li>
 <li>A set of integer values for year, month, day, hour, minute, and seconds. For example, <code>var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);</code>.</li>
</ul>

<p><strong>JavaScript 1.2 and earlier</strong><br>
 The <code>Date</code> object behaves as follows:</p>

<ul>
 <li>Dates prior to 1970 are not allowed.</li>
 <li>JavaScript depends on platform-specific date facilities and behavior; the behavior of the <code>Date</code> object varies from platform to platform.</li>
</ul>

<h3 id="Methods_of_the_Date_Object">Methods of the Date Object</h3>

<p>The <code>Date</code> object methods for handling dates and times fall into these broad categories:</p>

<ul>
 <li>"set" methods, for setting date and time values in <code>Date</code> objects.</li>
 <li>"get" methods, for getting date and time values from <code>Date</code> objects.</li>
 <li>"to" methods, for returning string values from <code>Date</code> objects.</li>
 <li>parse and UTC methods, for parsing <code>Date</code> strings.</li>
</ul>

<p>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 <code>getDay</code> method that returns the day of the week, but no corresponding <code>setDay</code> method, because the day of the week is set automatically. These methods use integers to represent these values as follows:</p>

<ul>
 <li>Seconds and minutes: 0 to 59</li>
 <li>Hours: 0 to 23</li>
 <li>Day: 0 (Sunday) to 6 (Saturday)</li>
 <li>Date: 1 to 31 (day of the month)</li>
 <li>Months: 0 (January) to 11 (December)</li>
 <li>Year: years since 1900</li>
</ul>

<p>For example, suppose you define the following date:</p>

<pre class="brush: js">var Xmas95 = new Date("December 25, 1995");
</pre>

<p>Then <code>Xmas95.getMonth()</code> returns 11, and <code>Xmas95.getFullYear()</code> returns 1995.</p>

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

<p>For example, the following code displays the number of days left in the current year:</p>

<pre class="brush: js">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
</pre>

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

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

<pre class="brush: js">var IPOdate = new Date();
IPOdate.setTime(Date.parse("Aug 9, 1995"));
</pre>

<h3 id="Using_the_Date_Object_an_Example">Using the Date Object: an Example</h3>

<p>In the following example, the function <code>JSClock()</code> returns the time in the format of a digital clock.</p>

<pre class="brush: js">function JSClock() {
  var time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  var temp = "" + ((hour &gt; 12) ? hour - 12 : hour);
  if (hour == 0)
    temp = "12";
  temp += ((minute &lt; 10) ? ":0" : ":") + minute;
  temp += ((second &lt; 10) ? ":0" : ":") + second;
  temp += (hour &gt;= 12) ? " P.M." : " A.M.";
  return temp;
}
</pre>

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

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

<p>The next statement appends a <code>minute</code> value to <code>temp</code>. If the value of <code>minute</code> 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 <code>temp</code> in the same way.</p>

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

<h2 id="Function_Object">Function Object</h2>

<p>The predefined <code>Function</code> object specifies a string of JavaScript code to be compiled as a function.</p>

<p>To create a <code>Function</code> object:</p>

<pre class="brush: js">var functionObjectName = new Function ([arg1, arg2, ... argn], functionBody);
</pre>

<p><code>functionObjectName</code> is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as <code>window.onerror</code>.</p>

<p><code>arg1</code>, <code>arg2</code>, ... <code>argn</code> are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".</p>

<p><code>functionBody</code> is a string specifying the JavaScript code to be compiled as the function body.</p>

<p><code>Function</code> objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.</p>

<p>In addition to defining functions as described here, you can also use the <a href="/en-US/docs/JavaScript/Reference/Statements/function" title="en-US/docs/JavaScript/Reference/Statements/function"><code>function</code> statement</a> and the function expression. See the <a href="/en-US/docs/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript Reference</a> for more information.</p>

<p>The following code assigns a function to the variable <code>setBGColor</code>. This function sets the current document's background color.</p>

<pre class="brush: js">var setBGColor = new Function("document.bgColor = 'antiquewhite'");
</pre>

<p>To call the <code>Function</code> object, you can specify the variable name as if it were a function. The following code executes the function specified by the <code>setBGColor</code> variable:</p>

<pre class="brush: js">var colorChoice="antiquewhite";
if (colorChoice=="antiquewhite") {setBGColor()}
</pre>

<p>You can assign the function to an event handler in either of the following ways:</p>

<ol>
 <li>
  <pre class="brush: js">document.form1.colorButton.onclick = setBGColor;
</pre>
 </li>
 <li>
  <pre class="brush: html">&lt;INPUT NAME="colorButton" TYPE="button"
  VALUE="Change background color"
  onClick="setBGColor()"&gt;
</pre>
 </li>
</ol>

<p>Creating the variable <code>setBGColor</code> shown above is similar to declaring the following function:</p>

<pre class="brush: js">function setBGColor() {
  document.bgColor = 'antiquewhite';
}
</pre>

<p>Assigning a function to a variable is similar to declaring a function, but there are differences:</p>

<ul>
 <li>When you assign a function to a variable using <code>var setBGColor = new Function("...")</code>, <code>setBGColor</code> is a variable for which the current value is a reference to the function created with <code>new Function()</code>.</li>
 <li>When you create a function using <code>function setBGColor() {...}</code>, <code>setBGColor</code> is not a variable, it is the name of a function.</li>
</ul>

<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:</p>

<ul>
 <li>The inner function can be accessed only from statements in the outer function.</li>
 <li>The inner function can use the arguments and variables of the outer function. The outer function cannot use the arguments and variables of the inner function.</li>
</ul>

<h2 id="Math_Object">Math Object</h2>

<p>The predefined <code>Math</code> object has properties and methods for mathematical constants and functions. For example, the <code>Math</code> object's <code>PI</code> property has the value of pi (3.141...), which you would use in an application as</p>

<pre class="brush: js">Math.PI
</pre>

<p>Similarly, standard mathematical functions are methods of <code>Math</code>. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write</p>

<pre class="brush: js">Math.sin(1.56)
</pre>

<p>Note that all trigonometric methods of <code>Math</code> take arguments in radians.</p>

<p>The following table summarizes the <code>Math</code> object's methods.</p>

<table class="standard-table">
 <caption>Table 7.1 Methods of Math</caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>abs</code></td>
   <td>Absolute value</td>
  </tr>
  <tr>
   <td><code>sin</code>, <code>cos</code>, <code>tan</code></td>
   <td>Standard trigonometric functions; argument in radians</td>
  </tr>
  <tr>
   <td><code>acos</code>, <code>asin</code>, <code>atan</code>, <code>atan2</code></td>
   <td>Inverse trigonometric functions; return values in radians</td>
  </tr>
  <tr>
   <td><code>exp</code>, <code>log</code></td>
   <td>Exponential and natural logarithm, base <code>e</code></td>
  </tr>
  <tr>
   <td><code>ceil</code></td>
   <td>Returns least integer greater than or equal to argument</td>
  </tr>
  <tr>
   <td><code>floor</code></td>
   <td>Returns greatest integer less than or equal to argument</td>
  </tr>
  <tr>
   <td><code>min</code>, <code>max</code></td>
   <td>Returns greater or lesser (respectively) of two arguments</td>
  </tr>
  <tr>
   <td><code>pow</code></td>
   <td>Exponential; first argument is base, second is exponent</td>
  </tr>
  <tr>
   <td><code>random</code></td>
   <td>Returns a random number between 0 and 1.</td>
  </tr>
  <tr>
   <td><code>round</code></td>
   <td>Rounds argument to nearest integer</td>
  </tr>
  <tr>
   <td><code>sqrt</code></td>
   <td>Square root</td>
  </tr>
 </tbody>
</table>

<p>Unlike many other objects, you never create a <code>Math</code> object of your own. You always use the predefined <code>Math</code> object.</p>

<h2 id="Number_Object">Number Object</h2>

<p>The <code>Number</code> object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:</p>

<pre class="brush: js">var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
</pre>

<p>You always refer to a property of the predefined <code>Number</code> object as shown above, and not as a property of a <code>Number</code> object you create yourself.</p>

<p>The following table summarizes the <code>Number</code> object's properties.</p>

<table class="standard-table">
 <caption>Table 7.2 Properties of Number</caption>
 <thead>
  <tr>
   <th scope="col">Property</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>MAX_VALUE</code></td>
   <td>The largest representable number</td>
  </tr>
  <tr>
   <td><code>MIN_VALUE</code></td>
   <td>The smallest representable number</td>
  </tr>
  <tr>
   <td><code>NaN</code></td>
   <td>Special "not a number" value</td>
  </tr>
  <tr>
   <td><code>NEGATIVE_INFINITY</code></td>
   <td>Special negative infinite value; returned on overflow</td>
  </tr>
  <tr>
   <td><code>POSITIVE_INFINITY</code></td>
   <td>Special positive infinite value; returned on overflow</td>
  </tr>
 </tbody>
</table>

<p>The Number prototype provides methods for retrieving information from Number objects in various formats. The following table summarizes the methods of <code>Number.prototype</code>.</p>

<table class="fullwidth-table">
 <caption>Table 7.3 Methods of Number.prototype</caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code>toExponential</code></td>
   <td>Returns a string representing the number in exponential notation.</td>
  </tr>
  <tr>
   <td><code>toFixed</code></td>
   <td>Returns a string representing the number in fixed-point notation.</td>
  </tr>
  <tr>
   <td><code>toPrecision</code></td>
   <td>Returns a string representing the number to a specified precision in fixed-point notation.</td>
  </tr>
  <tr>
   <td><code>toSource</code></td>
   <td>Returns an object literal representing the specified <code>Number</code> object; you can use this value to create a new object. Overrides the <code>Object.toSource</code> method.</td>
  </tr>
  <tr>
   <td><code>toString</code></td>
   <td>Returns a string representing the specified object. Overrides the <code>Object.toString </code>method.</td>
  </tr>
  <tr>
   <td><code>valueOf</code></td>
   <td>Returns the primitive value of the specified object. Overrides the <code>Object.valueOf </code>method.</td>
  </tr>
 </tbody>
</table>

<h2 id="RegExp_Object">RegExp Object</h2>

<p>The <code>RegExp</code> object lets you work with regular expressions. It is described in <a href="/en-US/docs/JavaScript/Guide/Regular_Expressions" title="en-US/docs/JavaScript/Guide/Regular Expressions">Regular Expressions</a>.</p>

<h2 id="String_Object">String Object</h2>

<p>The <code>String</code> object is a wrapper around the string primitive data type. Do not confuse a string literal with the <code>String</code> object. For example, the following code creates the string literal <code>s1</code> and also the <code>String</code> object <code>s2</code>:</p>

<pre class="brush: js">var s1 = "foo"; //creates a string literal value
var s2 = new String("foo"); //creates a String object
</pre>

<p>You can call any of the methods of the <code>String</code> object on a string literal value—JavaScript automatically converts the string literal to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. You can also use the <code>String.length</code> property with a string literal.</p>

<p>You should use string literals unless you specifically need to use a <code>String</code> object, because <code>String</code> objects can have counterintuitive behavior. For example:</p>

<pre class="brush: js">var s1 = "2 + 2"; //creates a string literal value
var s2 = new String("2 + 2"); //creates a String object
eval(s1); //returns the number 4
eval(s2); //returns the string "2 + 2"</pre>

<p>A <code>String</code> object has one property, <code>length</code>, that indicates the number of characters in the string. For example, the following code assigns <code>x</code> the value 13, because "Hello, World!" has 13 characters:</p>

<pre class="brush: js">var mystring = "Hello, World!";
var x = mystring.length;
</pre>

<p>A <code>String</code> object has two types of methods: those that return a variation on the string itself, such as <code>substring</code> and <code>toUpperCase</code>, and those that return an HTML-formatted version of the string, such as <code>bold</code> and <code>link</code>.</p>

<p>For example, using the previous example, both <code>mystring.toUpperCase()</code> and <code>"hello, world!".toUpperCase()</code> return the string "HELLO, WORLD!"</p>

<p>The <code>substring</code> method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, <code>mystring.substring(4, 9)</code> returns the string "o, Wo". See the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substring" title="en-US/docs/JavaScript/Reference/Global Objects/String/substring"><code>substring</code></a> method of the <code>String</code> object in the JavaScript Reference for more information.</p>

<p>The <code>String</code> object also has a number of methods for automatic HTML formatting, such as <code>bold</code> to create boldface text and <code>link</code> to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the <code>link</code> method as follows:</p>

<pre class="brush: js">mystring.link("http://www.helloworld.com")
</pre>

<p>The following table summarizes the methods of <code>String</code> objects.</p>

<table class="fullwidth-table">
 <caption>Table 7.4 Methods of String Instances</caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/anchor" title="en-US/docs/JavaScript/Reference/Global_Objects/String/anchor">anchor</a></code></td>
   <td>Creates HTML named anchor.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/big" title="en-US/docs/JavaScript/Reference/Global_Objects/String/big">big</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/blink" title="en-US/docs/JavaScript/Reference/Global_Objects/String/blink">blink</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/bold" title="en-US/docs/JavaScript/Reference/Global_Objects/String/bold">bold</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/fixed" title="en-US/docs/JavaScript/Reference/Global_Objects/String/fixed">fixed</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/italics" title="en-US/docs/JavaScript/Reference/Global_Objects/String/italics">italics</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/small" title="en-US/docs/JavaScript/Reference/Global_Objects/String/small">small</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/strike" title="en-US/docs/JavaScript/Reference/Global_Objects/String/strike">strike</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/sub" title="en-US/docs/JavaScript/Reference/Global_Objects/String/sub">sub</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/sup" title="en-US/docs/JavaScript/Reference/Global_Objects/String/sup">sup</a></code></td>
   <td>Create HTML formatted string.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/charAt" title="en-US/docs/JavaScript/Reference/Global_Objects/String/charAt">charAt</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt" title="en-US/docs/JavaScript/Reference/Global_Objects/String/charCodeAt">charCodeAt</a></code></td>
   <td>Return the character or character code at the specified position in string.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf" title="en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf">indexOf</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf" title="en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf">lastIndexOf</a></code></td>
   <td>Return the position of specified substring in the string or last position of specified substring, respectively.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/link" title="en-US/docs/JavaScript/Reference/Global_Objects/String/link">link</a></code></td>
   <td>Creates HTML hyperlink.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/concat" title="en-US/docs/JavaScript/Reference/Global_Objects/String/concat">concat</a></code></td>
   <td>Combines the text of two strings and returns a new string.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode" title="en-US/docs/JavaScript/Reference/Global_Objects/String/fromCharCode">fromCharCode</a></code></td>
   <td>Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/split" title="en-US/docs/JavaScript/Reference/Global_Objects/String/split">split</a></code></td>
   <td>Splits a <code>String</code> object into an array of strings by separating the string into substrings.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/slice" title="en-US/docs/JavaScript/Reference/Global_Objects/String/slice">slice</a></code></td>
   <td>Extracts a section of an string and returns a new string.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substring" title="en-US/docs/JavaScript/Reference/Global_Objects/String/substring">substring</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/substr" title="en-US/docs/JavaScript/Reference/Global_Objects/String/substr">substr</a></code></td>
   <td>Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/match" title="en-US/docs/JavaScript/Reference/Global_Objects/String/match">match</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/replace" title="en-US/docs/JavaScript/Reference/Global_Objects/String/replace">replace</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/search" title="en-US/docs/JavaScript/Reference/Global_Objects/String/search">search</a></code></td>
   <td>Work with regular expressions.</td>
  </tr>
  <tr>
   <td><code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase" title="en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase">toLowerCase</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase" title="en-US/docs/JavaScript/Reference/Global_Objects/String/toUpperCase">toUpperCase</a></code></td>
   <td>
    <p>Return the string in all lowercase or all uppercase, respectively.</p>
   </td>
  </tr>
 </tbody>
</table>

<p>autoPreviousNext("JSGChapters")</p>