JavaScript:
Finding the length of a string
How to:
JavaScript keeps it simple with the .length
property.
let greeting = 'Hello, World!';
console.log(greeting.length); // Output: 13
An empty string equals zero:
let empty = '';
console.log(empty.length); // Output: 0
Even spaces count:
let spaces = ' ';
console.log(spaces.length); // Output: 3
Deep Dive
The .length
property’s been around since the early JS days. It’s fast, as it’s not really a function but an instance property that’s stored with the string object.
Alternatives like looping through each character manually to count them exist, but they’re like taking stairs instead of the elevator – use only when necessary.
JavaScript treats strings as immutable, meaning .length
doesn’t change unless you assign a new string to the variable. The length is computed when the string is created.
Implementation wise, remember Unicode. Some characters (like emoji or certain language alphabets) might be represented by two or more code units in JavaScript’s UTF-16 encoding:
let smiley = '😊';
console.log(smiley.length); // Output: 2
Even if it looks like one character, some might count as two “lengths” because of how they’re encoded. Just something to remember if you’re dealing with diverse character sets!