Home > Web Front-end > JS Tutorial > 5 Typical JavaScript Interview Exercises

5 Typical JavaScript Interview Exercises

Joseph Gordon-Levitt
Release: 2025-02-21 09:23:10
Original
260 people have browsed it

5 Typical JavaScript Interview Exercises

Core points

  • Common JavaScript interview questions usually revolve around understanding key concepts, such as scope, creating native methods, promotion, this keywords, and call() and apply() functions.
  • In JavaScript, it is crucial to understand the context of a function and how to call it. The this keyword refers to the context, which varies depending on whether the function is called as part of an object or as a standalone function.
  • Elevation in JavaScript refers to the process in which variables and functions are moved to the top of their containment scope. However, while the function retains its initial value, the variable does not, and is initially set to undefined.

JavaScript developers are very popular in the IT field. If this role best reflects your knowledge, you have many opportunities to change your job company and increase your salary. But before you are hired by the company, you have to demonstrate your skills to pass the interview process. In this article, I will show you five common test candidate JavaScript skills and their related solutions in front-end job interviews. This will be fun!

Question 1: Scope

Consider the following code:

(function() {
   var a = b = 5;
})();

console.log(b);
Copy after login
Copy after login

What will the console print?

Answer

The above code prints 5. The trick of this problem is that in the Immediate Execution Function Expression (IIFE), there are two assignment statements, but the variable a is declared with the keyword var. This means that a is a local variable of the function. Instead, b is assigned to the global scope. Another trick with this problem is that it does not use strict pattern ('use strict';) inside the function. If strict mode is enabled, the code will throw an error "Uncaught ReferenceError: b is not defined". Remember, strict pattern requires you to explicitly refer to global scopes if that is the expected behavior. Therefore, you should write this:

(function() {
   'use strict';
   var a = window.b = 5;
})();

console.log(b);
Copy after login
Copy after login

Question 2: Create a "native" method

Define a String function on the repeatify object. This function accepts an integer, specifying the number of times the string needs to be repeated. This function returns a string that is repeated for a specified number of times. For example:

console.log('hello'.repeatify(3));
Copy after login
Copy after login

should be printed. hellohellohello

Answer

A possible implementation is as follows:

String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
       str += this;
   }

   return str;
};
Copy after login
Copy after login
This question tests developers' understanding of JavaScript inheritance and

properties. It also verifies that developers can extend the functionality of native data types (though it shouldn't be done). Another important point here is to prove that you understand how to avoid overwriting functions that may have been defined. This is done by testing whether the function does not exist before defining your own function: prototype

String.prototype.repeatify = String.prototype.repeatify || function(times) {/* code here */};
Copy after login
This technique is especially useful when you are asked to simulate a JavaScript function.

Question 3: Improve

What is the result of executing this code? Why?

(function() {
   var a = b = 5;
})();

console.log(b);
Copy after login
Copy after login

Answer

The result of this code is undefined and 2. The reason is that both the variable and the function are promoted (moved to the top of the function), but the variable does not retain any assigned values. So when printing the variable a it exists in the function (it is declared), but it is still undefined. In other words, the above code is equivalent to the following code:

(function() {
   'use strict';
   var a = window.b = 5;
})();

console.log(b);
Copy after login
Copy after login

Question 4: thisHow does it work in JavaScript

What is the result of the following code? Explain your answer.

console.log('hello'.repeatify(3));
Copy after login
Copy after login

Answer

Code prints Aurelio De Rosa and John Doe. The reason is that the context of the function (what does the this keyword refer to) in JavaScript depends on how the function is called, not how it is defined. In the first console.log() call, getFullname() is called as a function of the obj.prop object. Therefore, the context refers to the latter, and the function returns the fullname property of the object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. Therefore, the function returns the value of the attribute named window, which in this case is the value set by the code on the first line of the code snippet. fullname

Question 5: and call()apply() Fixed the bug in the previous issue so that the last one is printed

.

console.log()Aurelio De RosaAnswer

This problem can be fixed using the or

function to force the function's context. If you don't understand them and their differences, I suggest you read the article "The Difference between

and call()". In the following code, I will use apply(), but in this case, function.call will produce the same result: function.apply call() apply()

Conclusion
String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';

   for (var i = 0; i < times; i++) {
       str += this;
   }

   return str;
};
Copy after login
Copy after login

In this article, we discuss five common questions used to test JavaScript developers during interviews. Actual questions may vary from interview to interview, but the concepts and topics covered are often very similar. I hope you have fun and test your knowledge. If you are asked other interesting questions during the interview, feel free to share with us. This will help many developers.

FAQs (FAQ)

What common mistakes should be avoided in JavaScript encoding interviews?

One of the most common mistakes is not fully understanding the problem before starting to encode. Take the time to understand the problem and, if necessary, ask clarification. Another mistake is that the edge case is not considered. Always consider potential edge cases and how your code will handle them. Also, avoid hard-coded values. Your solution should work for all inputs, not just the examples provided. Finally, remember to communicate your thinking process. The interviewer is interested in your solution to your problem, not just the final solution.

How to prepare for JavaScript encoding interview?

First of all, you must thoroughly understand the basic knowledge of JavaScript. This includes understanding concepts such as closures, Promise, async/await and ES6 features. Practice coding problems on platforms such as LeetCode, HackerRank, and Codewars. Also, read common JavaScript interview questions and try to solve them yourself. Finally, understand the underlying working principle of JavaScript. This includes understanding the non-blocking features of event loops, call stacks, and JavaScript.

What are closures in JavaScript and why are they important?

Closures in JavaScript are functions that have access to parent scope, even if the parent function has been closed. They are important because they enable data privacy and are used in function factory and module patterns. Understanding closures is crucial because they are the basic part of JavaScript.

Can you explain the concept of "this" in JavaScript?

"this" in JavaScript is a special keyword, which refers to the context of calling a function. Its value depends on how the function is called. It can refer to a global object, an object currently being processed by a function, an object created by a constructor, or an object specified when using the call, apply or bind methods.

How does JavaScript handle asynchronous operations?

JavaScript uses callbacks, promises, and async/await to handle asynchronous operations. A callback is a function that is passed as an argument to other functions and is called after some operations are completed. Promise is an object that indicates that the asynchronous operation is finally completed or failed. async/await is the syntax sugar for Promise, which makes the asynchronous code look and behave like synchronous code.

What is a prototype in JavaScript?

The prototype in JavaScript is a mechanism for JavaScript objects to inherit features from each other. JavaScript is often called a prototype-based language, and understanding prototypes is the key to understanding JavaScript.

Can you explain the difference between "==" and "===" in JavaScript?

"==" is a loose equality operator that converts operands to the same type before making comparisons. "===" is a strict equality operator, which does not perform type conversion, it compares operands as is.

What is an event loop in JavaScript?

Event loop is a mechanism in JavaScript that constantly checks whether the call stack is empty. If yes, it takes the first task from the task queue and pushes it to the call stack. It allows JavaScript to become non-blocking and handles asynchronous operations.

What is JavaScript Promise?

Promise in JavaScript is an object that indicates that the asynchronous operation is finally completed or failed. They can be in one of three states: waiting, completed, or rejected. Promise is used to handle asynchronous operations in a more flexible way than callbacks.

What are some common JavaScript design patterns?

Some common JavaScript design patterns include module mode, prototype mode, observer mode, and singleton mode. Understanding these patterns can help you write more efficient, easier to maintain, and more extensible code.

The above is the detailed content of 5 Typical JavaScript Interview Exercises. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template