MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • JAVASCRIPT NAMING CONVENTIONS: VARIABLES
  • JAVASCRIPT NAMING CONVENTIONS: BOOLEAN
  • JAVASCRIPT NAMING CONVENTIONS: FUNCTION
  • JAVASCRIPT NAMING CONVENTIONS: CLASS
  • JAVASCRIPT NAMING CONVENTIONS: COMPONENT
  • JAVASCRIPT NAMING CONVENTIONS: METHODS
  • JAVASCRIPT NAMING CONVENTIONS: PRIVATE
  • JAVASCRIPT NAMING CONVENTIONS: CONSTANT
  • JAVASCRIPT NAMING CONVENTIONS: GLOBAL VARIABLE
  • JAVASCRIPT NAMING CONVENTIONS: UNDERSCORE
  • JAVASCRIPT NAMING CONVENTIONS: DASH
  1. 1st month
  2. Week 3
  3. Javascript
  4. All About Variables

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

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

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:

// 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:

// 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 prefix like is, are, or has helps every JavaScript developer to distinguish a boolean from another variable by just looking at it:

// 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

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.

// 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 JavaScript class is declared with a PascalCase in contrast to other JavaScript data structures:

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

// 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>  
);}
<div>  <UserProfile    user={{ firstName: 'Robin', lastName: 'Wieruch' }}  /></div>

JAVASCRIPT NAMING CONVENTIONS: METHODS

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

class SoftwareDeveloper {  constructor(firstName, lastName) {    
this.firstName = firstName;    
this.lastName = lastName;  
}  

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

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

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:

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

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

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;

JAVASCRIPT NAMING CONVENTIONS: GLOBAL VARIABLE

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

JAVASCRIPT NAMING CONVENTIONS: DASH

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.

PreviousNaming JavaScript VariablesNextJavaScript Scope

Last updated 1 year ago

Components are not everywhere in JavaScript, but commonly found in frontend frameworks like . Since a component is kinda instantiated -- but appended to the DOM instead -- like a JavaScript class, they are widely declared with Pascal Case too.

When a component gets used, it distinguishes itself from native HTML and , because its first letter is always written in uppercase.

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 , but it's capitalized naming suggests avoiding it.

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 . 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 ;-)

1️⃣
React
web components
const declaration of the variable for primitive data structures
APIs