String Methods : at() and charAt()

Table of contents

No heading

No headings in the article.

Difference Between at() and charAt() :-

  1. when we pass a negative value in the parameter.

    a) at() method:- when we use a negative value in the parameter then the count starts from the right side as -1, -2, -3 ... and so on till the first character and gives output as specified number but if we use further negative numbers then at() method gives undefined as output.

    e.g.- In the string "Lakshman", the total length is 8 and we cannot use -9, -10,..... if we use then got output is undefined as you can see in the below code.

     const myName = "Lakshman";
     console.log(myName.at(-3)); // m
     console.log(myName.at(-8)); // L
     console.log(myName.at(-10)); // undefined
    

    b) charAt() method:- when we use a negative value in the parameter of charAt() then it doesn't give any output only give whitespace.

    e.g.-

     const myName = "Lakshman";
     console.log(myName.charAt(-3));  
     console.log(myName.charAt(-10));
     // No output
    
    1. when we give a larger number than the length of the string.

      a) at() method:- It returns undefined as an output when we pass a

      parameter greater number than the length of the string.

      e.g.-

       const superHero = "Iron-man";
       console.log(superHero.at(4)); // -
       console.log(superHero.at(7)); // n 
       console.log(superHero.at(8)); // undefined
       console.log(superHero.at(13)); // undefined
      

      b) charAt() method:- when we pass a greater number than the length of the string as a parameter then it doesn't give any output.

      e.g.-

       const superHero = "Iron-man";
       console.log(superHero.charAt(8)); // 
       console.log(superHero.charAt(13)); // 
       // no output