Moshe
Moshe

Reputation: 58067

What does this JS Expression mean?

What does this JS expression mean? What are we returning?

return dihy(year) in {353:1, 383:1};

Upvotes: 2

Views: 211

Answers (5)

Charles Scalfani
Charles Scalfani

Reputation: 1

There is no reason to use an object here, i.e. {353: 1, 383: 1}. In fact, the values of 1 are confusing and can make the uninitiated think that the value of 1 is being returned when it is not and is purely arbitrary.

The following is equivalent:

dihy(year) in [353, 383]

Upvotes: 0

PleaseStand
PleaseStand

Reputation: 32052

This is a return statement that causes the containing function to return a Boolean value.

  1. It calls the function dihy() with the value of the variable year as its argument.
  2. It checks whether the return value is either 353 or 383 (the names of the properties that exist in the object literal). It does not matter what value the property has; it just needs to exist within the object. (That is, 1 is just an arbitrary value.)
  3. If so, the function returns true, otherwise false.

JavaScript programmers sometimes use this approach because it is shorter than checking against each value individually, and it is easy to programmatically add new values to check against:

var foo = {353: 1, 383: 1};

function bar(year) {
    return year in foo;
}

alert(bar(1955)); // false
foo[1955] = 1;
alert(bar(1955)); // true

You may want to look at the MDC documentation for the in operator.

Upvotes: 3

Cipi
Cipi

Reputation: 11343

Returns true or false, depending is the result that dihy() returns 353 or 383 (true for those two, anything else is false).

And it means exactly that... is the result of this function contained in this data collection...

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185883

This is an expression:

dihy(year) in {353:1, 383:1}

The dihy(year) function call presumably returns a Number value. If that value is either 353 or 383, the expression will evaluate to true, otherwise to false.

Note that your code is not an expression, but a statement, the return statement:

return expression; 

So, the return statement will either return true or false.

Upvotes: 1

Jakob
Jakob

Reputation: 24360

It will be true if the call to the function dihy with the argument year is a key in the object {353:1, 383:1} and false otherwise.

It could be rewritten like this for example:

var result = dihy(year);
return result == 353 || result == 383;

Upvotes: 2

Related Questions