Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to append elements to an array?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 797
    Comment on it

    There are methods to add elements to the array using push method and concat method.

    The array push method adds element at the end of an array and returns its new length.

    

    Syntax :- array.push(item1, item2, ..., itemX)

    Below is the example code :

    var arr = [
        one,
        two,
        Three
    ];
    
    // append new value to the array
    arr.push(four);
    
    // append multiple values to the array
    arr.push(five, six);
    
    // display all values
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }
    

    The array concat method also adds an element at the end of an array but it returns a new array unlike push method that returns the modified array.

    Syntax:-array1.concat(array2, array3,..., arrayX)

    Below is the example code:

    var ar1 = [1, 2, 3];
    var ar2 = [4, 5, 6];
    
    var ar3 = ar1.concat(ar2);
    
    console.log(ar1);
    console.log(ar2);
    console.log(ar3);
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: