JavaScript ES6 – What is variable?

Variable means anything that can change. Variables in JavaScript store data that can be changed later. Most JavaScript apps need to work with information and the data are almost always stored in variables.

In JavaScript, use let reserved keyword to declare a variable.

Declare and assign variables

        
          // declaring the variable
let note; 

// storing the string ‘my note’
note = ‘my note’; 

// OR

// Shorthand almost always used
let note = ‘my note’; 

// Use the variable by referencing the variable name “note”
console.log(note); 

// OUTPUT: my note        
      

The string is now stored in the memory area associated with the variable. You can see in the example above we referenced the variable name to output the value for that variable.

Variable naming rules

When it comes to naming variables in JavaScript you have to considered the following rules:

  • Name can only contain letters, numbers and the $, _ symbols only
  • Name cannot start with a number
  • Names are case sensitive let note; will be different than let Note;
  • Name is limitless, it could be in any length
  • Name shouldn’t match any JavaScript reserved keywords 
        
          let myNote // allowed
let my3rdNote // allowed
let $mynote // allowed
let _myNote // allowed
let my_note // allowed 
let my-note // not allowed
let 3rdNote // not allowed
let #myNote // not allowed
let public // Not allowed - public is reserved keyword
note = 'my note'; // storing the string 'my note'        
      

Unchanging variables

Constants are variables declared using the const syntax. Unlike let variables, the const variables cannot be changed.

        
          const PI = 3.14; // value cannot be updated within the application        
      

It’s considered best practice to name const variables all UPPERCASE letters to communicate to others that in fact variables are constant any attempt to update the value will result in an error.

Variable naming best practices

Variable names should have a clean, obvious meaning that describes the data it stores.

In programming, variable naming is one of the most important and complex skills. Variable names can reveal whether code was written by a beginner or an experienced developer.

  • Remember variable naming rules from above
  • Use camelCase naming conventions let myNote;
  • Or use PascalCase naming conventions let MyNote;
  • Or use snake_case naming conventions let my_note;
  • Don’t use short names, make it as descriptive as possible
  • Always use all UPPERCASE letters for const BRAND_COLOR = ‘#fe4321’;

For my years of experience with JavaScript I have always used camelCase naming conventions as seen by many other developers. snake_case and PascalCase are less known by developers respectively.

%d bloggers like this: