# JavaScript Naming Conventions

A JavaScript naming conventions introduction by example -- which gives you the common sense when it comes to naming variables, functions, classes or components in JavaScript. No one is enforcing these naming convention rules, however, they are widely accepted as a standard in the JS community.

### JAVASCRIPT NAMING CONVENTIONS: VARIABLES <a href="#javascript-naming-conventions-variables" id="javascript-naming-conventions-variables"></a>

**JavaScript variables are case sensitive**. Therefore, JavaScript variables with lowercase and uppercase characters are different:

```javascript
var name = 'Robin Wieruch';
var Name = 'Dennis Wieruch';
var NAME = 'Thomas Wieruch';

console.log(name); // "Robin Wieruch"
console.log(Name); // "Dennis Wieruch"
console.log(NAME); // "Thomas Wieruch"
```

A **JavaScript variable should be self-descriptive**. It shouldn't be necessary to add a comment for additional documentation to the variable:

```javascript
// bad
var value = 'Robin';
// bad
var val = 'Robin';

// good
var firstName = 'Robin';
```

Most often you will find JavaScript variables declared with a camelCase variable name with a leading lowercase character:

```javascript
// bad
var firstname = 'Robin';
// bad
var first_name = 'Robin';
// bad
var FIRSTNAME = 'Robin';
// bad
var FIRST_NAME = 'Robin';
// good
var firstName = 'Robin';
```

There are exceptions for JavaScript constants, privates, and classes/components -- which we will explore later. However, in general a JavaScript variable -- a string, boolean or number, but also an object, array or function -- is declared with a camelCase variable name.

A brief overview about the different case styles:

* camelCase (used in JS)
* PascalCase (used in JS)
* snake\_case
* kebab-case

### JAVASCRIPT NAMING CONVENTIONS: BOOLEAN <a href="#javascript-naming-conventions-boolean" id="javascript-naming-conventions-boolean"></a>

A prefix like *is*, *are*, or *has* helps every JavaScript developer to distinguish a boolean from another variable by just looking at it:

```javascript
// bad
var visible = true;

// good
var isVisible = true;

// bad
var equal = false;

// good
var areEqual = false;

// bad
var encryption = true;

// good
var hasEncryption = true;
```

In contrast to strings and integers, you can see it as another *soft rule* for a JavaScript boolean naming convention besides being written in camel case.

### JAVASCRIPT NAMING CONVENTIONS: FUNCTION <a href="#javascript-naming-conventions-function" id="javascript-naming-conventions-function"></a>

JavaScript functions are written in camel case too. In addition, it's a best practice to actually tell *what the function is doing* by giving the function name a verb as prefix.

```javascript
// bad
function name(firstName, lastName) {  
    return `${firstName} ${lastName}`;
}

// good
function 

\getName(firstName, lastName) {  
    return `${firstName} ${lastName}`;
}
```

This verb as prefix can be anything (e.g. *get*, *fetch*, *push*, *apply*, *calculate*, *compute*, *post*). It's yet another *soft rule* to consider for having more self-descriptive JavaScript variables.

### JAVASCRIPT NAMING CONVENTIONS: CLASS <a href="#javascript-naming-conventions-class" id="javascript-naming-conventions-class"></a>

A JavaScript class is declared with a PascalCase in contrast to other JavaScript data structures:

```javascript
class SoftwareDeveloper {  
    constructor(firstName, lastName) {    
        this.firstName = firstName;    
        this.lastName = lastName;  
    }
}
    
var me = new SoftwareDeveloper('Robin', 'Wieruch');
```

Every time a JavaScript constructor is called to instantiate a new instance of a class, the name of the class should appear in Pascal Case, because the class has been declared with Pascal Case in the first place.

### JAVASCRIPT NAMING CONVENTIONS: COMPONENT <a href="#javascript-naming-conventions-component" id="javascript-naming-conventions-component"></a>

Components are not everywhere in JavaScript, but commonly found in frontend frameworks like [React](https://www.robinwieruch.de/javascript-fundamentals-react-requirements/). Since a component is kinda instantiated -- but appended to the DOM instead -- like a JavaScript class, they are widely declared with Pascal Case too.

```javascript
// badfunction 
userProfile(user) {  
return (    
<div>      
<span>First Name: {user.firstName}</span>   
   <span>Last Name: {user.lastName}</span>   
    </div>  
);}

// goodfunction 
UserProfile(user) {  
return (    
<div>      
<span>First Name: {user.firstName}</span>    
  <span>Last Name: {user.lastName}</span>   
</div>  
);}
```

When a component gets used, it distinguishes itself from native HTML and [web components](https://www.robinwieruch.de/web-components-tutorial/), because its first letter is always written in uppercase.

```
<div>  <UserProfile    user={{ firstName: 'Robin', lastName: 'Wieruch' }}  /></div>
```

### JAVASCRIPT NAMING CONVENTIONS: METHODS <a href="#javascript-naming-conventions-methods" id="javascript-naming-conventions-methods"></a>

Identical to JavaScript functions, a method on a JavaScript class is declared with camelCase:

<pre class="language-javascript" data-overflow="wrap"><code class="lang-javascript">class SoftwareDeveloper {  constructor(firstName, lastName) {    
this.firstName = firstName;    
this.lastName = lastName;  
}  

getName() {    
return `${this.firstName} ${this.lastName}`; 
}}
 
<strong>var me = new SoftwareDeveloper('Robin', 'Wieruch');console.log(me.getName());
</strong><strong>//"Robin Wieruch"
</strong></code></pre>

Here the same rules as for JavaScript functions apply -- e.g. adding a verb as a prefix --, for making the method name more self-descriptive.

### JAVASCRIPT NAMING CONVENTIONS: PRIVATE <a href="#javascript-naming-conventions-private" id="javascript-naming-conventions-private"></a>

Rarely you will find an underscore (\_) in front of a variable/function/method in JavaScript. If you see one, it is *intended* to be *private*. Even though it cannot be really enforced by JavaScript, declaring something as private tells us about how it should be used or how it should not be used.

For instance, a private method in a class should only be used internally by the class, but should be avoided to be used on the instance of the class:

```javascript
class SoftwareDeveloper {  
    constructor(firstName, lastName) {    
        this.firstName = firstName;    
        this.lastName = lastName;    
        this.name = _getName(firstName, lastName);  
    }  
    
    _getName(firstName, lastName) {    
        return `${firstName} ${lastName}`;  
    }
}

var me = new SoftwareDeveloper('Robin', 'Wieruch');

// goodvar 
name = me.name;
console.log(name); // "Robin Wieruch"
// bad
name = me._getName(me.firstName, me.lastName);
console.log(name); // "Robin Wieruch"
```

A private variable/function can occur in a JavaScript file as well. This could mean that the variable/function shouldn't be used outside of this file but only internally to compute further business logic for other functions within the same file..

### JAVASCRIPT NAMING CONVENTIONS: CONSTANT <a href="#javascript-naming-conventions-constant" id="javascript-naming-conventions-constant"></a>

Last but not least, there are constants -- intended to be non-changing variables -- in JavaScript which are written in capital letters (UPPERCASE):

```javascript
var SECONDS = 60;
var MINUTES = 60;
var HOURS = 24;

var DAY = SECONDS * MINUTES * HOURS;
```

If a variable has more than one word in its variable declaration name, it makes use of an underscore (\_):

```
var DAYS_UNTIL_TOMORROW = 1;
```

Usually JavaScript constants are defined at the top of a JavaScript file. As hinted before, no one enforces one to not change the variable here, except a [const declaration of the variable for primitive data structures](https://www.robinwieruch.de/const-let-var/), but it's capitalized naming suggests avoiding it.

### JAVASCRIPT NAMING CONVENTIONS: GLOBAL VARIABLE <a href="#javascript-naming-conventions-global-variable" id="javascript-naming-conventions-global-variable"></a>

A JavaScript variable is globally defined, if all its context has access to it. Often the context is defined by the JavaScript file where the variable is declared/defined in, but in smaller JavaScript projects it may be the entire project. There are no special naming conventions for global JavaScript variables.

* A global JavaScript variable is declared at the top of a project/file.
* A global JavaScript variable is written in camelCase if it is mutable.
* A global JavaScript variable is written in UPPERCASE if it is immutable.

### JAVASCRIPT NAMING CONVENTIONS: UNDERSCORE <a href="#javascript-naming-conventions-underscore" id="javascript-naming-conventions-underscore"></a>

So what about the underscore and dash in JavaScript variable namings? Since camelCase and PascalCase are primarily considered in JS, you have seen that the underscore is only rarely used for private variables or constants. Occasionally you will find underscores when getting information from third-parties like databases or [APIs](https://www.robinwieruch.de/what-is-an-api-javascript/). Another scenario where you might see an underscore are unused function parameters, but don't worry about these yet if you haven't seen them out there ;-)

### JAVASCRIPT NAMING CONVENTIONS: DASH <a href="#javascript-naming-conventions-dash" id="javascript-naming-conventions-dash"></a>

A dash in a JavaScript variable isn't common sense as well. It just makes things more difficult; like using them in an object:

```
// badvar 
person = {  'first-name': 'Robin',  'last-name': 'Wieruch',};
var firstName = person['first-name'];

// goodvar 
person = {  firstName: 'Robin',  lastName: 'Wieruch',};
var firstName = person.firstName;
```

It's even not possible to use a dash directly for a variable declaration:

```
var first-name = 'Robin';// Uncaught SyntaxError: Unexpected token '-'
```

That's why it's better to avoid them.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://edrus.gitbook.io/mt-it/1st-month/week-3/javascript/all-about-variables/javascript-naming-conventions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
