Yasser
Yasser

Reputation: 23

using javascript array method to print the value of x

Could someone explain following code to me and what happens in x.join = x.shift;?

x = [5, 10, 15];

x.join = x.shift;

if (x == 5 && x == 10 && x == 15)
  console.log('good');

Upvotes: 0

Views: 260

Answers (2)

Anis R.
Anis R.

Reputation: 6922

First, the array function shift removes the first element of an array and returns it. So, for example:

x = [5, 10, 15]
a = x.shift() #now a = 5 and x = [10, 15]

Next, the line x.join = x.shift in your code basically reassigns your array's (x's) join method to call shift instead of join. And as join is (apparently ?) used in ==, then at each comparison, x's shift() method is called and returns the first available element.

So your code is equivalent to:

x = [5, 10, 15];

if (x.shift() == 5 && x.shift() == 10 && x.shift() == 15)
  console.log('good');

Which is just an overkill way to check the array's first, second and third values against the values 5, 10, and 15.

Upvotes: 0

epascarello
epascarello

Reputation: 207537

When you are doing the x== it calls toString. They replace join() with shift() which pulls off the first index.

x = [5, 10, 15];

console.log(x.toString())

x.join = x.shift;

console.log(x.toString())
console.log(x.toString())
console.log(x.toString())

Please do not do this....

Upvotes: 2

Related Questions