Reading a book by David Flenegan stumbled upon such a code.

var isArray = Function.isArray || function(o) { return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]"; }; 

This code by definition defines a function for checking the type of a variable on an array. But I do not understand why this thing is needed: Function.isArray || . I need an explanation, on the Internet, the search for this was not successful.

PS The title for the title is very bad and I understand, but I can’t do anything about it.

Update:

  1. Several people here answered supposedly see how Boolean logic works. But I know how it works (lazy calculation from left to right)
  2. Special thanks to @andreymal he imbued with what I was asking.

Update 2:

In general, the following chapter has the same code:

 Array.join = Array.join || function(a,sep) { return Array.prototype.join.call(a,sep); }; Array.slice = Array.slice || function(a,from,to) { return Array.prototype.slice.call(a,from,to); }; Array.map = Array.map || function(a, f, thisArg) { return Array.prototype.map.call(a, f, thisArg); } 

Is this code needed to define your own functions? And if they are defined not to redefine? Then why is it not written like this Array.prototype.join || , Array.slice = Array.prototype.slice || , Array.map = Array.prototype.map || ?

  • add more specifically what the book and in which chapter this code is - Grundy
  • @Grundy Chapter 7.10 Type Array - MaximPro
  • and what's the book called? - Grundy
  • Yes, this is a common typo. Above in the text, this is Array.isArray - Grundy
  • @Grundy aha clear, look I added another interesting piece (I will not add anything else this is the final version) - MaximPro

2 answers 2

Operator || returns the first operand whose boolean representation is true .

In the question code, the isArray variable will be equal to Function.isArray , if Function.isArray defined, or function(o) { ... } - otherwise.

 var a; var b = 123; var c = 456; var d = a || b; console.log(d); var e = b || c; console.log(e); var f = b || a; console.log(f); 

  • one
    How does || - it is clear, but why this thing is needed from the question - it is still unclear - andreymal
  • The fact that Function.isArray is taken if it is defined is understandable, only now, as far as I know js and if I don’t lie to Google, Function.isArray never defined anywhere at all - andreymal

This code means that if there is a standard Function.isArray function, then use it, and if there is no such function, then define your own function for testing.

  • And when is Function.isArray available? I checked in all the nearest browsers and even in nodejs - I don't have it anywhere - andreymal
  • five
    @andreymal, in fact, it should have been Array.isArray - Grundy
  • @Grundy, if it were, then everything would be clear) - andreymal
  • one
    @andreymal, most likely a typo :) - Grundy