Doubt about the use of the Join method

Asked

Viewed 347 times

7

I’m doing a Javascript course and I came up with a question in one of the exercises.

Below is the exercise:

Given the following object array:

var usuarios = [
  {
    nome: 'Diego',
    habilidades: ['Javascript', 'ReactJS', 'Redux']
  },
  {
    nome: 'Gabriel',
    habilidades: ['VueJS', 'Ruby on Rails', 'Elixir']
  }
];

Write a function that produces the following result:

O Diego possui as habilidades: Javascript, ReactJS, Redux
Gabriel possui as habilidades: VueJS, Ruby on Rails, Elixir

Tip: To traverse an array, you must use the syntax for...of and to merge values from an array with a separator, use the join."

My resolution:

for (let dados of usuarios) {
  console.log("O " + dados.nome + " possui as habilidades: " + dados.habilidades.join(", "));
}

I did not understand very well the use of the method join in this exercise. If I take it from the console.log, the result is exactly the same on the console. I am using wrong or the result is really the same using or not it?

I read in the documentation method, but did not understand the use in this exercise, in case it would join the arrays in a single string?

  • Se eu tirá-lo do console.log, o resultado é exatamente o mesmo no console. here lacked to say the moment. Basically your doubt perhaps lacks to put in some context.

  • That’s when I call the "console.log ("O " +data.name+ " has the abilities: "+data.hability.Join(", "));" If I put console.log ("O " +data.name+ " has the abilities: " +data.abilities); The result is the same

  • It is not a problem in itself, it is a doubt about the use of Join, and if I take it, what appears on the console with or without it is the same thing. This I didn’t understand in the exercise, since the given tip is to use Join()

  • this console.log behavior that should be your question.

  • And why this console behavior.log?

  • https://answall.com/questions/38057/o-que-%C3%A9-console-log on the website itself the answer

  • https://www.geeksforgeeks.org/javascript-console-log-with-examples/

Show 2 more comments

2 answers

5


There is a difference between the two examples. Also, this behavior is not due to the console.log nor the method join. This is by the method toString array, which is called when concatenation is done.

As you can read in this answer, the operator of concatenation (+) that you are using will convert all operands to the string type if one of the operands is string. This means that in the example below:

const arr = ['L', 'u', 'i', 'z'];
const str = 'As letras são: ' + arr;

console.log(str);

As one of the operator’s operands + is string, the value of arr will be converted to string. And this happens through the method toString. In the case of arrays, the method toString return the elements of the semicolon-separated array.

This behavior also happens in interpolations, which also call the method toString. Behold:

const fake = {
  toString: () => 'Some Value'
};

console.log(`O valor é: ${fake}.`);

And if you try to convert an object that does not have a method toString, value, an error will be launched.

// Criará um objeto sem nenhum método em seu protótipo.
const obj = Object.create(null);

console.log(`Valor: ${obj}`); // Erro!

So there’s a difference yes between using the method join and do not use it. If you do not use the method join, the values at all times shall be separated by commas. The join allows you to choose a custom tab.

See the difference:

const letters = ['L', 'u', 'i', 'z'];

console.log(letters.toString());
console.log(letters.join());
console.log(letters.join(', '));
console.log(letters.join(' - '));

It is also valid to quote that if no argument is passed to the method join, the separator will be ,, equal to toString. Anyway, it’s very similar - coincidence, but it’s not the same.

3

The result isn’t exactly the same if you just take the join() just by to run and see that it is not. Your:

var usuarios = [
    {
        nome: "Diego",
        habilidades: ["Javascript", "ReactJS", "Redux"]
    },
    {
        nome: "Gabriel",
        habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
    }
];
for (let dados of usuarios) console.log("O " + dados.nome + " possui as habilidades: " + dados.habilidades.join(", "));

And now without the join():

var usuarios = [
    {
        nome: "Diego",
        habilidades: ["Javascript", "ReactJS", "Redux"]
    },
    {
        nome: "Gabriel",
        habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
    }
];
for (let dados of usuarios) console.log("O " + dados.nome + " possui as habilidades: " + dados.habilidades);

Have you noticed there’s a difference? It’s similar but it’s not the same.

By chance the impression of array is almost what you need, and if you didn’t want to make the text grammatically correct you could use the standard print from array and would do the same. But it’s just coincidence.

If you want to print a data list with a specific separation you term that control in hand how it will be printed, can not get default value. In some cases it will have to be very close at hand (imagine if the latter had to be separated with the e and not with a comma), but there are cases that change little and the join() can resolve. In this case it is assembling a text with each of the elements of array with a separation indicated by a comma and a space.

I’m going to give a hint that a lot of people don’t like. And that defines a lot of how the person will evolve in the area of development. Don’t believe in "worked" coincidences. You have to understand what is happening there, otherwise you are wrong even if you have no problem, you are wrong because you do not know why it worked, so it may have been coincidence. This sounds silly, but it’s very important, most people who are skating in programming stay in this situation because they believe in "it worked".

Nice to have asked, but be careful because the premise of the question is wrong in two points, the first already said, the results are not equal. The second is a hypothesis: you are believing in the "it worked". Don’t use the fact that it worked out more or less right, because next time it might not be what you need.

The documentation of the method is very clear in saying what I said here, I would not even say differently. Which is unclear, but the logic should indicate that the array prints in one way, there is no way you can say as you want.

Print without concatenation

Let’s make another example:

var usuarios = [
    {
        nome: "Diego",
        habilidades: ["Javascript", "ReactJS", "Redux"]
    },
    {
        nome: "Gabriel",
        habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
    }
];
for (let dados of usuarios) console.log(dados.habilidades);

I put in the Github for future reference.

Look how it’s changed. For me this is one of the points I hate about Javascript, it changes the result according to the context where the data was used. Terrible. But there’s one other thing that most people make mistakes about.

Internally what the console.log() is to call a method toString() of that kind of data. For some reason it goes beyond my comprehension (JS always does these weird things) if you use concatenation it does not use the toString() and decides to ride the way he thinks best and is almost what you want.

Almost everyone makes wrong use, but having a die printed directly like this is usually wrong. It makes sense in very simple data, but when it is composed the data that is generated by toString() is not for printing. This is answered in What is the function of the toString method()?.

Then we get into another question that all printed data is text, so all types need to have one toString(). Many people believe they are printing numbers, dates, various objects or arrays, but in fact, you only print a textual representation of the data, always, it is not possible to print the pure data, unless it is already a text, which is the case of the type string.

Completion

In your case the join() seems to fall like a glove (we are not sure because we do not have the detailed requirements, and this is the most important and other valuable tip to become a good developer without excellent requirements, the solution will not be good). If he does exactly what he wants then he solves.

If the requirement did not speak in detail of how it should be printed then without it it could solve as well, but it gets a little worse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.