86

A friend and I had an argument last week. He stated there were no such things as classes in JavaScript.

I said there was as you can say var object = new Object()

He says "as there is no word class used. It's not a class."

Who is right?

Edit: July 2017

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. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

- Mozilla ES6 Classes: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Glycerine
  • 7,157
  • 4
  • 39
  • 65
  • in the example above it's talking about class Rectangle, so to define a class we don't need to use function keyword anymore i.e (function Rectangle(dimensions) { } ? Now there is a class keyword for classes? – Roxy'Pro Nov 30 '17 at 21:09
  • I found this reddit thread that gives a lot of people's perspectives on this topic. The majority seem to be saying that es6 classes count as real classes, but of course there's some conflicting opinions. Anyone who wants to dive a little deeper into this question and develop their own opinion can take a peek: https://www.reddit.com/r/javascript/comments/8q6267/why_are_js_classes_not_real_classes/ – Scotty Jamison Jan 05 '21 at 18:46

14 Answers14

122

Technically, the statement "JavaScript has no classes" is correct.

Although JavaScript is object-oriented language, it isn't a class-based language—it's a prototype-based language. There are differences between these two approaches, but since it is possible to use JavaScript like a class-based language, many people (including myself) often simply refer to the constructor functions as "classes".

Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • 4
    You can simulate classes using prototypes and prototypes using classes, e.g. look at he Prototype design pattern. – Gabriel Ščerbák May 02 '10 at 10:35
  • I think I've earned my fiver! Nice one steve – Glycerine May 02 '10 at 10:50
  • 2
    @SteveHarrison, JavaScript classes introduced in ECMAScript 2015 are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. So this means javascript is becoming now class-based language? – Roxy'Pro Nov 30 '17 at 21:11
  • yeah as a Java dev, I often point this out to people. Javascript has 'OBJECTS' but not classes. What people refer to as a 'class' is actually an object. – Orubel Oct 26 '18 at 17:53
  • 2
    Even though ES6 classes are mostly syntax sugar, anyone wanting to disregard them as not being real will have to be careful not to use arguments that also exclude classes from other dynamic languages. Javascript classes have become just as real as a python class. – Scotty Jamison Jan 05 '21 at 18:04
28

Javascript is an object oriented programming language, nevertheless in 2015 with ECMA script 6 classes have been introduced and now is correct to use them like other class based languages like Java. Of course as pointed out by the user codemagician in his/her comment, there are some deep differences between how classes work in js and java or other "class based" programming languages.

Nevertheless now in js programming it is possible to use for example code like:

class Animal { 
  constructor(name) {
    this.name = name;
  }


class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

That has something in common with classical class-based languages. The problems still is the browser support of this new technology that is just at start at the moment. So it still is not good to use it on productions products. But I don't have any doubt that this issue is going to be solved fast.

Hence the question remains if js has become a class-based programming language because of the implementation of this new features or does it still remain an object prototyping oriented programming language.

Pynchia
  • 10,996
  • 5
  • 34
  • 43
willy wonka
  • 1,440
  • 1
  • 18
  • 31
  • @Bhargav Rao Hi. Tnx for the comment. I don't mean to be polemic but the question was "Does JavaScript have classes?" I said "Classes in js have been introduced in ECMA script 6 in 2015" This IMHO gives an updated answer to the question... Doesn't it? And also at the same time my response tries to "converse" with other devs about their point of view about this new EC6 situation. Might be I'm wrong, in this case I'm sorry for my mistake. – willy wonka Sep 25 '16 at 07:16
  • 2
    Can I humbly ask why about down votes so I can learn on my own mistakes? Tnx in advance. – willy wonka Sep 25 '16 at 07:32
  • I haven't down voted. I guess it's because of flags. Usually they're the culprits. Wait for a day or two. Other domain experts will see your post and vote accordingly. Don't worry much about these sudden down votes. – Bhargav Rao Sep 25 '16 at 07:35
  • 2
    @Bhargav Rao Ah OK anyway I didn't say that was you to down vote: I didn't mean to accuse anybody, I was talking in general just hoping to get an explication to improve my behavior into stack overflow to be helpful for both myself and others on this awesome community: I'll take my time, I'm still new, ;-) – willy wonka Sep 25 '16 at 07:43
  • 4
    Your answer is misleading. It's not true to say "now is correct to use them like other class based languages like Java". Java is an OO class-based language. Instances of classes make _copies_ of properties on each instance created. "classes" in JS are nothing more than syntactical sugar to wire up Objects Linked to Other Objects (OLOO) - the fundamental model on which JS is based. The OLOO model will always use the prototype chain to provide "inheritance" (in reality it's _delegation_), there is never a true _copy_ of the "instance" properties. A "class" is not static as in a true OO language. – Andy Fusniak Aug 27 '17 at 11:46
8

In Javascript pretty much everything is an object (objects can inherit from other objects). It does not have classes in the classical sense.

Although you can reproduce most of the functionality of traditional class definition / instantiation by function prototyping.

ChristopheD
  • 112,638
  • 29
  • 165
  • 179
8

Listen to Douglas Crockford's talk here:
http://developer.yahoo.com/yui/theater/video.php?v=crockonjs-2

He directly addresses your question in his presentation:

The most controversial feature of the language is the way it does inheritance, which is radically different than virtually all other modern languages. Most languages use classes – I call them ‘classical languages’ – JavaScript does not. JavaScript is class free. It uses prototypes. For people who are classically trained who look at the language, they go: well, this is deficient. You don’t have classes, how can you get anything done? How can you have any confidence that the structure of your program’s going to work? And they never get past that. But it turns out…

Christopher Altman
  • 4,868
  • 2
  • 33
  • 49
5

From You-Dont-Know-JS book at https://github.com/getify/You-Dont-Know-JS

Chapter 4: Mixing (Up) "Class" Objects

...

JS has had some class-like syntactic elements (like new and instanceof) for quite awhile, and more recently in ES6, some additions, like the class keyword.

But does that mean JavaScript actually has classes? Plain and simple: No

I am not going to copy and past other parts here but encourage to read chapter 3 & chapter 4 and run samples.

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch3.md

https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch4.md

Alireza Fattahi
  • 42,517
  • 14
  • 123
  • 173
  • 1
    great reference! – Adam Aug 15 '19 at 18:42
  • 1
    Fixed links: [You Don't Know JS: this & Object Prototypes Chapter 3: Objects](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch3.md) [You Don't Know JS: this & Object Prototypes Chapter 4: Mixing (Up) "Class" Objects](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch4.md) – Wulf Solter Oct 08 '19 at 04:54
4

By "language X has classes" people usually mean support of object oriented programming.

Yes, Javascript is an object oriented language.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67
2

When I think of classes I think of types and the fact that classes allow me to define new types. In js you can't create new types. You can do all sorts of fancy oo stuff with prototypes but the fact that everything is still an object really hits home the class-less nature of js. I think that people using 'class' terminology when talking about js confuses the js as a prototype language vs js as a classical language even more than the ugly new operator. In short, just because js is OO doesn't imply that classes need to exist.

fthinker
  • 646
  • 2
  • 9
  • 17
2

In simple words - Yes. All you need is Babel.js transpiler, because all browsers does not support it except Chrome browser. A JavaScript class is a type of function. Classes are declared with the class keyword. We use function expression syntax to initialize a function and class expression syntax to initialize a class.

Here is an example of JavaScript class using function:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100
1

To add in with the other answers, javascript does not have classes, although I'm starting to see statements where it is described as something like classes, but I believe that just confuses the issue.

JavaScript has prototypes, not classes, but they accomplish the same thing, prototypes are objects that define objects, hence the confusion.

A prototype is a representation of private internal state that a class would manage in Java for example. Instead of putting that internal state in a class and presenting an interface for manipulating behaviour, as in java, JavaScript exposes the data structure for JavaScript programs to manipulate directly.

This is the best description I've found on the subject, Prototypes are not Classes.

James Drinkard
  • 15,342
  • 16
  • 114
  • 137
0

Although JavaScript didn't have classes prior to ES6, class-like behavior could be implemented in ES5 by sealing objects (thereby making objects non-extensible). In a sealed object, new properties and methods cannot be added and properties are not configurable. Property values can still be set and read. I say class-like, because there's one caveat. A sealed object's method definitions can still be modified. That's because property values can still be set, unless you change all method properties to be non-writeable -- at which point you've reproduced class behavior pretty closely using ES5.

Puneet Lamba
  • 755
  • 8
  • 15
0

Yes. Yes, javascript has classes and objects. This is an example of making blockchain by using javascript/NodeJS classes and objects:-

// coded by Alfrick Opidi in Smashing Magazine blog
// https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/

const SHA256 = require('crypto-js/sha256');
const fs = require('fs')

class CryptoBlock{
    constructor(index, timestamp, data, precedingHash=" "){
     this.index = index;
     this.timestamp = timestamp;
     this.data = data;
     this.precedingHash = precedingHash;
     this.hash = this.computeHash();     
    }
    computeHash(){
        return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)).toString();
    }   
}

class CryptoBlockchain{
    constructor(){
        this.blockchain = [this.startGenesisBlock()];     
    }
    startGenesisBlock(){
        return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain, its also called genisis", "0");
    }
    obtainLatestBlock(){
        return this.blockchain[this.blockchain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.precedingHash = this.obtainLatestBlock().hash;
        newBlock.hash = newBlock.computeHash();        
        this.blockchain.push(newBlock);
    }
}

 let smashingCoin = new CryptoBlockchain();

smashingCoin.addNewBlock(new CryptoBlock(1, "01/06/2020", {sender: "Iris Ljesnjanin", recipient: "Cosima Mielke", quantity: 50}));
smashingCoin.addNewBlock(new CryptoBlock(2, "01/07/2020", {sender: "Vitaly Friedman", recipient: "Ricardo Gimenes", quantity: 100}) );
fs.writeFile('genisis.json', JSON.stringify(smashingCoin), function (err) {
    if (err) throw err;
    console.log('Saved!');
  }); 
console.log(JSON.stringify(smashingCoin, null, 4));
aakash4dev
  • 774
  • 4
  • 13
0

Javascript is more of an Object based programming language rather than Object oriented programming language.

Amith_RV
  • 1
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 12 '22 at 04:52
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32891212) – Gwhyyy Oct 13 '22 at 17:29
-1

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  // Getter
  get area() {
    return this.calcArea();
  }
  // Method
  calcArea() {
    return this.height * this.width;
  }
}

const square = new Rectangle(10, 10);

console.log(square.area); // 100
-8

AFAIK Javascript use the prototype concept and it's not OO. That's means that you can't use the typical concepts of OOP like inheritance or polymorphism.

Cesar
  • 4,418
  • 2
  • 31
  • 37