Can someone help me with this code?


#1

So, i’m new to this whole thing and i am trying to understand the way js works. Right now i’m studying the array methods and understanding it’s syntax. I created this code and tried to call it on paragraph, but when i load it somehow it’s undefined, can someone explain why this happened?

var lista = [“Carro”, “moto”, “avião”];
var lista2 = [“Busão”];
function listagem(){
lista.push(“bike”);
lista.shift();
lista.concat(lista2);
}
document.getElementById(“forma”).innerHTML = listagem();


#2

This is because the function listagem() does not return anything. It throws an undefined because there is nothing to set the innerhtml to.

Try the following code. I commented what i added.

var lista = [“Carro”, “moto”, “avião”];
var lista2 = [“Busão”];
function listagem(){
    lista.push(“bike”);
    lista.shift();
    lista.concat(lista2);
    return lista; // added this line so the function will return something.
}
document.getElementById(“forma”).innerHTML = listagem();

#3

Is this possible to invoke these array methods in the function at the same time? The way you set the code just showed the array without any alterations.


#4

the changes are made fine? bike is added to the array just fine. However you check concat documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

you can read the following:

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

which is interesting.

also, updating global variable within a function is not a good idea.