-2

Say I have these two:

class Foo {}
const Bar = function() {}

// Then somewhere I have an object:
const variable = Foo;
// OR
const variable = Bar;

How can I know if variable is a function or a class? The problem here is that typeof Foo or typeof Bar both return function.

Kousha
  • 32,871
  • 51
  • 172
  • 296

1 Answers1

1

This question was to be expected with the confusion caused by the new syntactic sugar added recently.

From the MDN doc on Classes:

JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript.
[...]
Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

The MDN doc on class expressions shows what you already know about typeof:

'use strict';
var Foo = class {}; // constructor property is optional
var Foo = class {}; // Re-declaration is allowed

typeof Foo; //returns "function"
typeof class {}; //returns "function"

Foo instanceof Object; // true
Foo instanceof Function; // true
class Foo {}; // Throws TypeError, doesn't allow re-declaration

But unlike the class expression, the class declaration doesn't allow an existing class to be declared again and will throw a type error if attempted.
[...]
Class declarations are not hoisted (unlike function declarations).

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129