chore(curriculum): add JS array transcripts (#58461)

Co-authored-by: Tom <20648924+moT01@users.noreply.github.com>
This commit is contained in:
Dario-DC 2025-02-05 21:57:30 +01:00 committed by GitHub
parent 672ab0a684
commit 1743d9c434
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
10 changed files with 600 additions and 61 deletions

View File

@ -10,6 +10,41 @@ dashedName: what-are-the-key-characteristics-of-javascript-arrays
Watch the video lecture and answer the questions below.
# --transcript--
What are key characteristics of JavaScript arrays?
An array in JavaScript is an ordered collection of values, each identified by a numeric index. The values in a JavaScript array can be of different data types, including numbers, strings, booleans, objects, and even other arrays.
To create an array in JavaScript, you can use square brackets, `[]`, and separate the values with commas. Here's an example:
```js
let fruits = ["apple", "banana", "orange"];
```
In this example, we declare a variable `fruits` and assign it an array containing three string values: `apple`, `banana`, and `orange`.
One of the key characteristics of arrays is that they are zero-indexed, meaning that the first element in an array has an index of `0`, the second element has an index of `1`, and so on. You can access individual elements in an array using their index. For example:
```js
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "orange"
```
In this example, we use the index `0` to access the first element (`apple`) and the index `2` to access the third element (`orange`).
Arrays in JavaScript have a special `length` property that returns the number of elements in the array. You can access this property using the `length` keyword. For example:
```js
let fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 3
```
Another key characteristic of arrays in JavaScript is that they are dynamic, meaning that their size can change after they are created. You can add or remove elements from an array using various array methods, such as `push()`, `pop()`, `shift()`, `unshift()`, `splice()`, and more. These methods will be taught in upcoming lectures videos.
JavaScript arrays are versatile and useful when it comes to data storage inside your programs. Throughout this module, you'll get to see firsthand how working with arrays will help you efficiently manage and manipulate collections of data.
# --questions--
## --text--
@ -94,7 +129,7 @@ Remember that arrays in JavaScript are zero-indexed.
What will be the output of the following code?
```js
let colors = ['red', 'green', 'blue'];
let colors = ["red", "green", "blue"];
console.log(colors.length);
```

View File

@ -10,6 +10,43 @@ dashedName: how-do-you-access-and-update-elements-in-an-array
Watch the lecture video and answer the questions below.
# --transcript--
How do you access and update elements in an array?
In the previous lecture video, you were first introduced to working with arrays and accessing different elements from arrays. Here is a reminder on how to access the second element from an array:
```js
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // "banana"
```
Since arrays are zero based indexed, the first element will be at index `0`, the second index will be at index `1`, etc. It's important to note that if you try to access an index that doesn't exist in the array, JavaScript will return `undefined`.
```js
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[3]); // undefined
```
In this example, there is no index `3` for the `fruits` array. So the log will show `undefined`. Now, let's look at how to update elements in an array. You can update an element by assigning a new value to a specific index.
```js
let fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "cherry"]
```
In this example, we've replaced `banana` with `blueberry` at index `1`. This method allows you to change any element in the array, as long as you know its index. You can also add new elements to an array by assigning a value to an index that doesn't yet exist:
```js
let fruits = ["apple", "banana", "cherry"];
fruits[3] = "date";
console.log(fruits); // Outputs: ["apple", "blueberry", "cherry", "date"]
```
However, exercise caution when doing this. If you assign a value to an index that is much larger than the current length of the array, you will create undefined elements for the indices in between, which can lead to unexpected behavior. As you continue to work with JavaScript, you'll find that these ways of accessing and updating array elements are fundamental to many programming tasks. Whether you're building a simple todo list or processing complex data structures, these skills will be invaluable.
# --questions--
## --text--

View File

@ -10,6 +10,66 @@ dashedName: how-do-you-add-and-remove-elements-from-the-beginning-and-end-of-an-
Watch the lecture video and answer the questions below.
# --transcript--
How do you add/remove elements from the beginning and end of an array?
Arrays in JavaScript are dynamic, which means you can easily add or remove elements from them. There are four main methods for adding and removing elements from the beginning and end of an array: `push()`, `pop()`, `shift()`, and `unshift()`. Let's explore each of these methods in detail.
The `push()` method is used to add one or more elements to the end of an array. The return value for the `push()` method is the new length of the array. Here's an example of adding a new fruit to the existing `fruits` array:
```js
const fruits = ["apple", "banana"];
const newLength = fruits.push("orange");
console.log(newLength); // 3
console.log(fruits); // ["apple", "banana", "orange"]
```
In this example, we start with an array called `fruits` which contains two elements. We then use the `push()` method to add the string `orange` to the end of the array.
You might have noticed that we are using `const` when declaring the `fruits` array. But why is it possible to add more elements to this `fruits` array when `fruits` is a constant? This is possible because declaring an array with the `const` keyword creates a reference to the array. While the array itself is mutable and can be modified, you cannot reassign a new value to the `fruits` constant, like this:
```js
const fruits = ["apple", "banana"];
fruits = ["This", "will", "not", "work"];
console.log(fruits); // Uncaught TypeError: Assignment to constant variable.
```
The next method we will look at is the `pop()` method. The `pop()` method removes the last element from an array and returns that element. It also modifies the original array. Here's how it works:
```js
let fruits = ["apple", "banana", "orange"];
let lastFruit = fruits.pop();
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "orange"
```
In this example, we start with an array of three fruits. The `pop()` method removes the last element (`orange`) from the array and returns it. The original `fruits` array is modified and contains only two elements.
The `unshift()` method adds one or more elements to the beginning of an array and returns its new length. It works similarly to `push()`, but modifies the start of the array instead of the end. Here's an example:
```js
let numbers = [2, 3];
let newLength = numbers.unshift(1);
console.log(numbers); // [1, 2, 3]
console.log(newLength); // 3
```
In this example, we use `unshift()` to add the number `1` to the beginning of the `numbers` array. The method returns the new length of the array, which is `3`.
Finally, the `shift()` method removes the first element from an array and returns that element. It's similar to `pop()`, but it works at the beginning of the array instead of the end. Here's how it works:
```js
let colors = ["red", "green", "blue"];
let firstColor = colors.shift();
console.log(colors); // ["green", "blue"]
console.log(firstColor); // "red"
```
In this example, we start with an array of three colors. The `shift()` method removes the first element (`red`) from the array and returns it. The original `colors` array is modified to contain only two elements.
Note that while `push()` and `unshift()` can add multiple elements at once, `pop()` and `shift()` remove only one element at a time.
# --questions--
## --text--
@ -60,7 +120,7 @@ Consider the order of operations and what each method does to the array.
What will be the output of the following code?
```js
let arr = ['a', 'b', 'c', 'd'];
let arr = ["a", "b", "c", "d"];
let first = arr.shift();
let last = arr.pop();
console.log(first, last, arr);
@ -68,11 +128,11 @@ console.log(first, last, arr);
## --answers--
`'a' 'd' ['b', 'c']`
`"a" "d" ["b", "c"]`
---
`'d' 'a' ['b', 'c']`
`"d" "a" ["b", "c"]`
### --feedback--
@ -80,7 +140,7 @@ Remember that `shift()` removes from the beginning and `pop()` removes from the
---
`'a' 'b' ['c', 'd']`
`"a" "b" ["c", "d"]`
### --feedback--
@ -88,7 +148,7 @@ Remember that `shift()` removes from the beginning and `pop()` removes from the
---
`'b' 'c' ['a', 'd']`
`"b" "c" ["a", "d"]`
### --feedback--
@ -103,19 +163,19 @@ Remember that `shift()` removes from the beginning and `pop()` removes from the
What will be the result of the following code?
```js
let arr = ['a', 'b', 'c'];
arr.unshift('x', 'y');
let arr = ["a", "b", "c"];
arr.unshift("x", "y");
arr.pop();
console.log(arr);
```
## --answers--
`['x', 'y', 'a', 'b']`
`["x", "y", "a", "b"]`
---
`['x', 'y', 'a', 'b', 'c']`
`["x", "y", "a", "b", "c"]`
### --feedback--
@ -123,7 +183,7 @@ Pay attention to the order of operations and what each method does to the array.
---
`['a', 'b', 'x', 'y']`
`["a", "b", "x", "y"]`
### --feedback--
@ -131,7 +191,7 @@ Pay attention to the order of operations and what each method does to the array.
---
`['y', 'x', 'a', 'b']`
`["y", "x", "a", "b"]`
### --feedback--

View File

@ -10,6 +10,52 @@ dashedName: what-is-the-difference-between-one-dimensional-and-two-dimensional-a
Watch the lecture video and answer the questions below.
# --transcript--
What is the difference between one-dimensional and two-dimensional arrays?
In programming, arrays are fundamental data structures used to store collections of elements. Understanding the difference between one-dimensional and two-dimensional arrays is crucial for organizing and manipulating data effectively. Let's explore these concepts in a way that's easy for beginners to grasp.
A one-dimensional array, often called an array, is like a single row of boxes. Imagine you have a line of storage lockers at a train station. Each locker can hold one item, and you can access any locker directly if you know its number.
In programming terms, each item in a one-dimensional array is accessed using a single index. For example, in JavaScript, you might create and use a one-dimensional array like this:
```js
let fruits = ["apple", "banana", "cherry", "date"];
console.log(fruits[2]); // Outputs: "cherry"
```
Here, `fruits` is a one-dimensional array. You can think of it as a single row of fruit names. To access any fruit, you use one number (the index) inside square brackets.
Now, let's move on to two-dimensional arrays. If a one-dimensional array is like a single row of lockers, a two-dimensional array is like a grid of lockers multiple rows and columns. In programming, a two-dimensional array is essentially an array of arrays. It's used to represent data that has a natural grid-like structure, such as a chessboard, a spreadsheet, or pixels in an image.
To access an element in a two-dimensional array, you need two indices: one for the row and one for the column. Here's an example of how you might create and use a two-dimensional array in JavaScript:
```js
let chessboard = [
["R", "N", "B", "Q", "K", "B", "N", "R"],
["P", "P", "P", "P", "P", "P", "P", "P"],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "],
["p", "p", "p", "p", "p", "p", "p", "p"],
["r", "n", "b", "q", "k", "b", "n", "r"]
];
console.log(chessboard[0][3]); // Outputs: "Q"
```
In this example, `chessboard` is a two-dimensional array representing a chess game's initial setup. To access the queen (`Q`) in the top row, we use two indices: `[0][3]`. The first index, `0`, selects the first row, and the second index, `3`, selects the fourth column in that row.
The key difference between one-dimensional and two-dimensional arrays lies in how you access and organize the data. One-dimensional arrays use a single index and are suitable for linear data like lists or sequences. Two-dimensional arrays use two indices and are ideal for grid-like data structures.
It's worth noting that in JavaScript, two-dimensional arrays are actually arrays of arrays. This means each element of the outer array is itself an array. This nested structure allows for great flexibility but also requires careful handling to avoid errors.
As you progress in your programming journey, you'll find that choosing between one-dimensional and two-dimensional arrays depends on the nature of your data and how you need to manipulate it.
One-dimensional arrays are simpler and sufficient for many tasks, while two-dimensional arrays become invaluable when dealing with more complex, structured data.
# --questions--
## --text--

View File

@ -10,6 +10,80 @@ dashedName: what-is-array-destructuring-and-how-does-it-work
Watch the lecture video and answer the questions below.
# --transcript--
What is array destructuring, and how does it work?
Array destructuring is a feature in JavaScript that allows you to extract values from arrays and assign them to variables in a more concise and readable way. It provides a convenient syntax for unpacking array elements into distinct variables.
This technique is particularly useful when working with arrays and functions that return multiple values. Here is an example of using array destructuring:
```js
let fruits = ["apple", "banana", "orange"];
let [first, second, third] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(third); // "orange"
```
In this example, we have an array called `fruits` with three elements. Using array destructuring, we assign the first element to the variable `first`, the second element to `second`, and the third element to `third`. This allows us to easily access individual elements of the array without using index notation.
Here is what it would look like if you accessed each of those elements by their index instead of using array destructuring:
```js
const fruits = ["apple", "banana", "orange"];
const first = fruits[0];
const second = fruits[1];
const third = fruits[2];
console.log(first); // "apple"
console.log(second); // "banana"
console.log(third); // "orange"
```
Array destructuring also allows you to skip elements you're not interested in by using commas. For instance:
```js
let colors = ["red", "green", "blue", "yellow"];
let [firstColor, , thirdColor] = colors;
console.log(firstColor); // Output: "red"
console.log(thirdColor); // Output: "blue"
```
In this example, we skip the second element of the `colors` array by using an extra comma. This assigns `red` to `firstColor` and `blue` to `thirdColor`, effectively ignoring `green`.
Another powerful feature of array destructuring is the ability to use default values. If the array has fewer elements than the variables you're trying to assign, you can provide default values:
```js
let numbers = [1, 2];
let [a, b, c = 3] = numbers;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
```
Here, we assign default value `3` to `c` because the `numbers` array doesn't have a third element.
Now, let's discuss the rest syntax, denoted by three dots (`...`). It allows you to capture the remaining elements of an array that havent been destructured into a new array. Here's how it works:
```js
let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let [first, second, ...rest] = fruits;
console.log(first); // "apple"
console.log(second); // "banana"
console.log(rest); // ["orange", "mango", "kiwi"]
```
In this example, `first` and `second` capture the first two elements of the `fruits` array, and `rest` captures all remaining elements as a new array. The rest syntax must be the last element in the destructuring pattern.
Array destructuring is a powerful feature that can make your code more concise and easier to read. It's especially useful when working with arrays, and when you need to extract specific elements from an array.
# --questions--
## --text--
@ -59,8 +133,8 @@ Pay attention to the comma placement in the destructuring assignment and remembe
What will be the output of the following code?
```js
let colors = ['red', 'green', 'blue'];
let [primary, secondary, tertiary, quaternary = 'yellow'] = colors;
let colors = ["red", "green", "blue"];
let [primary, secondary, tertiary, quaternary = "yellow"] = colors;
console.log(quaternary);
```
@ -82,7 +156,7 @@ Consider what happens when you try to destructure more variables than there are
---
`'yellow'`
`"yellow"`
---
@ -101,14 +175,14 @@ Consider what happens when you try to destructure more variables than there are
What will be the output of the following code?
```js
let fruits = ['apple', 'banana', 'orange', 'grape'];
let fruits = ["apple", "banana", "orange", "grape"];
let [first, ...rest, last] = fruits;
console.log(first, rest, last);
```
## --answers--
`'apple' ['banana', 'orange'] 'grape'`
`"apple" ["banana", "orange"] "grape"`
### --feedback--
@ -116,7 +190,7 @@ Consider the placement of the rest syntax in the destructuring assignment and th
---
`'apple' ['banana', 'orange', 'grape'] undefined`
`"apple" ["banana", "orange", "grape"] undefined`
### --feedback--
@ -128,7 +202,7 @@ This will throw a `SyntaxError`.
---
`'apple' [] 'grape'`
`"apple" [] "grape"`
### --feedback--

View File

@ -10,6 +10,46 @@ dashedName: how-do-you-get-the-index-for-an-element-in-an-array-using-the-indexo
Watch the video lecture and answer the questions below.
# --transcript--
How do you get the index for an element in an array using the `indexOf` method?
In JavaScript, the `indexOf()` method is useful for finding the first index of a specific element within an array. If the element cannot be found, then it will return `-1`. Here is the basic syntax:
```js
array.indexOf(element, fromIndex)
```
`element` represents the value you want to search for within the array, and the `fromIndex` parameter is the position from which the search should start. The `fromIndex` parameter is optional. If `fromIndex` is not provided, the search starts from the beginning of the array. Let's look at an example:
```js
let fruits = ["apple", "banana", "orange", "banana"];
let index = fruits.indexOf("banana");
console.log(index); // 1
```
In this example, we have an array `fruits` containing various fruit names. We use the `indexOf()` method to find the index of the string `banana` within the `fruits` array. Since `banana` is present at index `1`, the method returns `1`, which is stored in the `index` variable and logged to the console.
If the element you're searching for is not found in the array, `indexOf()` returns `-1`. For example:
```js
let fruits = ["apple", "banana", "orange"];
let index = fruits.indexOf("grape");
console.log(index); // -1
```
Here, we search for the string `grape` in the fruits array using `indexOf()`. Since `grape` is not present in the array, the method returns `-1`, which is stored in the `index` variable and logged to the console.
If you want to start looking for an item after a specific index number, then you can pass a second argument like in this example:
```js
let colors = ["red", "green", "blue", "yellow", "green"];
let index = colors.indexOf("green", 3);
console.log(index); // 4
```
In this example, the search does not start from the start of an array, rather it starts from the index number `3` which is `yellow` and gets the output of `4`.
# --questions--
## --text--
@ -28,7 +68,7 @@ console.log(index);
### --feedback--
The `indexOf()` method returns the index of the first occurrence of the given element in the array.
The ``indexOf()`` method returns the index of the first occurrence of the given element in the array.
---
@ -40,7 +80,7 @@ The `indexOf()` method returns the index of the first occurrence of the given el
### --feedback--
The `indexOf()` method returns the index of the first occurrence of the given element in the array.
The ``indexOf()`` method returns the index of the first occurrence of the given element in the array.
---
@ -48,7 +88,7 @@ The `indexOf()` method returns the index of the first occurrence of the given el
### --feedback--
The `indexOf()` method returns the index of the first occurrence of the given element in the array.
The ``indexOf()`` method returns the index of the first occurrence of the given element in the array.
## --video-solution--
@ -59,8 +99,8 @@ The `indexOf()` method returns the index of the first occurrence of the given el
What will be the output of the following code?
```js
let fruits = ['apple', 'banana', 'orange', 'grape'];
let index = fruits.indexOf('kiwi');
let fruits = ["apple", "banana", "orange", "grape"];
let index = fruits.indexOf("kiwi");
console.log(index);
```
@ -70,7 +110,7 @@ console.log(index);
### --feedback--
The `indexOf()` method returns `-1` if the given element is not found in the array.
The ``indexOf()`` method returns `-1` if the given element is not found in the array.
---
@ -82,7 +122,7 @@ The `indexOf()` method returns `-1` if the given element is not found in the arr
### --feedback--
The `indexOf()` method returns `-1` if the given element is not found in the array.
The ``indexOf()`` method returns `-1` if the given element is not found in the array.
---
@ -90,7 +130,7 @@ An error will occur.
### --feedback--
The `indexOf()` method returns `-1` if the given element is not found in the array.
The ``indexOf()`` method returns `-1` if the given element is not found in the array.
## --video-solution--
@ -101,8 +141,8 @@ The `indexOf()` method returns `-1` if the given element is not found in the arr
What will be the output of the following code?
```js
let colors = ['red', 'green', 'blue', 'yellow', 'green'];
let index = colors.indexOf('green', 2);
let colors = ["red", "green", "blue", "yellow", "green"];
let index = colors.indexOf("green", 2);
console.log(index);
```
@ -112,7 +152,7 @@ console.log(index);
### --feedback--
The `indexOf()` method can take a second argument to specify the starting index for the search.
The ``indexOf()`` method can take a second argument to specify the starting index for the search.
---
@ -120,7 +160,7 @@ The `indexOf()` method can take a second argument to specify the starting index
### --feedback--
The `indexOf()` method can take a second argument to specify the starting index for the search.
The ``indexOf()`` method can take a second argument to specify the starting index for the search.
---
@ -132,7 +172,7 @@ The `indexOf()` method can take a second argument to specify the starting index
### --feedback--
The `indexOf()` method can take a second argument to specify the starting index for the search.
The ``indexOf()`` method can take a second argument to specify the starting index for the search.
## --video-solution--

View File

@ -10,6 +10,92 @@ dashedName: how-do-you-add-remove-elements-from-the-middle-of-an-array
Watch the lecture video and answer the questions below.
# --transcript--
How do you add/remove elements from the middle of an array?
The `splice()` method in JavaScript is a powerful way for modifying arrays. It allows you to add or remove elements from any position in an array, including the middle. The return value for the `splice()` method will be an array of the items removed from the array. If nothing was removed, then an empty array will be returned.
It is important to note that this method will mutate the original array, modifying it in place rather than creating a new array. This is something to be aware of when working with `splice()`. Here is the basic syntax:
```js
array.splice(startIndex, itemsToRemove, item1, item2)
```
`startIndex` specifies the index at which to begin modifying the array, while `itemsToRemove` is an optional parameter indicating how many elements to remove. If `itemsToRemove` is omitted, `splice()` will remove all elements from `startIndex` to the end of the array. The subsequent parameters (`item1`, `item2`, and so on) are the elements to be added to the array, beginning at the start index.
Let's start with an example of removing elements from the middle of an array:
```js
let fruits = ["apple", "banana", "orange", "mango", "kiwi"];
let removed = fruits.splice(2, 2);
console.log(fruits); // ["apple", "banana", "kiwi"]
console.log(removed); // ["orange", "mango"]
```
In this example, `splice(2, 2)` starts at index `2` and removes `2` elements. The modified array will now consist of only `apple`, `banana`, and `kiwi`. Now, let's look at how to add elements to the middle of an array:
```js
let colors = ["red", "green", "blue"];
colors.splice(1, 0, "yellow", "purple");
console.log(colors); // ["red", "yellow", "purple", "green", "blue"]
```
Here, `splice(1, 0, "yellow", "purple")` starts at index `1`, removes `0` elements, and inserts `yellow` and `purple`. The second parameter (`0`) means no elements are removed before insertion. You can also use `splice()` to simultaneously remove and add elements:
```js
let numbers = [1, 2, 3, 4, 5];
numbers.splice(1, 2, 6, 7, 8);
console.log(numbers); // [1, 6, 7, 8, 4, 5]
```
In this case, `splice(1, 2, 6, 7, 8)` starts at index `1`, removes `2` elements (`2` and `3`), and inserts `6`, `7`, and `8`. If you need to keep the original array unchanged, you should create a copy before using `splice()`:
```js
let original = [1, 2, 3, 4, 5];
let copy = [...original];
copy.splice(2, 1, 6);
console.log(original); // [1, 2, 3, 4, 5]
console.log(copy); // [1, 2, 6, 4, 5]
```
In this example, to create a copy of the `original` array without modifying it, we use the spread operator (`...`). The spread operator will create a shallow copy of the elements of the `original` array into a new array. You will learn more about this in future lecture videos.
When we use `copy.splice(2, 1, 6)`, it modifies the copy array by removing the element at index `2` (which is `3`) and inserting the new element `6` at that position.
One common use case for `splice()` is to remove a single element from an array when you know its index:
```js
let fruits = ["apple", "banana", "orange", "mango"];
let indexToRemove = fruits.indexOf("orange");
if (indexToRemove !== -1) {
fruits.splice(indexToRemove, 1);
}
console.log(fruits); // ["apple", "banana", "mango"]
```
In this example, we first use the `indexOf()` method to find the index of the element `orange` in the `fruits` array. The `indexOf()` method returns the index of the first occurrence of the given element or `-1` if the element is not found in the array.
We then compare `indexToRemove` with `-1` to ensure that the element exists in the array before attempting to remove it. If `indexToRemove` is not equal to `-1` (meaning the element is found), we use `splice()` to remove one element starting from the `indexToRemove` position.
You can also use `splice()` to clear an array by removing all elements:
```js
let array = [1, 2, 3, 4, 5];
array.splice(0);
console.log(array); // []
```
While `splice()` is powerful, it's worth noting that for very large arrays, it can be less efficient than other methods, especially when modifying the beginning of the array. This is because `splice()` may need to shift all subsequent elements. In such cases, if you're only adding or removing elements at the end of the array, methods like `push()`, `pop()`, `unshift()`, and `shift()` might be more appropriate.
In conclusion, the `splice()` method is a versatile way for modifying arrays in JavaScript. It allows for precise control over adding and removing elements from any position in an array. Understanding how to use `splice()` effectively can greatly enhance your ability to manipulate arrays in your JavaScript code.
# --questions--
## --text--
@ -32,7 +118,7 @@ console.log(arr);
### --feedback--
Consider what the second parameter (`0`) means in the `splice()` method.
Consider what the second parameter (`0`) means in the ``splice()`` method.
---
@ -40,7 +126,7 @@ Consider what the second parameter (`0`) means in the `splice()` method.
### --feedback--
Consider what the second parameter (`0`) means in the `splice()` method.
Consider what the second parameter (`0`) means in the ``splice()`` method.
---
@ -48,7 +134,7 @@ Consider what the second parameter (`0`) means in the `splice()` method.
### --feedback--
Consider what the second parameter (`0`) means in the `splice()` method.
Consider what the second parameter (`0`) means in the ``splice()`` method.
## --video-solution--
@ -56,7 +142,7 @@ Consider what the second parameter (`0`) means in the `splice()` method.
## --text--
Which of the following `splice()` calls would remove the last two elements from an array?
Which of the following ``splice()`` calls would remove the last two elements from an array?
## --answers--
@ -64,7 +150,7 @@ Which of the following `splice()` calls would remove the last two elements from
### --feedback--
Think about how negative indices work with `splice()` and what the second parameter represents.
Think about how negative indices work with ``splice()`` and what the second parameter represents.
---
@ -72,7 +158,7 @@ Think about how negative indices work with `splice()` and what the second parame
### --feedback--
Think about how negative indices work with `splice()` and what the second parameter represents.
Think about how negative indices work with ``splice()`` and what the second parameter represents.
---
@ -84,7 +170,7 @@ Think about how negative indices work with `splice()` and what the second parame
### --feedback--
Think about how negative indices work with `splice()` and what the second parameter represents.
Think about how negative indices work with ``splice()`` and what the second parameter represents.
## --video-solution--
@ -92,7 +178,7 @@ Think about how negative indices work with `splice()` and what the second parame
## --text--
What does the `splice()` method return?
What does the ``splice()`` method return?
## --answers--

View File

@ -10,6 +10,56 @@ dashedName: how-can-you-check-if-an-array-contains-a-certain-value
Watch the lecture video and answer the questions below.
# --transcript--
How can you check if an array contains a certain value?
In JavaScript, the `includes()` method is a simple and efficient way to check if an array contains a specific value. This method returns a boolean value: `true` if the array contains the specified element, and `false` otherwise.
The `includes()` method is particularly useful when you need to quickly verify the presence of an element in an array without needing to know its exact position. Let's start with an example of how to use the `includes()` method:
```js
let fruits = ["apple", "banana", "orange", "mango"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
```
In this example, we have an array of fruits. We use the `includes()` method to check if `banana` is in the array. It returns `true` because `banana` is indeed present. We then check for `grape`, which returns `false` because it's not in the array.
The `includes()` method is case-sensitive when dealing with strings. This means that `Banana` with a capital B and `banana` with all lowercase letters are considered different values. Here's an example that illustrates this:
```js
let fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("Banana")); // false
```
In this case, `banana` (all in lowercase) is found in the array, but `Banana` (with the first letter capitalized) is not, so the second `includes()` call returns `false`.
The `includes()` method can also accept an optional second parameter that specifies the position in the array to start the search. This is useful if you want to check for an element's presence in a specific part of the array. Here's how you can use this feature:
```js
let numbers = [10, 20, 30, 40, 50, 30, 60];
console.log(numbers.includes(30, 3)); // true
console.log(numbers.includes(30, 4)); // true
```
For the first `console.log`, we are looking for the number `30` starting at index `3`. In this case, there is a number `30` that appears after index `3`, so the `includes()` method returns `true`.
The same is true for the second `console.log`. We are looking for the number `30` starting at index `4`. Since the number `30` does appear after that index, then it will return `true`.
It's worth noting that `includes()` uses the strict equality comparison (`===`), which means it can distinguish between different types. For example:
```js
let mixedArray = [1, "2", 3, "4", 5];
console.log(mixedArray.includes(2)); // false
console.log(mixedArray.includes("2")); // true
```
In this case, the number `2` and the string `"2"` are considered different data types. So, the first `console.log` will return `false`, while the second `console.log` will return `true`.
The `includes()` method is a powerful tool for checking the presence of elements in arrays. It's simple to use, efficient, and can save you from writing more complex loops or conditions to search through arrays. Whether you're working with strings, numbers, or mixed data types, `includes()` provides a straightforward way to verify if a value exists in your array.
# --questions--
## --text--
@ -27,7 +77,7 @@ console.log(arr.includes(3, 3));
### --feedback--
The second parameter of `includes()` specifies the starting position for the search.
The second parameter of ``includes()`` specifies the starting position for the search.
---
@ -39,7 +89,7 @@ The second parameter of `includes()` specifies the starting position for the sea
### --feedback--
The second parameter of `includes()` specifies the starting position for the search.
The second parameter of ``includes()`` specifies the starting position for the search.
---
@ -47,7 +97,7 @@ This will throw an error.
### --feedback--
The second parameter of `includes()` specifies the starting position for the search.
The second parameter of ``includes()`` specifies the starting position for the search.
## --video-solution--
@ -58,8 +108,8 @@ The second parameter of `includes()` specifies the starting position for the sea
What will be the output of the following code?
```js
let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.includes('C'));
let arr = ["a", "b", "c", "d", "e"];
console.log(arr.includes("C"));
```
## --answers--
@ -68,7 +118,7 @@ console.log(arr.includes('C'));
### --feedback--
Remember that `includes()` is case-sensitive when dealing with strings.
Remember that ``includes()`` is case-sensitive when dealing with strings.
---
@ -80,7 +130,7 @@ Remember that `includes()` is case-sensitive when dealing with strings.
### --feedback--
Remember that `includes()` is case-sensitive when dealing with strings.
Remember that ``includes()`` is case-sensitive when dealing with strings.
---
@ -88,7 +138,7 @@ This will throw an error.
### --feedback--
Remember that `includes()` is case-sensitive when dealing with strings.
Remember that ``includes()`` is case-sensitive when dealing with strings.
## --video-solution--
@ -99,8 +149,8 @@ Remember that `includes()` is case-sensitive when dealing with strings.
What will be the output of the following code?
```js
let arr = [1, '2', 3, '4', 5];
console.log(arr.includes('3'));
let arr = [1, "2", 3, "4", 5];
console.log(arr.includes("3"));
```
## --answers--
@ -109,7 +159,7 @@ console.log(arr.includes('3'));
### --feedback--
The `includes()` method uses strict equality (`===`) for comparison.
The ``includes()`` method uses strict equality (`===`) for comparison.
---
@ -121,7 +171,7 @@ The `includes()` method uses strict equality (`===`) for comparison.
### --feedback--
The `includes()` method uses strict equality (`===`) for comparison.
The ``includes()`` method uses strict equality (`===`) for comparison.
---
@ -129,7 +179,7 @@ This will throw an error.
### --feedback--
The `includes()` method uses strict equality (`===`) for comparison.
The ``includes()`` method uses strict equality (`===`) for comparison.
## --video-solution--

View File

@ -10,6 +10,65 @@ dashedName: what-is-a-shallow-copy-of-an-array-and-what-are-some-ways-to-create-
Watch the lecture video and answer the questions below.
# --transcript--
What is a shallow copy of an array, and what are some ways to create these copies?
A shallow copy of an array is a new array that contains references to the same elements as the original array. Creating shallow copies of arrays is a common operation, especially when you want to manipulate an array without modifying the original.
There are several methods for creating shallow copies of arrays, and we'll explore some of the most common ones: `concat()`, `slice()`, and the spread operator.
Let's start with the `concat()` method. This method creates a new array by merging two or more arrays. When used with a single array, it effectively creates a shallow copy. Here's an example:
```js
let originalArray = [1, 2, 3];
let copyArray = [].concat(originalArray);
console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
```
In this example, we are using the `concat()` method to concatenate an empty array to the `originalArray`. This will create a new array that is a shallow copy of `originalArray`.
The `copyArray` contains the same elements as `originalArray`, but it is a different array object, which is why the strict equality check (`===`) returns `false`.
Another method to create a shallow copy is the `slice()` method. When called without arguments, `slice()` returns a shallow copy of the entire array. Here's how it works:
```js
let originalArray = [1, 2, 3];
let copyArray = originalArray.slice();
console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
```
In this case, `originalArray.slice()` creates a new array that is a shallow copy of `originalArray`. Again, the `copyArray` contains the same elements but is a different array object.
The spread operator (`...`), introduced in ES6, provides another concise way to create shallow copies of arrays. Here's an example:
```js
let originalArray = [1, 2, 3];
let copyArray = [...originalArray];
console.log(copyArray); // [1, 2, 3]
console.log(copyArray === originalArray); // false
```
The spread operator (`...`) spreads the elements of `originalArray` into a new array, effectively creating a shallow copy. It's important to note that all these methods create new array objects, which means you can modify the copy without affecting the original array. For example:
```js
let originalArray = [1, 2, 3];
let copyArray = [...originalArray];
copyArray.push(4);
console.log(originalArray); // [1, 2, 3]
console.log(copyArray); // [1, 2, 3, 4]
```
In this example, adding an element to `copyArray` doesn't affect `originalArray`.
In summary, shallow copies of arrays can be easily created using methods like `concat()`, `slice()`, or the spread operator. These methods are useful for creating new arrays that can be manipulated independently of the original array.
# --questions--
## --text--
@ -60,7 +119,7 @@ The `slice()` method creates a shallow copy of the array.
What will be the output of the following code?
```js
let fruits = ['apple', 'banana', 'orange'];
let fruits = ["apple", "banana", "orange"];
let fruitsCopy = [...fruits];
console.log(fruitsCopy.length);
```

View File

@ -10,6 +10,58 @@ dashedName: how-can-you-use-string-and-array-methods-to-reverse-a-string
Watch the lecture video and answer the questions below.
# --transcript--
How can you use string and array methods to reverse a string?
Reversing a string is a common programming task that can be accomplished in JavaScript using a combination of string and array methods. The process involves three main steps:
- Splitting the string into an array of characters.
- Reversing the array.
- Joining the characters back into a string.
Let's explore each of these steps using the `split()`, `reverse()`, and `join()` methods.
The first step in reversing a string is to convert it into an array of individual characters. We can do this using the `split()` method. The `split()` method divides a string into an array of substrings and specifies where each split should happen based on a given separator. If no separator is provided, the method returns an array containing the original string as a single element. Examples of common separators include:
- An empty string (`""`), which splits the string into individual characters.
- A single space (`" "`), which splits the string wherever spaces occur.
- A dash (`"-"`), which splits the string at each dash.
Here's an example of using the split method to create an array of characters:
```js
let str = "hello";
let charArray = str.split("");
console.log(charArray); // ["h", "e", "l", "l", "o"]
```
In this example, we use `split("")` (with an empty string pass to it) to convert the string `hello` into an array of its individual characters. Once we have an array of characters, we can use the `reverse()` method to reverse the order of elements in the array.
The `reverse()` method is an array method that reverses an array in place. This means it modifies the original array rather than creating a new one. Here's how we can use it:
```js
let charArray = ["h", "e", "l", "l", "o"];
charArray.reverse();
console.log(charArray); // ["o", "l", "l", "e", "h"]
```
In this example, `reverse()` changes the order of elements in `charArray`, reversing it from `["h", "e", "l", "l", "o"]` to `["o", "l", "l", "e", "h"]`.
The final step is to convert the reversed array of characters back into a string. We can accomplish this using the `join()` method. The `join()` method creates and returns a new string by concatenating all of the elements in an array, separated by a specified separator string. If you want to join the characters without any separator, you can use an empty string as the argument. Here's an example:
```js
let reversedArray = ["o", "l", "l", "e", "h"];
let reversedString = reversedArray.join("");
console.log(reversedString); // "olleh"
```
In this example, `join("")` (with an empty string pass to it as an argument) combines all the characters in the array into a single string without any separator between them.
Remember that strings in JavaScript are immutable, which means you can't directly reverse a string by modifying it. That's why we need to convert it to an array, reverse the array, and then convert it back to a string. This combination of string and array methods provides a powerful and flexible way to manipulate strings in JavaScript.
# --questions--
## --text--
@ -18,7 +70,7 @@ What will be the output of the following code?
```js
let str = "coding";
let reversed = str.split('').reverse().join('');
let reversed = str.split("").reverse().join("");
console.log(reversed);
```
@ -56,7 +108,7 @@ Remember the order of operations: `split`, `reverse`, then `join`.
## --text--
What will be the result of `"hello".split('')`?
What will be the result of `"hello".split("")`?
## --answers--
@ -64,7 +116,7 @@ What will be the result of `"hello".split('')`?
### --feedback--
The `split('')` method splits a string into an array of individual characters.
The `split("")` method splits a string into an array of individual characters.
---
@ -72,7 +124,7 @@ The `split('')` method splits a string into an array of individual characters.
### --feedback--
The `split('')` method splits a string into an array of individual characters.
The `split("")` method splits a string into an array of individual characters.
---
@ -84,7 +136,7 @@ The `split('')` method splits a string into an array of individual characters.
### --feedback--
The `split('')` method splits a string into an array of individual characters.
The `split("")` method splits a string into an array of individual characters.
## --video-solution--
@ -96,9 +148,9 @@ What will be the output of the following code?
```js
let word = "hello";
let chars = word.split('');
let chars = word.split("");
chars.reverse();
console.log(chars.join('-'));
console.log(chars.join("-"));
```
## --answers--