1.9. Usage of Data Structures, Modern Operators and Strings
1.9. Usage of Data Structures, Modern Operators and Strings
Basic Features
Usage of
1. Table of Contents
2.1. Introduction
Data structures are essential for storing and manipulating data, modern operators can help to make
code more concise and efficient, and strings are a versatile data type that can be used to represent a
wide variety of data. In JavaScript, there are three main data structures: arrays, objects, and strings.
Operators are used to assign values, compare values, perform arithmetic operations, and more.
There are different types of JavaScript operators:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Conditional Operators
Type Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y =
5, the table below explains the arithmetic operators
Assignment operators are used to assign values to JavaScript variables. Given that x = 10 and y = 5,
the table below explains the assignment operators
The + operator, and the += operator can also be used to concatenate (add) strings. Given that t1 =
"Good ", t2 = "Morning", and t3 = "", the table below explains the operators:
Oper Example t1 t2 t3
+ t3 = t1 + t2 "Good " "Morning" "Good Morning"
+= t1 += t2 "Good Morning" "Morning" "Good Good Morning"
Comparison operators are used in logical statements to determine equality or difference between
variables or values. Given that x = 5, the table below explains the comparison operators:
Syntax Example
(condition) ? x : y (z < 18) ? x : y
2.2.6. Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x = 6 and y
= 3, the table below explains the logical operators:
The ?? operator returns the first argument if it is not nullish (null or undefined). Otherwise it returns
the second argument.
Example 1:
function greet(name) {
return "Hello, " + (name ?? "Guest") + "!";
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet(null)); // Output: Hello, Guest!
console.log(greet(undefined)); // Output: Hello, Guest!
Example 2:
The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).
Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32
bit number. The result is converted back to a JavaScript number.
The typeof operator returns the type of a variable, object, function or expression:
const person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
delete person.age;
The delete operator deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables
or functions.
Note:
The delete operator should not be used on the properties of any predefined JavaScript objects
(Array, Boolean, Date, Function, Math, Number, RegExp, and String).
The void operator evaluates an expression and returns undefined. This operator is often used to
obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without
using the return value).
<a href="javascript:void(0);">
Useless link
</a>
<a href="javascript:void(document.body.style.backgroundColor='red');">
Click me to change the background color of body to red
</a>
2.3. Destructuring Arrays
When destructuring arrays, the order that variables are declared is important. Example with
destructuring:
If we only want the car and suv we can simply leave out the truck but keep the comma:
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
1. Given an array, use destructuring to swap the values of the first and last elements.
const numbers = [0, 9, 1, 4, 8];
//Given an array, use destructuring to swap the values of the first and
last elements.
console.log(firstElementOfSecondArray); // Output: 6
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' +
vehicle.brand + ' ' + vehicle.model + '.';
Here
} is the new way of using an object inside a function: Example with destructuring: Notice that
the object properties do not have to be declared in a specific order
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
function myVehicle({type, color, brand, model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' +
model + '.';
}
We can even destructure deeply nested objects by referencing the nested object then using a colon
and curly braces to again destructure the items needed from the nested object:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
}
}
myVehicle(vehicleOne)
function myVehicle({ model, registration: { state } }) {
const message = 'My ' + model + ' is registered in ' + state + '.';
}
The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object
into another array or object.
The spread operator is often used in combination with destructuring. For example, assign the first
and second items from numbers to variables and put the rest in an array:
Until now, we have learned about the following complex data structures:
However, that is not enough for real life. That is why Map and Set also exist.
2.3.1. Map
Map is a collection of keyed data items, just like an Object. But the main difference is that Map
allows keys of any type.
For instance
});
2.3.3. Object.entries: Map from Object
When a Map is created, we can pass an array (or another iterable) with key/value pairs for
initialization, like this:
If we have a plain object, and we’d like to create a Map from it, then we can use built-in method
Object.entries(obj) that returns an array of key/value pairs for an object exactly in that format.
let obj = {
name: "John",
age: 30
};
let map = new Map(Object.entries(obj));
console.log(map.get('name')); // John
Here, Object.entries returns the array of key/value pairs: [ ["name","John"], ["age", 30] ]. That is
what Map needs.
We’ve just seen how to create Map from a plain object with Object.entries(obj).
There’s Object.fromEntries method that does the reverse: given an array of [key, value] pairs, it
creates an object from them:
['banana', 1],
['orange', 2],
['meat', 4]
]);
// now prices = { banana: 1, orange: 2, meat: 4 }
console.log(prices.orange); // 2
E.g. we store the data in a Map, but we need to pass it to a 3rd-party code that expects a plain
object.
Here we go:
map.set('banana', 1);
map.set('orange', 2);
map.set('meat', 4);
2.3.5. Set
A Set is a special type collection – “set of values” (without keys), where each value may occur only
once.
The main feature is that repeated calls of set.add(value) with the same value don’t do anything.
That’s the reason why each value appears in a Set only once.
For example, we have visitors coming, and we’d like to remember everyone. But repeated visits
should not lead to duplicates. A visitor must be “counted” only once.
The map(), filter(), and reduce() functions are three of the most important array functions in
JavaScript. They allow you to transform, filter, and reduce arrays in a concise and efficient way.
2.4.1. map()
The map() function takes an array as an argument and returns a new array with the results of
applying a function to each element in the original array. The function that you pass to the map()
function is called the callback function. This callback function takes two arguments: the current
element in the array and the index of the element. The callback function should return a new value
that will be placed in the new array.
For example, the following code uses the map() function to create a new array with the squares of
the elements in the original array:
2.4.2. filter()
The filter() function takes an array as an argument and returns a new array with the elements that
meet a certain condition. The condition is specified by a callback function. The callback function
takes two arguments: the current element in the array and the index of the element. The callback
function should return a boolean value. If the callback function returns true, the element will be
included in the new array. If the callback function returns false, the element will be excluded from
the new array.
For example, the following code uses the filter() function to create a new array with the even
numbers in the original array:
const array = [1, 2, 3, 4, 5];
const newArray = array.filter(x => x % 2 === 0);
console.log(newArray); // [2, 4]
2.4.3. reduce()
The reduce() function takes an array as an argument and reduces the array to a single value. The
reduction is performed by a callback function. The callback function takes three arguments: the
current accumulator value, the current element in the array, and the index of the element. The
accumulator value is the value that is accumulated as the array is reduced. The callback function
should return the new accumulator value.
The first time the callback function is called, the accumulator value is the initial value. The initial
value can be any value. The callback function is then called for each element in the array. The new
accumulator value is the result of applying the callback function to the previous accumulator value
and the current element in the array.
For example, the following code uses the reduce() function to calculate the sum of the elements in
the array:
The reduce() function can also be used to perform other kinds of reductions, such as finding the
minimum or maximum value in an array. map(), filter(), and reduce() are powerful tools that can be
used to perform a variety of tasks on arrays.
2.5. Exercises
// Example:
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30
You can provide default values using the assignment operator (=).
// Example:
const person = { name: 'John' };
const { name, age = 25 } = person;
console.log(name); // Output: John
console.log(age); // Output: 25 (default value)
// Example:
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
You can swap variables using array destructuring without the need for an additional temporary
variable.
// Example:
let x = 5, y = 10;
[x, y] = [y, x];
console.log(x); // Output: 10
console.log(y); // Output: 5
5. What are spread operators in JavaScript? How are they used with arrays?
Spread operators allow you to expand arrays or objects into individual elements.
// Example:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
// Example:
const originalObj = { x: 1, y: 2 };
const clonedObj = { ...originalObj };
console.log(clonedObj); // Output: { x: 1, y: 2 }
Map is a built-in JavaScript object that allows you to store key-value pairs.
// Example:
const myMap = new Map();
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
console.log(myMap.get('key1')); // Output: value1
8. How can you iterate over the entries of a Map using destructuring?
You can use array destructuring to iterate over the entries of a Map.
// Example:
const myMap = new Map();
myMap.set('name', 'John');
myMap.set('age', 30);
Set is a built-in JavaScript object that allows you to store unique values.
// Example:
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Adding duplicate value, which will be ignored
10. How can you convert a Set to an array using the spread operator?
// Example:
const mySet = new Set([1, 2, 3]);
const myArray = [...mySet];
console.log(myArray); // Output: [1, 2, 3]
11. What are rest parameters in functions, and how do they relate to spread operators?
Rest parameters allow you to represent an indefinite number of arguments as an array, while spread
operators allow you to spread an array into individual elements.
// Example:
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
12. How can you combine objects using the spread operator?
You can combine objects using the spread operator.
// Example:
const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
// Example:
function greet(name, age) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
14. How can you merge two arrays using the spread operator?
// Example:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
15. How can you use the spread operator to concatenate strings from an array?
You can concatenate strings from an array using the spread operator.
// Example:
const words = ['Hello', ' ', 'World', '!'];
const message = [...words].join('');
console.log(message); // Output: Hello World!
The ellipsis (...) is used for various purposes, such as object and array destructuring, spread
operators, and rest parameters.
17. How do you use array destructuring with the rest parameter?
You can use array destructuring with the rest parameter to capture remaining elements in an array.
// Example:
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]
18. How can you use destructuring to access nested properties of an object?
// Example:
const person = {
name: 'John',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};
19. Can you use the spread operator to merge two objects with the same property names?
Yes, the spread operator can merge objects with the same property names. The last property
encountered will override the earlier ones
// Example:
const obj1 = { x: 1, y: 2 };
const obj2 = { y: 3, z: 4 };
20. How can you use the Map object to maintain the insertion order of keys?
The Map object automatically maintains the insertion order of keys, so keys are stored in the order
they were added.
// Example:
const myMap = new Map();
myMap.set('first', 1);
myMap.set('second', 2);
myMap.set('third', 3);
for (const [key, value] of myMap) {
console.log(key, value);
}
// Output:
// first 1
// second 2
// third 3
21. How can you use the reduce function to find the maximum value in an array?
You can use the reduce function to find the maximum value in an array.
22. Given the following array const numbers = [1, 2, 3, 4, 5]; Calculate the sum of the squares
of even numbers using map, filter, and reduce together