JS Test #4: try/catch
Coderslang: Become a Software Engineer
Posted on February 4, 2021
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
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')
ANSWER: the expression in the console.log
will be evaluated as true
and logged to the screen.
Posted on February 4, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.