Data types are fundamental building blocks in any programming language. They define the type of values your variables can hold and how operations are performed on them. JavaScript is a dynamically typed language, meaning data types are associated with values, not variables themselves.Primitive Data Types:
JavaScript offers seven basic data types categorized as primitive:
- Strings: Represent sequences of characters enclosed in single (‘), double (“), or backtick (““) quotes.
JavaScript
let name = “Alice”;
let message = ‘Hello, World!’;
let greeting = `It’s a great day!`; - Numbers: Can be integers (whole numbers) or floating-point numbers (decimals). JavaScript uses 64-bit floating-point representation for all numbers.
JavaScript
let age = 30;
let pi = 3.14159; - Booleans: Represent logical values: true or false.
JavaScript
let isLoggedIn = true;
let isSunny = false; - null: Represents the intentional absence of a value.
JavaScript
let emptyVariable = null; - undefined: Represents a variable that has been declared but not assigned a value.
JavaScript
let uninitializedVar;
console.log(typeof uninitializedVar); // Output: “undefined” - BigInt (ES6+): Introduced in ES6, BigInt allows storing integers larger than the typical number range. Represented by a trailing n.
JavaScript
let largeNumber = 12345678901234567890n; - Symbol (ES6+): Also introduced in ES6, Symbol creates unique and immutable primitive values. Useful for creating object properties that won’t clash with other names.
JavaScript
let uniqueSymbol = Symbol(“customSymbol”);
Non-Primitive Data Type:
- Object: A complex data type that allows storing collections of key-value pairs. We’ll explore objects in detail in a separate chapter.
Type Coercion:
JavaScript can automatically convert between certain data types during operations. This can sometimes lead to unexpected results, so be mindful of type coercion.
JavaScript
let num = 10;
let str = “5”;
console.log(num + str); // Output: “105” (string concatenation)
console.log(num * str); // Output: 50 (string converted to number)
Checking Data Types:
Use the typeof operator to determine a variable’s data type at runtime.
JavaScript
let x = “hello”;
console.log(typeof x); // Output: “string”
Dynamic Typing Benefits:
Considerations:
Best Practices:
- Use meaningful variable names to indicate their expected data type.
- Consider using type checking tools or libraries for larger projects.
- Be aware of potential type coercion behavior.
By understanding data types, you can write more predictable and robust JavaScript code!
Source: hashnode.com