JS Strings

JavaScript Strings: Representing and Manipulating Text

A JavaScript String is a sequence of characters, typically used to represent text. Whether you are displaying a simple message to a user or parsing complex data, strings are one of the most fundamental and frequently used data types in JavaScript.


What is a JavaScript String?

In JavaScript, strings are used to store and manipulate text. They can be enclosed within single quotes ('...'), double quotes ("..."), or backticks (`...`) for template literals.

JavaScript String Example:

let greeting = "Hello, World!";
let singleChar = 'A';

console.log(greeting); console.log(singleChar);


No Separate Character Type

In JavaScript, there is no separate character type. This is similar to Python, but quite different from languages like C, C++, and Java (which use a specific char type).

Because there is no dedicated character data type, a single-character string is used whenever we need to represent a single character in JavaScript.

// This is just a string with a length of 1
let letter = "A"; 
console.log(typeof letter); // Outputs: "string"

String Immutability in JavaScript

Just like in Java and Python, strings in JavaScript are immutable.

Immutability means that once a string is created, its value cannot be changed or modified directly in memory. If you perform an operation that seems to alter a string (like replacing a word or converting it to uppercase), JavaScript does not change the original string. Instead, it creates and returns a completely new string.

String Immutability Example:

let str = "Hello";

// Trying to change the first character directly will NOT work str[0] = "Y";

console.log(str); // Still outputs "Hello"


Exercise

?

Are strings in JavaScript mutable or immutable?