According to the tutorial I am reading, the program below displays “Hello Ima Reader.”
I have one question about this program. Why does it, in its final line, insert a “2” into alert(name[2])?
When the function is called in the second last line, it only passes “name”, but when the alert is run it uses a “2”. I’m assuming that 2 refers to the length of name, but is it necessary? If so, Why?
function makeHello(name) {
name[name.length] = "Hello" + name [0] + " " + name[1];
}
var name = new Array ('Ima', 'Reader');
makeHello(name);
alert(name[2]);
The line
var name = new Array ('Ima', 'Reader');creates an array callednamewith element0set to"Ima"and element1set to"Reader".The next line,
makeHello(name);, invokes themakeHellofunction which creates an element2in thenamearray set to"Hello Ima Reader".The last line,
alert(name[2]);merely displays the element2that was created by themakeHellofunction.