Lesson 3 - Data Types in JavaScript
Just like the way we have different types of objects in real world, we also have different kinds of objects in your code. Because your code creates some kind of virtual world similar to the real world. These types are called Data Type.
It can be useful for example when you are creating variables. You can create a variable to contain a number, or another variable to contain a name(or a string of letters), etc.
Now let me show you how it's done:
// Examples of data types
let str = "Hello"; // String
let num = 42; // Number
let isActive = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
console.log(typeof str, typeof num, typeof isActive, typeof nothing, typeof notDefined);
Explanation:
JavaScript has multiple data types: String, Number, Boolean, Null, and Undefined.
typeof
is used to check the type of a variable.
Try your hand
1. Create a File:
- Open your favorite code editor (e.g., VS Code or Notepad++).
- Open your code editor and create a new file named lesson3-data-types.html.
2. Write the Code:
Copy and paste the following HTML and JavaScript code::
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 3 - Data Types</title>
</head>
<body>
<script>
// Examples of data types
let str = "Hello"; // String
let num = 42; // Number
let isActive = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
console.log(typeof str, typeof num, typeof isActive, typeof nothing, typeof notDefined);
</script>
</body>
</html>
- Save the file in a folder where you can find it easily.
3. Preview the File:
- Open the file in your browser (e.g., Chrome or Firefox). You can double-click on it or right-click -> open with... -> choose your browser
- Press
Ctrl + Shift + J
(Windows) orCmd + Option + J
(Mac) to open the browser's developer console. - Observe the output:
string number boolean object undefined
4. Experiment:
- Change the values of the variables (
str
,num
, etc.) and save the file. - Refresh the browser and note the changes in the console
That was fantastic!