JavaScript Arrays and Strings for Interview Prep
Introduction
Welcome to this course!
Before we delve deeper into JavaScript essentials for interview prep, let's start with some foundational JavaScript features — specifically, arrays and strings. These features allow JavaScript to group multiple elements, such as numbers or characters, under a single entity.
Revising Arrays and Strings
As our starting point, it's crucial to understand how arrays and strings function in JavaScript. An array is a built-in object that provides a way to store multiple values in a single variable and is mutable (we can change it after creation), while strings are immutable (unalterable post-creation). Let's see examples:
Diving Into Lists
Arrays in JavaScript allow us to organize data so that each item holds a definite position or an index. The index allows us to access or modify each item individually. For accessing elements, JavaScript arrays use zero-based indexing. This means the first element in the array is accessed with index 0, the second element with index 1, and so on. To get the last element of the array, we subtract one from the array's length (fruits.length - 1 in the example below).
Working with arrays in JavaScript is as simple as this:
The splice method takes three parameters:
- The start index where elements will be added or removed.
- The number of elements to remove from the start index.
- The elements to add at the start index.
In the example fruits.splice(fruits.indexOf("banana"), 1);:
fruits.indexOf("banana")returns the index of the element"banana", which is2in this case.- The first parameter
2specifies the start index for removal. - The second parameter
1indicates that we want to remove one element starting from index2.
As a result, the element "banana" at index 2 is removed from the array.
