In this article
Top 30 JavaScript Interview Questions and Answers
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 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.
Please wait ..
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.
// 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.
// 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.
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.
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.
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.
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.
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.
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"?
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.
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.
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.
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.
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.
// Syntax
(function () {
// write your code here
}());
// Example
(function () {
console.log(
"cdn.kouroshzz.autos 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.
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.
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.
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.
function functionName(...restParameter) {
// Body of the function
}
// Example 2
function functionName(value1, value2, ...restParameter) {
// Body of the function
}
What are arrow functions, and how do they differ from regular functions?
Arrow functions are a shorter way to write functions in JavaScript, which came out in ES6 2015. It uses an arrow (=>
) symbol to define (create) a function instead of the function keyword. Arrow functions bind "this'' to the surrounding scope. This means they inherit the same meaning of the "this" keyword as the code around them. It makes it easier to work with variables, functions, objects, etc., outside the arrow function, but still accessible within it.
Regular functions, on the other hand, bind the "this" keyword to the function itself. The "this" keyword changes based on how you call the function, but it can sometimes cause errors. For example, if you call a regular function as a method of an object, "this" will refer to that object. But if you call the same function as a standalone function, "this" will refer to the global object (usually the window object in a browser).
// arrow function with this
function personName(name) {
this.name = name;
this.sayName = () => {
console.log(this.name); // 'this' is inherited from the surrounding context (constructor function: personName)
};
}
const cess = new personName("cess");
cess.sayName(); // cess
// regular function with this
function Person(name) {
this.name = name; // Assigns the "name" parameter as the "name" property of the object you created.
this.sayName = function () {
console.log(this.name); // Refers to the "name" property of the object that calls this function.
};
}
const cess = new Person("cess");
cess.sayName(); // cess
In arrow functions, if there is only one expression, you can skip the curly braces {}
and the return keyword. It makes your code cleaner and easier for you and external developers to read. If you have two or more expressions, use the return keyword and put your code in curly braces {}
.
// regular function
function doMath(a,b) {
return a + b;
}
console.log(doMath(200, 500)); // 700
// arrow function
const doMath = (a, b) => a + b; // single expression
console.log(doMath(200, 500)); // 700
// multiple expression
let doMath = (a, b) => {
let result = a * b;
return result;
};
console.log(doMath(200, 500)); // 100,000
Explain the concept of function scope with an example
Function scope refers to the scope of variables defined within a function. You can only access variable values within the scope and not outside. It helps to avoid having the same variable names and keeps your JavaScript code clean.
function myStudyPlan() {
var studyPlanOne = "Top JavaScript interview questions for web developers";
let studyPlanTwo = "Top JavaScript interview questions for web developers";
const studyPlanThree = "Top JavaScript interview questions for web developers";
console.log(studyPlanOne);
console.log(studyPlanTwo);
console.log(studyPlanThree);
}
myStudyPlan(); // Calls the function
Objects and Prototypes
Explain the concept of prototype inheritance in JavaScript
Prototype inheritance is when objects can inherit properties and methods from other objects. Each item has a "prototype," i.e., the parent object. Whenever you want to use a property or method on an object, JavaScript first checks if it has it. If not, it looks at the object's prototype to see if it has it. If the prototype has it, then the object "inherits" it. This process continues until it finds the property it's looking for or hits the end of the prototype chain.
For example, Date objects, like timestamps, inherit their properties and methods from the Date prototype. Math objects provide existing tools and features for math tasks, but do not rely on or inherit from a Math prototype. Array objects, like lists, get their features and actions from the Array prototype.
How do you add a method to an object?
Adding methods to an object allows you to keep your code organized and easy to reuse. One way to make this happen is by assigning a function to the object's property:
var obj = {
name: "Cess",
work: "developer",
countryVisits: 3
};
// assigning a function to the object's property
obj.newMethod = function() {
console.log("Hello, I'm " + this.name + " and I work as a " + this.work );
};
obj.newMethod(); // Hello, I'm Cess and I work as a developer
How can you check if an object has a specific property?
There are different ways to check if an object has a specific property. The method you choose depends on what you want to check and why. I'll be using the Object.hasOwn
method to check if an object has a property that belongs only to it, not to its parent or inherited prototype.
var obj = {
name: "Cess",
work: "developer",
countryVisits: 3,
};
console.log(Object.hasOwn(obj, "name")); // true
console.log(Object.hasOwn(obj, "developer")); // false
How do you define a constructor function in JavaScript?
A constructor function creates multiple objects with the same properties and methods. Using the "new" keyword with a constructor function creates a new object and sets "this" to that object.
It's usually a good idea, but not required, to start the name of a constructor function with a capital letter. Doing this helps differentiate constructor functions from your regular functions and variables.
function myDetails(name, visits) {
this.name = name; // Set the name parameter to the object
this.visits = visits; // Set the visits parameter to the object
this.newDetails = function () {
console.log(
`Hi, I'm ${this.name} and I have visited ${this.visits} countries.`
);
};
}
// Create objects using the constructor
let runDetails = new myDetails("Cess", 2);;
runDetails.newDetails(); // Hi, I'm Cess and I have visited 2 countries.
Write a JavaScript code snippet to create a new object using the Object.create() method
To create a new object using Object.create()
method, here's an example that demonstrates it in action
// Create a parent object
let myDetails = {
newDetails: function () {
console.log(
`Hello, I'm ${this.name} and I have traveled to ${this.visits} countries`
);
}
};
// Create a new object using Object.create() with myDetails as prototype
let runDetails = Object.create(myDetails);
// Add properties to the new object
runDetails.name = "Cess";
runDetails.visits = 2;
// Using inheritance method
runDetails.newDetails(); // Hello, I'm Cess and I have traveled to 2 countries
Arrays
How do you create an array in JavaScript?
You use array literals with square brackets [] to create JavaScript arrays.
let myArray = [firstArr, secondArr, thirdArr];
Explain the array prototype methods with an example
Array methods help you add, delete, or change elements (values) in an array. Some array methods to check out are:
- push(): The push() method adds one or more elements to the end of an array and tells you the new length of the array in return.
- pop(): The pop() method removes the last element from an array and returns that element.
- shift(): The shift() method removes and returns the first element from an array.
- unshift(): It adds one or more elements to the start of an array and tells you the new length of the array in return.
How do you add or remove items from an array?
Adding or removing items from an array using the push()
and pop()
methods:
// using push() method
let coding = ["Java", "JavaScript"];
coding.push("React");
console.log(coding); // ["Java", "JavaScript", "React"]
// using pop() method
let coding = ["Java", "JavaScript"];
let removeJavaScript = coding.pop();
console.log(coding); // ['Java']
console.log(removeJavaScript); JavaScript
What is a recursive function? Provide an example using arrays
A recursive function is a function that calls itself to solve a particular problem. It breaks down a big problem into smaller parts with each call and solves them one by one. The function has two main parts: the base case, which stops the repetition, and the recursive case, which repeats the steps until it reaches the base.
function myArray(arrOld) {
// Base case: empty array
if (arrOld.length === 0) {
return 0;
}
else {
// Recursive case: Add the first element + sum of the rest arrays
return arrOld[0] + myArray(arrOld.slice(1));
}
}
let newArray = [20, 30, 40, 50];
console.log(myArray(newArray)); // 140
How do you loop through the items in an array?
Below is an example of looping through an array using the for loop method:
let coding = ["java", "python", "JavaScript"];
for (let i = 0; i < coding.length; i++) {
console.log(coding[i]);
}
// java
// python
// JavaScript
What are the different ways to clear an array in JavaScript?
There are several ways to clear an array in JavaScript. However, I'll focus on the three most common methods.
// Setting the length of an array property to 0:
let num = [20, 30, 40, 50];
num.length = 0;
console.log(num); // []
// Using the splice() method:
let num = [20, 30, 40, 50];
num.splice(0, num.length);
console.log(num); // []
// Assigning an empty array:
let num = [20, 30, 40, 50];
num = [];
console.log(num); // []
What are the different methods to remove duplicates from a JavaScript array?
You can use the filter()
, reduce()
method, and more to remove duplicates from an array. I'll be using the set()
method as an example:
let myArray = [30,30,30,40,50,50,60,60];
let newArray = [...new Set(myArray)]; // removes duplicates and converts back to an array
console.log(newArray); // [30, 40, 50, 60]
How would you use the spread operator to merge objects instead of arrays?
The spread operator (...
) allows you to merge objects through a function call or directly combine objects. Below is an example using a function call:
function mergeObj(firstObj, secondObj) {
return {...firstObj, ...secondObj} // merge both objects
}
let firstObj = { name: "cess", city: "Lagos"};
let secondObj = {occupation: "developer", countriesVisited: 2};
let newObj = mergeObj(firstObj, secondObj);
console.log(newObj); // {name: 'cess', city: 'Lagos', occupation: 'developer', countriesVisited: 2}
What is the output of the following JavaScript code? const arr1 = [1,2,3]; const arr2 = [...arr1, 4, 5, 6]; console.log(arr2);
const arr1 = [1,2,3];
const arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // what ?
console.log(arr2); // [1, 2, 3, 4, 5, 6]
Error Handling
Explain the difference between a reference error and a syntax error with examples
A syntax error happens when you write code that the JavaScript engine can't understand, so your code won't run. It can be when you make a typo spelling a keyword or forget to close a bracket, parenthesis, or curly brace.
console.log("JavaScript interview questions"
A reference error occurs when you try to use a variable or a function that doesn't exist. The code will run, but it won't find what you're referencing since you didn't create the variable using let, var, and const keywords.
console.log(myStudy);
Explain a logical error with an example
A logical error is when your code runs without syntax or reference errors. But when it runs, it won't do what you want it to because of a mistake in how you wrote it.
Suppose you're trying to add two numbers together in a function. But instead of using the plus sign, you use the multiplication sign by mistake. The code will still run, but you won't get your desired answer.
How do you log and monitor errors in a JavaScript application, especially in a production environment?
Keeping track of errors in your JavaScript application is important, especially when it's up and running and people are using it. This will allow you to find and correct mistakes to make your application reliable and easier to use.
These methods will help you keep tabs on what's happening with your application once it's in production:
- Try-Catch Blocks: Use a try...catch block to catch errors before they cause your application to crash.
- Track uncaught errors: Use a window.oneerror to catch errors outside a try...catch block.
- External services: Use external services like Sentry to track errors in production.
- Send errors to a server: Use AJAX or fetch API to send error data to the server for analysis.
Advanced concepts
What is the Document Object Model (DOM)?
The DOM is a structured representation of a webpage's elements (HTML or XML page). Whenever an HTML page loads, the web browser creates a DOM for that page. It's a way for JavaScript to understand and change a webpage's content, layout, and style.
The DOM represents the web page as a tree-like structure of objects. Each web page element, like paragraphs and images, becomes an object in this tree. JavaScript uses the DOM to manipulate these objects and make the webpage interactive.
For example, imagine you're watching a JavaScript tutorial on YouTube that you enjoy and decide to click the "like" button. When you click the "like" button, the text changes to "unlike," and the like counter goes up. JavaScript accesses and changes the DOM to update the button's text from "like" to "unlike."
How do you use CSS style selectors with JavaScript to manipulate an HTML element?
Advanced concepts
There are several methods to manipulate HTML elements using CSS style selectors. But I'll be using the document.getElementById
to style a paragraph element with an ID="styleP"
<p id="styleP">
Top JavaScript interview questions for web developers
</p>
// Get the HTML element with the ID "styleP"
const styleP = document.getElementById("styleP");
// Apply styles to the element
styleP.style.color = "red";
styleP.style.border = "3px solid black";
console.log(styleP.style);
Differentiate between innerHTML and innerText
Advanced concepts
innerHTML is what you use to get or change the HTML content of an element. It shows you the plain text and the HTML tags used to create the text. For example, if you have a paragraph with an italics tag, innerHTML will show the em tags in the final result.
<p id="text">
<em>
JavaScript interview questions
</em>
</p>
let textOne = document.getElementById("text");
console.log(textOne.innerHTML); // <em>JavaScript interview questions</em>
On the other hand, innerText gets or changes the plain text inside an element. It shows you the text on the page but not the HTML tags used to create the text.
<p id="text">
<em>
JavaScript interview questions
</em>
</p>
let textOne = document.getElementById("text");
console.log(textOne.innerText); // JavaScript interview questions
What is the difference between a window object and a document object in JavaScript?
A window object represents the entire browser or tab. It controls everything on the page, from loading content to responding to your clicks. The window object is a topmost object that helps manage the browser window.
In contrast, the document object is a window property. The document object represents the web page's content (HTML document) you're looking at in the browser, such as the text. It enables you to interact with, change, and style web elements such as paragraphs using methods like getElementById()
.
What is the Browser Object Model (BOM)?
The BOM is a set of tools that allows JavaScript to interact with the browser. It controls browser functionalities without needing to interact with the HTML document. You can open and close a browser window, access a browsing history, and more. Examples of the BOM include window, browser, and history objects.
How do you use destructuring in JavaScript?
Destructuring lets you take out values from arrays or objects and put them into separate variables. It makes your code easier to read and reduces mistakes when writing code. You don't have to deal with extra variables; what you assign to each variable is obvious.
// list of languages
let pLang = ["Java", "JavaScript", "Python"]
// using destructuring to take out each language into separate variable:
let [pLang1, pLang2, pLang3] = pLang;
console.log(pLang1); // Java
console.log(pLang2); // JavaScript
console.log(pLang3); // Python
What is asynchronous JavaScript, and how does it handle code execution?
Asynchronous JavaScript is a way of writing code that can carry out many tasks at once. It saves you time, especially when working on tasks that take effort, like fetching data from a server.
Async JavaScript lets your code run at the same time as other tasks while waiting for it to complete. Your code doesn't stop and wait for a task to finish, but it keeps checking now and then to see if the task is complete. Once it's done, either a promise or a callback function responds to the result of the task.
What is the purpose of the strict mode in JavaScript?
Advanced concepts
JavaScript's strict mode makes you follow strict rules (best practices) when writing code. It prevents common mistakes JavaScript often ignores, such as undeclared variables, and keeps your code safe. Add the string "use strict";
at the top of the JavaScript file or function to enable strict mode.
// Without strict mode
courseNo = "200";
console.log(courseNo); // 200
// With strict mode
"use strict"; // top of your JS file
courseNo= "200";
console.log(courseNo); // courseNo is not defined i.e, you didn't create it using the var, const, or let keywords.
// Strict mode: Functions
function strictExample() {
"use strict";
courseNumber = "200"; // Error: courseNumber is not defined
console.log(courseNumber ); // code won't run
}
strictExample(); // ReferenceError
What are imports and exports in JavaScript?
Advanced concepts
Using "import" and "export" makes sharing code among many files easier. The "export" keyword shares code and data like variables, classes, and functions. On the other hand, the "import" keyword brings in these values, so you can use them in a different file.
For example, you have two files called function.js
and another file called app.js
. app.js
contains the original code you want to move to function.js using import and export.
You'll need to create an HTML page and link it to function.js
instead of app.js
. This is because app.js
contains the original code but cannot run on its own. Also, make sure to add function.js to the HTML with the type attribute set to "module" to prevent errors from occurring.
<!-- Link to HTML with type="module" attribute -->
<script type="module" src="function.js"></script>
// Export the function in file 1 "app.js"
export function studyJs(course) {
return `Read the JavaScript guide on, ${course}`;
}
// In file 2 the "js import" statement brings the "studyJs" function from "app.js" to "function.js"
import { studyJs } from './app.js';
console.log(studyJs("cdn.kouroshzz.autos")); // Read the JavaScript guide on, cdn.kouroshzz.autos
What are the ways of adding JavaScript to an HTML file?
Advanced concepts
You can add JavaScript to an HTML file in three ways: inline, internal, and external JavaScript. Internal JavaScript lets you add code inside the HTML markup file between <script>
tags. You can place internal JavaScript code inside the <head>
or <body>
section.
Internal JavaScript is great for small amounts of code and keeps everything in one place. But it can mess up your HTML markup file and make it hard to read, especially if you have a lot of code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Practice</title>
<!-- JavaScript -->
<script>
console.log("Study Javascript");
</script>
<!-- End -->
</head>
<body>
<!-- JavaSCript -->
<script>
console.log("Hi, I'm Cess");
</script>
<!-- End -->
</body>
</html>
Another method is to create an external file for your JavaScript. It lets you write your JavaScript code in a separate .js extension and link it to your HTML code file. You can link to the external JavaScript in your HTML's <head>
or <body>
section.
Doing this keeps your HTML clean and lets you use the same JavaScript code in many HTML pages. The downside is that it means an extra HTTP request to load the JavaScript file, which might slow down how fast your page loads.
For example, when you create a file called app.js
, you'll include it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Practice</title>
<!-- JavaScript -->
<script src="app.js"></script>
<!-- End -->
</head>
<body>
<!-- JavaSCript -->
<script src="app.js"></script>
<!-- End -->
</body>
</html>
Inline JavaScript lets you place your JavaScript code into an HTML element's attribute. You can do this using an HTML element's attribute, like onclick, onsubmit, and onselect.
Using inline JavaScript is suitable for fast and easy tasks. But it can make your HTML code difficult to read, especially if you have a lot of JavaScript code.
<button onclick="console.log('A click occured')">
Sign up on cdn.kouroshzz.autos
</button>
What are some popular JavaScript frameworks, and what are their primary use cases?
Listed below are some common JavaScript frameworks and their uses:
- Node.js: Builds backend web apps and APIs.
- React: Good for building single-page apps (SPAs), e.g., chat apps.
- Angular: Building web apps like social media apps and features like user authentication.
Wrapping up
Learning JavaScript is a continuous process that requires regular practice, self-assessment, and dedication. By studying the JavaScript interview questions and answers above, you have made considerable progress in improving your skills and confidence.
Feel free to mix it up during your study hours by asking different questions and using various scenarios. It'll make you feel more at ease and ready for whatever JavaScript interview questions you might see in actual interviews.
Set aside time each day or week to practice coding problems, work on your projects, and study. Also, jot down notes, make summaries, or even teach someone else. Doing this will solidify your learning and show you where you need extra work.
To improve at JavaScript and find more helpful resources, check out the JavaScript guide on cdn.kouroshzz.autos. It has valuable resources to help you learn and prepare for JavaScript interviews.