What would be the function of this array?

Asked

Viewed 92 times

2

Seeing a little about the Javascript language, I noticed a code in which a syntax I didn’t know.

In the code in question I have two variables with languages containing the values passed to the function and the function that returns an object:

let languages = 'Javascript';
let notExist = 'Go';
const program = (languages) => ({
  'Javascript': 'Belongs to the js universe!',
  'Typescript': 'Belongs to the js universe!',
  'Ecmascript': 'Belongs to the js universe!',
  'Default': 'Does not belong to the js universe!!'
})[languages];

console.log(program(languages));

console.log(program(notExist) ? program(notExist) : program('Default'));

My doubt concerns the array statement at the end of the function containing the variable languages:

  • What is the array for and its usefulness?
  • At the end of functions like this, I can declare other types of values like {} for example?

2 answers

5

First I suggest changing the learning strategy. First you learn the concepts then you go to codes. We are seeing many people asking here using the same strategy as you and our observation is that it is not working, people are skating in learning.

Array

I start with the question explicitly asked in the question.

What is the array for, what is its usefulness?

What is actually the array?

Specifically that array works more like a array associative, also called in some dictionary situations, a hash table or map. You can see more on What is the difference between a map, a dictionary, an associative array and a hash table?.

And This is how Javascript assembles its objects. See also Objects are similar to arrays?.

Then in this case you have a list of elements with key and value. The key will serve to access one of the elements and get the corresponding value.

The other question is confusing I do not know answer and the other answer does not answer either, if it was important I should rewrite this part to be clearer.

Proper code

In such an example it makes little sense because all information is available and this particular code is a huge complication. It serves only to present the mechanism. It is good to make this clear.

Then through the variable languages will be determined which is the element you are interested in. Note that if the variable comes a data that does not match any existing key will give error. This code is not a good example so also.

And it actually shows that this mechanism is quite wrong, a simple switch would solve the case well.

Then we go into another misuse of the mechanism, which is to create an anonymous function for something that doesn’t need to be anonymous.

What I’m trying to say is that you’re using a complex example and you’re likely to catch programming addictions doing so.

Understanding a concept is good, learning how a mechanism works is very interesting, but many examples they put around don’t teach you where to use, how to use, don’t give you a context, and so they teach you wrong.

I’m going to tell you how this code can be better written, even if it’s different from what’s originally in the question because that’s how it should be done. The code of the question.

function program(languages) {
    switch (languages) {
    case 'Javascript':
    case 'Typescript':
    case 'Ecmascript': return 'Belongs to the js universe!';
    default : return 'Does not belong to the js universe!!'
    }
}

console.log(program('Javascript'));
console.log(program('Go'));

I put in the Github for future reference.

Maybe a if it would work even better, but I don’t know if it would be changed. Exactly so I think it would work well even with a conditional operator:

function program(languages) {
    return (languages === 'Javascript' || languages === 'Typescript' || languages === 'Ecmascript') ? 'Belongs to the js universe!' : 'Does not belong to the js universe!!';
}

console.log(program('Javascript'));
console.log(program('Go'));

I put in the Github for future reference.

In addition to simpler tends to be faster running, and a little more robust.

In the context used there is no reason to use something more complicated than this. Can there be contexts that something like this is useful? It can, but it would need to be fully demonstrated, put this way leads people to program in a confusing way.

Of course, everyone can choose the way they think best to do it, I just gave the simple one. For example, someone must have thought that this form is wrong for having negatively answered, it is typical of those who prefer confusing things.

  • Thanks for the explanation Maniero, I know about arrays, only had not understood its use there in that context declared soon after the function. Thanks!

  • You explicitly asked about it: Para que serve o array e qual sua utilidade?. I introduced this and showed you that in this context this is not the right way to do this code and justified in the answer.

  • 1

    In the first paragraph already won my vote of usefulness, you have to make it bold.

4


Apart from the similar notation, this has nothing to do with array. In this case, the brackets denote a property advisor.

Note, in your example, that you are creating an object through its literal form:

{
  'Javascript': 'Belongs to the js universe!',
  'Typescript': 'Belongs to the js universe!',
  'Ecmascript': 'Belongs to the js universe!',
  'Default': 'Does not belong to the js universe!!'
}

There are two main ways to access object properties:

  • Point notation;
  • Bracket notation.

See the difference between them:

const obj = {
  'Javascript': 'Belongs to the js universe!',
  'Typescript': 'Belongs to the js universe!',
  'Ecmascript': 'Belongs to the js universe!',
  'Default': 'Does not belong to the js universe!!'
};

// Notação ponto:
console.log(obj.Javascript);
console.log(obj.Typescript);

// Notação colchete:
console.log(obj['Ecmascript']);
console.log(obj['Default']);

But note that in the advisor syntax via square brackets, you can pass a string, which allows you a certain dynamism in that access, unlike the other point notation, which is "hard-coded".

This dynamism allows you to do things like:

const obj = {
  'Javascript': 'Belongs to the js universe!',
  'Typescript': 'Belongs to the js universe!',
  'Ecmascript': 'Belongs to the js universe!',
  'Default': 'Does not belong to the js universe!!'
};

const prop = 'Ecmascript';

console.log(obj[prop]);

From there you can map one value to another. In the case of the question, you are mapping the name of a programming language to a given string.

Note that, as previously seen, bracket notation allows us to access these properties dynamically, see:

let exist = 'Javascript';
let notExist = 'Go';

const obj = {
  'Javascript': 'Belongs to the js universe!',
  'Typescript': 'Belongs to the js universe!',
  'Ecmascript': 'Belongs to the js universe!',
  'Default': 'Does not belong to the js universe!!'
};

console.log(obj[exist]);
console.log(obj[notExist]); // undefined

Note in the above example that we declare two variables to achieve this. However, this is not necessary. Objects allow you to do this directly, like this:

console.log(
  {
    name: 'Foo',
    age: 100
  }.name
); // Foo

console.log(
  {
    name: 'Foo',
    age: 100
  }['age']
); // 100

So you can create functions (as asked in the question) that isolate this behavior. You can even create a function that returns a default value if the property does not exist (and return undefined):

function getLanguageFeature(language) {
  return {
    'Go': 'Simple',
    'JS': 'Bizarre',
    'TS': 'JavaScript, but type safe'
  }[language] || 'Unknown language';
}

console.log(getLanguageFeature('Go')); // Simple
console.log(getLanguageFeature('JS')); // Bizarre
console.log(getLanguageFeature('TS')); // JavaScript, but type safe
console.log(getLanguageFeature('WOOT')); // Unknown language

Note that we use the OR operator (||) (as a function of short circuit) to ensure that we return the string Unknown language in case we search for a language that was not declared on the map. This is because property advisors return undefined if the lit property does not exist.

This can be seen as an alternative to the switch statement. In Python, for example, this construction does not exist and dictionaries are often used as substitutes.

  • Show Luiz, very well explained! Thanks :)

Browser other questions tagged

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