Explore JavaScript data type manipulation through practical exercises involving numbers, strings, booleans, and more. Learn operations like concatenation, arithmetic, and logical comparisons with built-in methods.
Welcome to the exciting world of data type manipulation in JavaScript! In this section, we will explore how to work with different data types through practical exercises. By the end of this chapter, you’ll be comfortable performing operations like concatenation, arithmetic, and logical comparisons using JavaScript’s built-in methods. Let’s dive in!
Before we jump into exercises, let’s briefly revisit the primary data types in JavaScript:
'
), double ("
), or backticks (`
).true
or false
.Number
type can safely handle.Task: Perform basic arithmetic operations and explore built-in methods for numbers.
Math
object to round numbers and find the maximum and minimum values.// Declare two numeric variables
let num1 = 25;
let num2 = 10;
// Perform arithmetic operations
let sum = num1 + num2; // Addition
let difference = num1 - num2; // Subtraction
let product = num1 * num2; // Multiplication
let quotient = num1 / num2; // Division
console.log(`Sum: ${sum}`); // Output: Sum: 35
console.log(`Difference: ${difference}`); // Output: Difference: 15
console.log(`Product: ${product}`); // Output: Product: 250
console.log(`Quotient: ${quotient}`); // Output: Quotient: 2.5
// Use Math object methods
let rounded = Math.round(quotient); // Round the quotient
let max = Math.max(num1, num2); // Find maximum
let min = Math.min(num1, num2); // Find minimum
console.log(`Rounded Quotient: ${rounded}`); // Output: Rounded Quotient: 3
console.log(`Max: ${max}`); // Output: Max: 25
console.log(`Min: ${min}`); // Output: Min: 10
The Math
object provides several methods for mathematical operations. In this example, we used Math.round()
to round a number, Math.max()
to find the maximum, and Math.min()
to find the minimum. Experiment with other methods like Math.sqrt()
for square roots or Math.pow()
for exponentiation.
Task: Concatenate strings and explore string methods.
+
operator and template literals.toUpperCase()
, toLowerCase()
, and slice()
.// Declare two string variables
let greeting = "Hello";
let name = "World";
// Concatenate strings
let message1 = greeting + " " + name + "!"; // Using + operator
let message2 = `${greeting} ${name}!`; // Using template literals
console.log(message1); // Output: Hello World!
console.log(message2); // Output: Hello World!
// Use string methods
let upperCaseMessage = message1.toUpperCase(); // Convert to uppercase
let lowerCaseMessage = message1.toLowerCase(); // Convert to lowercase
let slicedMessage = message1.slice(0, 5); // Extract a portion of the string
console.log(`Uppercase: ${upperCaseMessage}`); // Output: Uppercase: HELLO WORLD!
console.log(`Lowercase: ${lowerCaseMessage}`); // Output: Lowercase: hello world!
console.log(`Sliced: ${slicedMessage}`); // Output: Sliced: Hello
String manipulation is a powerful tool in JavaScript. The toUpperCase()
and toLowerCase()
methods are useful for normalizing text, while slice()
allows you to extract specific parts of a string. Try experimenting with other methods like substring()
and replace()
.
Task: Perform logical comparisons and explore boolean operations.
&&
, ||
, !
) to evaluate expressions.// Declare two boolean variables
let isSunny = true;
let isWeekend = false;
// Logical operations
let goForAWalk = isSunny && isWeekend; // Logical AND
let stayIndoors = !isSunny || !isWeekend; // Logical OR and NOT
console.log(`Go for a walk: ${goForAWalk}`); // Output: Go for a walk: false
console.log(`Stay indoors: ${stayIndoors}`); // Output: Stay indoors: true
// Compare numbers and strings
let isEqual = (5 === 5); // Strict equality
let isNotEqual = ("hello" !== "world"); // Strict inequality
console.log(`Is equal: ${isEqual}`); // Output: Is equal: true
console.log(`Is not equal: ${isNotEqual}`); // Output: Is not equal: true
Boolean logic is fundamental in controlling program flow. The logical operators &&
(AND), ||
(OR), and !
(NOT) allow you to build complex conditions. Remember, ===
checks for strict equality, meaning both value and type must match.
Task: Differentiate between undefined
and null
and handle them in code.
null
to a variable and compare it with undefined
.undefined
and null
.// Declare a variable without assigning a value
let uninitializedVariable;
// Assign null to a variable
let emptyValue = null;
// Compare undefined and null
let isUndefined = (uninitializedVariable === undefined);
let isNull = (emptyValue === null);
console.log(`Is undefined: ${isUndefined}`); // Output: Is undefined: true
console.log(`Is null: ${isNull}`); // Output: Is null: true
// Handle undefined and null
if (uninitializedVariable === undefined) {
console.log("Variable is undefined.");
} else if (emptyValue === null) {
console.log("Variable is null.");
} else {
console.log("Variable has a value.");
}
undefined
is the default value for uninitialized variables, while null
is an assignment value representing “no value.” Use conditional statements to check for these states and handle them appropriately in your code.
Task: Create and use symbols as unique identifiers.
// Create a symbol
let uniqueId = Symbol("id");
// Use symbols as object keys
let user = {
[uniqueId]: 12345,
name: "Alice"
};
console.log(user[uniqueId]); // Output: 12345
// Compare symbols
let anotherId = Symbol("id");
console.log(uniqueId === anotherId); // Output: false
Symbols are unique and immutable, making them ideal for object keys where uniqueness is required. Even if two symbols have the same description, they are different entities.
Task: Perform operations with BigInt
for large integers.
BigInt
variable.BigInt
.BigInt
with regular numbers.// Declare a BigInt variable
let bigIntValue = 1234567890123456789012345678901234567890n;
// Perform arithmetic operations
let bigIntSum = bigIntValue + 10n;
let bigIntProduct = bigIntValue * 2n;
console.log(`BigInt Sum: ${bigIntSum}`); // Output: BigInt Sum: 1234567890123456789012345678901234567900n
console.log(`BigInt Product: ${bigIntProduct}`); // Output: BigInt Product: 2469135780246913578024691357802469135780n
// Compare BigInt with regular numbers
let regularNumber = 12345;
console.log(bigIntValue > regularNumber); // Output: true
BigInt
allows you to work with integers beyond the safe limit of the Number
type. Note that operations between BigInt
and regular numbers require explicit conversion.
Now it’s your turn! Modify the examples above to experiment with different inputs and operations. For instance, try using different string methods, or explore more Math
object functions. The more you practice, the more comfortable you’ll become with data type manipulation in JavaScript.
To help visualize how JavaScript handles different data types, let’s look at a simple flowchart illustrating the process of manipulating a string and a number:
flowchart TD A[Start] --> B[Declare a String] B --> C[Declare a Number] C --> D[Concatenate String and Number] D --> E[Perform Arithmetic on Number] E --> F[Output Results] F --> G[End]
Caption: This flowchart represents a basic process of declaring a string and a number, concatenating them, performing arithmetic on the number, and outputting the results.
BigInt
for large integers.Remember, this is just the beginning. As you progress, you’ll build more complex and interactive web pages. Keep experimenting, stay curious, and enjoy the journey!