We touched on variables in our last post we touched on variables and default values inside of functions. Variables can be used to store numbers or strings. There are 2 ways to declare variables, using let or automatically. In the past using the keyword var would also work, but that should only be used for older browsers. Below are some examples of how you would call the variables:
let a=5;
b=15;
In the example above a and b can be changed later in the code. Constants cannot be changed once they are declared. A constant is basically a variable that can only be set once. You’d declare constants by using the keyword const.
const c=15;
Variables and constants are defined as blocked scope. That means that variable “a” in a function would be separate than “a” in a separate function or outside of functions all together.
function testVar(a=1){
alert(a);
}
let a=2;
alert(a);
testVar();
The code above will alert 2 and then alert 1 since the two “a” variables are in different scopes. Admittedly all of this can get confusing. It’s even more confusing when you have thousands of lines of code to go through, so how do you keep track of it? You can leave comments in the code to help explain what code does or notes for the future. Anything commented will not execute. To leave comments, you would use the // for single line comments and between /* and */ for multi-line comments.
function testVar(a=1){
alert(a); //This will alert 1
}
let a=2;
alert(a); /* This will alert as 2.
The two a variables are completely separate*/
testVar();
And there you have it. Variables, constants, and comments are three of the most common things you will see in JavaScript.