Week 11: Demo


String Basics

Strings are variable types that hold alphanumeric information. Strings are always defined by wrapping the value with quotation marks. Even a number can be treated as a string by wrapping it in quotation marks. Below are a number of examples of strings being declared and defined.

var stringA = "This is a whole sentence";
var stringB = "word";
var stringC = "123";

Strings can be concatenated by using the + (plus sign) operator, which is also used to perform addition on numbers.

var stringA = "Happy ";
var stringB = "Birthday!";
var stringC = stringA + stringB;
// stringC will be assigned the value "Happy Birthday!"

One of the most useful properties of a string is its length property, which will return the number of characters contained in the string.

var stringA = "This is a whole sentence";
// this will print to the console the number 24.

String Methods

Since strings are technically objects in JavaScript, they have both properties and methods that can be read from and used to manipulate the string. All string methods return a new string. They don't modify the original string.

String Comparison

Strings can be compared against each other using the == (double equal sign) operator or the === (triple equal sign) operator. The double eual sign operator will check to see if the value is the same, whereas the triple equal sign operator will check to see if the value is the same AND the data type is the same.

var stringA = "password";
if(stringA == "password"){
} else {
    console.log("access denied");

It's important to remember that strings are case sensitive, so "Password" will not match with "password". If you want to ensure case-insensitivity when making a comparison of strings, then convert both of them to all upper case or all lower case so that case is consistent across all characters.