Core points
- Common JavaScript interview questions usually revolve around understanding key concepts, such as scope, creating native methods, promotion,
this
keywords, andcall()
andapply()
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);
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);
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));
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; };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 */};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);
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);
Question 4: this
How does it work in JavaScript
What is the result of the following code? Explain your answer.
console.log('hello'.repeatify(3));
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 Rosa
Answer
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()
String.prototype.repeatify = String.prototype.repeatify || function(times) { var str = ''; for (var i = 0; i < times; i++) { str += this; } return str; };
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
