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 var
, let
, and const
.
In JavaScript, setting variables happens in two phases:
let newVariable;
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.
JavaScript gives us a few ways we can name variables. Here are four easy rules that assist in proper naming conventions:
myVariableName
javaScript
, javascript
, andJAVASCRIPT
are three different variables.Let’s take a look at each variable in detail and discuss use cases.
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