JavaScript Interview Questions Guide
JavaScript Interview Questions Guide
Interview Questions
[Link] 1/80
9/15/23, 8:44 PM Interview Questions
History of JavaScript
1. What is the history of JavaScript?
Answer: JavaScript was created by Brendan Eich in just 10 days while he was
working at Netscape Communications Corporation in 1995. Initially named
"Mocha" and later "LiveScript," it was eventually renamed JavaScript to
leverage the popularity of Java. In 1997, JavaScript was standardized as
ECMAScript by Ecma International.
Answer: JavaScript and Java are unrelated despite the similar name.
JavaScript is a lightweight, interpreted scripting language used for web
development, while Java is a strongly-typed, compiled language used for
various applications, including server-side development.
[Link] 2/80
9/15/23, 8:44 PM Interview Questions
Answer: JavaScript has expanded beyond web development and is now used
for server-side programming ([Link]), mobile app development (React
Native and NativeScript), desktop application development (Electron), and
even in machine learning ([Link]). Its versatility has made it a
dominant programming language in the tech industry.
[Link] 3/80
9/15/23, 8:44 PM Interview Questions
13. What are the key differences between JavaScript and Java?
Answer: JavaScript and Java are unrelated despite the similar name.
JavaScript is a lightweight, interpreted scripting language used for web
development, while Java is a strongly-typed, compiled language used for
various applications, including server-side development.
14. Explain the role of Netscape in the history of JavaScript.
Answer: Netscape played a crucial role in the history of JavaScript by
commissioning Brendan Eich to create a scripting language for their
Navigator browser. JavaScript was initially introduced in Netscape Navigator
2.0 in 1995.
15. What is ECMAScript, and why is it important in the context of JavaScript?
[Link] 4/80
9/15/23, 8:44 PM Interview Questions
[Link] 5/80
9/15/23, 8:44 PM Interview Questions
[Link] 6/80
9/15/23, 8:44 PM Interview Questions
[Link] 7/80
9/15/23, 8:44 PM Interview Questions
2. What is the Document Object Model (DOM), and how does JavaScript
interact with it?
3. How does JavaScript handle asynchronous operations, and what are the
common methods for achieving this?
5. What is the same-origin policy, and how does it affect JavaScript in the
context of web security?
Answer: The same-origin policy is a security feature that restricts web pages
from making requests to a different domain than the one that served the
web page. JavaScript adheres to this policy to prevent cross-site request
forgery (CSRF) and other security threats.
[Link] 8/80
9/15/23, 8:44 PM Interview Questions
Answer: JavaScript can validate form input fields by checking user input
against predefined rules, such as required fields, email formats, or password
strength. This validation occurs before the form is submitted, providing
immediate feedback to users.
7. What is the role of a JavaScript runtime environment, and how does it
differ from a web browser's engine?
Answer: Closures are functions that have access to variables from their
containing (enclosing) function, even after the enclosing function has
finished executing. Here's an example:
10. What are the benefits and drawbacks of using JavaScript frameworks and
libraries in web development?
Answer: JavaScript frameworks and libraries like React, Angular, and [Link]
simplify web development by providing pre-built components and
abstractions. They improve developer productivity but may introduce a
learning curve and add complexity to projects.
[Link] 9/80
9/15/23, 8:44 PM Interview Questions
3. Why is version control important, and what are some popular version
control systems used in JavaScript development?
4. How do you initialize a new [Link] project using npm, and why is
[Link] important?
Answer: To initialize a new [Link] project, you can run npm init in your
project directory. This command generates a [Link] file, which
contains metadata about your project, including its dependencies and
scripts.
Answer: The .gitignore file specifies which files and directories should be
excluded from version control. It helps keep the repository clean and
prevents sensitive or unnecessary files from being committed to Git.
6. What is the difference between global and local npm packages, and how
can you install them?
Answer: Global npm packages are installed globally on your system and are
typically used for command-line tools. Local npm packages are project-
specific and are installed in the project's directory. You can install global
packages using npm install -g and local packages using npm install .
[Link] 10/80
9/15/23, 8:44 PM Interview Questions
Answer: A JavaScript linter, such as ESLint, checks your code for style and
syntax errors. It enforces coding standards and helps maintain consistency
and quality across a project.
9. What is the purpose of a development server in JavaScript development,
and how can you set one up?
[Link] 11/80
9/15/23, 8:44 PM Interview Questions
[Link] 12/80
9/15/23, 8:44 PM Interview Questions
7. How does JavaScript handle asynchronous tasks, and what are the
mechanisms for achieving asynchronicity?
Answer: JavaScript handles asynchronous tasks through mechanisms like
callbacks, Promises, and async/await. These allow code to continue
executing while waiting for asynchronous operations to complete,
preventing blocking behavior.
8. Explain the role of the Event Loop and the Callback Queue in handling
asynchronous code.
Answer: The Event Loop continuously checks the call stack and, when it's
empty, looks for pending tasks in the Callback Queue. If tasks are found,
they are moved to the call stack for execution. This process allows JavaScript
to handle asynchronous code in a non-blocking way.
9. What is the purpose of the Web APIs in the context of JavaScript
execution in the browser?
Answer: Web APIs provide browser-specific functionality like DOM
manipulation, HTTP requests, and timers. These APIs allow JavaScript to
interact with the browser environment and perform tasks like updating the
UI and making network requests.
10. How can you optimize JavaScript code for better performance in the
browser?
[Link] 13/80
9/15/23, 8:44 PM Interview Questions
3. How can you include JavaScript code within an HTML file using inline
<script> tags?
Answer: You can include JavaScript code within an HTML file using <script>
tags in the following way:
Answer: The defer attribute loads the script in the background while
parsing the HTML and executes it after the HTML is parsed. The async
attribute loads the script asynchronously and executes it as soon as it's
available, which may not preserve the order of execution. These attributes
can improve page load performance.
[Link] 14/80
9/15/23, 8:44 PM Interview Questions
5. How can you link an external JavaScript file to an HTML document using
the <script> tag's src attribute?
Answer: You can link an external JavaScript file using the <script> tag with
the src attribute like this:
<script src="[Link]"></script>
6. What is the purpose of the HTML data-* attribute, and how can you use
it in combination with JavaScript?
Answer: The data-* attribute is used to store custom data private to the
page or application. JavaScript can access and manipulate these attributes to
store and retrieve data associated with HTML elements dynamically.
7. How can you include JavaScript code in an HTML document using event
attributes like onclick and onload ?
Answer: You can include JavaScript code in an HTML document using event
attributes like this:
8. Explain the usage of JavaScript templates and how they can be employed
in modern web development.
Answer: JavaScript templates, such as template literals (``), allow you to
embed JavaScript expressions directly within strings. They are commonly
used for string interpolation, generating dynamic HTML, and simplifying
complex string concatenation.
9. What is the purpose of JavaScript modules, and how can they be included
in web applications?
[Link] 15/80
9/15/23, 8:44 PM Interview Questions
10. How can you use JavaScript frameworks like React or [Link] to build web
applications?
[Link] 16/80
9/15/23, 8:44 PM Interview Questions
[Link]("Hello, world!");
Answer: To log multiple values, you can separate them with commas within a
single [Link] statement:
[Link]();
[Link] 17/80
9/15/23, 8:44 PM Interview Questions
[Link] 18/80
9/15/23, 8:44 PM Interview Questions
alert
1. What is the purpose of the alert function in JavaScript?
Answer: The alert function is used to display a pop-up dialog box with a
message to the user. It is often used for simple notifications and alerts in
web applications.
2. How do you use the alert function to display a message in a web page?
Answer: You can use the alert function like this:
3. Can you customize the text displayed in an alert dialog box? If so, how?
Answer: No, the alert dialog box's appearance and text cannot be
customized. It typically displays a standard message box with an OK button
and the provided message.
Answer: The alert function does not return a value. It is a void function,
meaning it does not produce any result that can be assigned to a variable.
6. Are there any alternatives to the alert function for displaying messages
or notifications to users in a more user-friendly way?
Answer: Yes, alternatives to alert include:
• Using modal dialogs or pop-up windows created with HTML and CSS.
[Link] 19/80
9/15/23, 8:44 PM Interview Questions
7. Can you use JavaScript to capture the user's response to an alert dialog
box?
Answer: No, the alert function does not provide a way to capture the
user's response. It simply displays a message and waits for the user to close
the dialog box.
8. What is the difference between alert , confirm , and prompt in
JavaScript?
Answer:
• prompt displays a message with an input field for the user to enter text
and returns the entered text as a string or null if canceled.
9. Why should you use confirm or prompt instead of alert for user
interactions that require a response?
[Link] 20/80
9/15/23, 8:44 PM Interview Questions
prompt()
1. What is the purpose of the prompt() function in JavaScript?
Answer: The prompt() function is used to display a dialog box that allows
the user to enter input, typically in the form of text or a response to a
question.
2. How do you use the prompt() function to get user input in a web page?
Answer: You can use the prompt() function like this:
3. What is the syntax of the prompt() function, and what parameters does it
accept?
Answer: The prompt() function has the following syntax:
4. What is the return value of the prompt() function, and how can you
access the user's input?
Answer: The prompt() function returns a string that represents the user's
input. You can access it by storing the return value in a variable, as shown in
the example above.
5. What happens if the user clicks "OK" in the prompt() dialog without
entering any input?
Answer: If the user clicks "OK" without entering any input, the prompt()
function returns an empty string ( "" ).
[Link] 21/80
9/15/23, 8:44 PM Interview Questions
• prompt() displays a dialog box with an input field to collect user input.
• alert() displays a dialog box with a message but doesn't allow user
input. It's typically used for notifications.
7. Can the prompt() function be used for collecting sensitive information
like passwords? Why or why not?
Answer: While the prompt() function can be used to collect input, it's not
secure for collecting sensitive information like passwords. User input in a
prompt() dialog can be easily accessed and is not encrypted.
8. How can you handle user cancellation when using the prompt() function?
Answer: You can check the return value of the prompt() function to handle
user cancellation. If the user clicks "Cancel" or closes the dialog, the function
returns null . You can use conditional statements to check for null and
handle it appropriately.
• Check if the input meets your specific criteria (e.g., required fields, valid
formats).
[Link] 22/80
9/15/23, 8:44 PM Interview Questions
2. What are literals in JavaScript, and how do they differ from variables?
Answer: Literals are fixed values directly written in your code (e.g., numbers,
strings, objects) without using variables or expressions. Variables, on the
other hand, are symbolic names that can reference any value, including
literals.
3. Explain the difference between var , let , and const when declaring
variables.
Answer:
Answer: Template literals (``) are a type of string literal that allow for easy
string interpolation and multiline strings. They use backticks and ${} to
embed variables and expressions within strings.
[Link] 23/80
9/15/23, 8:44 PM Interview Questions
9. What is the undefined and null value in JavaScript, and how are they
different?
Answer:
[Link] 24/80
9/15/23, 8:44 PM Interview Questions
Answer:
• var declares variables with function scope and allows for variable
hoisting.
4. What happens if you declare a variable with var but don't initialize it with
a value?
Answer: If you declare a variable with var but don't initialize it, it will be
assigned the value undefined by default.
5. How do you declare and initialize a variable using let in JavaScript?
Answer: You can declare and initialize a variable using let like this:
let count = 0;
6. Can you reassign a value to a variable declared with const after its
initialization?
[Link] 25/80
9/15/23, 8:44 PM Interview Questions
7. What is the scope of a variable declared using var , and how does it differ
from let and const ?
Answer: Variables declared with var have function scope, meaning they are
accessible throughout the function containing their declaration. In contrast,
let and const variables have block scope and are limited to the block
they are declared in.
8. Explain the "Temporal Dead Zone" (TDZ) in the context of let and const
declarations.
Answer: The Temporal Dead Zone is the period between entering scope and
the actual variable declaration. During this time, accessing the variable
results in a ReferenceError . It helps catch potential issues related to
variable use before declaration.
9. What is the purpose of the typeof operator in JavaScript, and how can it
be used with variable declarations?
Answer: The typeof operator is used to determine the data type of a value
or variable. You can use it with variable declarations to check the type of a
variable:
10. What is the best practice for variable naming in JavaScript, and are there
any naming conventions to follow?
Answer: In JavaScript, it's a best practice to use descriptive variable names in
camelCase. Variables should start with a lowercase letter and use meaningful
names to make the code more readable and maintainable. There are no
strict naming conventions, but consistency within a project or team is
essential.
[Link] 26/80
9/15/23, 8:44 PM Interview Questions
Manipulating Variables
Answer:
For example:
[Link] 27/80
9/15/23, 8:44 PM Interview Questions
4. How can you concatenate strings in JavaScript, and what operators are
commonly used for this purpose?
Answer: You can concatenate strings in JavaScript using the + operator. For
example:
Answer:
[Link] 28/80
9/15/23, 8:44 PM Interview Questions
Answer: You can check if a variable is defined using the typeof operator or
by comparing it to undefined . For example:
9. Explain how to clone or copy the value of one variable into another
variable.
Answer: You can clone or copy the value of one variable into another
variable using the assignment operator ( = ). This creates a new variable with
the same value as the original variable.
10. How can you swap the values of two variables without using a temporary
variable in JavaScript?
Answer: You can swap the values of two variables without a temporary
variable using destructuring assignment. For example:
[Link] 29/80
9/15/23, 8:44 PM Interview Questions
Arithmetic
1. What are the basic arithmetic operations available in JavaScript?
Answer: You can add two numbers in JavaScript using the addition operator
(+). For example:
4. What is the purpose of the modulus operator (%) in JavaScript, and how
does it work?
Answer: The modulus operator (%) calculates the remainder when one
number is divided by another. For example:
[Link] 30/80
9/15/23, 8:44 PM Interview Questions
Answer: You can calculate the square root of a number using the
[Link]() method. For example:
[Link] 31/80
9/15/23, 8:44 PM Interview Questions
Relational
1. What are relational operators in JavaScript, and what is their primary
purpose?
Answer:
• Strict equal to ( === ): Compares if two values are strictly equal, without
type coercion.
• Strict not equal to ( !== ): Compares if two values are strictly not equal,
without type coercion.
• Greater than ( > ): Compares if the left operand is greater than the right
operand.
• Less than ( < ): Compares if the left operand is less than the right
operand.
• Less than or equal to ( <= ): Compares if the left operand is less than or
equal to the right operand.
Example:
[Link] 32/80
9/15/23, 8:44 PM Interview Questions
Answer:
• === is strict equality and does not perform type coercion. It only returns
true if both the value and type of the operands are the same. "5" === 5
is false.
=== is preferred in most cases to avoid unexpected type-related issues.
[Link] 33/80
9/15/23, 8:44 PM Interview Questions
7. How can you compare non-primitive data types (e.g., objects and arrays)
using relational operators?
9. Explain the concept of truthy and falsy values in JavaScript and how they
relate to relational operators.
[Link] 34/80
9/15/23, 8:44 PM Interview Questions
Equality
Certainly! Here are 10 interview questions on equality in JavaScript, along with
their answers, to help you prepare for interviews at top tech companies:
Answer:
• == performs type coercion and checks if the values are equal after type
conversion.
• === checks for strict equality, ensuring both the value and type are
identical.
Answer:
Type coercion is the automatic conversion of one data type to another when
performing operations. In equality comparisons, type coercion can lead to
unexpected results. For example:
3. What are truthy and falsy values in JavaScript, and how do they relate to
equality comparisons?
Answer:
In JavaScript, truthy values are values that evaluate to true in a Boolean
context, while falsy values evaluate to false . Inequality comparisons
consider the truthiness or falsiness of values. For example, 0 == false is
true because both are falsy.
Answer: NaN is not equal to itself, so NaN == NaN evaluates to false. This is
because NaN represents an undefined or unrepresentable value.
[Link] 35/80
9/15/23, 8:44 PM Interview Questions
Answer: [Link]() is used for value and type equality comparisons, just
like === . However, it has some differences:
Answer:
Both null == undefined and null === undefined evaluate to true because
JavaScript treats them as equal. However, they are distinct values with
different use cases.
7. Explain how to avoid unexpected type coercion in equality comparisons in
JavaScript.
Answer:
To avoid unexpected type coercion, it's recommended to use strict equality
( === ) whenever possible. Strict equality checks both value and type,
preventing type coercion.
8. What are the best practices for performing equality comparisons in
JavaScript, especially when dealing with different data types?
Answer:
• Use strict equality ( === ) to avoid type coercion and ensure both value
and type are identical.
• When dealing with complex data structures (e.g., objects), consider using
deep equality comparison libraries like lodash or implementing custom
comparison logic.
Answer:
Both null == undefined and null === undefined evaluate to true because
JavaScript treats them as equal. The difference is in their type: null is an
object type, while undefined is an undefined type.
[Link] 36/80
9/15/23, 8:44 PM Interview Questions
10. How can you compare two objects for equality in JavaScript?
Answer:
Comparing two objects for equality in JavaScript requires custom
comparison logic because objects are compared by reference, not by their
content. You can use deep comparison functions, such as those provided by
libraries like lodash , or implement your own recursive comparison
algorithm.
These questions and answers should help you demonstrate your understanding
of equality comparisons in JavaScript during interviews at top tech companies.
[Link] 37/80
9/15/23, 8:44 PM Interview Questions
Logical
1. What are logical operators in JavaScript, and what is their primary
purpose?
Answer: Logical operators are used to perform logical operations on Boolean
values and expressions. They are primarily used for making decisions and
controlling the flow of code.
2. List the three main logical operators in JavaScript and describe their
behavior.
Answer:
• && (Logical AND): Returns true if both operands are true , otherwise,
it returns false .
[Link] 38/80
9/15/23, 8:44 PM Interview Questions
8. Explain how to use logical operators to check for multiple conditions with
different outcomes.
Answer: You can use logical operators to check for multiple conditions with
different outcomes by combining them with if , else if , and else
statements. For example:
• && returns true if both operands are truthy and short-circuits if the
first operand is falsy.
[Link] 39/80
9/15/23, 8:44 PM Interview Questions
10. How can you use logical operators to simplify conditional expressions and
make code more concise?
Answer: Logical operators can help simplify conditional expressions by
combining conditions in a concise manner. For example:
[Link] 40/80
9/15/23, 8:44 PM Interview Questions
Assignment
1. What is assignment in JavaScript, and what is its primary purpose?
3. Explain the difference between var , let , and const when assigning
values to variables.
Answer:
• var has function scope and can be redeclared within the same scope.
• let has block scope and can be reassigned within the same scope.
[Link] 41/80
9/15/23, 8:44 PM Interview Questions
Answer: You can assign values to multiple variables in a single line using
destructuring or by separating variable assignments with commas. For
example:
[Link] 42/80
9/15/23, 8:44 PM Interview Questions
10. What is variable hoisting in JavaScript, and how does it affect variable
assignment?
[Link] 43/80
9/15/23, 8:44 PM Interview Questions
4. Explain the difference between the + operator used for addition and the
+ operator used for string concatenation in JavaScript.
6. How can you explicitly specify the order of evaluation for operators with
the same precedence?
Answer: You can use parentheses to explicitly specify the order of evaluation
for operators with the same precedence. Expressions within parentheses are
evaluated first.
[Link] 44/80
9/15/23, 8:44 PM Interview Questions
Answer: The ternary conditional operator has lower precedence than most
operators and is right-associative. It's used for conditional expressions and
helps assign values based on a condition.
10. Give an example of how operator precedence and associativity can impact
the result of an expression.
[Link] 45/80
9/15/23, 8:44 PM Interview Questions
Strings
1. What is a string in JavaScript, and how is it represented?
• Single quotes (' ') and double quotes (" ") are interchangeable and can
be used to define strings.
• Backticks ( ) are used for template literals and allow for string
interpolation, multiline strings, and embedding expressions.
4. How can you concatenate strings in JavaScript, and provide examples for
each method?
Answer: You can concatenate strings using the + operator or the concat()
method. For example:
[Link] 46/80
9/15/23, 8:44 PM Interview Questions
6. What is the length property of a string, and how can you use it to
determine the length of a string?
Answer: The length property of a string returns the number of characters in
the string. You can use it like this:
[Link] 47/80
9/15/23, 8:44 PM Interview Questions
9. What is string interpolation in JavaScript, and how can you achieve it?
Answer: String interpolation allows you to embed expressions or variables
within a string. In JavaScript, you can achieve it using template literals
(backticks). For example:
10. Explain how to check if a substring exists within a string in JavaScript, and
provide an example.
Answer: You can use the includes() method to check if a substring exists
within a string. For example:
[Link] 48/80
9/15/23, 8:44 PM Interview Questions
String functions
1. What is a string in JavaScript, and how can you create one?
Answer: A string in JavaScript is a sequence of characters enclosed in single
('') or double ("") quotes. You can create a string using quotes:
[Link] 49/80
9/15/23, 8:44 PM Interview Questions
Examples:
[Link] 50/80
9/15/23, 8:44 PM Interview Questions
Example:
8. What is the replace() method in JavaScript, and how can you use it to
replace text in a string?
[Link] 51/80
9/15/23, 8:44 PM Interview Questions
10. What is the purpose of the trim() method in JavaScript, and how can it
be used with strings?
Answer: The trim() method removes leading and trailing whitespace from
a string and returns the trimmed string. For example:
[Link] 52/80
9/15/23, 8:44 PM Interview Questions
Type Coercion
1. What is type coercion in JavaScript, and why does it occur?
Answer: Type coercion in JavaScript is the automatic conversion of one data
type to another when performing operations or comparisons. It occurs to
ensure that different data types can be used together in expressions.
2. Explain the difference between implicit and explicit type coercion in
JavaScript.
Answer:
Answer: When you add a string and a number in JavaScript, type coercion
converts the number to a string, and the values are concatenated. For
example: "5" + 3 results in the string "53" .
4. How can you use the Number() function for explicit type coercion in
JavaScript?
Answer: The Number() function can be used to explicitly convert a value to a
number data type. For example:
5. Explain the concept of truthy and falsy values in the context of type
coercion.
Answer: Truthy values are values that evaluate to true in a Boolean context,
while falsy values evaluate to false . Type coercion often plays a role in
determining truthiness or falsiness, especially in conditional statements.
[Link] 53/80
9/15/23, 8:44 PM Interview Questions
7. How can you use the Boolean() function for explicit type coercion in
JavaScript?
Answer: The Boolean() function can be used to explicitly convert a value to
a Boolean data type. For example:
8. What is the purpose of the String() function for explicit type coercion in
JavaScript?
Answer: The String() function is used to explicitly convert a value to a
string data type. It ensures that the value is treated as a string when
concatenated or used in string operations.
9. What are the potential pitfalls of relying on implicit type coercion in
JavaScript, and why is it important to be aware of them?
10. Explain how you can avoid unintended type coercion in JavaScript by
using strict equality ( === ).
Answer: Strict equality ( === ) compares values without type coercion,
ensuring that both the value and type are identical. Using === instead of
== can help you avoid unintended type coercion and produce more reliable
code.
[Link] 54/80
9/15/23, 8:44 PM Interview Questions
[Link] 55/80
9/15/23, 8:44 PM Interview Questions
5. How can you convert a value to a string in JavaScript using explicit type
conversion?
Answer: You can convert a value to a string using the String() constructor
or the .toString() method. For example:
6. What is the purpose of the Boolean() function in JavaScript, and how can
you use it for type conversion?
[Link] 56/80
9/15/23, 8:44 PM Interview Questions
9. How can you check if a value is a finite number in JavaScript after type
conversion?
Answer: You can check if a value is a finite number using the isFinite()
function. It returns true if the value is a finite number; otherwise, it returns
false .
10. Explain the concept of "truthy" and "falsy" values in JavaScript and how
they relate to type conversion.
Answer: Truthy values are values that evaluate to true in a Boolean context,
while falsy values evaluate to false . JavaScript uses truthy and falsy values
in conditional statements and type coercion. For example, empty strings, 0 ,
NaN , and null are falsy, while non-empty strings, numbers other than 0 ,
and objects are truthy.
[Link] 57/80
9/15/23, 8:44 PM Interview Questions
Boolean
1. What is a Boolean in JavaScript, and what are its possible values?
Answer: A Boolean in JavaScript is a data type that represents a binary value:
true or false. These values are used for logical comparisons and conditional
statements.
2. What are the three logical operators in JavaScript for combining Boolean
values, and how do they work?
• ! (logical NOT): Negates the value of the operand; true becomes false,
and vice versa.
3. How can you convert other data types (e.g., numbers, strings) to Booleans
in JavaScript?
Answer: You can convert other data types to Booleans using the Boolean()
function. Any non-falsy value will convert to true , while falsy values will
convert to false .
4. What are falsy values in JavaScript, and can you name a few examples?
Answer: Falsy values are values that evaluate to false when converted to
Booleans. Examples include false , 0 , null , undefined , NaN , and an
empty string ( "" ).
5. How can you check if a variable is a Boolean in JavaScript?
Answer: You can check if a variable is a Boolean using the typeof operator:
[Link] 58/80
9/15/23, 8:44 PM Interview Questions
8. How can you compare two Boolean values for equality in JavaScript, and
do you need to use strict equality?
Answer: You can compare two Boolean values for equality using strict
equality ( === ). Since Boolean values have a finite set of possible values
( true and false ), strict equality is sufficient for comparison.
9. What is the difference between == and === when comparing a Boolean
value with a non-Boolean value?
Answer:
• == (loose equality) performs type coercion and may convert the non-
Boolean value to a Boolean before comparison.
• === (strict equality) checks both value and type, so a Boolean value will
never be equal to a non-Boolean value using strict equality.
10. Can you explain the concept of truthy and falsy values in the context of
JavaScript's logical operations?
[Link] 59/80
9/15/23, 8:44 PM Interview Questions
Null
1. What is the purpose of the null value in JavaScript?
Answer:
• undefined is a value that indicates a variable has been declared but not
assigned a value, or that an object property does not exist.
4. How can you explicitly assign the value null to a variable in JavaScript?
Answer: You can assign the null value to a variable like this:
5. What is the result of comparing null and undefined using the strict
equality operator ( === )?
[Link] 60/80
9/15/23, 8:44 PM Interview Questions
7. What is the result of using the typeof operator on a variable assigned the
value null ?
Answer: The typeof operator applied to a null value returns the string
"object" . This is a historical quirk in JavaScript and not an accurate
reflection of the null type.
10. What are some potential pitfalls or challenges when working with null in
JavaScript, and how can they be mitigated?
Answer: Challenges with null in JavaScript can include:
[Link] 61/80
9/15/23, 8:44 PM Interview Questions
Undefined
1. What is the undefined value in JavaScript?
[Link] 62/80
9/15/23, 8:44 PM Interview Questions
let x = undefined;
• An undeclared variable is one that has not been declared with any
keyword ( var , let , const ) and will throw a reference error if you
attempt to use it.
9. What happens when you access an object property that doesn't exist, and
how is it related to undefined ?
Answer: Accessing an object property that doesn't exist returns undefined .
For example:
[Link] 63/80
9/15/23, 8:44 PM Interview Questions
Answer: The code will output "Truthy" because the string "hello" is a truthy
value.
Answer: The ternary operator is used for conditional expressions. You can
use it to handle truthy and falsy values by providing two different values or
expressions based on the condition. For example:
[Link] 64/80
9/15/23, 8:44 PM Interview Questions
9. What happens when you use the typeof operator with a falsy value, such
as null or undefined ?
Answer: When you use the typeof operator with a falsy value, it returns a
string representing the data type of that value. For example, typeof null
returns "object" and typeof undefined returns "undefined" .
10. Explain the potential pitfalls of relying solely on truthy and falsy values for
equality comparisons.
Answer: Relying solely on truthy and falsy values for equality comparisons
can lead to unexpected behavior when non-Boolean values are involved. It's
essential to use strict equality ( === ) when precise type and value
comparisons are required to avoid type coercion issues.
These questions and answers should help you demonstrate your understanding
of truthy and falsy values in JavaScript during interviews at top tech companies.
[Link] 65/80
9/15/23, 8:44 PM Interview Questions
[Link] 66/80
9/15/23, 8:44 PM Interview Questions
[Link] 67/80
9/15/23, 8:44 PM Interview Questions
6. What is the purpose of the switch statement in JavaScript, and how does
it differ from if-else-if chains?
Answer: The switch statement is used for multi-branching based on the
value of an expression. It's more suitable when you have a single expression
to compare against multiple values, whereas if-else-if chains are used for
more complex conditions and comparisons.
7. How can you use logical operators ( && , || ) in conjunction with if
statements to create compound conditions?
8. What is the "truthy" and "falsy" concept in JavaScript, and how does it
affect if statements?
Answer: In JavaScript, values are evaluated as "truthy" if they are considered
true in a Boolean context, and "falsy" if they are considered false. In if
statements, non-falsy values are treated as true , and falsy values are
treated as false .
9. How do you write an if statement that checks whether a variable is
defined?
Answer: You can use the typeof operator to check if a variable is defined:
[Link] 68/80
9/15/23, 8:44 PM Interview Questions
[Link] 69/80
9/15/23, 8:44 PM Interview Questions
Ternary Operator
1. What is the ternary operator in JavaScript, and what is its purpose?
Answer: The ternary operator, also known as the conditional operator ( ? : ),
is a shorthand way to write conditional expressions. It allows you to evaluate
a condition and return one of two values based on whether the condition is
true or false.
2. What is the syntax of the ternary operator in JavaScript?
Answer: The syntax of the ternary operator is as follows:
3. How do you use the ternary operator to assign a value to a variable based
on a condition?
Answer: The ternary operator evaluates the condition first. If the condition is
true, it returns the value of expressionIfTrue ; otherwise, it returns the value
of expressionIfFalse .
[Link] 70/80
9/15/23, 8:44 PM Interview Questions
6. What are some advantages of using the ternary operator over if...else
statements in JavaScript?
Answer: Advantages of the ternary operator include:
• It can make code more readable when the condition and expressions are
short and straightforward.
Answer: The ternary operator is primarily used for assigning values based on
conditions, not for executing statements. For executing statements
conditionally, if...else statements are more appropriate.
9. What is the result of the following ternary expression: true ? 1 : false ?
2 : 3 ?
Answer: The result is 1 . The ternary operator is evaluated from left to right,
so it first checks true ? 1 , which is true, and returns 1 . It doesn't evaluate
the subsequent conditions.
10. What are some common use cases for the ternary operator in JavaScript?
Answer: Common use cases for the ternary operator include:
[Link] 71/80
9/15/23, 8:44 PM Interview Questions
Nested if...else
1. What is a nested if...else statement in JavaScript?
Answer: A nested if...else statement is when one if...else statement is
placed inside another if or else block. This allows for more complex
conditional logic.
2. Explain the syntax of a nested if...else statement in JavaScript.
Answer: The syntax of a nested if...else statement is as follows:
Answer:
[Link] 72/80
9/15/23, 8:44 PM Interview Questions
Answer:
• Code readability can suffer when there are too many nested levels.
Answer: Nested if...else statements are suitable for situations where you
need to evaluate multiple conditions in a hierarchical manner. For example,
in a video game, you might use nested if...else statements to determine
the outcome of a player's actions based on various in-game conditions.
8. How can you avoid excessive nesting and improve code readability when
dealing with complex conditional logic?
Answer:
[Link] 73/80
9/15/23, 8:44 PM Interview Questions
10. Can you rewrite a deeply nested if...else statement using a more
readable and maintainable approach?
Answer: Certainly! Here's an example of refactoring a deeply nested
if...else statement using a more structured approach:
[Link] 74/80
9/15/23, 8:44 PM Interview Questions
switch...case
1. What is the purpose of the switch...case statement in JavaScript?
Answer: The switch...case statement is used for conditional branching in
JavaScript. It allows you to test a value against multiple possible cases and
execute different code blocks based on the matched case.
2. Explain the basic syntax of the switch...case statement in JavaScript.
Answer: The basic syntax of a switch...case statement is as follows:
[Link] 75/80
9/15/23, 8:44 PM Interview Questions
Answer: Yes, you can have multiple cases that execute the same code block
by omitting the break statement in each case. This is often used to group
cases that should have the same behavior.
8. What is the purpose of the break statement in a switch...case block?
Answer: The break statement is used to exit the switch...case block once
a matching case has been found and executed. It prevents the execution of
subsequent cases.
[Link] 76/80
9/15/23, 8:44 PM Interview Questions
while loop
1. What is a while loop in JavaScript, and what is its primary purpose?
Answer: A while loop is a control flow structure in JavaScript used to
repeatedly execute a block of code as long as a specified condition is true.
2. Explain the basic syntax of a while loop in JavaScript.
Answer: The basic syntax of a while loop is as follows:
3. What is the key difference between a while loop and a for loop in
JavaScript?
Answer: The primary difference is that a for loop is typically used when you
know the number of iterations in advance, while a while loop is used when
you need to repeat a task until a certain condition becomes false.
4. What happens if the condition in a while loop is initially false?
Answer: If the condition in a while loop is initially false, the loop's code
block will not be executed at all.
5. Explain the concept of an infinite loop and how it can be created using a
while loop.
6. How can you avoid creating infinite loops unintentionally in your code?
[Link] 77/80
9/15/23, 8:44 PM Interview Questions
7. What is the purpose of the break statement in a while loop, and how is
it used?
9. How can you convert a for loop into an equivalent while loop, and vice
versa?
Answer: You can convert a for loop into a while loop by initializing the
loop variable before the while loop and using a while loop's condition.
Conversely, you can convert a while loop into a for loop by using the
for loop's initialization, condition, and increment parts.
10. When should you use a while loop over other loop types, such as for or
forEach ?
Answer: You should use a while loop when the number of iterations is not
known in advance and is determined by a specific condition. for and
forEach loops are more suitable when you have a predetermined number
of iterations.
[Link] 78/80
9/15/23, 8:44 PM Interview Questions
do while loop
1. What is the do...while loop in JavaScript, and how does it differ from
other types of loops like for and while loops?
Answer: A do...while loop is useful when you want to ensure that a block
of code runs at least once, regardless of whether the condition is initially
true or false. It is commonly used for tasks where the code should execute
before condition checking, such as user input validation.
Answer: Even if the condition is initially false, the code block inside the
do...while loop will execute at least once before the condition is checked.
If the condition is false after the initial execution, the loop will exit.
[Link] 79/80
9/15/23, 8:44 PM Interview Questions
7. Write a do...while loop that counts from 1 to 10 and prints the numbers.
Answer:
8. Can you use the break statement inside a do...while loop to exit it
prematurely?
Answer: Yes, the break statement can be used inside a do...while loop to
exit the loop prematurely if a certain condition is met.
9. What is the difference between the while loop and the do...while loop?
Answer:
• The while loop checks the condition before executing the code block,
which means the code block may not execute if the condition is initially
false.
• The do...while loop executes the code block at least once before
checking the condition, ensuring the code block runs at least once.
10. When should you choose a do...while loop over a for or while loop in
JavaScript?
[Link] 80/80