JavaScript try/catch blocks [Tech Interview Quiz]
try
blocks in JavaScript help you execute dangerous code that can throw errors. You can catch those errors in the catch
blocks and handle them gracefully.
Error handling is an important part of software development, so try/catch
questions appear very frequently in JavaScript technical interviews.
Consider the following code snippet and describe what would happen when you try to run it.
Code snippet as a picture
|
|
How will the try/catch
blocks behave? What will be logged to the console? (think well, then click for the answer and explanation)
Explanation
So, we have 2 variables and 2
try/catch
blocks that supposedly catch errors and put them intoe1
ande2
.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
ande2
. To do that, we need to check the code in thetry
blocks. Both trying to get tonull.length
andundefined.length
will throw an error as neitherundefined
nornull
have thelength
property.These errors will be caught in the catch blocks as
e
and then assigned to the variablese1
ande2
.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:
1 2
Cannot read property 'length' of null Cannot read property 'length' of undefined
Then,
.split(' ')[0]
gives us the first words of these sentences which isCannot
in both cases. So ultimately, the program can be simplified to:
1
console.log('Cannot' === 'Cannot')
Answer
The expression in the
console.log
will be evaluated astrue
and logged to the screen