JavaScript Strings and Arrays
Strings
Slice
The
slice()method returns a part of the original string as a new string.Example:
str.slice(5)returns"Coding".str.slice(1, 4)returns"love".str.slice(-num)is equivalent tostr.slice(length-num).
String Slice Examples
Example:
This will output "hell".
Example:
This will output "college".
Using
msg.lengthfor the end index:This is equivalent to
msg.slice(4).
Omitting the end index:
This will output "college".
Using negative indices: console.log(msg.slice(-1)); //11-1 => 10
This will output "e".
console.log(msg.slice(-2); //11-2 => 9This will output "ge".
Replace
The
replace()method searches for a value in the string and returns a new string with the value replaced.Example:
The original string is not modified.
Repeat
The
repeat()method returns a string with the number of copies of a string.Example:
Arrays (Data Structure)
Array Basics
An array is a linear collection of things.
Example:
Accessing elements:
accesses the first element ("aman").
Array Visualization and Access
Arrays can be visualized with indices, e.g.,
Indices: 0 1 2 3
Accessing elements:
is 2,
is 4,
is 6,
is 8.
is undefined because it is out of bounds.nums.lengthis 4.typeof numsis 'object'.
Creating Arrays
Different ways to create arrays:
Array Length and Accessing Elements
Arrays can hold mixed data types.
Accessing elements and their properties:
info.lengthis 3.info[0]is 'shradha'.info[0][0]is 's'.info[0][1]is 'h'.info[0].lengthis 7.
Empty arrays:
empArr.lengthis 0.empArr[0]is undefined.[].lengthis 0.[1, 2, 3, 4].lengthis 4.
Arrays are Mutable
Arrays are mutable, meaning their elements can be changed after creation.
Example:
Now,
fruitsis["banana", "apple", "litchi"].
Strings, on the other hand, are immutable.
Array Mutability Details
Example showing array mutability:
fruitsbecomes['banana', 'pineapple', 'litchi', empty x 7, 'papaya'].
Array Methods
push(): Adds element to the end of the array.pop(): Deletes element from the end and returns it.unshift(): Adds element to the start of the array.shift(): Deletes element from the start and returns it.Example:
Array Methods in Action
Demonstrating
push()andpop():Demonstrating
unshift()andshift():Example using
shift()to remove the first element:
Array Practice Question
Given an array, modify it using array methods to achieve a final state:
Start:
['january', 'july', 'march', 'august']Final:
['july', 'june', 'march', 'august']
Array Methods: indexOf and includes
indexOf(): Returns the index of an element in the array.Returns -1 if the element is not found.
includes(): Checks if an array includes a certain value.Returns
trueorfalse.
Array Methods: indexOf Examples
Demonstrating
indexOf():
Array Methods: concat and reverse
concat(): Merges two arrays.reverse(): Reverses an array.
Array Methods: concat Details
concat()creates a new array without modifying the original arrays.
Array Methods: reverse Details
reverse()modifies the original array.
Array Methods: slice
slice(start, end): Copies a portion of an array into a new array.endis optional.
Array Methods: slice Examples
Demonstrating
slice():
Array Methods: splice
splice(start, deleteCount, item0...itemN): Removes/replaces/adds elements in place.
Array Methods: splice Examples
Demonstrating
splice():
Array Methods: sort
sort(): Sorts an array in ascending order (by default).
Array Methods: sort Details
sort()sorts elements as strings by default.
Array References
Arrays in JavaScript are reference types.
Comparing arrays directly with
==or===returnsfalsebecause it compares memory addresses, not the array content.
Array References in Memory
Arrays are stored as references in memory.
When an array is copied using
=, both variables point to the same memory location.Changes to one array will affect the other.
Array References: Copying Arrays
When assigning an array to another variable, you are creating a reference, not a new copy.
Both
arrandarrCopywill be['a', 'b', 'c'].
Array References: Demonstration
Demonstrates how changes to a referenced array affect all variables pointing to it.
To create a new, independent array, you need to use methods like
slice()orconcat().
Creating an Array Copy
To create a new array that doesn't reference the original, you must explicitly create a new array.
Constant Arrays
Using
constwith arrays means the variable cannot be reassigned to a new array, but the array's contents can still be modified.