In our previous post , we’ve discussed, basic Concepts of JavaScript like, statements, delimiter, comments, variables, data types, objects, conditionals, loops, functions. In this post, mainly we are dividing our blog into two different parts. In the first part we’ll discuss about – maps, filter, reduce concepts and in the second part we’ll discuss about common errors in programming languages, error handling techniques. So, Let’s get started.
1.Map, Filter, and Reduce in JavaScript:
When you are working on JavaScript projects, you inevitably come across some situations where you need to do some data manipulation. You can use a for-loop to get the desired result, but the problem is a for-loop can quickly become a quite messy and large. At that times it can be much easier to use these map, filter, reduce operators. The map, reduce, filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. So, let’s discuss one by one briefly.
1.1 Map:
The map() method is used to apply a function on every element in an array. A new array is then returned.
let newArr = oldArr.map((value, index, arr) => {
//return element to new Array
});
Let’s see an example.
let stuArr = [
{"name":"Charishma", "age":20, "rollno":4},
{"name":"Tarun", "age":21, "rollno":5},
{"name":"Vamsi", "age":21, "rollno":6}
];
//Now lets double the value of rollno
let modRollno= stuArr.map( item => ({
...item,
rollno: item.rollno*2
}))
console.log(modRollno);
/* output: [
{"name":"Charishma", "age":20, "rollno":8}
{"name":"Tarun", "age":21, "rollno":10}
{"name":"Vamsi", "age":21, "rollno":12}
] */
stuArr is the array of objects we’ve map over. Since we want to double the value of the rollno to each object, all we did here is multiplying the rollno value with 2. Now, when we log out the value of our two arrays of objects, we can see the stuArr array is unchanged, and the modRollno array has our new values.
1.2 Filter:
What if you have an array, but only want some of the elements in it? That’s where filter() comes in.
let newArr = oldArr.filter(callback);
Here the newArr that is returned , the oldArr is to run the filter function and the callback function is used to test each element of the oldArr . If it returns true value then the corresponding element will be pushed onto the newArr or else it skips over the element.
Let’s see an example.
let stuArr = [
{"name":"Charishma", "age":20, "rollno":4},
{"name":"Tarun", "age":21, "rollno":5},
{"name":"Vamsi", "age":21, "rollno":6},
{"name":"Surya", "age":51, "rollno":7},
{"name":"Bhanuja", "age":18, "rollno":8},
{"name":"Raji", "age":17, "rollno":9}
];
let modArr= stuArr.filter( item => item.age> 18)
console.log(modArr);
/* output: [
{name: "Charishma", age: 20, rollno: 4}
{name: "Tarun", age: 21, rollno: 5}
{name: "Vamsi", age: 21, rollno: 6}
{name: "Surya", age: 51, rollno: 7}
] */
Excellent! All we need to do is define what you want to keep and then return true for those elements. Filter() will handle the rest.
3.Reduce:
This method is used to apply a function to each element in the array to reduce the array to a single value.
let result = arr.reduce(callback, initValue);
// Here initial value is optional
In the result single value is returned, the arr array is to run the reduce function, the callback function is used to execute each element of an array and the initValue is optional if this value is not specified, the 0th element is used as the initial value.
Our callback function can take four arguments. You will recognize three arguments from map() and filter() methods. The new argument is the accumulator. The accumulator accumulates all of the callbacks returned values.
let distances = [
{ 'from': 'New York', 'to': 'Dhaka', 'distance': 12654},
{ 'from': 'Vizag', 'to': 'Chennai', 'distance': 8858},
{ 'from': 'Kakinada', 'to': 'Hyderabad', 'distance': 1270}
]
let reducedDistance = distances.reduce((prevVal, item) => prevVal + item.distance, 0)
console.log(reducedDistance)
// output: 22782
Here, distances is the array of the object we’re going to reduce. We are finding the sum of the values of the distance in our array of objects. To do this, we used accumulator. The accumulator initial value is zero, for each iteration the value of the accumulator is updated and at last we will get the sum of all the items of the distance and it is stored in reducedDistance array.
4.Errors and Exception Handling:
In every programming language the common three errors are Syntax Errors , Logical Errors and Runtime Errors. Before going to exception handling let’s first discuss about this.
Syntax Errors:
Syntax errors occur at compile time in traditional programming languages whereas in JavaScript it occurs at interpret time. Now, let’s see one example.
console.log("I Love JavaScript";
// Syntax Error
Here, we missed the parentheses. so, we will get a syntax error.
Logical Errors:
Logical errors are difficult to track down. These occur when you make a mistake in the logic of the program which results an unexpected output.
You cannot catch those errors, because it depends on your requirement what type of logic you want to put in your program. Let’s see one example.
let x=3;
for( var i=0; i<x; i++)
{
console.log(x);
}
/* Expected output:
0
1
2 */
/* Actual output:
3
3
3 */
Runtime Errors:
Runtime errors occur during execution of the program (but after compilation/interpretation). Let’s see an example.
window.show();
Here, we will get a runtime error because we are trying to call a function that does not exist.
JavaScript has the capability to handle some of these type of errors by using try…catch…finally constructs as well as the throw operator. Is it interesting! so let’s see how it is possible.
Exceptional Handling:
The try…catch…finally:
The try…catch allows you to catch errors so the script can execute instead of dying. The throw statement is used to throw an error and the catch statement will catch that error and execute the code present in the catch block. If you want to finalize the program in any case of outcome we use finally statement.
Note: You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
Now, let’s see an example.
let x="Hello World";
try
{
if(isNaN(x)) throw "The given input is not a number.";
}
catch(error)
{
console.log(error);
}
finally
{
console.log("Finally, the code is ended!");
}
/* output: The given input is not a number.
Finally, the code is ended! */
As you see the code here, if the given input is number only the finally block is executed. if it is a string try..catch…finally blocks are executed.
You can download the following programs from our GitHub repo.
Conclusion:
In this blog, we have discussed the basics of JavaScript – maps, filters, reduce, errors and exception handling. In the next post, we’ll discuss about classes and many more. Until then, Stay home. Stay safe. Cheers✌️.