DEV Community

Cover image for JS Test #4: try/catch
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Edited on • Originally published at learn.coderslang.com

JS Test #4: try/catch

code-snippet
What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

So, we have 2 variables and 2 try/catch blocks that supposedly catch errors and put them into e1 and e2.

Then, the content of errors is analyzed, compared and the comparison result is logged to the screen.

First, let’s determine what’s inside of e1 and e2. To do that, we need to check the code in the try blocks. Both trying to get to null.length and undefined.length will throw an error as neither undefined nor null have the length property.

These errors will be caught in the catch blocks as e and then assigned to the variables e1 and e2.

The content of these errors will be a bit different. If we were to log e.message to the screen in the catch block, we would see the following:

Cannot read property 'length' of null
Cannot read property 'length' of undefined
Enter fullscreen mode Exit fullscreen mode

Then, .split(' ')[0] gives us the first words of these sentences which is Cannot in both cases. So ultimately, the program can be simplified to:

console.log('Cannot' === 'Cannot')
Enter fullscreen mode Exit fullscreen mode

ANSWER: the expression in the console.log will be evaluated as true and logged to the screen.

Learn Full Stack JavaScript

Top comments (2)

Collapse
 
petermoyano profile image
Pedro Ignacio Moyano

Won't e1.message.split("")[0] give you the first letter of Cannot ? So the expression actually evaluates C === C. Great series though, it's really helpfull for us begginers. Thank you Coderslang.

Collapse
 
darrylnoakes profile image
Darryl Noakes

It's splitting on " ", not "", so it will split on spaces, not every character. That means the first element will be the word "Cannot".