DEV Community

Cover image for 6 Interesting JavaScript Questions You Should Know
Chris1993
Chris1993

Posted on

6 Interesting JavaScript Questions You Should Know

As the primary development language for front-end developers, JavaScript itself has a relatively simple syntax and a well-developed ecosystem, which is gaining more and more influence in the community.

In our development process using JavaScript, we often encounter all kinds of strange problems that make us feel headache.

I have compiled 6 common and interesting questions to share with you.

Inspiration comes from WTFJS.

1. A strange try...catch

❓ Problem

What does executing the following code return? 2 or 3?

(() => {
  try {
    return 2;
  } finally {
    return 3;
  }
})();
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

The answer is 3. Why is that?

This is because in the try...catch...finally statements, the finally clause is executed whether or not an exception is thrown.

In addition, if an exception is thrown, the statement in the finally clause is executed even if there is no catch clause to handle the exception.

πŸ“š Reference

2. [] and null are objects

❓ Problem

What does the next three lines of code return?

typeof [];
typeof null;

null instanceof Object;
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

The result is:

typeof []; // -> 'object'
typeof null; // -> 'object'

null instanceof Object; // false
Enter fullscreen mode Exit fullscreen mode

The typeof operator returns a string that must conform to Table 37: The typeof operator returns the value.

It returns the string 'object' for null, normal, standard specific, and nonstandard specific objects that do not implement [[Call]].

console.log(typeof 42);
// expected output: "number"

console.log(typeof '@Chris1993');
// expected output: "string"

console.log(typeof true);
// expected output: "boolean"

console.log(typeof undeclaredVariable);
// expected output: "undefined"
Enter fullscreen mode Exit fullscreen mode

However, you can check the type of the object using the toString method.

Object.prototype.toString.call([]);
// -> '[object Array]'

Object.prototype.toString.call(new Date());
// -> '[object Date]'

Object.prototype.toString.call(null);
// -> '[object Null]'
Enter fullscreen mode Exit fullscreen mode

πŸ“š Reference

3. The Arrow function expressions return undefined

❓ Problem

Why did the function f2 return undefined?

let f1 = () => '@Chris1993';
f1(); // -> '@Chris1993'

let f2 = () => {};
f2(); // -> undefined
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

We thought we should return {}, but why did return undefined, in fact, because the arrow function returns {} is part of the Arrow function expressions syntax, we write a test case can see:

let f2 = () => {
    return '@Chris1993'
};
f2(); // -> '@Chris1993'
Enter fullscreen mode Exit fullscreen mode

So the f2 function above returns undefined.

of course, if you want to return an {} object, you can just put {} it inside the parentheses:

let f2 = () => ({});
f2(); // -> {}
Enter fullscreen mode Exit fullscreen mode

4. Can the function be executed using backquotes?

❓ Problem

Is there any other way to call a function other than the following?

function f(...args) {
  return args;
}

f(1, 2, 3); // -> [ 1, 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

Of course, we can use backquotes to call:

f`Hello string ${'@Chris1993'}, Hello boolean ${false}, Hello array ${[1, 2, 3]}`;
/*
[
    ["Hello string ",  ", Hello boolean ", ", Hello array ", ""],
    "@Chris1993",
    false,
    [1, 2, 3]
]
*/
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

This looks amazing in appearance, but in fact, is template string. This is an advanced form of template string, a labeled template string.

In the example code above: the f function is the tag of a template literal, and the tag can be used to parse the template string. The first argument to the label function contains an array of string values. The remaining parameters are expression dependent.

πŸ“š Reference

5. Tags in JavaScript?

❓ Problem

What does the following code execution output?

foo: {
  console.log("Hello");
  break foo;
  console.log("@Chris1993");
}
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

The answer is yes, it returns the string Hello. Since foo is recognized as a label, then execute the following console.log("Hello"), and then execute break foo to break execution.

We often use labeled statements together with break and continue statements to end or continue a loop:

let str = '';

loop1:
for (let i = 0; i < 5; i++) {
  if (i === 1) {
    continue loop1;
  }
  str = str + i;
}

console.log(str);
// expected output: "0234"
Enter fullscreen mode Exit fullscreen mode

πŸ“š Reference

6. {}{} is undefined

❓ Problem

Write them in the console. They will return the value defined in the last object.

{}{}; // -> undefined
{}{}{}; // -> undefined
{}{}{}{}; // -> undefined
{foo: 'bar'}{}; // -> 'bar'
{}{foo: 'bar'}; // -> 'bar'
{}{foo: 'bar'}{}; // -> 'bar'
{a: 'b'}{c:' d'}{}; // -> 'd'
{a: 'b', c: 'd'}{}; // > SyntaxError: Unexpected token ':'
({}{}); // > SyntaxError: Unexpected token '{'
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Answer

When inspecting each {}, they returns undefined. If you inspect {foo: 'bar'}{}, you will find {foo: 'bar'} is 'bar'.

There are two meanings for {}: an object or a block. For example, the {} in () => {} means block. So we need to use () => ({}) to return an object.

Let's use {foo: 'bar'} as a block. Write this snippet in your console:

if (true) {
  foo: "bar";
} // -> 'bar'
Enter fullscreen mode Exit fullscreen mode

Surprisingly, it behaviors the same! You can guess here that {foo: 'bar'}{} is a block.πŸ‘

Welcome to follow me, I will share more useful contentπŸ˜„ ~

Happy coding! ❀️

Top comments (5)

Collapse
 
idodav profile image
Ido David

You post is great and I was really surprised by the first example with the try catch
You have an error in the third example with the object in the last code block
you wrote

let f2 = () => ({});
f2(); // undefined
Enter fullscreen mode Exit fullscreen mode

It should be

let f2 = () => ({});
f2(); // {}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chris1993 profile image
Chris1993

thinks πŸ˜„

Collapse
 
zhouyg profile image
zhou-yg

like something terrible in javascript

Collapse
 
chris1993 profile image
Chris1993

😁😁

Collapse
 
tibabit profile image
Vikash Kesarwani

Interesting