Passing array as parameter in function, JavaScript

I’m trying to pass an array in a parameter…:

const names = ['Jin', 'Kazuya', 'Heiachi']
function Intro(parameter1) {
    document.write("My name is " + parameter1 + );
}

Intro(names[2], ' salesman', ' Chicago');
console.log(intro);   // this works, 

// But how come this does not work?
 function Intro(names[2]){
document.write.("My name is + names[2]);
}

Intro(names[2]);
console.log(intro);   //not working....

What do you mean by work and not working? Is the result not the one expected? Is there some kind of error?

console.log(intro); // this works,

There is no intro variable in the code you posted, what does that log?
By the way, the difference between the first call to Intro and the second are few:

  • In the second call you missed a double quote^^
  • names[2] will result in a single element of the array while parameter1 is composed by three string ( and there is a plus sign at the end of the string quite weird :stuck_out_tongue
  • When you use names[2] in the second ‘definition’ of Intro it will be considered as a parameter named names[2], not as the third element of the above array ^^
  • there is a dot just before the parenthesis that is not supposed to be there ( in your second ‘definition’ of the Intro function)^^

Thank you so much for the feedback. Let me try to clarify it a bit better :slight_smile:


const names = ['Jin', 'Kazuya', 'Heiachi']
function Intro(parameter1) {
    document.write("My name is " + parameter1);
}

Intro(names[2]);
console.log(intro);   // this works,  I get : "My name is Jin"

// But how come this does not work?

 function Intro(names[2]){
document.write("My name is + names[2]);
}

Intro(names[2]);
console.log(intro);   // not working " I get : (My name is names[2])"

Uhm, probably i miss something, anyway:

const names = ['Jin', 'Kazuya', 'Heiachi']
function Intro(parameter1) {
    document.write("My name is " + parameter1);
}

console.log(Intro(names[2]));

This snippet is supposed to print “My name is Heiachi”

 function Intro(names[2]){
document.write("My name is + names[2]");
}

console.log(Intro(names[2]));

This one is supposed to print “My name is + names[2]”, because here

document.write(“My name is + names[2]”);

you consider the whole statement as a string, whereas in the previous function

document.write("My name is " + parameter1);

the string is just the one within double quotes, and the parameter will take the value of the one you pass to the function ^^

I believe I understand it now. I really appreciate your help. Thank you. :slightly_smiling_face:

1 Like