JavaScript Strings and Arrays

Strings

Slice

  • The slice() method returns a part of the original string as a new string.

  • Example:
    letstr="IloveCoding";let str = "IloveCoding";

  • str.slice(5) returns "Coding".

  • str.slice(1, 4) returns "love".

  • str.slice(-num) is equivalent to str.slice(length-num).

String Slice Examples

  • Example: letmsg="hello";let msg = "hello"; console.log(msg.slice(0,4))console.log(msg.slice(0, 4))

    • This will output "hell".

  • Example: letmsg="apnacollege";let msg = "apnacollege"; console.log(msg.slice(4,11));console.log(msg.slice(4, 11));

    • This will output "college".

  • Using msg.length for the end index: letmsg="apnacollege";let msg = "apnacollege"; console.log(msg.slice(4,msg.length));console.log(msg.slice(4, msg.length));

    • This is equivalent to msg.slice(4).

  • Omitting the end index: letmsg="apnacollege";let msg = "apnacollege"; console.log(msg.slice(4));console.log(msg.slice(4));

    • This will output "college".

  • Using negative indices: letmsg="apnacollege";let msg = "apnacollege"; console.log(msg.slice(-1)); //11-1 => 10

    • This will output "e".
      letmsg="apnacollege";let msg = "apnacollege";
      console.log(msg.slice(-2); //11-2 => 9

    • This will output "ge".

Replace

  • The replace() method searches for a value in the string and returns a new string with the value replaced.

  • Example:
    letstr="IloveCoding";let str = "IloveCoding";
    str.replace("love","do")//"IdoCoding"str.replace("love", "do") // "IdoCoding"
    str.replace("o","x")//"IlxveCoding"str.replace("o", "x") // "IlxveCoding"

  • The original string is not modified.

Repeat

  • The repeat() method returns a string with the number of copies of a string.

  • Example:
    letstr="Mango";let str = "Mango";
    str.repeat(3)//"MangoMangoMango"str.repeat(3) // "MangoMangoMango"

Arrays (Data Structure)

Array Basics

  • An array is a linear collection of things.

  • Example:
    letstudents=["aman","shradha","rajat"]let students = [ "aman", "shradha", "rajat"]

  • Accessing elements:
    students[0]students[0] accesses the first element ("aman").

Array Visualization and Access

  • Arrays can be visualized with indices, e.g., letnums=[2,4,6,8];let nums = [ 2, 4, 6, 8 ];

    • Indices: 0 1 2 3

  • Accessing elements:
    nums[0]nums[0] is 2,
    nums[1]nums[1] is 4,
    nums[2]nums[2] is 6,
    nums[3]nums[3] is 8.
    nums[4]nums[4] is undefined because it is out of bounds.

  • nums.length is 4.

  • typeof nums is 'object'.

Creating Arrays

  • Different ways to create arrays:
    letmarks=[99,85,93,76,62];let marks = [99, 85, 93, 76, 62];
    letnames=["adam","bob","catlyn"];let names = ["adam", "bob", "catlyn"];
    letinfo=["aman",25,6.1];//mixedarraylet info = ["aman", 25, 6.1]; //mixed array
    letnewArr=[];//emptyarraylet newArr = []; //empty array

Array Length and Accessing Elements

  • Arrays can hold mixed data types.

  • Accessing elements and their properties: letinfo=["shradha",23,89.9];let info = ["shradha", 23, 89.9];

    • info.length is 3.

    • info[0] is 'shradha'.

    • info[0][0] is 's'.

    • info[0][1] is 'h'.

    • info[0].length is 7.

  • Empty arrays: letempArr=[];let empArr = [];

    • empArr.length is 0.

    • empArr[0] is undefined.

    • [].length is 0.

    • [1, 2, 3, 4].length is 4.

Arrays are Mutable

  • Arrays are mutable, meaning their elements can be changed after creation.

  • Example: letfruits=["mango","apple","litchi"];let fruits = ["mango", "apple", "litchi"]; fruits[0]="banana";fruits[0] = "banana";

    • Now, fruits is ["banana", "apple", "litchi"].

  • Strings, on the other hand, are immutable.

Array Mutability Details

  • Example showing array mutability: letfruits=["mango","apple","litchi"];let fruits = ["mango", "apple", "litchi"]; fruits[0]="banana";//Modifiesthearrayfruits[0] = "banana"; // Modifies the array fruits[1]="pineapple";fruits[1] = "pineapple"; fruits[10]="papaya";//Addsanelementatindex10fruits[10] = "papaya"; // Adds an element at index 10

    • fruits becomes ['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:
    letcars=["audi","bmw","maruti","xuv"];let cars = ["audi", "bmw", "maruti", "xuv"];
    cars.push("toyota");//Addstoyotatotheendcars.push("toyota"); // Adds 'toyota' to the end

Array Methods in Action

  • Demonstrating push() and pop():
    letcars=[audi,bmw,xuv,maruti];let cars = ['audi', 'bmw', 'xuv', 'maruti'];
    cars.push("toyota");//Returns5,carsisnow[audi,bmw,xuv,maruti,toyota]cars.push("toyota"); // Returns 5, cars is now ['audi', 'bmw', 'xuv', 'maruti', 'toyota']
    cars.push("ferrari");//Returns6,carsisnow[audi,bmw,xuv,maruti,toyota,ferrari]cars.push("ferrari"); // Returns 6, cars is now ['audi', 'bmw', 'xuv', 'maruti', 'toyota', 'ferrari']
    cars.pop();//Returnsferrari,carsisnow[audi,bmw,xuv,maruti,toyota]cars.pop(); // Returns 'ferrari', cars is now ['audi', 'bmw', 'xuv', 'maruti', 'toyota']
    cars.pop();//Returnstoyota,carsisnow[audi,bmw,xuv,maruti]cars.pop(); // Returns 'toyota', cars is now ['audi', 'bmw', 'xuv', 'maruti']

  • Demonstrating unshift() and shift():
    cars.unshift("toyota");//Returns5,carsisnow[toyota,audi,bmw,xuv,maruti]cars.unshift("toyota"); // Returns 5, cars is now ['toyota', 'audi', 'bmw', 'xuv', 'maruti']
    cars.unshift("ferrari");//Returns6,carsisnow[ferrari,toyota,audi,bmw,xuv,maruti]cars.unshift("ferrari"); // Returns 6, cars is now ['ferrari', 'toyota', 'audi', 'bmw', 'xuv', 'maruti']
    cars.shift();//Returnsferrari,carsisnow[toyota,audi,bmw,xuv,maruti]cars.shift(); // Returns 'ferrari', cars is now ['toyota', 'audi', 'bmw', 'xuv', 'maruti']

  • Example using shift() to remove the first element:
    letfollowers=["a","b","c"];let followers = ["a", "b", "c"];
    letblocked=followers.shift();//blocked=a,followers=[b,c]let blocked = followers.shift(); // blocked = 'a', followers = ['b', 'c']

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.
      letprimary=["red","yellow","blue"];let primary = ["red", "yellow", "blue"];
      primary.indexOf("yellow");//Returns1primary.indexOf("yellow"); // Returns 1
      primary.indexOf("green");//Returns1primary.indexOf("green"); // Returns -1
      primary.indexOf("Yellow");//Returns1(casesensitive)primary.indexOf("Yellow"); // Returns -1 (case-sensitive)

  • includes(): Checks if an array includes a certain value.

    • Returns true or false.
      primary.includes("red");//Returnstrueprimary.includes("red"); // Returns true
      primary.includes("green");//Returnsfalseprimary.includes("green"); // Returns false

Array Methods: indexOf Examples

  • Demonstrating indexOf():
    letcars=[audi,bmw,xuv,maruti];let cars = ['audi', 'bmw', 'xuv', 'maruti'];
    cars.indexOf("bmw");//Returns1cars.indexOf("bmw"); // Returns 1
    cars.indexOf("xuv");//Returns2cars.indexOf("xuv"); // Returns 2
    cars.indexOf("XUV");//Returns1(casesensitive)cars.indexOf("XUV"); // Returns -1 (case-sensitive)
    letmarks=[99,89,67,42,100];let marks = [99, 89, 67, 42, 100];
    marks.indexOf(100);//Returns4marks.indexOf(100); // Returns 4
    marks.indexOf(97);//Returns1marks.indexOf(97); // Returns -1

Array Methods: concat and reverse

  • concat(): Merges two arrays.
    letprimary=["red","yellow","blue"];let primary = ["red", "yellow", "blue"];
    letsecondary=["orange","green","violet"];let secondary = ["orange", "green", "violet"];
    primary.concat(secondary);//Returns[red,yellow,blue,orange,green,violet]primary.concat(secondary); // Returns ['red', 'yellow', 'blue', 'orange', 'green', 'violet']

  • reverse(): Reverses an array.
    primary.reverse();//Modifiesprimaryto[blue,yellow,red]primary.reverse(); // Modifies primary to ['blue', 'yellow', 'red']

Array Methods: concat Details

  • concat() creates a new array without modifying the original arrays.
    letprimary=["red","yellow","blue"];let primary = ["red", "yellow", "blue"];
    letsecondary=["orange","green","violet"];let secondary = ["orange", "green", "violet"];
    letallColors=primary.concat(secondary);//allColorsis[red,yellow,blue,orange,green,violet]let allColors = primary.concat(secondary); // allColors is ['red', 'yellow', 'blue', 'orange', 'green', 'violet']
    secondary.concat(primary);//Returns[orange,green,violet,red,yellow,blue]secondary.concat(primary); // Returns ['orange', 'green', 'violet', 'red', 'yellow', 'blue']

Array Methods: reverse Details

  • reverse() modifies the original array.
    letcars=[audi,bmw,xuv,maruti];let cars = ['audi', 'bmw', 'xuv', 'maruti'];
    cars.reverse();//carsisnow[maruti,xuv,bmw,audi]cars.reverse(); // cars is now ['maruti', 'xuv', 'bmw', 'audi']
    cars.reverse();//carsisbackto[audi,bmw,xuv,maruti]cars.reverse(); // cars is back to ['audi', 'bmw', 'xuv', 'maruti']

Array Methods: slice

  • slice(start, end): Copies a portion of an array into a new array.

    • end is optional.
      letcolors=["red","yellow","blue","orange","pink","white"];let colors = ["red", "yellow", "blue", "orange", "pink", "white"];
      colors.slice();//Returnsacopyoftheentirearraycolors.slice(); // Returns a copy of the entire array
      colors.slice(2);//Returns[blue,orange,pink,white]colors.slice(2); // Returns ['blue', 'orange', 'pink', 'white']
      colors.slice(2,3);//Returns[blue](exclusiveofindex3)colors.slice(2, 3); // Returns ['blue'] (exclusive of index 3)
      colors.slice(2);//Returns[pink,white]colors.slice(-2); // Returns ['pink', 'white']

Array Methods: slice Examples

  • Demonstrating slice():
    letcars=[audi,bmw,xuv,maruti];let cars = ['audi', 'bmw', 'xuv', 'maruti'];
    cars.slice();//Returnsacopyoftheentirearraycars.slice(); // Returns a copy of the entire array
    cars.slice(1);//Returns[bmw,xuv,maruti]cars.slice(1); // Returns ['bmw', 'xuv', 'maruti']
    cars.slice(1,3);//Returns[bmw,xuv]cars.slice(1, 3); // Returns ['bmw', 'xuv']
    cars.slice(3);//Returns[maruti]cars.slice(3); // Returns ['maruti']
    cars.slice(cars.length1);//Returns[maruti]cars.slice(cars.length-1); // Returns ['maruti']
    cars.slice(5);//Returns[]cars.slice(5); // Returns []
    cars.slice(cars.length);//Returns[]cars.slice(cars.length); // Returns []

Array Methods: splice

  • splice(start, deleteCount, item0...itemN): Removes/replaces/adds elements in place.
    letcolors=["red","yellow","blue","orange","pink","white"];let colors = ["red", "yellow", "blue", "orange", "pink", "white"];
    colors.splice(4);//Removesfromindex4totheend,returns[pink,white],colorsisnow["red","yellow","blue","orange"]colors.splice(4); // Removes from index 4 to the end, returns ['pink', 'white'], colors is now ["red", "yellow", "blue", "orange"]
    colors.splice(0,1);//Removes1elementstartingfromindex0,returns[red],colorsisnow["yellow","blue","orange"]colors.splice(0, 1); // Removes 1 element starting from index 0, returns ['red'], colors is now ["yellow", "blue", "orange"]
    colors.splice(0,1,"black","grey");//Removes1elementfromindex0andadds"black"and"grey",returns[yellow],colorsisnow["black","grey","blue","orange"]colors.splice(0, 1, "black", "grey"); // Removes 1 element from index 0 and adds "black" and "grey", returns ['yellow'], colors is now ["black", "grey", "blue", "orange"]

Array Methods: splice Examples

  • Demonstrating splice():
    letcars=[audi,bmw,xuv,maruti];let cars = ['audi', 'bmw', 'xuv', 'maruti'];
    cars.splice(3);//Returns[maruti],carsisnow[audi,bmw,xuv]cars.splice(3); // Returns ['maruti'], cars is now ['audi', 'bmw', 'xuv']
    cars.splice(0,1);//Returns[audi],carsisnow[bmw,xuv]cars.splice(0, 1); // Returns ['audi'], cars is now ['bmw', 'xuv']
    cars.push("maruti");cars.push("maruti");
    cars.push("ferrari");//carsisnow[bmw,xuv,maruti,ferrari]cars.push("ferrari"); // cars is now ['bmw', 'xuv', 'maruti', 'ferrari']
    cars.splice(1,2);//Removes2elementsstartingfromindex1,returns[xuv,maruti],carsisnow[bmw,ferrari]cars.splice(1, 2); // Removes 2 elements starting from index 1, returns ['xuv', 'maruti'], cars is now ['bmw', 'ferrari']
    cars.splice(0,0,"toyota","xuv","maruti");//Insertstoyota,xuv,marutiatindex0,returns[],carsisnow[toyota,xuv,maruti,bmw,ferrari]cars.splice(0, 0, "toyota", "xuv", "maruti"); // Inserts 'toyota', 'xuv', 'maruti' at index 0, returns [], cars is now ['toyota', 'xuv', 'maruti', 'bmw', 'ferrari']
    cars.splice(1,0,"mercedes");//Insertsmercedesatindex1,returns[],carsisnow[toyota,mercedes,xuv,maruti,bmw,ferrari]cars.splice(1, 0, "mercedes"); // Inserts 'mercedes' at index 1, returns [], cars is now ['toyota', 'mercedes', 'xuv', 'maruti', 'bmw', 'ferrari']
    cars.splice(1,1,"gwagon");//Replacesmercedeswithgwagon,returns[mercedes],carsisnow[toyota,gwagon,xuv,maruti,bmw,ferrari]cars.splice(1, 1, "gwagon"); // Replaces 'mercedes' with 'gwagon', returns ['mercedes'], cars is now ['toyota', 'gwagon', 'xuv', 'maruti', 'bmw', 'ferrari']

Array Methods: sort

  • sort(): Sorts an array in ascending order (by default).
    letdays=["monday","sunday","wednesday","tuesday"];let days = ["monday", "sunday", "wednesday", "tuesday"];
    days.sort();//daysisnow[monday,sunday,tuesday,wednesday]days.sort(); // days is now ['monday', 'sunday', 'tuesday', 'wednesday']
    letsquares=[25,16,4,49,36,9];let squares = [25, 16, 4, 49, 36, 9];
    squares.sort();//sortsasstrings,squaresisnow[16,25,36,4,49,9]squares.sort(); // sorts as strings , squares is now [16, 25, 36, 4, 49, 9]

Array Methods: sort Details

  • sort() sorts elements as strings by default.
    letcars=[toyota,gwagon,xuv,maruti,bmw,ferrari];let cars = ['toyota', 'gwagon', 'xuv', 'maruti', 'bmw', 'ferrari'];
    cars.sort();//carsisnow[bmw,ferrari,gwagon,maruti,toyota,xuv]cars.sort(); // cars is now ['bmw', 'ferrari', 'gwagon', 'maruti', 'toyota', 'xuv']
    letchars=[b,d,e,a];let chars = ['b', 'd', 'e', 'a'];
    chars.sort();//charsisnow[a,b,d,e]chars.sort(); // chars is now ['a', 'b', 'd', 'e']
    letmarks=[99,89,67,42,100];let marks = [99, 89, 67, 42, 100];
    marks.sort();//marksisnow[100,42,67,89,99](Stillstringcomparison)marks.sort(); // marks is now [100, 42, 67, 89, 99] (Still string comparison)

Array References

  • Arrays in JavaScript are reference types.

  • Comparing arrays directly with == or === returns false because it compares memory addresses, not the array content.
    [1]===[1]//false[1] === [1] // false
    [1]==[1]//false[1] == [1] // false
    "name"=="name"//true"name" == "name" // true
    "name"==="name"//true"name" === "name" // true

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.
      letarr1=[1];let arr1 = [1];
      letarr2=[1];let arr2 = [1];

Array References: Copying Arrays

  • When assigning an array to another variable, you are creating a reference, not a new copy. letarr=[a,b];let arr = ['a', 'b']; letarrCopy=arr;//arrCopynowreferencesthesamearrayasarrlet arrCopy = arr; // arrCopy now references the same array as arr arrCopy.push(c);//ModifiesthearraythatbotharrandarrCopypointtoarrCopy.push('c'); // Modifies the array that both arr and arrCopy point to

    • Both arr and arrCopy will be ['a', 'b', 'c'].
      arr==arrCopy//true(becausetheyreferencethesamearray)arr == arrCopy // true (because they reference the same array)
      arr===arrCopy//truearr === arrCopy // true

Array References: Demonstration

  • Demonstrates how changes to a referenced array affect all variables pointing to it.
    letarr=[a,b,c];let arr = ['a', 'b', 'c'];
    letarrCopy=arr;let arrCopy = arr;
    arr.push(d);//arrandarrCopybothbecome[a,b,c,d]arr.push('d'); // arr and arrCopy both become ['a', 'b', 'c', 'd']
    arrCopy.pop();//arrandarrCopybothbecome[a,b,c]arrCopy.pop(); // arr and arrCopy both become ['a', 'b', 'c']

  • To create a new, independent array, you need to use methods like slice() or concat().

Creating an Array Copy

  • To create a new array that doesn't reference the original, you must explicitly create a new array.
    letarr=[a,b,c,d];let arr = ['a', 'b', 'c', 'd'];
    letarrCopy=[a,b,c];//Createsanewarraylet arrCopy = ['a', 'b', 'c']; // Creates a new array
    arr.push(d);//Onlyarrismodifiedarr.push('d'); // Only arr is modified

Constant Arrays

  • Using const with arrays means the variable cannot be reassigned to a new array, but the array's contents can still be modified.
    constarr=[1,2,3,4];const arr = [1, 2, 3, 4];