JavaScript Variables
Variables
JavaScript variables are containers used to store data values. The most common thing to use when writing JavaScript is “variables”. It is very simple to use. Let’s give it a small example.
var x = 20;
var y = "javascipt"
It is necessary to give the appropriate name when giving the names to the variables. This allows us not to be forced if we make changes to the code.
For example, a code like this is not wrong. But it leads to trouble in large projects:
var number = "javascirpt";
var text = [1,2,3]
For example, a code would be very accurate:
var leonidas = "this is javascript"

Variable Analysis
var web = "truecodes.org"
Let’s analyze this place.
- We have created a variable with “var” (variable).
- We named this variable as “web”.
- We matched this “web” variable to “truecodes.org”.
- If we use the name “web” in written codes then “truecodes.org” will return.
document.write(web);
//or
console.log(web)
output:
truecodes.org
wrong use:
x = 20;
y = 10;
document.write(x+y)
“var” can not be written without the variable.
JavaScript Variables Examples
Example 1
var x = 20;
var y = 10;
document.write(x+y)
output:
30
Example 2
var name = "true";
var surname = "codes";
document.write(
"name : " + name + "<br>" +
"surname : " + surname
)
output:
name : true
surname : codes
Example 3
var car = {
name: "audi",
date: 2019,
model: "X",
}
document.write(
"car name: " + car.name + "<br>"+
"model : " + car.model + "<br>" +
"date : " + car.date
)
output:
car name: audi
model : X
date : 2019
Points to Remember :
- Variable stores a single data value that can be changed later.
- Variables can be defined using var keyword. Variables defined without var keyword become global variables.
- Variables must be initialized before using.
- Multiple variables can be defined in a single line. e.g. var one = 1, two = 2, three = “three”;
- Variables in JavaScript are loosely-typed variables. It can store value of any data type through out it’s life time.