
- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Roadmap
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Safe Assignment Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Handler
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Asynchronous
- JavaScript - Asynchronous
- JavaScript - Callback Functions
- JavaScript - Promises
- JavaScript - Async/Await
- JavaScript - Microtasks
- JavaScript - Promisification
- JavaScript - Promises Chaining
- JavaScript - Timing Events
- JavaScript - setTimeout()
- JavaScript - setInterval()
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods & Properties
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Attributes (Attr)
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM NodeList
- JavaScript - DOM DOMTokenList
- JavaScript Advanced Chapters
- JavaScript - Bubble Sort Algorithm
- JavaScript - Circular Reference Error
- JavaScript - Code Testing with Jest
- JavaScript - CORS Handling
- JavaScript - Data Analysis
- JavaScript - Dead Zone
- JavaScript - Design Patterns
- JavaScript - Engine and Runtime
- JavaScript - Execution Context
- JavaScript - Function Composition
- JavaScript - Immutability
- JavaScript - Kaboom.js
- JavaScript - Lexical Scope
- JavaScript - Local Storage
- JavaScript - Memoization
- JavaScript - Minifying JS
- JavaScript - Mutability vs Immutability
- JavaScript - Package Manager
- JavaScript - Parse S-Expressions
- JavaScript - Prototypal Inheritance
- JavaScript - Reactivity
- JavaScript - Require Function
- JavaScript - Selection API
- JavaScript - Session Storage
- JavaScript - SQL CRUD Operations
- JavaScript - Supercharged Sorts
- JavaScript - Temporal Dead Zone
- JavaScript - Throttling
- JavaScript - TRPC Library
- JavaScript - Truthy and Falsy Values
- JavaScript - Upload Files
- JavaScript - Date Comparison
- JavaScript - Recursion
- JavaScript - Data Structures
- JavaScript - Base64 Encoding
- JavaScript - Callback Function
- JavaScript - Current Date/Time
- JavaScript - Date Validation
- JavaScript - Filter Method
- JavaScript - Generating Colors
- JavaScript - HTTP Requests
- JavaScript - Insertion Sort
- JavaScript - Lazy Loading
- JavaScript - Linked List
- JavaScript - Nested Loop
- JavaScript - Null Checking
- JavaScript - Get Current URL
- JavaScript - Graph Algorithms
- JavaScript - Higher Order Functions
- JavaScript - Empty String Check
- JavaScript - Form Handling
- JavaScript - Functional Programming
- JavaScript - Parameters vs Arguments
- JavaScript - Prototype
- JavaScript - Reactive Programming
- JavaScript - Reduce Method
- JavaScript - Rest Operator
- JavaScript - Short Circuiting
- JavaScript - Undefined Check
- JavaScript - Unit Testing
- JavaScript - Validate URL
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
Javascript Interview Questions
These JavaScript Interview Questions have been specially created to familiarize you with the nature of questions you may encounter during your interview. These questions are curated by analyzing recently asked JavaScript questions from different companies' interviews.
JavaScript Interview Question Sets
Here we have categorized the curated questions into three different sets as mentioned below.
Beginner Level JavaScript Interview Question
These questions can be asked at the start of your interview, regardless of your experience level. These questions are based on JavaScript fundamentals. You can go through these questions to test your fundamental knowledge.
1. What is JavaScript?
Ans: JavaScript is a single-threaded programming language that we can use for client-side or server-side development. It is a dynamically typed programming language, which means that we dont care about variable data types while writing the JavaScript code. Also, it contains the control statements, operators, and objects like Array, Math, Data, etc.
2. What are the advantages and disadvantages of JavaScript?
Ans: Every language has pros and cons and JavaScript is no different from others.
Advantages of JavaScript- Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
- Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to enter something.
- Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
- Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.
We can not treat JavaScript as a full fledged programming language. It lacks the following important features.
- Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
- JavaScript can not be used for Networking applications because there is no such support available.
- JavaScript doesn't have any multithreading or multiprocessor capabilities.
3. Is JavaScript a case-sensitive language?
Ans: Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
4. What are the variable naming conventions in JavaScript?
Ans: While naming your variables in JavaScript keep following rules in mind.
- You should not use any of the JavaScript reserved keyword as variable name. You can check all the reserved keywords.
- JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but _123test is a valid one.
- JavaScript variable names are case sensitive. For example, Name and name are two different variables.
5. How typeof operator works?
Ans: The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.
6. How to create an Array in JavaScript?
Ans: You can define arrays using the array literal as follows
var x = []; var y = [1, 2, 3, 4, 5];
7. How to read elements of an array in JavaScript?
Ans: An array has a length property that is useful for iteration. We can read elements of an array as follows.
var x = [1, 2, 3, 4, 5]; for (var i = 0; i < x.length; i++) { // Do something with x[i] }
To know morea about JavaScript array check the attached link.
8. How to create an Object in JavaScript?
Ans: JavaScript supports Object concept very well. You can create an object using the object literal as follows.
var emp = { name: "Zara", age: 10 };
9. How to read properties of an Object in JavaScript?
Ans: You can write and read properties of an object using the dot notation as follows.
// Getting object properties emp.name // ==> Zara emp.age // ==> 10 // Setting object properties emp.name = "Daisy" // <== Daisy emp.age = 20 // <== 20
To know more about the JavaScript object please check the attached link.
What are the different data types in JavaScript?
Ans: JavaScript data types can be categorized as primitive and non-primitive.
- Primitive: Predefined data types by JavaScript is know as primitive data types like -
- Non-Primitive: These data types are derived from primitive data types.
Intermediate Level JavaScript Interview Question
1. What are the valid scopes of a variable in JavaScript?
Ans: The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
- Global Variables: A global variable has global scope which means it is visible everywhere in your JavaScript code.
- Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.
2. Which type of variable among global and local, takes precedence over other if names are same?
Ans: A local variable takes precedence over a global variable with the same name.
3. What is a named function in JavaScript? How to define a named function?
Ans: A named function has a name when it is defined. A named function can be defined using function keyword as follows.
function named(){ // do some stuff here }
4. How many types of functions JavaScript supports?
Ans: A function in JavaScript can be either named or anonymous.
To know more abut the JavaScript functions please check the attached link.
5. How to define a anonymous function?
Ans: An anonymous function can be defined in similar way as a normal function but it would not have any name.
// Named function function namedFunction() { return "I have a name"; } // Anonymous function const anonymousFunction = function() { return "I don't have a name"; };
6. Can you assign a anonymous function to a variable?
Ans: Yes! An anonymous function can be assigned to a variable.
7. What is the purpose of 'this' operator in JavaScript?
Ans: JavaScript 'this' keyword contains the reference to the object. It represents the context of the function or current code. It is used to access the properties and methods of the current object.
8. What is Date object in JavaScript?
Ans: The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ).
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
9. What is Number object in JavaScript?
Ans: JavaScript Number object represents numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.
Syntax: Creating a number object
var val = new Number(number);
If the argument cannot be converted into a number, it returns NaN (Not-a-Number)
10. Which built-in method reverses the order of the elements of an array?
Ans: JavaScript reverse() method reverses the order of the elements of an array The first becomes the last, and the last becomes the first.
11. How to redirect a url using JavaScript?
Ans: To redirect using JavaScript at client side. To redirect your site visitors to a new page by using following ways.
// Simulate a mouse click: window.location.href = "https://www.tutorialspoint.com/"; // Simulate an HTTP redirect: window.location.replace("https://www.tutorialspoint.com/");
12. How to print a web page using JavaScript?
Ans: JavaScript helps you to implement this functionality using print function of window object. The JavaScript print function window.print() will print the current web page when executed.
<html> <head> <title>Print Page</title> <script> function printpage() { window.print(); } </script> </head> <body> <h2>This is a sample page to print</h2> <button onclick="printpage()">Print Page</button> </body> </html>
13. What typeof returns for a null value?
Ans: It returns "object".
14. How to dynamically create new elements in JavaScript?
Ans: We will have a button element and on clicking it, we will generate a new p element and append it to the DOM.
<body> <h3>How to dynamically create new elements in JavaScript?</h3> <div id="container"> <!-- Newly created elements will be appended here --> </div> <button onclick="createNewElement()">Create Element</button> <script> function createNewElement() { // Create a new paragraph element var newParagraph = document.createElement('p'); // Set the text content of the paragraph newParagraph.textContent = 'This is a dynamically created paragraph.'; // Append the paragraph to the container div var container = document.getElementById('container'); container.appendChild(newParagraph); } </script> </body>
15. What is Function Hoisting?
Ans: The function hoisting in JavaScript is a default behavior in which function declarations are moved at the top of their local scope before execution of the code.
Advanced Level JavaScript Interview Question
1. What is callback?
Ans: A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered.
2. What is closure?
Ans: Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope.
<body> <p id = "demo"> </p> <script> const output = document.getElementById("demo"); function outer() { output.innerHTML += "The outer function is executed! <br>"; function inner() { output.innerHTML += "The inner function is executed! <br>"; } inner(); } outer(); </script> </body>
3. What is arguments object in JavaScript?
Ans: JavaScript variable arguments represents the arguments passed to a function.
4. How can you get the type of arguments passed to a function?
Ans: Using typeof operator, we can get the type of arguments passed to a function.
function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3
5. How can you get the total number of arguments passed to a function?
Ans: Using arguments.length property, we can get the total number of arguments passed to a function.
function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3
6. How can you get the reference of a caller function inside a function?
Ans: The arguments object has a callee property, which refers to the function you're inside of.
function func() { return arguments.callee; } func();
7. Can you pass a anonymous function as an argument to another function?
Ans: Yes! An anonymous function can be passed as an argument to another function.
8. How to handle exceptions in JavaScript?
Ans: The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
9. What is purpose of onError event handler in JavaScript?
Ans: The onError event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
The onError event handler provides three pieces of information to identify the exact nature of the error. Please check JavaScript - Errors & Exceptions Handling.
- Error message: The same message that the browser would display for the given error.
- URL: The file in which the error occurred.
- Line number: The line number in the given URL that caused the error.
10. Can you access Cookie using JavaScript?
Ans: JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.
11. How to create a Cookie using JavaScript?
Ans: The simplest way to create a cookie is to assign a string value to the document.cookie object.
document.cookie = "key1 = value1; key2 = value2; expires = date";
12. How to read a Cookie using JavaScript?
Ans: Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.
You can use strings' split() function to break the string into key and values.
13. How to delete a Cookie using JavaScript?
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.
To know all about Cookies please click on attached link.
14. What will be the output order and why?
console.log('1'); setTimeout(() => { console.log('2'); Promise.resolve().then(() => { console.log('3'); }); }, 0); Promise.resolve().then(() => { console.log('4'); setTimeout(() => { console.log('5'); }, 0); }); console.log('6');
Output: First, synchronous code execution prints 1 and 6 the the first Promise microtask queues up and prints 4. After 4, a new setTimeout is queued and original setTimeout executes and prints 2. Promise within first setTimeout prints 3 and finally, last setTimeout executes and prints 5
1, 6, 4, 2, 3, 5
15. Fixed the provide incorrect code to print 0,1,2,3,4
for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, i * 1000); }
Ans: To fix the provided code to print 0,1,2,3,4. We need to change var to let as var has function scope, not block scope.
for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, i * 1000); }
Understanding Interview Dynamics
Good interviewers hardly plan to ask any particular question during interviews, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer. So always clear your basic fundamentals to create a good impression.