In Javascript, variables are used to store data.
In the example, variables a
, b
, and c
are defined and assigned values.
var a = 5;
var b = 6;
var c = a + b;
Defined variables:
- The value of
a
variable is 5 - The value of variable
b
is 6 - The value of variable
c
becomes 11.
Variable definition
All Javascript variable names must be unique.
Javascript variable names are called identifiers.
Identifiers can be short like a
and b
, or more descriptive like birthDate
, firstName
, age
Variable declaration rules
- Variable names can contain letters, numbers, underscores, and dollar signs.
- Variable names can begin with a letter, underscore, or dollar sign.
- Variable names are CASE-sensitive. (a and A are different variables)
- No spaces between variable names.
- Javascript keywords cannot be used as variable names. (
var
,debugger
,if
,while
, etc…)
Value assignment
The equal (=
) operator is used to assign a value to a variable in Javascript.
var a = 5;
Variable types
Javascript variables can take numeric values like 100
or text values like Baransel Arslan
.
Strings are written in single or double quotes, while numeric values are written without quotation marks.
If numeric values are enclosed in quotes, Javascript will define the variable as a string.
var pi = 3.14;
var name = "Baransel Arslan";
var age = 21;
Creating a variable
Javascript variable creation is called variable declaration.
The var
, const
, let
keyword is used to create variables with Javascript.
We will learn about
const
andlet
keywords in the later post.
var name;
After creating a variable, the variable has no value. (The variable value is defined as undefined
.)
The equal (=
) operator is used to assign a value to a variable.
name = "Baransel Arslan";
We can also assign a value to a variable while creating a variable.
var name = "Baransel Arslan";
Variable arithmetic
We can use arithmetic operators on Javascript variables.
var a = 5 + 2 + 3;
When we use arithmetic operators on string values, it will act as a concatenation operator.
var a = "Baransel " + "Arslan";
When numbers are written in quotes, the Javascript string concatenation operator will be performed.
var a = "5" + 2 + 3;