Arrays, Function and String in JavaScript

 

Arrays

Array is an ordered collection of the elements which stores the data.

Syntax:

There are 2 syntaxes for creating an empty array:

                let  arr = [];

                let arr = new Array();

 Ex

Mostly the first syntax is used to create an array, We can initialize values as follows:

let  fruits = [“Pineapple”, ”Mango”, ”Watermelon”];

Array elements are ordered and starts with index 0 (zero)

We can access array elements by its numbers

                let  fruits = [“Pineapple”, ”Mango”, ”Watermelon”];

                document.write(fruits[0]);

                document.write(fruits[1]);

                document.write(fruits[2]);

Replacing array values

We can replace values as follows:

                fruits [1] = “Guava”;

Above statement will replace “Mango” with “Guava”.

We can add elements into array as follows:

                fruits[3] = “Orange”;

Above statement will add one more element to array.

We can calculate length of array:

                document.write(fruits.length);

Above statement will calculate the number of elements in an array.

Methods

Array support two operations of Stack

Push: adds an element to the end

Pop: removes an elements from the end

The new elements are added and removed from the end only

These above methods works at the end of the array

Pop: 

extracts the last element from array and returns it.

Example:

                    let fruits = ["Apple", "Orange", "Pear"];

                    document.write( fruits.pop() ); // remove "Pear" and display it

                    document.write( fruits ); // Displays Apple, Orange

Push: 

appends the element at the end of the array.

Example:

                let fruits = ["Apple", "Orange"];

                fruits.push(“Mango"); //adds “Mango” at the end of the array

                document.write( fruits ); // Apple, Orange, Mango

Here are 2 more methods that works at the start of the array:

shift: removes the element from the start of the array

unshift: add the element at the beginning of the array


shift

removes the element from the beginning of the array,

Extracts the first element and moves the second position element to the first position

                    let fruits = ["Apple", "Orange", “mango"];

                    document.write( fruits.shift() ); // remove Apple and displays it

                    document.write( fruits ); // Displays Orange, Mango


unshift: 

add the element at the beginning of the array.

Shifts the first position element to second position and add new elements at first position

                    let fruits = ["Orange", “Mango"];

                    fruits.unshift('Apple'); // adds Apple at the first position

                    document.write( fruits ); // Apple, Orange, Mango


push and unshift methods can add multiple items at a time.


let fruits = ["Apple"];

fruits.push("Orange", “Guava");

fruits.unshift("Pineapple", “Mango"); 

// ["Pineapple", “Mango", "Apple", "Orange", “Guava"]

document.write( fruits );


Traversing an Array

We can traverse (to visit array elements) array by using loops

Very traditional way to traverse is use of for loop

Using for Loop

Lets see example :

    let arr = ["Apple", "Orange", "Pear"];

    for (let i = 0; i < arr.length; i++)

    {

        document.write( arr[i] );

    }

 

Using for ... of

Another form of loop for array is for … of

    let fruits = ["Apple", "Orange", "Plum"];

    // iterates over array elements

        for (let x of fruits)

            {

                document.write( x );

            }

Above loop iterates through array and x is variable which accepts value from fruits[0] to end of an Array

Using for ... in

As array are objects we can also iterate it by using for … in as follows:

        let arr = ["Apple", "Orange", "Pear"];

            for (let key in arr)

            {

                document.write( arr[key] ); // Apple, Orange, Pear

            }

In above example key extracts index number from arr and and utilized for printing the array

new Array()

There is one more syntax to create an Array

                    let arr = new Array("Apple", “Mango", "etc");

If new Array is called with a single argument which is a number, then it creates an array without items, but with the given length.

                let arr = new Array(2); // will it create an array of [2] ?

                document.write( arr[0] ); // undefined! no elements.

                document.write( arr.length ); // length 2

new Array(number) has all elements undefined.


Multidimensional Array

To create multidimensional array there are 2 methods

Method 1 : Create 1 Dimensional array and then add that array in another 2 Dimensional array

For Example:

          let arr1 = ["Ajay", 24, 18000];

          let arr2 = [“Mayur", 30, 30000];

          let arr3 = [“Mehak", 28, 41000];

          let arr4 = [“Rajni", 31, 28000];

          let arr5 = [“Yuvraj", 29, 35000];

Here we have created 5 array elements

Here we create again 1 Dimensional array which consist array elements

                    let salary = [arr1, arr2, arr3, arr4, arr5];

Above statement create multidimensional array of size 3*5 (3 columns and 5 rows)

Method 2: we can directly assign multidimensional array

For Example:

let salary = [

["Ajay", 24, 18000],

[“Mayur", 30, 30000],

[“Mehak", 28, 41000],

[“Rajni", 31, 28000],

];

Here we have created 2 D array with size 3*4 (3 columns and 4 rows).

We can also initialize array by using commas on the separate line

Accessing Multidimensional Array

Below code is used for accessing multidimensional array

for (let i = 0, l1 = salary.length; i < l1; i++)

{

// This loop is for inner-arrays

for (let j = 0, l2 = salary[i].length; j < l2; j++) {

// Accessing each elements of inner-array

document.write( salary[i][j] );

}

}

Here we are printing the elements of 2D array variable i.e. salary

 Strings

String is called as collection of characters. Usually string is called a character array. 
In JavaScript the textual data is stored as a String. In JavaScript a single character is also treated as a String, there is no separate data type for storing a single character value. 
There are 3 ways used to represent a String
1. Using Double Quotes 

for example:

var str;

str="Welcome to Program";  

2. Using Single Quotes

for example:

var str;

str='Welcome to Program';

3. Using Backticks Quotes

for example:

var str;

str=` Welcome to Program `;

Single quotes and Double quotes are used for the same purpose but the backticks are used for some special purpose. 

Finding Character at by Index Position or Traversing a String

A String is a collection of characters or we may say it is a character array. As we say it is an array, we can traverse it or we may visit every character of a String.
To visit every character of a string we have to traverse through a String. To traverse a String there are two ways available

1. Traditional way to traverse string by an index position

for example:
    
    string[index]

The above statement will print the character of the mentioned index position. 

for example

var  str = "Welcome to Program";

document.write( " Character at index position 3 is "+str[ 3 ] );

above statement will print 'c' , as 'c' is present at index number 3

2.  Traverse string by an charAt() function

for example:
    
    string.charAt(index);

The above statement will print the character of the mentioned index position. 

for example

var  str = "Welcome to Program";

document.write( " Character at index position 5 is "+charAt[ 5 ] );

above statement will print 'm' , as 'm' is present at index number 5.

String Function

String is collection of characters or is called as a character array, one can perform many operations on string. Operations like changing the case of string, replacing part of string, breaking string into parts, extracting some part from string, searching some part inside a string etc...

1. Changing the Case of a Sting

To change the case of a string following two functions are used

toUpperCase( ) is used to convert complete string into Uppercase Letters and toLowerCase( ) is used to convert complete string into Lowercase Letters.

for Example:

var  str = "programming in javascript";

var str1 = "PROGRAM OF JAVASCRIPT";

var  s = str.toUpperCase();

document.write( "Sting converted in UpperCase " +s );

//Above statement will print "PROGRAMMING IN JAVASCRIPT"

var s1 = str1.toLowerCase();

document.write( " String converted in LowerCase " +s1 );

//Above statement will print "program of javascript"

2. Searching a Specific word into a String:

indexOf() function is used to search a specific word inside a given string. There are two syntax of the indexOf() function are as follows:

int  indexOf ( word )

where word is a substring or word to be searched into a given string and it will search the word from beginning of the String
 
int  indexOf ( word,  index )

where word is a substring or word to be searched into a given string and index is the location from where the search will begin

Above both functions will return a number, 
if the substring or word is found, it will return the starting index number of the substring or word
if not found in the string then it will return the  -1   

for example:

var  str = " Welcome to JavaScript Program " ;

document.write ( str.indexOf ( " Welcome " ) ) ;

//above statement will print 0 because Welcome is present at index number 0.

document.write ( str.indexOf ( " welcome " ) ) ;

//above statement will print -1, because welcome is not present in String as the search is case sensitive

document.write ( str.indexOf ( " Program " ) ) ;

//above statement will print 22 because Welcome is present at index number 22.

indexOf ( ) will search the first occurrence of the substring or word. remaining occurrences are remained unsearched. 

3. Separating or dividing specific part of the string

  Separating or dividing a string is also known as slicing a part of the string, 3 methods are available to divide a string into parts or to separate a part from a string.

slice, substring and substr

slice ( )

Syntax:
    
    string  slice ( begin_index , end_index ); 

it will return a part of string from begin index to end index (but it will not include end index character in the separated string)

for example:

var  str = " JavaScript Program " ;

document.write ( str . slice ( 0, 5 ) );

above statement will print JavaS and it will not include 'c' as it is at index number 5 which is not included by slice.

If there is no end_index provided, it will slice the complete string from the begin_index up to the last index of the string. 

var  str = " JavaScript Program " ;

document.write ( str . slice ( 4 ) );

above statement will print Scipt Program, as the end_index is not mentioned in above example.

substring ( )

Syntax:

        string  substring ( begin_index , end_index )

it almost works similar like slice ( ) function, the added advantage is, we can put the begin_index value greater than end_index value.

for example: 

    var  str = " JavaScript Program ";

    document.write( str . substring ( 0, 5 ) ); 

    document.write( str . substring ( 5, 0 ) ); 

above statements will print the same output JavaS

substr ( )

Syntax:

    string  substr ( begin_index , length )

this function returns a substring starting with the begin_index and specified length characters. This method allows us to specify the number of characters (length) instead of the end_index.

for example:

    var  str  = " JavaScript Program " ;

document.write ( str . substr ( 3, 6 ) );

above statement will print the output aScrip, as it starts to divide separate a part of string from begin_index i.e. 3 and the mentioned length i.e. 6 number of characters.

4. Converting a number into a String:

To convert a specified or given number into a string toString ( ) function is used. 
toString ( ) function converts number format to string format.

for example:

var  value = 2000;

var  str  =  value.toString ( );

above statement converts number 2000 to string 2000.

5. Convert string into a number:

To convert string into a number parseInt ( ) function is used. 

for example:

var  str  = "2000";

var value = parseInt(str);

above statement converts "2000" into a number 2000. so that any mathematical operation can be performed with the value.

6. Replacing a part of string:

To replace a specified part of a string in given string replace ( ) function is used. This function do not make changes in the original string instead it returns a newly updated string. It replaces only the first occurrence of the specified string/word. To replace all the occurrences we need to take support of regular expressions. 

Syntax:

    string  replace ( old_word, new_word )

Above statement replaces the old_word present in the string with the new_word specified and retuns newly updated string.

for example:

    var  str = " Welcome to JavaScript Program ";

    var  s = str . replace ( "Program" , " Language" );
    
    document.write ( s );

    above statement will print the output Welcome to JavaScript Language, it will replace Program word with Language word and returned a new String Welcome to JavaScript Language
  
replace ( ) function is a case sensitive function so it will not replaced the word with case sensitive details. To replace case sensitive word regular expression /i is used. 

for example: 

    var  str = " Welcome to JavaScript Program ";

    var  s = str . replace ( /program/i , " Language" );
    
    document.write ( s );

above statement will print the output Welcome to JavaScript Language, it will replace program word with Language word and returned a new String Welcome to JavaScript Language

To replace all the occurrences of the old_word regular expression /g is used. 

for example:

    var  str = "Sumit is a good athlete, Sumit runs very fast, Sumit covers 100 meter distance in 9 seconds ";

    var  s = str . replace ( /Sumit/g , "Raghav" );

    document.write ( s );

above statement will replace all the occurrences of Sumit and replace it with Raghav and the output will be  Raghav is a good athlete, Raghav runs very fast, Raghav covers 100 meter distance in 9 seconds





Comments

Popular posts from this blog

Introduction to JavaScript

Forms and Form Events