JavaScript Interview Questions, Answers, and Explanations
JavaScript is the most widely used programming language in the world. It's also one of the three core building blocks of the web, along with HTML and CSS. This has led to high demand for JavaScript developers and a proliferation of free and paid courses promising to teach people JavaScript in just a few weeks. The quality of these courses varies greatly, so you'll need to carefully vet before hiring JavaScript developers.
Once you've posted a comprehensive job description and you're interviewing top candidates, you want to get an idea of their overall conceptual understanding of JavaScript as well as their ability to put it into practice. Plan your time to include common JavaScript interview questions about how JavaScript works and short coding challenges. You'll also want to make sure an applicant has the soft skills to work effectively as part of a team and will be able to communicate with customers and stakeholders. In this guide, we've included sample JavaScript interview questions that cover all of these areas.
JavaScript Core Concepts and Basic Interview Questions
If you're hiring an entry-level JavaScript developer or you just want to start with some easy concepts, these are some good JavaScript basic interview questions to ask:
What is JavaScript?
There's nothing wrong with starting with the basics. Obviously, if a candidate can't tell you what JavaScript is, you shouldn't hire them. A good answer to this question will include the fact that JavaScript is both a client-side and server-side language that's used for scripting and programming. It should also mention that JavaScript is inserted into HTML pages to allow you to create dynamically updating content.
Explain the most common primitive data types in JavaScript.
Primitive data types store only one value and include:
- Strings: A collection of alphanumeric characters, used to store data such as names or addresses
- Numbers: Can include integers and decimals but can't include letters, often used in mathematical operations
- Booleans: Can only have one of two values, true or false
- Undefined: Variable has been created but hasn't been given a value
- Null: Variable is empty or nothing
What is hoisting and why is it important?
Hoisting is the default behavior in JavaScript where all declarations are moved to the top. It lets you use a variable before it has been declared. If this function is something you don't understand or aren't aware of, it can cause bugs in your program.
What is the isNaN function?
NaN stands for Not-a-Number. The isNaN function converts a value to a number before testing it and returns true if the value is not a number.
What is the difference between "=" "==" and "===" operators?
In JavaScript:
- The assignment operator "=" is used to assign value to a variable
- The comparison operator "==" is used to compare two variables without considering the type of data
- The comparison operator "===" is used to compare two variables of the same data type
Explain the types of scope in JavaScript.
Scope defines where variables can be accessed in the program. The four types of scopes are:
- Block Scope: Defined with the keywords "let" and "const" but not "var", cannot be accessed outside of the block
- Local Scope: Defined within the function, can only be recognized within the function, allows variables with the same name to be used in different functions
- Function Scope: Defined and recognized within the function, may contain several local scopes
- Global Scope: Declared outside of a function, can be accessed by all scripts and functions within the program
How do timing events work in JavaScript?
Timing events are used to run a piece of code at a certain time. These are global methods available in the "Window" object. Timers are operated within a single thread, so they may queue up to be executed. Events include:
- setTimeout(): Usually written within a function, used to execute code after a set amount of time
- clearTimeout(): Used to cancel a timeout set with the setTimeout method, stops the execution of a function past a set parameter
- setInterval(): Used to execute code repeatedly within a fixed time interval between each call
- clearInterval(): Used to cancel the repeated action in the setInterval
What types of popup boxes are available in JavaScript?
There are three types of popup boxes:
- Alert: When you want to make sure a user understands something, must click "OK" to clear
- Confirm: When you want the user to verify something, must click "OK" or "Cancel" to clear
- Prompt: When you want the user to enter a value, must click "OK" or "Cancel" to clear
Explain the different types of programming errors in JavaScript.
There are three categories of JavaScript programming errors:
- Syntax errors: These parsing errors occur at interpret time and only affect code within the same thread unless code in other threads depends on the erroneous code
- Runtime errors: These exceptions occur during execution, only affect the thread they occur in, others continue to be executed
- Logical errors: These errors occur as a result of faulty logic driving your script, most difficult type to catch
How do you handle errors and exceptions?
You can catch syntax and runtime errors with the "try...catch...finally" construct. The "throw" statement allows you to raise your exceptions so that they can be captured later. The "onerror" event handler gives you the error message, URL, and line number of the code that caused the error.
Common JavaScript Interview Practical Questions
Once a candidate has demonstrated basic JavaScript proficiency, you can move on to more intermediate interview questions. These questions will give you a good idea of an applicant's practical knowledge.
How can HTML elements be accessed by JavaScript code?
There are four ways HTML elements can be accessed:
- getElementById(‘idname’): Finds an element by ID name
- getElementsByClass(‘classname’): Finds elements with the given classname
- getElementsByTagName(‘tagname’): Finds elements with the given tag name
- querySelector(): Returns the first selected element with the given css style selector
What are the ways you can define a variable in JavaScript?
Declaring a variable in JavaScript is done with one of three keywords:
- var: used to declare a variable that will be processed before execution of the code
- const: used to declare a block-scoped variable that can't be changed through reassignment or redeclared
- let: used to declare a variable that may be reassigned but will only be used in the block where it's defined
What's the difference between a window and a document?
The window is the first object that gets loaded into the browser. It contains most of the properties such as length, innerWidth, innerHeight, name, and more, as well as history, location, and functions. The document is loaded inside the window and is a property of the window. It contains html, aspx, php, or other document objects that will be loaded into the browser.
How are primitive and object types passed in functions?
Primitive data types are passed by value, which is done by creating a copy of the original.
Object data types are passed by reference, which is done by creating an alias of the original.
What is event bubbling?
Event bubbling explains how JavaScript handles event propagation. When an event occurs on an element, it first runs the event handlers on it, then those on its parent, and so on until it reaches the body element.
What are closures in JavaScript?
A closure is a combination of a function and references to its surrounding state, including any local variables that were in-scope when the closure was created. Closures are created whenever a function is created.
Explain imports and exports in JavaScript.
Imports and exports let you create modules in JavaScript. Once you create a module, which can contain classes, functions, variables, and objects, it can be used in other files as well. Export and import are the keywords used to export and import members in a module. You can export variables by using the export keyword in front of the variable declaration. You can also export a function or a class by using the export keyword in front of it.
You can import modules by using the import keyword. You can specify what you want to import from a JavaScript file. You can use an alias to import from a member. You can also import all of the members using the * symbol.
What is the difference between a JavaScript framework and a JavaScript library?
A JavaScript framework defines the design of the application. It calls and uses code in a specific way. A framework uses prewritten code to perform routine programming features to make development easier.
A JavaScript library contains snippets of code that can be used to perform common functions. You can call specific functions from a library from its parent code. A JavaScript framework is a more encompassing solution than a library.
What are some popular JavaScript frameworks, and what are they used for?
AngularJS is used to create single-page applications (SPAs). SPAs function like mobile apps so they don't need to be refreshed to function. They use HTML vocabulary on dynamic web pages by loading content from the webserver rather than the web browser.
Vue.js is a framework for building user interface (UI) and SPA. It uses the architecture pattern of model-view-view-model (MVVM), which allows the model to be separated from the UI. It contains directives, which are HTML attributes that allow you to extend HTML. It's useful for prototyping, UI projects, and mobile applications.
React is a JavaScript framework that simplifies the process of creating interactive UIs. Its hot reload feature allows developers to immediately see changes as they're made. It's part of React Native, which is used to create mobile applications. React's one-way data flow is more intuitive than two-way data binding.
Learn More: Software Development KPIs for Managers, Developers, and Teams
Advanced JavaScript Interview Question Examples
If you're hiring a senior-level JavaScript developer, you'll want to ask harder questions to ensure they have an in-depth and thorough understanding of JavaScript. Here are some questions that will test more obscure topics:
What is a promise in JavaScript?
A promise is an object that shows the eventual outcome of asynchronous options and the resultant value. It allows you to handle multiple asynchronous operations. There are three possible states of a promise:
- Pending is the initial state, which has been neither fulfilled nor rejected
- Fulfilled means the operation has been completed successfully
- Rejected means that the operation failed
How can you empty a JavaScript array?
There are several different methods you can use to empty a JavaScript array:
- Redefine the array as empty
- Set the length of the array to zero
- Use splice() to update the array to contain zero elements
- Remove the elements using array methods pop() or shift()
What is a pure function?
A pure function is free from any side effects. Given the same input, it will return the same output. A pure function must always return a value. The return value depends on the inputs and arguments passed in the value. A pure function:
- Produces a predictable output
- Can be read as a standalone unit
- Can be reused at multiple points without altering its behavior
- Can be tested as an independent unit
What is an immediately invoked function expression (IIFE)?
An IIFE executes immediately after it's created. It can be used to avoid polluting the global namespace since the variables created inside the IIFE are only visible inside its scope.
What are the benefits of consistently using arrow functions where possible?
The benefits of using arrow functions in ES6 include:
- Arrow functions are easier to read and write
- With consistent use, arrow functions guarantee that everything uses the same thisObject as the root
- Regular functions are more noticeable and can be used to define the scope
What is a generator in JavaScript?
A generator is a function that can be exited and then later reentered, and the context will be saved across reentries. The function* syntax is used to create generator functions. When it's initially called, a generator function doesn't execute its code. Instead, it returns an iterator called a generator. When the generator's "next" method is called, the generator's code is executed until the keyword "yield" is reached.
A generator lets you choose to jump out of a function and lets the outer code determine when to jump back in. It also lets you control asynchronous call outside of your code.
Explain the temporal dead zone (TDZ).
The TDZ is the state where the variables "let" and "constr" can't be reached. They are in scope, but they haven't been declared. Variables exist in the TDZ from the place they get bound until they're declared. If you try to access the variable when it's in the TDZ, you'll get a "ReferenceError." The TDZ doesn't occur with "var" because its default value is undefined in the process of hoisting.
What is the difference between a forEach loop and a .map() loop, and why would you choose one instead of the other?
A forEach loop iterates through the elements of an array, executes a callback for each element, and does not return a value. A .map() loop iterates through the elements of an array and creates a new array by mapping each element to a new element by calling the function on each element. A forEach loop doesn't return a new array but the .map() loop does.
If you don't want to change the original array, use the .map() loop. If you just need to iterate over an existing array, use the forEach loop.
Can you write a multi-line string in JavaScript?
Yes, you can write a multi-line string in JavaScript in three ways:
- Backticks
- + operator
- Backslash
Why would you wrap the entire contents of a JavaScript source file into a function block?
Many of the most popular JavaScript libraries are doing this because it creates a closure around the entire contents of the file. This helps avoid potential namespace clashes with other JavaScript modules and libraries by creating a private namespace. This also allows you to create a shorter reference for a global variable.
What are the benefits of using strict mode at the beginning of a JavaScript file?
"Use strict" enforces stricter parsing and error handling on JavaScript code at runtime. Code errors that would have been overlooked will generate errors and exceptions. The benefits of using strict mode are:
- Easier debugging since you'll see errors sooner
- Preventing accidental globals by throwing an error when you assign a value to an undeclared variable
- Eliminates "this" conversion by preventing you from referencing a "this" value that is null or undefined
- Prevents duplicate parameter values by throwing an error for a duplicate named argument for a function
- Variables and functions created inside an eval() are not created in the containing scope in strict mode
- Alerts you of invalid uses of "delete"
Recruitment JavaScript Coding Challenges
No matter how well a candidate answers questions about JavaScript, you'll ultimately want to see them put their knowledge into action by doing some actual coding. Here are some coding challenges you can use to gauge how an applicant handles coding problems.
Determine if a string is a palindrome
A palindrome is a word or phrase that reads the same backward and forward, such as "Hannah" or "Taco Cat." The first step to solving this challenge is removing all punctuation, spacing, and symbols from the string and converting all of them to the same case. Then use the split() method to convert the string into an array. Next, the reverse() method will reverse the original array. Finally, the join() method groups the values of the array into a string. You can then compare the arrays and return "true" if they match and "false" if they don't.
Fizz buzz challenge
This coding challenge is based on the classic children's counting game used to teach about multiples. In the game, players sit in a circle counting by one, replacing each multiple of three with fizz and each multiple of five with buzz.
The coding challenge asks an applicant to print the numbers from 1 to 100, replacing multiples of three with fizz and multiples of five with buzz. There are many ways to solve this challenge, but one of the simplest is using the for loop:
for (var i=1; i < 101; i++){
if (i % 15 == 0) console.log("FizzBuzz");
else if (i % 3 == 0) console.log("Fizz");
else if (i % 5 == 0) console.log("Buzz");
else console.log(i);
}
Hoisting challenge
You can test an applicant's understanding of hoisting with a question about the output of the following code:
function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 5;
}
}
test();
The result of this code will be undefined and 5 because variables don't retain any assigned value when they're hoisted.
Scope question
Scope can be tricky to understand in action, so use the following code snippet and ask what will be returned:
(function() {
var a = b = 2;
})();
console.log(b);
The answer is 2. In this example, there are two assignments in the IIFE, but because "a" is declared with the keyword var, it's a local variable of the function, while "b" is assigned to the global space.
You can make this question more complex by asking what would be returned if it were coded in strict mode. In that case the error "Uncaught ReferenceError: b is not defined" would be printed because the global scope was not specifically referenced.
Understanding "this"
To test a candidate's understanding of "this", ask them to explain the result of the following code:
var fullname = 'John Smith';
var obj = {
fullname: 'Don Quixote',
prop: {
fullname: 'Emma Woodhouse',
getFullname: function() {
return this.fullname;
}
}
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());
The answer is Emma Woodhouse and John Smith because the context of a function depends on how it's invoked, not how it's defined. In this example, the function returns the property "full name" of "window."
Interviewing JavaScript Developers for Soft Skills
While hard skills are essential in a JavaScript developer, soft skills are just as important. A developer who can't communicate well or work as part of a cohesive team will slow down development and impede progress. Here are some questions you can ask to judge a candidate's soft skills:
Communication
You want to look for answers that demonstrate the candidate can communicate clearly and effectively when conflict arises. On the flip side, reacting defensively or argumentatively are red flags. Some questions you can ask include:
- Tell me about a time you disagreed with a team member about how to approach a coding problem.
- How did you defend your point of view? What was the result?
- How would you explain a delay or error in a project to a senior manager?
Collaboration
In an Agile environment, your developers won't be working in silos. They'll need to communicate with team members as well as other departments to scale products, ensure customer satisfaction, and implement updates. Some questions you can ask regarding collaborative skills include:
- Have you ever had to work with an uncooperative team member? How did you handle it?
- What makes a good team member?
- How would you work with two team members who had very different ideas about how to approach a problem?
Innovation
Innovation tops the list of desired qualities in JavaScript developers. Ideally, your developers will be overflowing with new ideas and eager to work on them. Some questions that address innovation are:
- What personal projects are you working on?
- Give an example of when you used a creative and unconventional approach to a coding problem.
- How have you positively contributed to a product or company?
Flexibility
Rapidly-growing companies can be stressful places to work, and you'll need developers who can adapt to change. There will be a lot of instances where developers will have to deal with problems and situations that are beyond their control. Here are some questions that allow candidates to express their ability to be flexible:
- What would you do if you were an hour away from your deadline and your code wasn't working?
- Describe a situation where you experienced unexpected and unwelcome changes. How did you deal with it?
- Would you be able to tell your team leader if you felt you had taken on more than you could handle?
- Have scalability concerns affected the way you code? If so, how?
Attention to detail
JavaScript developers have to be meticulous and thorough. One small error can set your project schedule back significantly, so you want developers who can catch errors early and quickly. Ask these questions to assess an applicant's attention to detail:
- Describe your debugging process. What tools do you use to check your work?
- Would you rather get work finished quickly or have it done to a high standard? How do you balance the two?
- What methods do you use to try to avoid coding errors?
Final Thought on Hiring JavaScript Developers
Finding the right candidates and hiring qualified JavaScript developers can be a prolonged process. Because of its popularity, JavaScript developers are in high demand. Asking interview questions that cover basic concepts, intermediate and advanced functions, and soft skills will help you determine if a developer is a good fit for your team.
Working with a tech talent partner like Revelo can help you scale your JavaScript development team. We prescreen developers to provide you with highly skilled JavaScript developers from Latin America. You can quickly grow your team by choosing prevetted developers. You'll be able to focus on growing your business while we handle the payroll, taxes, and compliance issues of hiring outside the U.S. Contact us today to start interviewing candidates in as little as three days.
Related Pages:
Alternative Softeware Developer Pipeline