JavaScript Data Types- Javascript tutorial
#JavaScript Data Types- Javascript turial
In JavaScript, data types are fundamental building blocks that define the type of data a variable can hold. Understanding data types is essential for writing reliable and bug-free code. This tutorial will cover all the key data types in JavaScript, how they behave, and how to use them effectively.
JavaScript has seven primitive data types. These are immutable and represent a single value.
Represents a sequence of characters.
let name = "John";
Represents both integers and floating-point numbers.
let age = 25;
let price = 99.99;
Represents either true
or false
.
let isLoggedIn = true;
A variable that has been declared but not assigned a value.
let score;
console.log(score); // undefined
Represents an explicitly empty or non-existent value.
let data = null;
Represents a unique and immutable value.
let id = Symbol("id");
Used to represent integers with arbitrary precision.
let bigNumber = 1234567890123456789012345678901234567890n;
These are more complex data types and are mutable.
Used to store collections of data.
let person = {
name: "Alice",
age: 30
};
A special type of object used to store ordered collections.
let colors = ["red", "green", "blue"];
Functions are objects that can be executed.
function greet() {
console.log("Hello World");
}
You can check the type of a variable using the typeof
operator:
typeof "hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof null; // "object" (this is a quirk in JavaScript)
typeof undefined;// "undefined"
typeof []; // "object"
typeof {}; // "object"
typeof function() {}; // "function"
JavaScript is dynamically typed, which means variables can hold values of any type and can be reassigned:
let data = "Hello";
data = 42; // valid
JavaScript automatically converts data types in some cases (type coercion), and you can also convert manually:
let result = "5" + 1; // "51"
Number("5"); // 5
String(123); // "123"
Boolean(0); // false
Understanding JavaScript data types is essential for mastering the language. Whether you're working with simple strings and numbers or complex objects and functions, knowing how data types behave will help you write clean, efficient, and bug-free code.
Keep practicing, and explore how different types interact with each other as you build more complex applications!