Link Search Menu Expand Document

String, Number, and Array Methods

So far, we have seen two basic data types, string and number. We have also seen how objects allow us to store a group of data and functions together. These structures are great for storing individual pieces of data. To store collections of the same data type together (i.e. a list of numbers), we use arrays. In this section, we will explore how to work with string, numbers, and arrays to store and modify data.

String Methods

Strings can be treated as objects in their own right due to the fact that they store data and have methods natively associated with each string instance. This means that you can modify any string data with these same built-in methods.

Example: Make All Characters in a String Lowercase

Let’s say you have an application where usernames are stored all lowercase. However, people might still include capitals when logging in. To ensure that the data is all lowercase, we can take the user’s input and force casing with the toLowerCase() string method.

let username = window.prompt("What is your username?")
// You can make any string lowercase with the toLowerCase() method.
username = username.toLowerCase()
document.body.innerHTML = "Welcome, " + username

Example Program Flow

  • User types in "BobJohnson" for their username.
  • Program forces casing, storing "bobjohnson" in the username variable.
  • User sees Welcome, bobjohnson on the screen.
PropertyDescription
lengthGets the length of the string (e.g. varName.length).
replace(old, new)Replace a portion of a string with another.
slice(start, end)Returns a segment of the string.
toLowerCase()Returns a lowercase version of the string.
toUpperCase()Returns an uppercase version of the string.

More Practice and Resources

Number Methods

Like strings, numbers have properties and methods associated with them.

Example: Get a Money Value From a User

Let’s say you have an awesome app where users just give you money all the time. Here’s how we could ensure that the money they input is formatted correctly; as a number with two decimal points.

let money = window.prompt("How much money are you going to give me today?")
// Convert the users input string to a float (decimal number)
money = parseFloat(money)
// Ensure that there are two decimal places
money = money.toFixed(2)
document.body.innerHTML = `Thank you for sending me $${money}.`

Example Program Flow

  • User types in "$25" and that is stored as a string in money.
  • After parseFloat, the value of money is 25 (number).
  • After toFixed(2) the value of money is 25.00.
  • User sees Thank you for sending me $25.00. on the screen.
PropertyDescription
Number.MAX_VALUEThe maximum value that can be stored with the number data type.
Number.parseInt(value)Converts a data type like a string to a number (no decimals).
Number.parseFloat(value)Converts a data type like a string to a number (with decimals).
Number.toFixed(decimalPlaces)Represents data as a fixed-point number with a certain number of decimal places.
Number.toPrecision(decimalPlaces)Like toFixed but returns a string instead.

More Practice and Resources

Arrays

An array is a list of values in JavaScript. Arrays are especially powerful for working with a collection of elements in the DOM.

Example 1: Creating and Accessing Values From an Array

// Initialize an array of names.
// Notice the use of const, this is common practice (instead of using let).
const names = ["Jeff", "Katie", "Lisa", "Mike"]
// Access the 0th element in the list.
console.log(names[0])
// Access the 3rd element in the list.
console.log(names[3])
// How many items are in the list?
console.log(names.length)
Jeff
Mike
4

The position of each element in the array is known as the index. Notice that arrays are indexed starting with the number 0 for the leftmost element. The brackets [] are the array accessor operator and allow you to get an element by index.

Example 2: Setting a Value in the Array

You can also use the array accessor operator for changing values in an array.

const names = ["Jeff", "Katie", "Lisa", "Mike"]
// Change the name at index 0 to "Joe"
names[0] = "Jeff"
console.log(names)
["Joe", "Katie", "Lisa", "Mike"]

Array Methods

Here are some methods that allow you to perform more complex operations with arrays.

Example 1: Adding Elements to an Array with push

const names = ["Jeff", "Katie", "Lisa", "Mike"]
// Add Norman to the end of the array.
names.push("Norman")
console.log(names)
["Joe", "Katie", "Lisa", "Mike", "Norman"]

Example 2: Iteration with forEach

In this example, we are getting all the p elements from the DOM and changing the text color to green.

<body>
  <div>
    <p>Here's some text.</p>
    <p>Here's some more text.</p>
    <p>Here's even more text.</p>
  </div>
  <script>
    // Array.from() is needed to convert from an HTMLCollection object to an array
    const paragraphs = Array.from(document.querySelectorAll("p"))
    // forEach executes a callback function for each element in the array
    paragraphs.forEach(function (el, i) {
      el.style.color = "green"
    })
  </script>
</body>

Here's some text.

Here's some more text.

Here's even more text.

Arrow Functions

Here’s a more concise way to write the same JavaScript above, by replacing the function with an arrow function. Arrow functions are typically used as a parameter to another function (in this case, as a parameter to the forEach function). For more on arrow functions, visit w3schools.

const paragraphs = Array.from(document.querySelectorAll())
paragraphs.forEach((el, i) => {
  el.style.color = "green"
})

Example 3: Item Removal with splice

<body>
  <div>
    <p>Here's some text.</p>
    <p>Here's some more text.</p>
    <p>Here's even more text.</p>
  </div>
  <script>
    let paragraphs = Array.from(document.querySelectorAll("p"))
    // clear the div of its paragraphs
    const div = document.querySelector("div")
    div.innerHTML = ""
    // remove the second paragraph (index 1) from the paragraphs array
    paragraphs.splice(1, 1)
    // add each paragraph back to the div
    paragraphs.forEach((el, i) => {
      div.innerHTML += `<p>${el.innerText}</p>`
    })
  </script>
</body>

Here's some text.

Here's even more text.

MethodDescription
forEach(callbackFn)Executes a callback function for each element in the array.
pop()Removes the last item of the array.
push(item)Appends an item to the end of the array.
sort(compareFn)Given a compare function, sorts the array.
splice(index, amount)Removes a certain amount of element(s) from the array by index. You can also use splice to insert elements at a specific index.

More Practice and Resources

Practice Task: Remove Items From List

Make an app that allows you to remove items from a list with the click of a button. Here’s some example starting HTML:

<h1>Favorite Sports</h1>
<button>Remove Item</button>
<ul>
  <li>Ultimate Frisbee</li>
  <li>Basketball</li>
  <li>Running</li>
</ul>
  • Have a list of at least 3 items in HTML. Use a <ol> or <ul> element for the list wrapper element and <li> elements for the list items. (2 pts)
  • Have a button that removes one item from the list at a time. (6 pts)
    • Which item the button removes is up to you.
    • If there are no items, do nothing.
    • After an item is removed, the updated list should be shown in the HTML.
  • Use at least one of the following array methods: forEach, splice. (2 pts)