0% found this document useful (0 votes)
7K views

1.9. Usage of Data Structures, Modern Operators and Strings

The document discusses JavaScript operators and data structures. It covers modern operators like arithmetic, assignment, comparison, logical and type operators. It also discusses data structures like arrays, objects and strings. It provides examples and explanations of destructuring, maps, sets and array methods like map, filter and reduce.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views

1.9. Usage of Data Structures, Modern Operators and Strings

The document discusses JavaScript operators and data structures. It covers modern operators like arithmetic, assignment, comparison, logical and type operators. It also discusses data structures like arrays, objects and strings. It provides examples and explanations of destructuring, maps, sets and array methods like map, filter and reduce.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Learning outcome1:

Use Fundamental Features of

Basic Features

Usage of
1. Table of Contents

1. Table of Contents ............................................................................................................................ 2


2. Data structures, modern operators and Strings ............................................................................. 3
2.1. Introduction ............................................................................................................................ 3
2.2. Modern operators................................................................................................................... 3
2.2.1. Arithmetic Operators ...................................................................................................... 3
2.2.2. JavaScript Assignment Operators ................................................................................... 4
2.2.3. JavaScript String Operators ............................................................................................. 4
2.2.4. Comparison Operators .................................................................................................... 4
2.2.5. Conditional (Ternary) Operator ...................................................................................... 4
2.2.6. Logical Operators ............................................................................................................ 5
2.2.7. The Nullish Coalescing Operator (??) .............................................................................. 5
2.2.8. The Optional Chaining Operator (?.) ............................................................................... 6
2.2.9. JavaScript Bitwise Operators .......................................................................................... 6
2.2.10. The typeof Operator ....................................................................................................... 6
2.2.11. The delete Operator........................................................................................................ 7
2.2.12. The Spread (...) Operator ................................................................................................ 7
2.2.13. The in Operator ............................................................................................................... 7
2.2.14. The instanceof Operator ................................................................................................. 8
2.2.15. The void Operator ........................................................................................................... 8
2.3. Destructuring Arrays ............................................................................................................... 9
2.3.1. Exercise on destructuring an array ................................................................................. 9
2.1. Destructuring object ............................................................................................................. 10
2.2. Spread Operator ................................................................................................................... 11
2.3. Map and Set .......................................................................................................................... 12
2.3.1. Map ............................................................................................................................... 12
2.3.2. Iteration over Map ........................................................................................................ 12
2.3.3. Object.entries: Map from Object .................................................................................. 13
2.3.4. Object.fromEntries: Object from Map .......................................................................... 14
2.3.5. Set ................................................................................................................................. 14
2.3.6. Iteration over Set .......................................................................................................... 16
2.4. Data Transformations: map, filter, reduce ........................................................................... 16
2.4.1. map() ............................................................................................................................. 16
2.4.2. filter() ............................................................................................................................ 16
2.4.3. reduce() ......................................................................................................................... 17
2.5. Exercises ................................................................................................................................ 18

2. Data structures, modern operators and Strings

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.

2.2. Modern operators

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

2.2.1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y =
5, the table below explains the arithmetic operators

Oper Name Example Results


+ Addition x=y+2 y=5, x=7
- Subtraction x=y-2 y=5, x=3
* Multiplication x=y*2 y=5, x=10
** Exponentiation ES2016 x=y**2 y=5, x=25
/ Division x=y/2 y=5, x=2.5
% Remainder x=y%2 y=5, x=1
++ Pre increment x = ++y y=6, x=6
++ Post increment x = y++ y=6, x=5
-- Pre decrement x = --y y=4, x=4
-- Post decrement x = y-- y=4, x=5
2.2.2. JavaScript Assignment 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

Oper Example Same As Result


= x=y x=y x=5
+= x += y x=x+y x = 15
-= x -= y x=x-y x=5
*= x *= y x=x*y x = 50
/= x /= y x=x/y x=2
%= x %= y x=x%y x=0
: x: 45 size.x = 45 x = 45

2.2.3. JavaScript String 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"

2.2.4. Comparison Operators

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:

Oper Name Comparing Returns


== equal to x == 8 false
== equal to x == 5 true
=== equal value and type x === "5" false
=== equal value and type x === 5 true
!= not equal x != 8 true
!== not equal value or type x !== "5" true
!== not equal value or type x !== 5 false
> greater than x>8 false
< less than x<8 true
>= greater or equal to x >= 8 false
<= less or equal to x <= 8 true

2.2.5. Conditional (Ternary) Operator

The conditional operator assigns a value to a variable based on a condition.

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:

Oper Name Example


&& AND (x < 10 && y > 1) is true
|| OR (x === 5 || y === 5) is false
! NOT !(x === y) is true
2.2.7. The Nullish Coalescing Operator (??)

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:

function discount(price, discountPercentage) {


const discount = discountPercentage ?? 0;
const discountedPrice = price - (price * discount / 100);
return discountedPrice;
}
console.log(discount(100, 10));// Output: 90
console.log(discount(50, null));// Output: 50 (no discount)
console.log(discount(75, undefined));// Output: 75 (no discount)
2.2.8. The Optional Chaining Operator (?.)

The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).

/** Given the following object, use optional chaining


to safely access the nested property.**/
const user = {
name: 'John',
address: {
street: '123 Main St',
city: 'Cityville',
zipcode: '12345'
}
};
// Use optional chaining to safely get the zipcode
const zipcode = user?.address?.zipcode;
console.log(zipcode); // Output: '12345'

2.2.9. JavaScript Bitwise Operators

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.

Oper Name Example Same as Result Decimal


& AND x=5&1 0101 & 0001 0001 1
| OR x=5|1 0101 | 0001 0101 5
~ NOT x=~5 ~0101 1010 10
^ XOR x=5^1 0101 ^ 0001 0100 4
<< Left shift x = 5 << 1 0101 << 1 1010 10
>> Right shift x = 5 >> 1 0101 >> 1 0010 2
>>> Unsigned right x = 5 >>> 1 0101 >>> 1 0010 2

2.2.10. The typeof Operator

The typeof operator returns the type of a variable, object, function or expression:

typeof "John" // is string


typeof 3.14 //is number
typeof NaN //is number
typeof false //is boolean
typeof [1, 2, 3, 4] //is object
typeof {name:'John', age:34} //is object
typeof new Date() //is object
typeof function () {} //is function
typeof myCar //is undefined
typeof null //is object
2.2.11. The delete Operator

The delete operator deletes a property from an object:

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).

This can crash your application.

2.2.12. The Spread (...) Operator

The ... operator expands an iterable into more elements:

const q1 = ["Jan", "Feb", "Mar"];


const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
The ... operator can be used to expand an iterable into more arguments for function calls:
const year = [...q1, ...q2, ...q3, ...q4];
Example:

const numbers = [23,55,21,87,56];


let maxValue = Math.max(...numbers);

2.2.13. The in Operator

The in operator returns true if a property is in an object, otherwise false:

const person = { firstName: "John", lastName: "Doe", age: 50 };


let isFirstNameExists= ("firstName" in person); // true
let isAgeExists= ("age" in person); // true
Note:
You cannot use in to check for array content like ("Volvo" in cars). See the example bellow

//in operator is not suitable to be used in Array Objects


const cars = ["Saab", "Volvo", "BMW"];
console.log("Saab" in cars)//false
console.log(undefined in cars)//false
console.log(0 in cars);//true
console.log(1 in cars);//true
console.log(2 in cars);//true
console.log(3 in cars);//false (because no value at this index)
console.log("length" in cars);//true

//in can be used in Predefined Objects


console.log("NaN" in Number);//true
console.log("PI" in Math);//true
console.log("length" in String);//true

2.2.14. The instanceof Operator

The instanceof operator returns true if an object is an instance of a specified object:

const cars = ["Saab", "Volvo", "BMW"];

(cars instanceof Array) // Returns true


(cars instanceof Object) // Returns true
(cars instanceof String) // Returns false
(cars instanceof Number) // Returns false

2.2.15. The void Operator

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:

const vehicles = ['mustang', 'f-150', 'expedition'];


const [car, truck, suv] = vehicles;

If we only want the car and suv we can simply leave out the truck but keep the comma:

const vehicles = ['mustang', 'f-150', 'expedition'];


const [car,, suv] = vehicles;

Destructuring comes in handy when a function returns an array:

function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;

return [add, subtract, multiply, divide];


}

const [add, subtract, multiply, divide] = calculate(3, 4);


console.log(calculate(3,4))

2.3.1. Exercise on destructuring an array

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.

const numbers = [0, 9, 1, 4, 8];

// Your code here

[numbers[0], numbers[numbers.length - 1]] = [numbers[numbers.length - 1],


numbers[0]];

console.log(numbers); // Output: [8, 9, 1, 4, 0 ]


2. Given an array with nested arrays, use destructuring to extract the element at index 2 of the
second nested array. const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

// Given an array with nested arrays, use destructuring to extract the


element at index 2 of the second nested array.

const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

// Your code here

const [, , firstElementOfSecondArray] = matrix[1];

console.log(firstElementOfSecondArray); // Output: 6

2.1. Destructuring object

Here is the old way of using an object inside a function

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 + '.';
}

2.2. Spread Operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object
into another array or object.

const numbersOne = [1, 2, 3];


const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

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:

const numbers = [1, 2, 3, 4, 5, 6];


const [one, two, ...rest] = numbers;
//We can use the spread operator with objects too
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
2.3. Map and Set

Until now, we have learned about the following complex data structures:

 Objects are used for storing keyed collections.


 Arrays are used for storing ordered collections.

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.

Methods and properties are:

new Map() //– creates the map.


map.set(key, value) //– stores the value by the key.
map.get(key) //– returns the value by the key, undefined if key doesn’t
exist in map.
map.has(key) //– returns true if the key exists, false otherwise.
map.delete(key) //– removes the element (the key/value pair) by the key.
map.clear() //– removes everything from the map.
map.size //– returns the current element count.

For instance

let map = new Map();

map.set('1', 'str1'); // a string key


map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key

// remember the regular Object? it would convert keys to string


// Map keeps the type, so these two are different:
alert( map.get(1) ); // 'num1'
alert( map.get('1') ); // 'str1'
alert( map.size ); // 3

2.3.2. Iteration over Map

For looping over a map, there are 3 methods

• map.keys() – returns an iterable for keys,


• map.values() – returns an iterable for values,
• map.entries() – returns an iterable for entries [key, value], it’s used by default in for..of.
For instance

let recipeMap = new Map([


['cucumber', 500],
['tomatoes', 350],
['onion', 50]
]);

// iterate over keys (vegetables)


for (let vegetable of recipeMap.keys()) {
console.log(vegetable); // cucumber, tomatoes, onion
}

// iterate over values (amounts)


for (let amount of recipeMap.values()) {
console.log(amount); // 500, 350, 50
}

// iterate over [key, value] entries


for (let entry of recipeMap) { // the same as of recipeMap.entries()
console.log(entry); // cucumber,500 (and so on)
}
// runs the function for each (key, value) pair
recipeMap.forEach((value, key, map) => {
console.log(`${key}: ${value}`); // cucumber: 500 etc

});
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:

// array of [key, value] pairs


If let
we have
map a=plain
newobject,
Map([and we’d like to create a Map from it, then we can use built-in method
Object.entries(obj) that
['1', 'str1'], returns an array of key/value pairs for an object exactly in that format
[1, 'num1'],
[true, 'bool1']
]);
console.log( map.get('1') ); // str1

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.

So we can create a map from an object like this:

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.

2.3.4. Object.fromEntries: Object from Map

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:

let prices = Object.fromEntries([

['banana', 1],
['orange', 2],
['meat', 4]
]);
// now prices = { banana: 1, orange: 2, meat: 4 }
console.log(prices.orange); // 2

We can use Object.fromEntries to get a plain object from Map.

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:

let map = new Map();

map.set('banana', 1);
map.set('orange', 2);
map.set('meat', 4);

let obj = Object.fromEntries(map.entries()); // make a plain object (*)


//Below line olso can do the same job
let obj = Object.fromEntries(map); // omit .entries()
// done!
// obj = { banana: 1, orange: 2, meat: 4 }
console.log(obj.orange); // 2

2.3.5. Set

A Set is a special type collection – “set of values” (without keys), where each value may occur only
once.

Its main methods are:


new Set([iterable])// – creates the set, and if an iterable object is
provided (usually an array), copies values from it into the set.

set.add(value) //– adds a value, returns the set itself.


set.delete(value) //– removes the value, returns true if value existed at
the moment of the call, otherwise false.
set.has(value) //– returns true if the value exists in the set, otherwise
false.
set.clear() //– removes everything from the set.
set.size //– is the elements count.

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.

Set is just the right thing for that:

let set = new Set();

let john = { name: "John" };


let pete = { name: "Pete" };
let mary = { name: "Mary" };

// visits, some users come multiple times


set.add(john);
set.add(pete);
set.add(mary);
set.add(john);
set.add(mary);

// set keeps only unique values


console.log( set.size ); // 3

for (let user of set) {


console.log(user.name); // John (then Pete and Mary)
}
2.3.6. Iteration over Set

We can loop over a set either with for..of or using forEach:

let set = new Set(["oranges", "apples", "bananas"]);

for (let value of set) console.log(value);

// the same with forEach:


set.forEach((value, valueAgain, set) => {
console.log(value);
});

2.4. Data Transformations: map, filter, reduce

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:

const array = [1, 2, 3];


const newArray = array.map(x => x * x);
console.log(newArray); // [1, 4, 9]

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.

The reduce() function returns the final accumulator value.

For example, the following code uses the reduce() function to calculate the sum of the elements in
the array:

const array = [1, 2, 3, 4, 5];


const sum = array.reduce((accumulator, element) => {
return accumulator + element;
}, 0);
console.log(sum); // 15

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

1. What is object destructuring in JavaScript? Provide an example.


Object destructuring allows you to extract properties from an object and assign them to variables.

// Example:
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30

2. How can you provide default values during object destructuring?

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)

3. Explain array destructuring in JavaScript with an example.


Array destructuring allows you to extract elements from an array and assign them to variables.

// 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

4. How can you swap variables using array destructuring?

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]

6. How can you use the spread operator to clone an object?


You can clone an object using the spread operator.

// Example:
const originalObj = { x: 1, y: 2 };
const clonedObj = { ...originalObj };
console.log(clonedObj); // Output: { x: 1, y: 2 }

7. What is the Map object in JavaScript? How do you use it?

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);

for (const [key, value] of myMap) {


console.log(key, value);
}
// Output:
// name John
// age 30
9. What is the Set object in JavaScript? How do you use it?

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

console.log(mySet); // Output: Set(2) { 1, 2 }

10. How can you convert a Set to an array using the spread operator?

You can 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);
}

console.log(sum(1, 2, 3, 4)); // Output: 10

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 };

const combinedObj = { ...obj1, ...obj2 };


console.log(combinedObj); // Output: { x: 1, y: 2, z: 3 }
13. Explain how to use the spread operator to pass arguments to a function.

You can pass arguments to a function using the spread operator.

// Example:
function greet(name, age) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}

const person = ['John', 30];


greet(...person); // Output: Hello, John! You are 30 years old.

14. How can you merge two arrays using the spread operator?

You can merge two arrays using the spread operator.

// Example:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const mergedArray = [...arr1, ...arr2];


console.log(mergedArray); // Output: [1, 2, 3, 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!

16. What is the use of the ellipsis (...) in JavaScript?

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?

You can use nested destructuring to access properties of nested objects.

// Example:
const person = {
name: 'John',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
};

const { name, address: { city, country } } = person;


console.log(name); // Output: John
console.log(city); // Output: New York
console.log(country); // Output: 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 };

const mergedObj = { ...obj1, ...obj2 };


console.log(mergedObj); // Output: { x: 1, 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.

const numbers = [12, 5, 27, 8, 16];

const maxNumber = numbers.reduce((max, current) => (current > max ? current :


max), numbers[0]);
console.log(maxNumber); // Output: 27

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

// Example: Calculate the sum of the squares of even numbers


const numbers = [1, 2, 3, 4, 5];
const result = numbers
.filter((num) => num % 2 === 0) // Filter even numbers
.map((num) => num * num) // Square each number
.reduce((acc, num) => acc + num, 0); // Sum the squares
console.log(result); // Output: 20 (2^2 + 4^2)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy