- .length
- Пример
- Как понять
- JavaScript String length
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- String: length
- Try it
- Value
- Description
- Examples
- Basic usage
- Strings with length not equal to the number of characters
- Assigning to length
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Array: length
- Try it
- Value
- Description
- Examples
- Iterating over an array
- Shortening an array
- Create empty array of fixed length
- Array with non-writable length
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
.length
Свойство length хранит длину строки, которое обычно совпадает с количеством символов в ней. Если в строке есть непростые символы, вроде эмодзи, они могут удлинять строку больше, чем на единицу.
Длина пустой строки равна 0.
Пример
Скопировать ссылку «Пример» Скопировано
const phrase = 'Съешь ещё этих мягких французских булок, да выпей же чаю'console.log(phrase.length)// 56 const empty = ''console.log(empty.length)// 0 const emoji = '👩💻'console.log(emoji.length)// 5 🤷♂️
const phrase = 'Съешь ещё этих мягких французских булок, да выпей же чаю' console.log(phrase.length) // 56 const empty = '' console.log(empty.length) // 0 const emoji = '👩💻' console.log(emoji.length) // 5 🤷♂️
Как понять
Скопировать ссылку «Как понять» Скопировано
Строки в JavaScript хранятся в виде последовательности символов в формате UTF-16. UTF-16 использует понятие юнита — одного значения из таблицы UTF-16. Все символы мировых алфавитов представляются в виде одного юнита.
Редкие символы могут использовать несколько юнитов. Если вы решите использовать символы из древнеегипетской письменности, то каждый из них будет занимать два юнита:
console.log('𓀿'.length)// 2
console.log('𓀿'.length) // 2
Эмодзи состоят из нескольких юнитов. Количество использованных юнитов зависит от эмодзи:
console.log('👩💻'.length)// 5console.log('😀'.length)// 2
console.log('👩💻'.length) // 5 console.log('😀'.length) // 2
JavaScript String length
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
String: length
The length data property of a String value contains the length of the string in UTF-16 code units.
Try it
Value
Property attributes of String: length | |
---|---|
Writable | no |
Enumerable | no |
Configurable | no |
Description
This property returns the number of code units in the string. JavaScript uses UTF-16 encoding, where each Unicode character may be encoded as one or two code units, so it’s possible for the value returned by length to not match the actual number of Unicode characters in the string. For common scripts like Latin, Cyrillic, wellknown CJK characters, etc., this should not be an issue, but if you are working with certain scripts, such as emojis, mathematical symbols, or obscure Chinese characters, you may need to account for the difference between code units and characters.
The language specification requires strings to have a maximum length of 2 53 — 1 elements, which is the upper limit for precise integers. However, a string with this length needs 16384TiB of storage, which cannot fit in any reasonable device’s memory, so implementations tend to lower the threshold, which allows the string’s length to be conveniently stored in a 32-bit integer.
- In V8 (used by Chrome and Node), the maximum length is 2 29 — 24 (~1GiB). On 32-bit systems, the maximum length is 2 28 — 16 (~512MiB).
- In Firefox, the maximum length is 2 30 — 2 (~2GiB). Before Firefox 65, the maximum length was 2 28 — 1 (~512MiB).
- In Safari, the maximum length is 2 31 — 1 (~4GiB).
For an empty string, length is 0.
The static property String.length is unrelated to the length of strings. It’s the arity of the String function (loosely, the number of formal parameters it has), which is 1.
Since length counts code units instead of characters, if you want to get the number of characters, you can first split the string with its iterator, which iterates by characters:
function getCharacterLength(str) // The string iterator that is used here iterates over characters, // not mere code units return [. str].length; > console.log(getCharacterLength("A\uD87E\uDC04Z")); // 3
Examples
Basic usage
const x = "Mozilla"; const empty = ""; console.log(`$x> is $x.length> code units long`); // Mozilla is 7 code units long console.log(`The empty string has a length of $empty.length>`); // The empty string has a length of 0
Strings with length not equal to the number of characters
const emoji = "😄"; console.log(emoji.length); // 2 console.log([. emoji].length); // 1 const adlam = "𞤲𞥋𞤣𞤫"; console.log(adlam.length); // 8 console.log([. adlam].length); // 4 const formula = "∀𝑥∈ℝ,𝑥²≥0"; console.log(formula.length); // 11 console.log([. formula].length); // 9
Assigning to length
Because string is a primitive, attempting to assign a value to a string’s length property has no observable effect, and will throw in strict mode.
const myString = "bluebells"; myString.length = 4; console.log(myString); // "bluebells" console.log(myString.length); // 9
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on May 31, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Array: length
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
Try it
Value
A nonnegative integer less than 2 32 .
Property attributes of Array: length | |
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
Description
The value of the length property is a nonnegative integer with a value less than 2 32 .
const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length
The array object observes the length property, and automatically syncs the length value with the array’s content. This means:
- Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
- Setting any array index (a nonnegative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
- Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.
When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.
const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, ] arr.forEach((element) => console.log(element)); // 1 // 2
Examples
Iterating over an array
In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.
const numbers = [1, 2, 3, 4, 5]; const length = numbers.length; for (let i = 0; i length; i++) numbers[i] *= 2; > // numbers is now [2, 4, 6, 8, 10]
Shortening an array
The following example shortens the array numbers to a length of 3 if the current length is greater than 3.
const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) numbers.length = 3; > console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; the extra elements are deleted
Create empty array of fixed length
Setting length to a value greater than the current length creates a sparse array.
const numbers = []; numbers.length = 3; console.log(numbers); // [empty x 3]
Array with non-writable length
The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.
"use strict"; const numbers = [1, 2, 3, 4, 5]; Object.defineProperty(numbers, "length", writable: false >); numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]' numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.