Let me break my answer into a few parts:
- Why is array1 'undefined'?
You are trying to use a variable that is lexically scoped to your function. Check out this post for more. Essentially, by using the keyword
var
inside of a function, you have declared a variable that can only be accessed from within that function block.
If you were to call console.log from within the function block, it would be defined. Eg:
function concatArray(array1, array2) {
var array1 = [1, 3, 7];
var array2 = [12, 21, 42];
console.log(array1.concat(array2));
}
- How can I pass two arrays as parameters?
Your current implementation does accept two parameters, but you immediately overwrite the values within your function. You can remove those declarations and count on the code that invokes the function to define your two arrays.
Like this:
function concatArray(array1, array2) {
console.log(array1.concat(array2));
}
- How do I write a function that concats two arrays?
You were really close with what you have. A few things you forgot: 1) a return statement in your function 2) an invocation of your function.
Try something like this:
// define our function
function concatArray(array1, array2) {
// return two concatted arrays
return array1.concat(array2);
}
// define our arrays
var myArray1 = [1, 3, 7];
var myArray2 = [12, 21, 42];
//invoke the function with our arrays as params and assign it to a variable
var result = concatArray(myArray1, myArray2);
//console log new results
console.log(result);