SOLFIND
Web Lens
Portal home

Top 30 JavaScript Interview Questions and Answers

https://roadmap.sh/questions/javascript • 257 KB fetched
Open original page


Top 30 JavaScript Interview Questions and Answers AI Tutor
*
Roadmaps
* AI Tutor
Lesson Packs Newsletters

Loading...

Top 30 JavaScript Interview Questions and Answers
Ekene Eze Prefer us on Google
JavaScript interviews can be rough, even for developers with years of experience. You're expected to understand the language's basics and more complex parts. Interviewers want to see how well you know the language and how you use it to solve problems. It's a good idea to brush up on some common JavaScript interview questions before your interview.
When preparing for a JavaScript interview, make sure you don't just memorize everything. Instead, focus on developing a good understanding of the language and getting to know it inside and out. Start by learning the basics, e.g., variables, and then you can move on to more advanced topics like async/await. Doing this will help you analyze things better and use your knowledge in building web apps.
In this Article
* Preparing for your JavaScript interview

* Test yourself with Flashcards

* Questions List

In this guide, I'll cover top JavaScript interview questions and answers to help you prepare well. I'll cover basic syntax, data types, and advanced concepts like async/await. You'll also find a collection of flashcards designed to help you practice and learn better. But if you want to research more on each topic or start learning about JavaScript, check out the JavaScript roadmap .
Preparing for your JavaScript interview
Prepare for your JavaScript interview by keeping these tips in mind:

* Improve your understanding of basic JavaScript concepts by learning variables, arrays, and more.

* Practice building projects using sites like LeetCode and HackerRank .

* Learn how to use advanced JavaScript topics such as async/await to create apps that fix everyday issues people deal with.

* If you need to, learn JavaScript frameworks and libraries like React and Angular for the job. Know how components and state management work in your chosen framework or library.

* Use this guide to understand common JavaScript interview questions. Practice answering them, and be ready to explain how you came up with your answers. Try practicing with a friend to get some feedback to help you improve.

* Learn about the company and what they're all about. It'll help you better understand what they want and how to answer the interview questions.

Test yourself with Flashcards
You can either use these flashcards or jump to the questions list section below to see them in a list format.

0 / 49
Knew 0 Items Learnt 0 Items Skipped 0 Items Reset Progress

Core Concepts
How does Java differ from JavaScript?

Click to Reveal the Answer

Java and JavaScript are different programming languages in terms of syntax and uses. Java is a programming language that Sun Microsystems created in the '90s and is now owned by Oracle. It is a general-purpose, object-oriented programming language often used for building software. Examples of this software include desktop, web apps, and mobile apps for Android.
Java is also a statically typed language, meaning a variable's data type must be known at compile time. Before starting the program, you must understand what kind of data you're working with.
In contrast, Brendan Eich created JavaScript, a scripting language, at Netscape in 1995. It is a dynamically typed language, meaning that a variable's data type is determined at runtime. You do not have to declare the data type of a variable before using it. Check out the guide on the differences between Java and JavaScript to learn more.

Hide the Answer

Already Know that Didn't Know that Skip Question

Questions List
If you prefer to see the questions in a list format, you can find them below.
Core Concepts
How does Java differ from JavaScript?
Java and JavaScript are different programming languages in terms of syntax and uses. Java is a programming language that Sun Microsystems created in the '90s and is now owned by Oracle. It is a general-purpose, object-oriented programming language often used for building software. Examples of this software include desktop, web apps, and mobile apps for Android.
Java is also a statically typed language, meaning a variable's data type must be known at compile time. Before starting the program, you must understand what kind of data you're working with.
In contrast, Brendan Eich created JavaScript, a scripting language, at Netscape in 1995. It is a dynamically typed language, meaning that a variable's data type is determined at runtime. You do not have to declare the data type of a variable before using it. Check out the guide on the differences between Java and JavaScript to learn more.

What are the various data types that exist in JavaScript?
Primitive and non-primitive data types are the two main data types in JavaScript. Primitive data types are the main elements that make up all the data you work with in JavaScript. They are immutable, meaning you can't change their values once you create them. Also, they're stored in memory as single values. Some examples of primitive data types include:

* Number (numeric values, e.g., 78).

* String (text values, e.g., "hey").

* Boolean values (true or false).

* Null

* Undefined

* Symbols

Non-primitive data types, also called reference data types, store groups of data or complex structures. They are mutable, meaning you can change their values once you create them. Unlike primitive data types, they're stored in memory as references rather than single values. Some examples of non-primitive data types include:

* Object (collection of key-value pairs, e.g., { name: 'cess', age: 26 };).

* Array (e.g., [10, 12, 13]).

* Function (e.g., function add(a = 10, b = 5) { return a + b; }).

What is the difference between undefined and null in JavaScript?
Undefined variables are variables that the developer has declared but not yet assigned a value.
javascript

// Example 1 let study; console.log(study); // undefined var // Example 2 let myObj = {}; // empty object console.log(myObj.name); // undefined because name does not exist

A null variable is a variable or property that is empty. You use null variables when you want to show that a variable has no values or want to clear the value of a variable.
javascript

// Example 1 let study = null; console.log(study); // null // Example 2 let obj = { name: "cess", }; obj.name = null; console.log(obj.name); // null

What is the use of the isNaN function?
You use the isNaN function to check when a value is "Not a Number." It attempts to convert the given value to a number and then checks if the result is a NaN. If the value is not a number, it'll return true, but if it is a number, it'll return false.
javascript

console.log(isNaN("study")); // true console.log(isNaN(4)); // false

What are the conventions of naming a variable in JavaScript?
The following are the naming conventions for variables in JavaScript:

* Write variable names in camelCase. Use lowercase letters to begin the variable name and then uppercase for each new word, e.g., myName.

* Use descriptive variable names. Instead of using "p" as a variable name for a password, use userPassword instead.

* Don't use JavaScript keywords such as if, for, or while as variable names.

* Don't include special characters like punctuation and math operators in your variable names. Only use underscores (_) and dollar signs ($).

* Don't start variable names with numbers; instead, place them at the end. For example, you can't have 99myName, but myName99 is okay.

What is a variable declaration, and how are var, let, and const keywords different?
A variable declaration is when you create a variable to store a value in JavaScript. You give it a descriptive name, which you can then use to store or retrieve the value. In JavaScript, you use var, let, and const keywords to declare variables.
Older versions of JavaScript used the var keyword to declare variables**.** Variables declared using the var keyword have a function scope. It lets you give variables the same name and a new value even in the same scope. However, it may result in confusion and errors, making debugging your code difficult.
javascript

var course = "java"; var course = "JavaScript interview questions"; // No error console.log(course); // JavaScript interview questions

The let keyword is a new way to declare variables in JavaScript in ECMAScript 2015 (ES6). Variables declared using the let keyword have a block scope. You can change the value, but you can't use the same name for a variable in the same block scope. It helps make debugging code easier compared to the var keyword.
javascript

let course = "java"; let course = "JavaScript interview questions"; console.log(course);// Identifier 'course' has already been declared // Example 2 let course = "java"; course = "JavaScript interview questions"; console.log(course);// JavaScript interview questions

The const keyword works as the let keyword since both are block-scoped. However, you cannot change the value or use the same name for a variable in the same scope.
javascript

const course = "java"; course = "JavaScript interview questions"; // Error: Assignment to constant variable.

Explain the concept of global scope and local scope in JavaScript
Global scope is all the variables you can access from anywhere in your JavaScript code. When you declare a variable outside of any function or block, it becomes a global variable. Using too many global variables can make your code difficult to read.
In contrast, local scope is a variable you can only access within a function. When you declare a variable inside any function or block of code, it becomes a local ****variable. It helps to organize your JavaScript code, making it easier to read. When coding in JavaScript, try to use local scope variables instead of global scope variables as much as possible.

Explain the concept of the global object in JavaScript
Global objects are containers for the global scope and its properties, e.g., variables. You can access its properties from anywhere within your code. In a web browser, the global object is the "window," while in Node.js, it is "global."

Explain the concept of hoisting in JavaScript with examples
Hoisting is when a variable or function declaration gets moved to the top of its scope before the code runs. It means you can use a variable or function before you create (declare) it.
javascript

console.log(hoistedVariable); // undefined var hoistedVariable = "initialized var hoistedVariable"; console.log(hoistedVariable); // correct value

In the example above, I used the variable "hoistedVariable" in the first console.log before creating it. Often, this would cause an error, but due to hoisting, it will show "undefined." The computer will move the variable creation var hoistedVariable to the top, but won't move the variable value. When I assign the value to the variable, the second console.log will show the correct answer.
The "let" and "const" keywords don't work well with hoisting. Even though they're moved to the top of their scope, they don't get a value right away. It creates a "temporal dead zone" where you can't access the variables until they're declared (created). If you try to use "let" or "const" variables before declaring them, you'll get a "ReferenceError."

What is the purpose of the "this" keyword in JavaScript?
The "this" keyword in JavaScript refers to the object or context on which a code runs. Examples of these codes include function calls, object methods, event handlers, and more. You use it to access the properties and methods of that object. The value of this keyword changes depending on how you use (or call) the function.
When you use "this" in the context of a method, "this" indicates the object that owns the method. For standalone functions, "this" is the global object, but in strict mode it's undefined. Also, in event handlers, "this" refers to the element that caused the event.

What is the difference between the "==" and "===" operators in JavaScript?
"==" and "===" are comparison operators, but they are different in how they treat type coercion. The "==" comparison operator checks if the values are the same, but doesn't care about the data type.
The "===" comparison operator, on the other hand, checks if both the value and the data type are the same.
javascript

console.log(50 == "50"); True: string "50" is converted to number 50 console.log(50 === "50"); False: false, no type coercion due to different data types

What would be the result of 10+2+"9"?
javascript

console.log(10 + 2 + "9"); // 129

JavaScript uses type coercion to convert values to the same type before operations. It'll first add both numbers 10 + 2 to get 12, and then try to add the number 12 to the string "9". Since you can't add a number and a string in JavaScript, it'll change the number 12 into a string "12," i.e., "12" + "9" = "129"

Functions
What are function declarations, and how are they different from function expressions?
A function declaration is a statement used to create functions in JavaScript. It starts with the function keyword followed by the function name and parameters. As long as you stick to the naming conventions, you can provide your function or parameters with any name you want. Also, function declarations are "hoisted," meaning you can call them before they're defined.
javascript

function functionName(parameters) { // Body of the function }

A function expression is also a statement, defining a function as an expression. It starts with you declaring a variable such as let, const, or var, followed by an assignment operator (=), and it doesn't need a name (an anonymous function) unless you give it one. Also, they are not "hoisted," meaning you can only use them after you define them, or you'll get an error.
javascript

let variableName = function(parameters) { // Body of the function } // The variableName will act as the function name in a function expression.

What is the difference between a "callback" function and a "higher-order" function, with examples
A callback function is a function that one function gives to another as an argument (value) . The second function then runs the callback function after it finishes its operation. Callbacks are often used with other functions to handle tasks like making API calls.
In the example below, the sendMessage function is a callback function because it's given (passed) to the sendNow function to run the code later.
javascript

function sendMessage(message) { console.log("Message: " + message); } function sendNow(callback, message) { callback(message); } sendNow(sendMessage, "Hello, I'm learning JavaScript!"); // Message: Hello, I'm learning JavaScript!

Just like callbacks, higher-order functions also work with other functions. It takes another function as an argument or returns a function as a result. They're often used to handle tasks like controlling asynchronous operations.
javascript

function createMessage(prefix) { return function (message) { // returns a new function console.log(prefix + " " + message); }; } const sendMessage = createMessage("Hello"); // creates a new function sendMessage("Cess!"); // Hello, Cess!

What is an immediately invoked function expression (IIFE)? Provide an example
Immediately invoked function expressions, or IIFEs, run as soon as they're created. It creates a local scope for variables so they don't mess with other parts of the code. You make an IIFE by placing your code inside the parentheses (). Also, adding another set of parentheses () at the function's end will make it run immediately.
javascript

// Syntax (function () { // write your code here }()); // Example (function () { console.log( "roadmap.sh helps prepare for JavaScript job interview questions" ); })();

How would you implement a JavaScript function to reverse a string?
You can reverse a string using the split() , reverse() , and join() method.
javascript

function reverseMyString(str) { return str.split("").reverse().join(""); } let myString = "Learn JavaScript"; let reverseString = reverseMyString(myString); console.log(reverseString); // tpircSavaJ nraeL

Write a JavaScript function to check if a number is even or odd
One way to check if a number is even or odd is by creating a function using the modulus operator ( % ). It's a mathematical operation that helps find the remainder of a division problem.
In the example below, the number used for the division is "2", which is already an even number. If the remainder of dividing a number by "2" is "0", then it's an even number. But if the remainder is not "0", it's an odd number.
javascript

function EvenOrOddNum(num) { if (num % 2 === 0) { return `${num} is even`; } else { return `${num} is odd`; } } console.log(EvenOrOddNum(30)); // 30 is even console.log(EvenOrOddNum(31)); // 31 is odd

Write a JavaScript function to check if a string contains a specific substring
You can use different methods like search() or indexOf() to see if a string has a particular word. But I'll use the includes() method to check if a string contains a specific substring. It'll return "true" if the substring is present in the string and "false" if not.
javascript

function findSubstring(mainString, substring) { return mainString.includes(substring); } console.log(findSubstring("Learn JavaScript", "JavaScript")); // True - It contains JavaScript console.log(findSubstring("Learn JavaScript", "Python")); // False - It doesn't contain Python

What is the rest parameter, and how does it work?
The rest parameter allows you to represent many arguments in an array. It's useful when you need a function to accept extra arguments beyond what you've listed.
The "rest parameter" syntax consists of three dots ( ... ) followed by the name of a parameter. Also, if you're using a rest parameter with other values, make sure it's the last one on the list.
javascript

function functionName(...restParameter) { // Body of the

Links found on this page

  1. AI Tutor [direct]
  2. Roadmaps [direct]
  3. Lesson Packs [direct]
  4. Newsletters [direct]
  5. Ekene Eze [direct]
  6. Prefer us on Google [direct]
  7. Preparing for your JavaScript interview [direct]
  8. JavaScript roadmap [direct]
  9. LeetCode [direct]
  10. HackerRank [direct]
  11. React [direct]
  12. Angular [direct]
  13. Java [direct]
  14. differences between Java and JavaScript [direct]
  15. roadmap.sh [direct]
  16. How Long Does It Take to Learn JS? A Career Seeker's Guide [direct]
  17. Is JavaScript Hard to Learn? Advice from a Pro [direct]
  18. TypeScript vs JavaScript: Which to Choose For Your Project [direct]
  19. 6th most starred project on GitHub [direct]
  20. Star us on GitHub Help us reach #1 [direct]
  21. Register yourself Commit to your growth [direct]
  22. Join on Discord Join the community [direct]
  23. Guides [direct]
  24. FAQs [direct]
  25. YouTube [direct]
  26. roadmap.sh [direct]
  27. @nilbuild @nilbuild [direct]
  28. Terms [direct]
  29. Privacy [direct]
  30. DevOps [direct]
  31. Kubernetes [direct]
  32. Cloud-Native [direct]