Search code examples
javascriptes6-classecmascript-next

Weird behavior when declaring class property with semicolon


class SomeClass {
  x: 5;
  y = 10;
}

const c = new SomeClass();
alert(c.x + ' : ' + c.y); 

Edit mqkw2zk94j

Why is the code compilable but the value of c.x is undefined?

What is the effect of declaring a class property with :?


Solution

  • Regarding the x: 5 part, although this is a valid javascript code, there is no much use for it.
    This is a javascript label and it used (if any) mostly within loops context.

    So to answer your questions:

    Why is the code compilable

    Because technically this is a valid javascript code (yet not a valid class field).

    but the value of c.x is undefined

    Because the x is a label and not a class field.

    What is the effect of declaring a class property with :

    You get a label instead of a class field.


    Addendum
    Another common mistake, is this code of block:

    class SomeClass {
      z = () => {
        x: 5;
      };
    }
    

    You would think that z() will return an object with an x key:

    `{x:5}`
    

    But actually you have a function with a label of x that just run an expression of 5.

    Just for completeness sake, the fix will be either to add an explicit return and another set of curly braces

    () => {return {x: 5}}
    

    Or just wrap the whole thing with parentheses

    () => ({x: 5})
    

    Edit
    As a followup to the comments below:
    Just to be clear, your code compiles on several environments that i tested as well as stack-snippets as can be seen below:

    class SomeClass {
      x: 5;
      y = 10;
    }
    
    const c = new SomeClass();
    console.log(c.x + ' : ' + c.y);