- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Data Types
JavaScript is a dynamically typed language. This means you don't have to explicitly declare the type of a variable when you create it. Instead, JavaScript determines the type automatically based on the value assigned to it. While this provides great flexibility, it also means developers need a solid grasp of how types behave to avoid bugs.
JavaScript data types can be broadly categorized into two groups:
- Primitive data types: The most basic building blocks. They are immutable (cannot be changed) and represent a single value.
- Object types: Complex data structures that can store collections of data or more complex entities.
Primitive Data Types
There are currently seven primitive data types in JavaScript (including BigInt, which is essential for modern web development):
- String: Used for text data. You can use single quotes (''), double quotes (""), or backticks (``) for template literals.
- Number: Represents both integers and floating-point numbers. JavaScript doesn't distinguish between "ints" and "floats" like other languages do.
- BigInt: Used for integers that are too large to be represented by the standard Number type.
- Boolean: Represents a logical entity with two values:
trueorfalse. - Undefined: A variable that has been declared but has not yet been assigned a value.
- Null: Represents the intentional absence of any object value. It is often used to "reset" a variable or signify that an object is empty.
- Symbol: A unique and immutable identifier, often used as keys for object properties to prevent naming collisions.
let myString = "Hello, World!"; // String
let myNumber = 42; // Number
let isTrue = true; // Boolean
let myUndefined; // Undefined (value is undefined)
let myNull = null; // Null (explicitly empty)
let mySymbol = Symbol('id'); // Symbol
let bigNumber = 9007199254740991n; // BigInt
`Hello, ${userName}!`.
undefined and null may seem similar, but they serve different purposes. undefined is the system default for uninitialized things, while null is what developers use to say "this is purposefully empty."
Object Data Type
Object: Unlike primitives, objects are used to store collections of data. They consist of key-value pairs and are the foundation of almost everything in JavaScript.
// Real-world example: Representing a user profile
let userAccount = {
username: 'dev_pro',
loginCount: 15,
isActive: true,
lastLogin: null
};
const to declare them if you don't intend to reassign the entire object to a new value. This prevents accidental overwriting of your data structures.
Special Data Types
In JavaScript, Arrays and Functions are actually special types of Objects, but they behave in unique ways that warrant their own discussion.
Function: A reusable block of code. In JavaScript, functions are "first-class citizens," meaning they can be stored in variables, passed as arguments, and returned from other functions.
function calculateTax(price, rate) {
return price * rate;
}
// Storing a function in a variable
const greet = function(name) {
return `Welcome, ${name}`;
};
Array: An ordered collection of values. While arrays are technically objects, they use numeric indices (starting at 0) to organize data.
// Real-world example: A list of products in a shopping cart
let shoppingCart = ['Laptop', 'Mouse', 'Keyboard'];
console.log(shoppingCart[0]); // Outputs: Laptop
typeof [], JavaScript will return "object". To specifically check for an array, use Array.isArray(myVariable).
Type Checking
To find out what type of data a variable holds, you can use the typeof operator. This is incredibly useful for debugging or when handling data from an external API.
console.log(typeof "JS Rocks"); // "string"
console.log(typeof 100); // "number"
console.log(typeof false); // "boolean"
console.log(typeof { a: 1 }); // "object"
console.log(typeof undefined); // "undefined"
typeof null returns "object". It should return "null", but it cannot be fixed now because it would break millions of existing websites.
Type Conversion
Sometimes you need to convert data from one type to another. This can happen explicitly (you do it manually) or implicitly (JavaScript does it for you, often called "coercion").
// Explicit conversion: Changing a string to a number for calculation
let inputAmount = "150.50";
let numericAmount = parseFloat(inputAmount);
// Explicit conversion: Changing a number to a string
let errorCode = 404;
let errorMessage = "Error found: " + String(errorCode);
"5" - 1 results in 4 (number), but "5" + 1 results in "51" (string). Always be explicit with your conversions to keep your code predictable.
Understanding these data types is the foundation of mastering JavaScript. Once you know how types work, you'll be able to handle data more effectively and write code that is much harder to break.