JavaScript Data Types
Data types define the type of data a variable can hold. In JavaScript, different data types are used to store numbers, text, true/false values, and more.
JavaScript is a dynamic language, which means you do not need to declare the type of a variable. The type is automatically determined.
Types of Data in JavaScript
JavaScript has several built-in data types. The most common ones are:
- String
- Number
- Boolean
- Undefined
- Null
String
A string is used to store text. It can be written inside single or double quotes.
<!DOCTYPE html> <html> <body> <p id="str"></p> <script> let name = 'John'; document.getElementById('str').innerHTML = name; </script> </body> </html>Try this code
Number
Numbers are used to store numeric values such as integers and decimals.
<!DOCTYPE html> <html> <body> <p id="num"></p> <script> let x = 10; let y = 5; document.getElementById('num').innerHTML = x + y; </script> </body> </html>Try this code
Boolean
A boolean data type can have only two values: true or false.
<!DOCTYPE html>
<html>
<body>
<p id="bool"></p>
<script>
let isOnline = true;
document.getElementById('bool').innerHTML = isOnline;
</script>
</body>
</html>
Try this code
Undefined
A variable that is declared but not assigned a value has the type undefined.
<!DOCTYPE html>
<html>
<body>
<p id="undef"></p>
<script>
let x;
document.getElementById('undef').innerHTML = x;
</script>
</body>
</html>
Try this code
Null
Null represents an empty value. It is intentionally assigned to a variable.
<!DOCTYPE html>
<html>
<body>
<p id="null"></p>
<script>
let data = null;
document.getElementById('null').innerHTML = data;
</script>
</body>
</html>
Try this code
The typeof Operator
The typeof operator is used to check the data type of a variable.
<!DOCTYPE html>
<html>
<body>
<p id="type"></p>
<script>
let x = 'Hello';
document.getElementById('type').innerHTML = typeof x;
</script>
</body>
</html>
Try this code
Why Data Types are Important
- They help in storing different kinds of data
- They make code easier to understand
- They prevent errors in programs
- They are essential for logical operations