Strings in JavaScript
Strings are primitive data type. Primitive doesn’t mean old, it just means they are as simple as old.
There are three ways to define strings and all of them are perfectly valid. You can either use single quotes, double-quotes, or backticks. Surprisingly, String is the only data type that uses quotes to define a value.
let myDogsname = "cujo";
let myFishsName = 'nemo';
let myPigsName = `babe`;
How do I check the data type?
If you have a variable in your code and you don't know what data type it is, check it by using a built-in JavaScript function called typeof(). It returns the data type name as “string” as an output. Likewise, it returns “integer” for integers, “float” for float, etc.
let myDogsName = "cujo";
console.log(typeof(myDogsname)); // returns "string"
How long my string value can be?
OK, here’s a little fun piece of information that you probably never going to use but it’s interesting. There is no theoretical limit to how long a string can be. JavaScript supports as many characters as 9,007,199,254,740,991.
Can I change a part of the string value?
Strings in JavaScript are immutable, which means you cannot modify them, but you can only replace them entirely. Confusing, huh! Let’s say if you have a string with value as “value1” and want to change it to “value2”, you can’t simply replace the last letter “1” with letter “2”. Instead, you have to replace the entire value. This also means if you define a string by using the const keyword, you cant even replace the value. Instead, you need to declare a new string variable. For more information about declaring strings, go to https://medium.com/@patelhemil/let-vs-const-in-javascript-bd09aacfe6c9.
let myDogsName = "cujo";
myDogsName = "dogo";
const myFishsName = "nemo";
myFishsName = "orange"; // myfishsname will throw this error: Uncaught TypeError: Assignment to constant variable.
That is all we need to know about the string data type. As I told you earlier, strings are one of the most common data types and are primitively simple!