Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes
Lesson 6, Topic 10
In Progress

JavaScript: Arrays and Functions

Yasin Cakal 16 Nov 2021
Lesson Progress
0% Complete

We discussed arrays being mutable, or changeable, throughout the lesson. So, what happens if we try to modify an array within a function? Is the array kept after the function call, or is it scoped to within the function?

Consider the following example, in which we use .push() on an array within a function. Remember that the .push() method modifies or changes an array:

const insects = ['ant', 'bee', 'mosquito'];
function addInsect(arr) {
  arr.push('butterfly');
}
addInsect(insects);
console.log(insects); 


// Output: [ 'ant', 'bee', 'mosquito', 'butterfly' ]

Let’s take a look at what happened in the example:

  • The insects array consists of 3 elements.
  • The function addInsect(), which takes an arr parameter, uses push() to insert a 'butterfly' element into arr.
  • We call addInsect() with an argument of insects, which executes the code contained within addInsect.
  • We examine the value of insects, and it now includes the 'butterfly' component! 

When you pass an array into a function, if the array is mutated within the function, the change is preserved outside the function as well. This concept is also known as pass-by-reference because what we’re actually passing the function is a reference to where the variable memory is stored, and we’re changing the memory.

Responses

Leave a Reply

%d bloggers like this: