Variables in JavaScript are a bit weird. They are awesome things that hold our data and they all kind of do it in a similar but important and different way. These data containers we are talking about are varlet, and const.

In JavaScript, setting variables happens in two phases:

  • Declaring — which is naming the variable let newVariable;
  • Initializing — which is setting/giving the variable a value let newVariable = 'I am an initialized variable now';

Declared variables (variables with values not yet initialized) are defaulted to undefined. They will not throw errors in your code and can be defined later in the script when use is necessary.

Variable Naming Conventions

JavaScript gives us a few ways we can name variables. Here are four easy rules that assist in proper naming conventions:

  1. Start variables with a lowercase letter. Variables cannot start with a number.
  2. Use CamelCase — myVariableName
  3. Don’t use JavaScript reserved words or future reserved words.
  4. Case matters! javaScriptjavascript, andJAVASCRIPT are three different variables.

Let’s take a look at each variable in detail and discuss use cases.


Var

var has been around forever, since JavaScript’s inception. It has a lot of issues surrounding scope and is generally not used as readily as it once was. There are a few reasons to use var with what JavaScript has post-2015.

var pi; //declares the variable 

//=> undefined // default value given to uninitialized variable
pi = 3.14; //initializes pi 
//=> 3.14 

var will not throw an error if you have two variables named the exact same thing. This can get messy. var also allows for variable reassignment. That is, you can change the value of var variables throughout your code.

var pi = 3.14;

//=> 3.14
pi = 'A delicious desert';
//-> 'A delicious desert'

#web-development #beginner-programmers #javascript #beginner-javascript #javascript-tips

JavaScript: Var, Let, or Const?
1.55 GEEK