JavaScript's data types and detailed what can be contained within the Object
data type.
JavaScript Data Types
JavaScript supports eight fundamental data types:
- String: Represents textual data.
- Number: Handles both integer and floating-point numbers.
- BigInt: Supports integers larger than those that
Number
can handle. - Boolean: Represents logical entities and can be either
true
orfalse
. - Undefined: Assigned to variables that have been declared but not yet assigned a value.
- Null: Denotes a deliberate non-value (used for indicating “no value”).
- Symbol: A unique and immutable primitive value that can be used as the key of an Object property.
- Object: The most complex data type that can represent any non-primitive value.
The Object Data Type
In JavaScript, an object is a non-primitive data type that can encapsulate complexities and can include:
- An object instance: Basic JavaScript objects created with braces
{}
. - An array: A list-like object whose prototype has methods to perform traversal and mutation operations.
- A date: An object representing date and time, which can be created using the
Date
constructor.
Examples
Numbers: Used for both integers and floating-point values.
let length = 16; // Integer
let weight = 7.5; // Floating-point number
Strings: Textual data enclosed in quotes.
let color = "Yellow"; // String with double quotes
let lastName = "Johnson"; // Another string
Booleans: Represents logical values true and false.
let x = true; // Boolean true
let y = false; // Boolean false
Object: Non-primitive type that stores collections of data.
const person = {firstName: "John", lastName: "Doe"}; // Object with properties
Array object: A special kind of object, structured as an ordered list of elements.
const cars = ["Saab", "Volvo", "BMW"]; // Array containing strings
Date object: Represents a single moment in time in a platform-independent format.
const date = new Date("2022-03-25"); // Date object representing March 25, 2022
Understanding Data Types in Programming
In programming, data types play a crucial role because they dictate how a computer interprets data and what kinds of operations can be performed. This is particularly evident in dynamic languages like JavaScript, where the type of a variable can affect the outcome of operations.
- Example of Data Type Impact
let x = 16 + "Volvo";
In this scenario, adding a number to a string might seem illogical, but JavaScript handles it by converting the number into a string, resulting in a concatenation of the two operands:
// JavaScript interprets it as:
let x = "16" + "Volvo"; // "16Volvo"
JavaScript's Type Coercion
When a number is combined with a string, JavaScript converts the number to a string. This process is known as type coercion.
- Further Examples
let x = 16 + "Volvo"; // "16Volvo"
let y = "Volvo" + 16; // "Volvo16"
JavaScript evaluates expressions from left to right, which can lead to different results depending on the sequence of operations:
let x = 16 + 4 + "Volvo"; // "20Volvo"
let y = "Volvo" + 16 + 4; // "Volvo164"
JavaScript Types are Dynamic
JavaScript is dynamically typed, meaning a variable declared in JavaScript can be assigned and reassigned different data types:
- Example of Dynamic Typing:
let x; // Initially, x is undefined
x = 5; // Now x holds a Number
x = "John"; // Now x is reassigned to hold a String
This flexibility allows developers to use the same variable for different types of data throughout a program. However, this feature also requires careful management to avoid errors related to unexpected data types, especially in complex applications. The ability to change types dynamically can lead to more versatile and adaptive code but necessitates a thorough understanding of type implications in your JavaScript logic.
JavaScript Strings
Quotes:Strings in JavaScript can be enclosed in single quotes ('
), double quotes ("
), or backticks (`
), allowing for flexibility depending on the context or developer preference:
let name1 = 'John Doe'; // Single quotes
let name2 = "Jane Doe"; // Double quotes
Backticks:Additionally, JavaScript ES6 introduced template literals, which use backticks and can include expressions inside ${}
:
let firstName = "John";
let lastName = "Doe";
let fullName = `${firstName} ${lastName}`; // "John Doe"
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>
<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>
<p id="demo"></p>
<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
document.getElementById("demo").innerHTML =
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>
</body>
</html>
JavaScript Numbers
In JavaScript, all numbers are stored in a 64-bit floating point format (IEEE 754), which is capable of representing both decimal (fractional) numbers and integers.
// With decimals:
let x1 = 34.00; // Although specified with decimals, it's equivalent to 34
// Without decimals:
let x2 = 34; // Internally stored as floating point
Exponential Notation in JavaScript
JavaScript supports exponential (scientific) notation for representing very large or very small numbers efficiently:
Examples
let y = 123e5; // Represents 12300000
let z = 123e-5; // Represents 0.00123
In these examples, e
(for exponent) links the number to the power of 10 by which it is multiplied. 123e5
means 123×105123×105, and 123e-5
means 123×10−5123×10−5.
Number Types in JavaScript vs. Other Languages
- JavaScript:
- All numbers in JavaScript are stored as 64-bit floating-point values (double), irrespective of whether they appear to be integers or decimals. This uniform type simplifies number management but may affect precision in certain cases.
- Other Programming Languages:
- Typically, languages like C, Java, or Python offer various number types to accommodate different needs:
- Whole numbers (integers):
- Sizes vary from
byte
(8-bit) up tolong
(64-bit), each fitting different ranges of values.
- Sizes vary from
- Real numbers (floating-point):
float
(32-bit) anddouble
(64-bit) to handle fractional numbers with varying degrees of precision.
- Whole numbers (integers):
- Typically, languages like C, Java, or Python offer various number types to accommodate different needs:
Why It Matters?
JavaScript's approach eliminates the need to declare number types explicitly, which can make the language easier to use for beginners and reduce complexity in coding. However, developers must be aware of the implications of using a single number type, especially when performing operations that require high precision or dealing with extremely large numbers. For such cases, JavaScript offers the BigInt
type, designed to handle integers that exceed the safe limit for standard numbers.
JavaScript BigInt
In JavaScript, the traditional number type is limited to representing numbers up to 253−1253−1 due to its 64-bit floating-point format. This limitation prompted the introduction of BigInt
in ES2020 for handling larger integers.
- What is
BigInt
?BigInt
is a built-in object that provides a way to represent whole numbers larger than the 53-bit limit of the standardNumber
type. This makesBigInt
invaluable for applications that require precise large integer calculations, such as cryptography or working with large databases. - Creating a
BigInt
:ABigInt
can be created by appendingn
to the end of an integer literal or by passing a string to theBigInt()
function if the number is too large to be represented as aNumber
.
Example Usage:
let x = BigInt("123456789012345678901234567890"); // From a string
let y = 123456789012345678901234567890n; // Using the BigInt literal
Key Points about BigInt
- Operations: Most mathematical operations that can be performed with
Number
are also available forBigInt
, except mixingBigInt
andNumber
directly in operations. For example, you cannot add aBigInt
and aNumber
without explicitly converting one type to the other. - Precision:
BigInt
allows for arbitrary precision, meaning it can handle operations on integers without losing accuracy, regardless of how large the numbers are. - Compatibility: Since
BigInt
is a relatively new feature in JavaScript, developers should be mindful of compatibility issues with older browsers or environments that might not yet supportBigInt
.
JavaScript Booleans
Booleans in JavaScript are a primitive data type that can only hold one of two possible values: true
or false
. This simplicity makes Booleans incredibly useful for any operations that require binary conditions such as checking if a condition is met, or toggling states in logical controls.
Example of Boolean Values:
let x = 5;
let y = 5;
let z = 6;
console.log(x == y); // Returns true because x and y have the same value
console.log(x == z); // Returns false because x and z have different values
In these examples:
x == y
evaluates totrue
because the values ofx
andy
are identical.x == z
evaluates tofalse
because the values ofx
andz
are different.
Usage of Booleans
Booleans are particularly helpful in if-else structures, loops, and any other control flow statements, where decisions need to be made based on the truthiness or falsity of a condition. For instance:
Conditional Execution:
if (x == y) {
console.log("x and y are equal."); // This will be executed
} else {
console.log("x and y are not equal.");
}
Logical Operations:
let conditionA = true;
let conditionB = false;
console.log(conditionA && conditionB); // Returns false
console.log(conditionA || conditionB); // Returns true
console.log(!conditionB); // Returns true, negating conditionB
JavaScript Arrays
JavaScript arrays are defined using square brackets, with items separated by commas. Here's an example that creates an array named cars
, containing three car names:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array indexes are zero-based, which means the first item is [0].</p>
<p id="demo"></p>
<script>
const cars = ["Saab","Volvo","BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html>
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
JavaScript Objects
JavaScript objects are defined using curly braces {}
. Properties within the object are expressed as name:value pairs, separated by commas. Here’s an example:
const person = {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
The typeof Operator
You can use the JavaScript typeof
operator to determine the type of a variable or the result of an expression. The typeof
operator returns a string indicating the type of the evaluated operand.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
typeof "" + "<br>" +
typeof "John" + "<br>" +
typeof "John Doe";
</script>
</body>
</html>
Undefined
In JavaScript, a declared variable that hasn't been assigned a value explicitly has the value undefined
. Additionally, the type of such a variable is also undefined
.
Here’s an example to illustrate this:
let car; // The value is undefined because it's not assigned any value
console.log(typeof car); // Outputs: "undefined"
This behavior highlights the importance of initializing variables to avoid potential issues related to undefined
values in your JavaScript code.
You can explicitly set the value of any variable to undefined
in JavaScript, which effectively "empties" it. When you assign undefined
to a variable, both the value and the type of the variable become undefined
.
let car = "Volvo";
car = undefined; // Now the value is undefined
console.log(typeof car); // Outputs: "undefined"
Empty Values
An empty string (""
) in JavaScript is a legitimate value and has its own type, distinct from undefined
.
Example:
let car = ""; // The value is an empty string
console.log(typeof car); // Outputs: "string"