Var Keyword In Javascript

var keyword → for a variable to be used anywhere in the program

You can use the var keyword to create a variable. Well, when we use the var keyword to create a variable, it either has a global scope or a function scope. Well, when we are creating a variable outside any function(we are going to discuss functions later), it has a global scope. Whereas, if we are creating a variable inside a function, it will be having a function scope(which means that the variable is going to be only used within the function).

You can refer to the below program where we have created a variable, and assigned a value to it which is a number, so the type of that variable is now a number. You can either assign a value to the variable at the time of the creation of the variable, or you can declare a variable, and then assign the value to it afterward.

Var Keyword In Javascript

However, if you only declare the variable and do not assign any value to it, then the type and the value of that variable will be undefined(this is discussed later… don’t worry). Also, remember that we are going to give some names to the variable.

To have the output, we have to move to the console now. So, let’s move to the console, and have a look at the output –

As you can see, we had first created a variable with a name number. It has the value 8, as we had given to it. On the other hand, the other variable, with the name of another number, was given no value, so the value and the type both, are undefined. We are going to discuss the types later. Also, we have not yet created any function, but we are surely going to have a look at it later.