0% found this document useful (0 votes)
75 views19 pages

Basic JavaScript Interview Questions

The document provides an overview of basic JavaScript interview questions and answers. It begins by explaining what JavaScript is and some of its key features. It then covers questions about data types, variables, functions, objects, and more. Examples are provided for many answers. The document is intended to help prepare for a junior-level JavaScript interview.

Uploaded by

ChitraChittu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
75 views19 pages

Basic JavaScript Interview Questions

The document provides an overview of basic JavaScript interview questions and answers. It begins by explaining what JavaScript is and some of its key features. It then covers questions about data types, variables, functions, objects, and more. Examples are provided for many answers. The document is intended to help prepare for a junior-level JavaScript interview.

Uploaded by

ChitraChittu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

Basic JavaScript Interview Questions

1. What is JavaScript?
JavaScript is a popular web scripting language that’s used for client-side and server-
side development. JavaScript can be inserted into HTML pages and executed by
web browsers.
Apart from web development, it’s used in mobile app development, game
development, querying databases, and more.
Note: This is the most basic JavaScript question, so it’s important not to overlook it.

2. List Some Key Features of JavaScript.


 Lightweight interpreted language with object-oriented programming (OOP)
 Dynamically-typed
 Platform-independent
 Offers client-side validation

3. How Is JavaScript Different From Java?


While they share some letters in their names, they are not interlinked and are
designed for different purposes. While Java is an OOP language, JavaScript is an
OOP script. This means that JavaScript is written in text and then interpreted, and
Java is compiled. In terms of apps, Java is used to create apps on devices or
browsers, and JavaScript is mainly used with HTML documents and browsers.

How Do You Add Comments to JavaScript Code?


For a single line of comment, you use two forward slash symbols (//)

What’s The Difference Between Undeclared & Undefined


Variables?
An undeclared variable has not been declared anywhere in the code, so said
variable does not exist. If you try to read an undeclared variable, JavaScript throws
an error.
An undefined variable has been declared in the program, but no value has been
assigned. This means the variable exists, but its value is yet to be defined.

6. Summarize the Primitive JavaScript Data Types.


 String: Represents text, denoted by single quotes, double quotes, or
backticks
 Number: Represents numbers (integer & floating-point values)
 BigInt: Represents very large numbers with precision
 Boolean: Represents true & false values
 Null: Represents empty, nothing, and unknown type of values
 Symbol: Used for creating unique identifiers for objects
 Undefined: When a variable is declared and not yet assigned a value

How Can You Embed Javascript Code in an HTML File?


1. Use the <script> tag to add JavaScript code to an HTML document.

<!DOCTYPE html>

<html>

<head>

<script>

console.log("This is JS code.");

</script>

</head>
<body>

</body>

</html>

2. Write JavaScript code in an external file with a .js extension, then use
the src property in the script tag.

<!DOCTYPE html>

<html>

<head>

<script src="file_path.js"></script>

</head>

<body>

</body>

</html>

11. Explain the Difference Between Double(==) And Triple(===) Equals.


Double equals (==) is used to compare values with no regard for types, and triple
equals (===) is used to compare values while also taking type into consideration.
This is shown in the example below where firstValue is loosely equal to
secondValue, which returns true for double equals.
But when we use strict equality with triple equals, it returns false because while they
both have a value of 1, firstValue is a Number type, and secondValue is
a String type.

var firstValue = 1;

var secondValue = "1";

console.log(firstValue == secondValue); // true

console.log(firstValue === secondValue); // false


12. What are POSITIVE_INFINITY & NEGATIVE_INFINITY
in JavaScript?
These are properties of the Number object in JavaScript, where
POSITIVE_INFINITY is higher than any other number and NEGATIVE_INFINITY is
lower than any other number. These can only be used as properties of a Number
object.

Number.POSITIVE_INFINITY;

Number.NEGATIVE_INFINITY;

13. Draw a Simple JavaScript Dom (Document Object Model).

14. What Is NaN in JavaScript?


NaN, or ‘Not a Number’, indicates that JavaScript does not recognize the value as a
legal number. You can check whether a value is NaN with the isNaN() function.

console.log(isNaN("John Doe")); //true

console.log(isNaN(25)); // false

15. What Are the Looping Structures in JavaScript?


 For loops
 While loops
 Do-while loops
16. What Is a Prompt Box?
An input container with a label and a text field that lets a user enter input.

17. What’s the Difference Between Alert & Confirmation Boxes?


An alert box shows a single ‘OK’ button to the user, while confirmation boxes show
two buttons with ‘OK’ and ‘Cancel’.

18. Is JavaScript Case-Sensitive?


Yes. A variable named sayHello and a variable named sayhello will be treated as
two separate variables.

19. How Can You Handle Exceptions With Javascript?


You use try…catch…finally syntax.

 try statement: defines the code you want to run


 catch statement: handle errors
 finally statement: code you want to run regardless of any errors

try {

// code to run

catch(err) {

// code to handle errors

finally {

// code to run regardless of try / catch result

20. How Do You Run a JavaScript File?


Add a script element in the head or body elements of your HTML file, then link to an
external script using the script element's src attribute.
To run a JavaScript file in your terminal, you must have Node installed on your
computer. Open your terminal and navigate to the .js file you want to run. Then, run
the command below.

node file_name.js

New to JavaScript? Check out our article on

How to Learn JavaScript

Intermediate JavaScript Interview Questions

21. How Do You Create an Array in Javascript?


1. Create an instance with the new keyword:

let myArray = newArray('value1', 'value2',..., 'valueN');

2. Use the Array.of() method:

let myArray = Array.of('value1', 'value2',..., 'valueN');

3. Use an array literal:

let myArray = [value1, value2,...., valueN];


Make sure you’re ready for JavaScript array interview questions, as they’re an easy
win!

22. How Do You Check if a Value Is in an Array in Javascript?


1. Using .includes()

let myArray = [1, 2, 3, 4, 5,];

console.log(myArray.includes(1)); // true

console.log(myArray.includes(7)); // false

2. Using .indexOf()

let myArray = [1, 2, 3, 4, 5];

console.log(myArray.indexOf(1) !== -1); // true

console.log(myArray.indexOf(7) !== -1) // false

3. Using .find()

let myArray = [1, 2, 3, 4, 5];

console.log(myArray.find(value => value === 1)); // 1


console.log(myArray.find(value => value === 7)); // undefined

23. Are Functions Objects in JavaScript?


Functions are class objects in JavaScript because they can be passed to or returned
from other functions, assigned to variables or properties, and they have properties
and methods like all objects.

24. What Is a Class in JavaScript?


A blueprint for creating objects, which provides a way to define object methods and
properties. You define these with the class keyword.

class Person {

constructor(name) {

this.name = name;

sayHi() {

console.log(`Hi ${this.name}`);

const user = new Person("Jane");

user.sayHi(); // "Hi Jane"

25. Is JavaScript a Class-Based Language?


No, it’s a prototype-based language. JavaScript uses prototypes to define object
properties, and objects are not instances of classes, but rather they inherit properties
and methods from other objects creating a prototype chain.
In a class-based language, objects are instances of classes, and classes define
object properties and methods.
Note this is one of those tricky JavaScript interview questions, so make sure you
know it.
26. What Is Hoisting in JavaScript?
Functions or variable declarations are promoted to the top of their scope no matter
where they’re located within the code.
This only applies to variables declared with the var keyword,
not let or const variables.

27. What’s the Difference Between Async/Await & Promise?


These both handle asynchronous code. Promises use a then() method for handling
resolved values and a catch() method for errors. Async/await is a syntax
wrapper around a promisethat uses try/catch blocks to handle errors and
the await keyword to wait for resolved values.

28. How Do You Create a New Object in JavaScript?


1. Using object literals

const user = {

name: "Jane Doe",

age: 25

};

2. Using the new keyword

const user = newObject();

user.name = "Jane Doe";

user.age = 25;

This is one of those nice and simple JavaScript coding questions to know.

29. What Is a Constructor in JavaScript?


A constructor is used to create an object instance of a class. To call the constructor,
you use the new keyword.

function User(name) {

this.name = name;

}
let firstUser = new User('John Doe');

30. How Can You Return a Character From a Specified Index?


Use the charAt() method. In the example below, we can retrieve the first char at
index 0 to fetch J.

let userName = "John";

console.log(userName.charAt(0)); // "J"

31. What Are the Advantages of Using External JavaScript Files?


It separates HTML and JS code, improves the readability of your code, makes it
easy to reuse your code, and improves page load speed with cached JS files.

32. What Is the “This” Keyword in JavaScript?


This allows you to refer to the object which was used to make the function call.

33. What Is the For...In Loop in JavaScript?


This is used to iterate over the properties of a JavaScript object. Every property
returns a key, which is used to access the value.

34. What’s the Difference Between Var, Let, & Const Keywords?
 Var: Declared variables are functionally scoped, or globally scoped when declared
outside a function. You can reassign new values and redeclare them.

 Let: Declared variables are block-scoped, meaning they can only be accessed within
their declaration scope. It’s possible to reassign different values to them, but you
cannot redeclare them.

 Const: These are constants, meaning they are block-scoped, and you cannot
reassign new values or redeclare them.

35. What Is a First-Class Function?


Functions that are viewed like any other variable, meaning they can be assigned to
other variables, passed as a function argument, or returned by another function.

36. What Is a Higher-Order Function?


Functions capable of accepting other functions as arguments and able to return
functions as their return value.
37. What Are the Escape Characters in JavaScript?
We use a backslash in front of special characters when we want to actually print or
log these characters. For example, this combination would print the double quote, \”.

38. What Is Garbage Collection in JavaScript?


This type of automatic memory management monitors memory allocation to reclaim
and free up allocated memory blocks that are no longer needed by the JavaScript
program.

39. List the 7 Error Types in JavaScript.


 EvalError: Error regarding the global function eval()
 InternalError: Internal error in the JS engine (stack overflow, etc)
 RangeError: Numeric variable or parameter is outside of valid range
 ReferenceError: Invalid variable reference
 SyntaxError: Syntax error while parsing code in eval()
 TypeError: Parameter or variable not of a valid type
 URIError: Invalid parameters passed to decodeURI() or encodeURI()

Want to boost your interview prep? Check out

The Best JavaScript Books

Advanced JavaScript Interview Questions

40. Explain the Use of Debuggers in JavaScript.


Debuggers help developers identify code errors by executing test runs, setting
breakpoints, and checking variable values at different stages. Popular web browsers
like Safari, Chrome, Firefox, Opera, etc., have a built-in debugger.
JavaScript also has a debugger keyword to replicate breakpoints, but it works only
when debugging is enabled in web browser settings.

41. What Are Factory Functions in JavaScript?


A function that creates and returns other functions - like a function manufacturer,
hence the term factory. These are often closures and have access to values in their
parent scope.
Factory functions help when creating similar functions with small changes. For
example, functions that perform similar operations but with different inputs, as shown
below.

function makeMultiplier(multiplier) {
return function(x) {

return x * multiplier;

let double = makeMultiplier(2);

console.log(double(5)); // prints 10

let triple = makeMultiplier(3);

console.log(triple(5)); // prints 15

42. Explain the Self-Invoking Function and Its Syntax.


These are functions that run immediately, even without being called. The syntax of a
self-invoking function is shown below. Note that you must wrap the function with
parentheses, and you must add () to the end.

(function sayHello () {

console.log("Hello World!")

}) ();

43. What’s the Difference Between a Function Declaration and


Expression?
Function Declaration Function Expression

Must have a name. Can be declared without a name.

Hoisted Not hoisted

Can be accessed before and after the function is Created when execution reaches it, and can only be acces
defined. after definition.
44. How Will You Create, Read, & Delete a Cookie Using
JavaScript?
Creating a cookie:
To create a cookie, you must assign a string to the cookie property of the document.

document.cookie = "username=John Doe";

Reading a cookie:
To read a cookie value, you call the cookie property of the document object.

let my_cookie = document.cookie;

Deleting a cookie:
Cookies are deleted by default when a user closes the browser. You can also set a
deletion time with an expiration date, and the expires parameter.

document.cookie = "username=John Doe; expires=Thu, 26 Jan 2023 00:00:00 GMT";

45. What Is a Closure in JavaScript?

This is a type of function that can access variables within its parent scope, even after
the parent function has returned, as shown below.
Closures are often used in JavaScript for things like private variables and methods
and for factory functions.

function parentFunc(name) {

let message = `Hello ${name}`;

function childFunc() {

console.log(message);

return childFunc;

let closure = parentFunc(`Jane`);

console.log(closure()); // "Hello Jane"

46. What Are Arrow Functions in JavaScript?


These are short and concise ways of writing function expressions and are typically
preferred for non-method functions. The general syntax is shown below.

const functionName = () => { };

47. What Is Prototypal Inheritance in JavaScript?


A way for objects to inherit properties and methods from other objects in JavaScript.
When an object is created, it has a reference to another object called its prototype,
and it can access the properties and methods of that prototype object.

48. How Can You Empty an Array in JavaScript?


1. Assign an empty array as the new value

let myArray = [1, 2, 3, 4];

myArray = [];
console.log(myArray); // []

2. Assign an array length of 0

let myArray = [1, 2, 3, 4];

myArray.length = 0;

console.log(myArray); // []

3. Apply the pop method while the length is greater than zero

let myArray = [1, 2, 3, 4];

while(myArray.length > 0) {

myArray.pop();

console.log(myArray); // []

4. Use the splice method

let myArray = [1, 2, 3, 4];

myArray.splice(0, myArray.length);

console.log(myArray); // []

49. Explain Event Bubbling and Event Capturing.


These relate to the propagation of the JavaScript event-listener from parent to child
and in reverse.

 Event Capturing: The event is handled by the outermost element, which is then
propagated to the innermost element

 Event Bubbling: The event is handled by the innermost element first and then
propagated to the outermost element (reverse of event capturing)
50. What’s the Difference Between the Javascript Engine &
Javascript Runtime?
The JavaScript engine converts JavaScript code into machine code that can be
executed by the computer, while the JavaScript runtime is the environment in which
the code is executed, such as a web browser or Node.js

51. How Can You Remove Duplicates From a Javascript Array?


1. Using filter(): This takes three arguments, the array, the current element, and the
index of the current element, and it returns all elements that pass a given condition.

function removeDuplicates(arr) {

return arr.filter((elem,

index) => arr.indexOf(elem) === index);

console.log(removeDuplicates([1,2,2,3,3])); // [1, 2, 3]

2. Using forEach(): You need to create an empty array, then use forEach() as you
iterate through the array, adding elements to the empty array if it’s not already a
member.

function removeDuplicates(arr) {
let uniqueArray = [];

arr.forEach(element => {

if (!uniqueArray.includes(element)) {

uniqueArray.push(element);

});

return uniqueArray;

console.log(removeDuplicates([1, 2, 2, 3, 3, 3])); // [1, 2, 3]

3. Using Set: The simplest approach, this is an inbuilt object for storing unique values
in an array.

let arrayWithDuplicates = [1, 2, 2, 3, 3];

let uniqueArray = [...new Set(arrayWithDuplicates)];

console.log(uniqueArray);

52. What Is the Event Loop in JavaScript?


A mechanism that allows the execution of code to be non-blocking by continually
checking the message queue and executing any code that is waiting in the queue.

53. What Is Strict Mode in JavaScript, And How Do You Enable


It?
This is a way to voluntarily opt into a restricted JavaScript variant, which also means
you have opted out of ‘sloppy mode’. Key changes made by using strict mode:

 Removes silent JavaScript errors by making them thrown errors


 Fixes errors that prevent JavaScript engines from performing optimizations
 Prevents use of syntax to be defined in future ECMAScript versions

54. What Role Do Deferred Scripts Play in JavaScript?


Using deferred scripts results in a delay in the script's execution when the HTML
parser is running. This ensures that the HTML is parsed first before the script is
executed This results in a reduction in the loading time of the webpage.
55. What Are Screen Objects? State Their Various Properties.
Screen objects read data from the client’s screen, and their properties include:

 AvailHeight: Height of client screen (Excludes taskbar)


 AvailWidth: Width of client screen (Excludes taskbar)
 ColorDepth: Bit depth of images supported by the client screen
 Height: Total height of the client screen
 Width: Total width of the client screen

56. What Is JSON?


JavaScript Object Notation, or JSON, uses JavaScript’s object syntax to send data
across networks with a file extension of .json and an “application/json” MIME type.

57. How Can You Optimize the Performance of a Javascript


Application?
 Minimize use of global variables
 Use caching & memoization
 Compressing code
 Use object & array literals instead of constructors
 Avoid unnecessary function calls

58. What Is a Debounce Function?


A debounce function delays the execution of a function until a certain amount of time
has passed without it being called.
By rate limiting the amount that a function can be called, you can ensure better
performance and prevent browser hanging issues. To implement a debounce
function in JavaScript, use the setTimeOut() method.

59. How Can You Measure the Performance of a JavaScript


Function?
You can use performance.now() to return high-resolution timestamps in milliseconds
and thus calculate the time it takes for a function to execute, as shown below.

const start = performance.now();

myFunction();

const end = performance.now();

console.log(`Time taken: ${end - start} milliseconds`);

This is one of those programming questions in JavaScript that you should know if
you’re a more experienced developer.
60. What Is Memoization in JavaScript?
Memoization is a technique to store results of expensive function calls and then
return cached results when the same inputs occur again. This helps to optimize
function performance by avoiding unnecessary re-computations and reducing time
complexity.

You might also like