Variables and Primitive Data Types
Variables :
Variable means anything that can vary. JavaScript includes variables which hold the data value and it can be changed anytime.
JavaScript uses reserved keyword var to declare a variable.
Example :
var x; // declaring a variable as x.
If you console log variable x, it will give output as undefined because no value is assigned to a variable x.
You can assign a value to a variable using equal to (=) operator when you declare it or before using it.
Example :
If a variable is neither declared nor defined then we try to reference such variable, the result will be not defined.
Example :
Rules for naming variables :
- Variable name can have digits, letters, $ symbol, underscore.
- Must start with letter or $ symbol or underscore.
- Variable name should not be a keyword.
- Variable name can not start with a number.
There are other variable keywords introduced in ES6. They are
- let - let keyword to define a variable with restricted scope.
- const - const keyword to define a variable that cannot be reassigned.
Primitive Data Types :
Primitive data types are stored as simple data types.
Primitive data types are immutable.
There are 6 primitive data types:
- string
- number
- boolean
- null
- undefined
- symbol()
string :
The sequence of characters delimited by either single or double-quotes.
Example :
number :
Any integer or floating-point numeric value.
Example :
boolean :
Which tells true or false
Example :
null :
This is special primitive-type that has only one value i.e., null.
Example :
In above example, as you can see it printed as object instead of null because it is a bug in javascript. It’s there since begining of javascript.
undefined :
A primitive type that had only value, undefined. The undefined is the value assigned to a variable that wasn’t initialized.
Example :
symbol( ) :
A unique and unaltered value.
Example :
Coercion
The way to convert from one data type to another(such as string to number, object to boolean, and so on) is called coercion.
In above example, JavaScript has coerced the 9 from a number into a string and then concatenated the two values together, resulting in a string of 59.
String Concatenation
The same + operator you use for adding two numbers can be used to concatenate two strings.
Example :
Referential Data Types (non-primitive)
- Functions
- Arrays
- Objects