0

I'm wondering if there is any benefit (maintainability, rendering, performance etc.) to having a constant declared as a static class property vs just being a constant within the file.

Is there any difference or is this just personal preference?

The code is just to show a simple example, I understand in this instance you would just have the string in the render and probably use a stateless component instead of a class.

class MyClass extends React.Component {
   static myText = "This is an example";
   render() {
     return <p>{MyClass.myText}</p>
   } 
}

vs

const myText = "This is an example";
class MyClass extends React.Component {
   render() {
     return <p>{myText}</p>
   } 
}
Zachary Raineri
  • 148
  • 1
  • 12
  • https://stackoverflow.com/questions/2216239/what-is-the-difference-between-a-static-and-const-variable – Jayraj Aug 21 '19 at 12:36
  • `const` value can't be changed later on – Justinas Aug 21 '19 at 12:36
  • `static` is mutable. `const` isn't. – Cerbrus Aug 21 '19 at 12:37
  • @Cerbrus yes and the scope is different – messerbill Aug 21 '19 at 12:37
  • The referenced question is for C++, I'm asking about react specifically – Zachary Raineri Aug 21 '19 at 12:38
  • Depending on where you declare them. – Cerbrus Aug 21 '19 at 12:38
  • @Cerbrus in the OP's example the const was defined out off the class so the scope is different – messerbill Aug 21 '19 at 12:38
  • @ZacharyRaineri: The `static` and `const` concepts aren't language-specific. – Cerbrus Aug 21 '19 at 12:38
  • 2
    @Cerbrus they mean very different things in JavaScript vs. C++. – Aluan Haddad Aug 21 '19 at 12:42
  • @AluanHaddad: Please elaborate? – Cerbrus Aug 21 '19 at 12:43
  • @Cerbrus in JavaScript, static members are always visible to consumers of the class (cannot be private). Furthermore, they are subject to shadowing (how overriding is accomplished). Specifically, in JavaScript both static and non-static members participate in inheritance. There are additional differences that I can elaborate on. – Aluan Haddad Aug 21 '19 at 12:46
  • @AluanHaddad: That's not specific to `static` / `const`, though. That's more related to how inheritance works in JS, and the fact that `private` doesn't exactly exist. – Cerbrus Aug 21 '19 at 12:48
  • @Cerbrus which means you would use them differently as, in JS, visibility restriction is accomplished by lexical scoping while C++ doesn't have "virtual" static members or first class classes. These considerations would be taken into account by a comprehensive answer to this question. – Aluan Haddad Aug 21 '19 at 12:52
  • The Op asked for the difference between `const` and `static`... The answers in the linked post cover that quite well. – Cerbrus Aug 21 '19 at 12:59

0 Answers0