How Can We Help?
What are JavaScript variables?
Variables are simply containers where we can store values. You can simply place the values in these containers after naming the containers and refer it for future use. Javascript uses the var keyword to declare a variable and the name of the variable must be unique. If you want to specify a value to a variable then it can be done using a ‘=’ operator after the variable name.
Syntax:
<script type = "text/javascript">
var name=”Sourav”;
var rollno=19;
</script>
There are certain rules we should know while declaring the variables :
- The name of the variables should start with letters (a to z or A to Z ), underscores( _ ), or dollar signs ($).
- We can only use the digits from (0 to 9) after a letter. for example- bag1
Correct naming of javascript variables examples:
var number = 10;
var _firstname="Hasan";
Incorrect naming of javascript variables examples:
var 786=30;
var *hi=320;
- The variables in javascript are case sensitive cat and CAT are treated totally different in javascript.
- You cannot use reserved keywords as variable names. For example int,if,instance of ,else etc.
Using let and const to assign a variable
With the advent of ES6 (Ecmascript 2015 version), we can assign variables using const and let as well . A variable assigned with use of const keyword cannot be reassigned whereas a variable assigned with let is block scoped.Unlike var let can be updated but not redeclared.
let example :
let greeting = "Hi How are you";
greeting = "Hello how are you doing?";
console.log("greeting variable value is: " + greeting);
Output of let example :
Hello how are you doing?
let example error:
let greeting = "say Hi";
let greeting = "say Hello instead";
console.log("greeting variable value is: " + greeting);
Output of let example error
Identifier ‘greeting’ has already been declared
const example :
const hight = 3.14;
console.log("hight variable value is: " + hight);
In this tutorial, we have explained What JavaScript variables are ? and How to use them ?.
If you have an inquiry or doubt don’t hesitate to leave them in comment. we are waiting your feedback.But remember to understand the concept very well, you need to practice more.
Hopefully, it was clear and concise.
JavaScript tutorials list:
- JavaScript tutorials list : access all JavaScript tutorials.