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.
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.
var x;
console.log(x); // Prints: undefined
You can assign a value to a variable using equal to (=) operator when you declare it or before using it.
var x = 5; // assigning value to a variable
console.log(x); // Prints: 5
If a variable is neither declared nor defined then we try to reference such variable, the result will be not defined.
var x = 5;
console.log(age); // ReferenceError: age is not defined
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 are stored as simple data types.
Primitive data types are immutable.
There are 6 primitive data types:
The sequence of characters delimited by either single or double-quotes.
var car = "Audi";
console.log(typeof car); // Prints: string
Any integer or floating-point numeric value.
var model = 2018;
console.log(typeof model); // Prints: number
Which tells true or false
var available = true;
console.log(typeof available); // Prints: boolean
This is special primitive-type that has only one value i.e., null.
var owner = null;
console.log(typeof owner);
// Prints: object
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.
A primitive type that had only value, undefined. The undefined is the value assigned to a variable that wasn’t initialized.
var condition = undefined;
console.log(typeof condition); // Prints: undefined
A unique and unaltered value.
var vol = Symbol();
console.log(typeof vol); // Prints: symbol
The way to convert from one data type to another(such as string to number, object to boolean, and so on) is called coercion.
var value1 = "5";
var value2 = 9;
var sum = value1 + value2;
console.log(sum); //Output: 59
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.
The same +
operator you use for adding two numbers can be used to concatenate two strings.
var msg1 = "There are ";
var numStudents = 25;
var msg2 = " students in class";
console.log(msg1 + numStudents + msg2); //Output: "There are 25 students"