Classes in javascript

Hi,

What does it mean when mosh says Classes in javascript are syntactic sugar over constructor functions ?

Can you refer to the video where Mosh says that?

I meant in general because he repeated that in js oop and react as well.
The reference for that is in js oop course section ES6 Classes the first video start taking about it from 02:00.
Is it because the type of the class in javascript is function ?

When he says that ES6 classes are syntactic sugar I think he means that the new syntax does the same as the old prototypes did. They are just a different form of expressing the same thing. Like a muffin with a fancy icing is still a muffin.

Or compare it to a variable declaration with inferred type in C# or Java:

var age = 18;

is exactly the same and compiles to the same byte code as

int age = 18;

You often find “syntactic sugar” as languages evolve and give you better means of expressing things while doing the same thing under the hood.

1 Like

From wikipedia:

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express.
It makes the language “sweeter” for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.

I like to imagine that it is like “a candy to sweeten the pill” where the pill is a piece of code not so easy to read and to use :slight_smile: :slight_smile:

1 Like

Syntactic sugar is some convenient syntactic feature that doesn’t rely on runtime features. By what this means, an example would explain this better:

class Person {
    name;
    constructor(name) {
         this.name = name;
    }
    sayHi() {
        console.log("Hi");
    }
}

will be secretly transcompiled into:

function Person(name) {
    let person = {};
    person.name = name;
    person.sayHi = function() { 
        console.log("Hi"); 
    }
    return person;
}

, making the language itself look more readable and more like a modern OOP language.

Feel free to ask if you need more explanation :wink:

Thank you @nekoiry for your explanation.
But i think @SAM explanation is more concise, easy to understand and more related to the subject.