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.
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:
JavaScript1const myList = [1, 2, 3, 4]; 2let myString = "hello"; 3 4// Now let's try to change the first element of both these features 5// Using index to change the element at the specified index (0 in this case) 6myList[0] = 100; 7myString[0] = "t"; // does not change anything 8// The following method does not change the string in place, 9// but returns a new string where 'h' is replaced with 'H' 10myString.replace('h', 'H'); 11// So it is possible to obtain a new string like this: 12const newString = myString.replace('h', 'H'); 13 14console.log(myList); // prints [100, 2, 3, 4] 15console.log(myString); // prints hello 16console.log(newString); // prints Hello
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:
JavaScript1const fruits = ["apple", "banana", "cherry"]; 2 3// Add a new element at the end 4fruits.push("date"); // ['apple', 'banana', 'cherry', 'date'] 5 6// Inserting an element at a specific position 7fruits.splice(1, 0, "bilberry"); // ['apple', 'bilberry', 'banana', 'cherry', 'date'] 8 9// Removing a particular element 10fruits.splice(fruits.indexOf("banana"), 1); // ['apple', 'bilberry', 'cherry', 'date'] 11 12// Accessing elements using indexing 13const firstFruit = fruits[0]; // apple 14const lastFruit = fruits[fruits.length - 1]; // date
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 is2
in this case.- The first parameter
2
specifies the start index for removal. - The second parameter
1
indicates that we want to remove one element starting from index2
.
As a result, the element "banana"
at index 2
is removed from the array.
Think of strings as a sequence of letters or characters. So, whether you're writing down a message or noting a paragraph, it all boils down to a string in JavaScript. Strings are enclosed by double quotes or single quotes.
JavaScript1const greetingString = "Hello, world!"; 2 3// Accessing characters using indexing 4const firstChar = greetingString[0]; // 'H' 5const lastChar = greetingString[greetingString.length - 1]; // '!' 6 7// Making the entire string lowercase 8const lowercaseGreeting = greetingString.toLowerCase(); // "hello, world!"
Though strings
are immutable, we can use string methods such as .toLowerCase()
, .toUpperCase()
, and .trim()
to effectively work with them. These methods essentially create a new string for us.
Both arrays
and strings
allow us to access individual elements through indexing. In JavaScript, we start counting from 0, implying the first element is at index 0, the second at index 1, and so on. Negative indexing is not directly supported in JavaScript, but you can work around it by adjusting indices based on the length of the collection.
We have many operations we can perform on our lists and strings. We can slice them, concatenate them, and even find an occurrence of a particular element!
JavaScript1const myList = [1, 2, 3, 4, 5]; 2const myString = "Hello"; 3 4// Slicing: `slice` for array and `substring` or `slice` for strings 5// Note: The first index is inclusive and the second index is exclusive 6const sliceList = myList.slice(2, 4); // [3, 4] 7const sliceString = myString.substring(1, 3); // "el" 8 9// Concatenation: `concat` or spread operator for lists and `+` operator or template literals for strings 10const concatenateList = myList.concat([6, 7, 8]); // [1, 2, 3, 4, 5, 6, 7, 8] 11const concatenateListSpread = [...myList, 6, 7, 8]; // [1, 2, 3, 4, 5, 6, 7, 8] 12const concatenateString = `${myString}, world!`; // "Hello, world!" 13const concatenateStringPlus = myString + ", world!"; // "Hello, world!" 14 15// Finding the index of an element in a list or a string 16// `indexOf` returns the first occurrence index of the element 17// returns -1 if the list or the string doesn't contain the element 18const indexList = myList.indexOf(3); // 2 - Index of element '3' 19const indexString = myString.indexOf('e'); // 1 - Index of character 'e' 20 21// Sorting items in array in non-increasing order 22const sortedList = [...myList].sort((a, b) => b - a); // [5, 4, 3, 2, 1]
When using the spread operator for concatenation (...myList
), the elements of myList
are expanded into individual elements and combined with additional elements [6, 7, 8]
.
Template literals, enclosed by backticks (`
), allow you to embed expressions inside a string using ${expression}
. This provides a cleaner and more readable way to concatenate strings compared to using the +
operator.
The spread operator, used in [...myList]
, creates a shallow copy of myList
, ensuring the original array remains unchanged. The sort method with a comparison function (a, b) => b - a
sorts the array in non-increasing order. Here's how it works:
- The comparison function receives two arguments,
a
andb
. - If the returned value is negative,
a
should come beforeb
. - If the returned value is positive,
b
should come beforea
. - If the returned value is zero, their positions are unchanged relative to each other.
By subtracting a
from b
, it sorts the elements in descending order (from highest to lowest). Thus, sortedList
will contain [5, 4, 3, 2, 1]
, a sorted copy of myList
in descending order.
Give yourself a pat on the back! You've navigated through arrays
and strings
, learning how to create, access, and manipulate them via various operations.
Up next, reinforce your understanding with plenty of hands-on practice. The comprehension of these concepts, combined with frequent practice, will enable you to tackle more complex problem statements with ease. Happy coding!