Javascript Function Argument Passing Pass array and individual array elements

Description

Javascript Function Argument Passing Pass array and individual array elements


let a = [ 1, 2, 3, 4, 5 ];

console.log( "Effects of passing entire array by reference" );
outputArray( "Original array: ", a );

modifyArray( a );  // array a passed by reference

outputArray( "Modified array: ", a );

console.log( "Effects of passing array " + 
   "element by value</h2>" + 
   "a[3] before modifyElement: " + a[ 3 ] );

modifyElement( a[ 3 ] ); // array element a[3] passed by value

console.log( "a[3] after modifyElement: " + a[ 3 ] );

// outputs heading followed by the contents of "theArray"
function outputArray( heading, theArray )
{
   console.log( heading + theArray.join( " " ));   
}

// function that modifies the elements of an array
function modifyArray( theArray )
{
   for ( let j in theArray )
      theArray[ j ] *= 2;   //from  w  w  w. java2s.  com
}

// function that modifies the value passed   
function modifyElement( e )
{
   e *= 2; // scales element e only for the duration of the
           // function                                     
   console.log( "value in modifyElement: " + e );
}



PreviousNext

Related