Submodule 6.3: JavaScript data types
Data types
There are three basic data types in JavaScript which can be inserted into a variable. These are:
- Number
- String
- Boolean
Number
The number data type, consist of any number with or without decimal places.
var number1 = 12.35;
var number2 = 123;
var bigNumber = 123e4; /*1230000*/
var smallNumber = 123e-4; //0.0123
String
The string type is any type of text. Text must be surrounded with " "
or ' '
. Note that the quotes are not displayed on the page. If you need to have quotes displayed you must use additional quotes which shouldn’t be of the same type that you used to symbolized your script in JavaScript. For example, if you had this:var name = "This is my name"
, and you want to display quotes between the text, you should write: var name = " 'This is my name ' "
.
var firstName = "Vasilis"; /*Vasilis*/
var lastName = 'Palilis'; //Palilis
var message = "It's alright"; //It's alright
Boolean
The Boolean type contains only two values, true
and false
. Booleans are commonly used on conditional as we will see later on the course.
var p = true;
var q = false;
var myBool = true; /*Boolean type*/
var myString = "true"; //String type
A variable type can change
If you do this:
var myVar = "true";
and then this:
var myVar = true;
the type of the variable is immediately changed from "string
" to "boolean
".
The JavaScript "typeof()"
JavaScript has an operation which gives us the type of a variable. This is the typeof()
operator.
Try this on your console. Go and type typeof(3)
or typeof (true)
. What do you see?
Exercise
- Open your editor, create a new file and save it as
exersice06.3.01.html
in the folder "Exercises". - Copy the below code and paste it into the new file.
- Save the file. You have your HTML page with the types of JavaScript variables. You can experiment on this!