Top 50+ JavaScript Interview Questions And Answers
JavaScript (also abbreviated as JS) is the world's most used language. It is one of the core languages of the World Wide Web (www) along with HTML and CSS. Developed by Brendan Eich, JavaScript is used for both client-server sides to make the webpage interactive. All major web browsers have a dedicated JS engine to execute the code on users' devices.
JS engines were originally used only in web browsers, but are now core components of some servers and a variety of applications. The most popular runtime system for this usage is Node.js. Although Java and JavaScript are similar in name, syntax and respective standard libraries the two languages are distinct and differ greatly in design.
Some examples of using this scripting language are:
- Loading new web page content without reloading the page, via Ajax or a Websocket For example, users of social media can send and receive messages without leaving the current page
- Web page animations, such as fading objects in and out, resizing and moving them
- Playing browser games
- Controlling the playback of streaming media
- Generating pop-up-adds
- Validating input values of web form before the data is sent to the web browser.
- Logging data about the user's behavior and then sending it to a server. The website owner can use this data for analytics, ad tracking, and personalization
- Redirecting a user to another page
JavaScript Interview Questions
If you are applying for the role of a web developer, some of these basic JavaScript interview questions will help you prepare better.
Q1. What is JavaScript?
JavaScript is a high-level, interpreted programming language that is primarily used for creating interactive and dynamic web pages. It was originally developed by Brendan Eich at Netscape Communications in the mid-1990s and has since become one of the most popular programming languages in the world.
JavaScript is primarily known for its use in web development, where it is used to enhance the functionality and interactivity of websites. It is a core technology of the web alongside HTML and CSS. JavaScript allows developers to add dynamic behavior to web pages, handle user interactions, manipulate and modify web page content, and communicate with servers to retrieve or send data asynchronously.
Q2. What is ECMA Script?
ECMAScript (or ES) is a scripting language specification standardized by Ecma International. It is the official standard for JavaScript, providing guidelines and specifications for the language syntax, features, and behavior. The terms "JavaScript" and "ECMAScript" are often used interchangeably, but it's important to note that JavaScript is the most popular implementation of the ECMAScript standard.
ECMAScript defines the core features and functionalities of the JavaScript programming language. It specifies the syntax, data types, control structures, object-oriented programming concepts, and built-in objects and functions that are available in JavaScript.
The ECMAScript specification is periodically updated to introduce new features, improvements, and modifications to the language. The different versions of ECMAScript are often referred to by their edition number, such as ECMAScript 5 (ES5), ECMAScript 6 (ES6), ECMAScript 2015 (ES2015), ECMAScript 2016 (ES2016), and so on.
New features and enhancements introduced in later editions of ECMAScript have significantly expanded the capabilities of JavaScript, enabling developers to write more efficient, concise, and expressive code. Some notable features introduced in recent ECMAScript versions include arrow functions, classes, template literals, object destructuring assignments, spread syntax, async/await, and more.
JavaScript engines implemented in web browsers and other JavaScript runtime environments adhere to the ECMAScript specifications to ensure consistency and compatibility across different platforms.
In summary, ECMAScript is the standardized specification that defines the syntax and features of the JavaScript programming language, and JavaScript is the most widely used implementation of that standard.
Q3. What are the different data types in Javascript?
JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.
- Primitive data type
- Non-primitive (reference) data type
Primitive Values (immutable datum represented directly at the lowest level of the language):- All types except objects define immutable values (that is, values that can't be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive values".
Boolean Type | Boolean represents a logical entity and can have two values., i.e, TRUE or FALSE |
Undefined Type | A variable that has not been assigned a value has the value undefined, i.e, let a; |
Number Type | An integer or a floating-point number. i.e, 3, 3.54 |
BigInt |
The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. Example- 900719925124740999n |
StringType |
JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Example- "hello world" |
Symbol Type |
Symbol is a unique and immutable primitive value and may be used as the key. In some programming languages, Symbols are called "atoms". Example: Let value = Symbol ('hello'); |
Non-Primitive data types
1. Objects: In computer science, an object is a value in memory that is possibly referenced by an identifier.
2. Properties: In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a string value or a symbol value.
There are mainly two properties,
- Data Property: The data property sets or returns the value of the data attribute of an <object> element.
- Accessor Property: Property accessors provide access to an object's properties by using the dot notation or the bracket notation.
Q4. What are callbacks?
In JavaScript, a callback is a function that is passed as an argument to another function and is executed later, typically after an asynchronous operation has completed or when a certain event occurs. Callbacks are a way to ensure that certain code snippet is executed only when a particular task is completed, allowing for asynchronous and non-blocking behavior in JavaScript.
Callbacks are commonly used in scenarios such as handling asynchronous operations like fetching data from a server, performing separate file I/O operations, or responding to user events. When an asynchronous operation is initiated, the callback function is provided as an argument, and it gets invoked by the system or the calling function once the operation is completed.
Here's an example to illustrate the concept of callbacks:
In the above example, the fetchData
function simulates an asynchronous operation that takes some time to complete (here simulated using setTimeout
). It accepts a callback function as an argument. Once the asynchronous operation is finished (after a 2-second delay), it invokes the provided callback function (processData
) and passes the fetched data as an argument.
The processData
function is defined separately and passed as a callback to the fetchData
function. It receives the fetched data as a parameter and processes it by logging it to the console.
By using callbacks, you can ensure that the processData
function is executed only after the data has been fetched, even though the actual fetching process takes some time. This allows for non-blocking execution and helps handle asynchronous operations in JavaScript effectively.
Q5. What are the scopes of variables in JavaScript?
In JavaScript, variables have different types of scope, which determine where a variable is accessible and how long it persists. The types of scope of variables in JavaScript are as follows:
Global Scope |
|
Local scope |
|
Function Scope |
|
Block Scope (Introduced in ES6) |
|
Q6. What is the unshift() method?
This method is functional at the start of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –
var name = [ "mysore" ];
name.unshift( "bangalore" );
name.unshift( "trivandrum", "chennai" );
console.log(name);
The output is shown below:
[" trivandrum ,"," chennai ,", " bangalore ", " mysore "]
Q7. Explain string in JavaScript.
A string is a sequence of characters, which is enclosed within a single (’ ’) or double (" ") quote.
Two ways to create a string in JS are:
1. String Literal: The string literal is created using single or double quotes.
Its syntax is as follows:
var stringname= "stringvalue";
<script>
var str="Unstop";
document.write(str);
</script>
Output: Unstop
2. String Object (Using Keyword)
The syntax for creating objects using new keywords is as follows:
var stringname=new String(”stringvalue”);
1.<script>
2.var stringname=new String("Dare To Compete");
3.document.write(stringname);
4.</script>
Output: Unstop
Some of the methods in JS string are as follows:
charAt() | Provides the value of the character present at the specified index |
concat() | A combination of two or more strings can be done using the concat() method |
indexOf() | Provides the position of the char value present in a given string. |
search() | It searches a specified regular expression in a given string and returns its position if a match occurs. |
match() | It searches a specified regular expression in a given string and returns the regular expression if the match occurs. |
replace() |
It is used to replace the given string with a specified replacement. |
substr() | It is used to fetch a part of the given string on the basis of a specified starting position and length. |
slice() | It is used to fetch the part of the given string. It allows us to assign positive as well negative indexes. |
trim() | It is used to trim the white spaces from the left and right sides of the string |
valueOf() | It provides the primitive value of the string object |
toUpper() | It converts the entire string into uppercase. |
toLower() | It converts the entire string into lowercase. |
Q8. Difference between search() and indexOf()?
The search()
and indexOf()
methods in JavaScript are used to search for a substring within a string. Here are the differences between these two methods:
indexOf() Method |
|
The |
The |
It does not support regular expressions; it performs a simple string search. |
It allows you to use regular expressions for searching. |
If the substring is found, the |
If the substring is found, the |
Example: var str = 'Hello World'; |
Example: var str = 'Hello World'; |
In summary, the main differences between search()
and indexOf()
are:
search()
allows the use of regular expressions for searching, whileindexOf()
performs a simple string search.search()
returns the index using regular expression matching, whileindexOf()
returns the index based on exact string matching.- Both methods return -1 if the substring is not found in the string.
indexOf(): Provides the position of the char value present in a given string.
<!DOCTYPE html> <html> <body> <h1>JavaScript Strings</h1> <h2>The indexOf() Method</h2> <p>indexOf() returns the position of the first occurrence of a value in a string.</p> <p>Find "welcome":</p> <p></p> <script> let text = "Hello world, welcome to the universe."; let result = text.indexOf("welcome"); document.getElementById("demo").innerHTML = result; </script> </body> </html>
Q9. Difference between an array and an object?
Here's a comparison between an array and an object :
Array | Object | |
---|---|---|
Definition | An ordered collection of values | An unordered collection of key-value pairs |
Access | Access elements using numeric indices | Access values using keys |
Order | Elements are ordered | Key-value pairs are unordered |
Length | Length can change dynamically | Number of key-value pairs can vary |
Iteration | Iterated using loops or array methods | Iterated using loops or object methods |
Elements | Elements have implicit indices | Properties have explicit keys |
Duplication | Allows duplicate values | Keys must be unique, values may or may not be unique |
Data Storage | Typically used for homogeneous data | Typically used for heterogeneous and structured data |
Use Cases | Storing and accessing multiple values | Representing entities, records, or structured data |
Arrays are primarily used when you need to store and access multiple values of the same type or when maintaining the order of elements is important. You can perform various operations on arrays, such as adding, removing, or modifying elements.
Objects, on the other hand, are used to represent entities, records, or structured data. They allow you to associate values (properties) with keys, making it easier to access and manipulate data based on meaningful names or identifiers.
In JavaScript, both arrays and objects have their distinct purposes and usage scenarios. They can be used in combination to create complex data structures and represent various aspects of a program or application.
Q10. Difference between "==" and "===" operators?
In JavaScript, the "==" (equality) and "===" (strict equality) operators are used for comparison between two values. Here's the difference between the two:
== (Equality Operator) | === (Strict Equality Operator) |
The "==" operator checks for equality between two values, allowing type coercion if necessary. |
The "===" operator checks for strict equality between two values without performing type coercion. |
If the types of the two values being compared are different, JavaScript attempts to convert one or both values to a common type before making the comparison. If the converted values are equal, the "==" operator returns |
It compares both the values and their types. If both the values and types are exactly the same, the "===" operator returns |
In general, it is recommended to use the "===" (strict equality) operator for most comparisons, as it ensures both value and type equality, without any unexpected type coercion. It helps prevent subtle bugs that can occur due to unintended type conversions. The "==" (equality) operator should be used with caution when type coercion is desired or explicitly handled.
Q11. Is JS static and dynamically typed?
JavaScript is a dynamically typed language, meaning that variable types are determined at runtime rather than explicitly declared. In JavaScript, you can assign values of different types to the same variable without explicitly specifying the variable's type.
Dynamic typing allows for greater flexibility and ease of use in JavaScript, as variables can be used to hold values of different types as needed. However, it also introduces the potential for type-related errors if not handled carefully. Developers need to pay attention to variable types and ensure that operations and functions are used correctly with the appropriate type of data.
Q12. What is isNaN() in Javascript?
In JavaScript, the isNaN()
function is used to determine whether a value is "Not-a-Number" (NaN) or not. It checks if the provided value is not a valid number and returns a boolean value indicating the result.
The isNaN()
function has the following behavior:
- If the provided value is not a number or cannot be converted to a number, it returns
true
. - If the provided value is a valid number or can be converted to a number, it returns
false
.
Here are some examples:
isNaN(42); // false, 42 is a valid number
isNaN('42'); // false, '42' can be converted to the number 42
isNaN('Hello'); // true, 'Hello' cannot be converted to a number
isNaN(undefined); // true, undefined cannot be converted to a number
isNaN(NaN); // true, NaN is considered as Not-a-Number
It's worth noting that the isNaN() function coerces the provided value to a number if it is not already a number. This coercion is done using the Number() function. If the value cannot be converted to a number, isNaN() returns true.
Q13. Explain pass-by-reference and pass-by-value.
In programming, "pass-by-reference" and "pass-by-value" are two different ways of passing arguments to functions or assigning values to variables. They determine how the data is handled and accessed within the function or variable assignment.
Pass-by-Value | Pass-by-Reference |
Pass-by-value is a mechanism where a copy of the value is passed to a function or assigned to a variable. |
Pass-by-reference is a mechanism where the memory address or reference of the value is passed to a function or assigned to a variable. |
In pass-by-value, any modifications made to the function parameter or variable inside the function do not affect the original value outside the function. |
In pass-by-reference, any modifications made to the function parameter or variable inside the function affect the original value outside the function. |
Primitive data types such as numbers, booleans, and strings are typically passed by value. |
Non-primitive data types such as objects and arrays are typically passed by reference. |
Example: function increment(number) { var x = 5; In this example, the value of |
Example: function changeName(person) { var user = { changeName(user); In this example, the reference of the |
Q14. Which company developed JavaScript?
JavaScript was developed by Brendan Eich, who was working at Netscape Communications Corporation (now known as Netscape Communications), during the mid-1990s. It was initially created for the Netscape Navigator web browser, which was one of the dominant browsers of that era. The development of JavaScript was driven by the need for a scripting language that could add interactivity and dynamic functionality to web pages. Brendan Eich designed and implemented JavaScript in just 10 days in May 1995, and it was first introduced in Netscape Navigator 2.0 in September 1995.
Q 15. What are the advantages of JS?
JavaScript (JS) offers several advantages that contribute to its popularity and widespread usage. Some of the key advantages of JavaScript include:
Client-Side Interactivity |
JavaScript is primarily used as a client-side scripting language, allowing developers to enhance the interactivity and user experience of web pages. It enables dynamic content updates, form validation, DOM manipulation, and interactive features without the need for server-side communication. |
Wide Adoption and Support |
JavaScript is supported by all major web browsers, making it a universal language for web development. It has a large and active community of developers, which leads to extensive resources, libraries, and frameworks that simplify development tasks. |
Versatility | JavaScript is a versatile language that can be used for various purposes, including web development, mobile app development (using frameworks like React Native and Ionic), server-side development (with Node.js), desktop application development (using frameworks like Electron), and even IoT (Internet of Things) development. |
Asynchronous Programming |
JavaScript supports asynchronous programming using features such as callbacks, Promises, and async/await. This allows non-blocking execution and efficient handling of tasks like fetching data from servers, performing animations, or handling user input without blocking the user interface. |
Easy Integration |
JavaScript can be easily integrated into existing web projects as it can be embedded directly within HTML or included from external files. It seamlessly interacts with HTML and CSS, making it straightforward to enhance the functionality and behavior of web pages. |
Rapid Development |
JavaScript promotes rapid development with its lightweight syntax and dynamic nature. It offers immediate feedback during development, making it easy to iterate and test code quickly. Additionally, the extensive ecosystem of libraries and frameworks (such as React, Vue.js, Angular) provides ready-made solutions for common tasks, reducing development time. |
Cross-Platform Compatibility |
JavaScript can run on various platforms, including different operating systems and devices. It powers web applications across desktops, laptops, tablets, smartphones, and even embedded systems, enabling developers to reach a wide audience with their applications. |
Scalability |
JavaScript allows developers to build scalable applications by leveraging modern frameworks and tools. With the introduction of server-side JavaScript frameworks like Node.js, developers can create highly scalable and efficient server-side applications using the same language as the client side. |
Q16. What are the disadvantages of JS?
JavaScript, like any programming language, has its disadvantages along with its strengths. Some of the disadvantages of JavaScript include:
Browser Compatibility |
JavaScript implementations may vary across different web browsers, leading to inconsistencies and compatibility issues. Developers often have to write code that accounts for these differences to ensure cross-browser compatibility. |
Security Vulnerabilities |
JavaScript executed on the client side is visible to the user, which makes it susceptible to manipulation and abuse. Malicious users can exploit vulnerabilities in JavaScript code to perform actions that compromise security, such as cross-site scripting (XSS) attacks.
|
Lack of Strong Typing |
JavaScript is a dynamically-typed language, which means variable types are determined at runtime. This flexibility can lead to issues and bugs due to unexpected type conversions or mismatches. It requires careful attention to variable types and may lead to runtime errors that could have been caught with static typing. |
Performance Limitations |
JavaScript is an interpreted language, and compared to compiled languages, it can have slower execution speeds. Although modern JavaScript engines have become highly optimized, JavaScript may not perform as well as lower-level languages in computationally intensive tasks. |
Limited File Access |
Due to security restrictions, JavaScript has limited access to the user's file system. It cannot directly read or write files on the user's machine for security reasons, which can be a limitation for certain types of applications. |
Lack of Multithreading | JavaScript is single-threaded, meaning it can only execute one operation at a time. This can be a disadvantage for highly parallel or CPU-intensive tasks, as it may lead to blocking and slower execution. |
Debugging Challenges |
Debugging JavaScript code can be challenging, especially when dealing with complex asynchronous operations or code that runs in different environments (browsers, server-side, etc.). Proper debugging tools and techniques are required to effectively troubleshoot issues. |
Q17. Define a named function in JS.
In JavaScript, a named function is a function that is assigned a name and can be referred to by that name for calling or referencing it later in the code. It is defined using the function
keyword followed by the function name, parentheses for optional parameters, and curly braces {}
to enclose the function body.
Named functions provide several advantages, including:
Readability and self-documentation | The name of the function describes its purpose, making the code easier to understand and maintain. |
Reusability | Named functions can be called multiple times from different parts of the code, avoiding code duplication. |
Recursion | Named functions can call themselves recursively by using their own name, allowing repetitive tasks to be solved elegantly. |
Q18. What are the looping structures in JavaScript?
JavaScript provides several looping structures to repeat a block of code multiple times. The commonly used looping structures in JavaScript are:
for loop |
The |
It consists of three parts: initialization, condition, and increment/decrement. |
|
Example: for (var i = 0; i < 5; i++) { |
|
while loop |
The |
It evaluates the condition before each iteration. |
|
Example: var i = 0; while (i < 5) { console.log(i); i++; } |
|
do-while loop |
The |
This ensures that the block of code is executed at least once, even if the condition is initially false. | |
Example: var i = 0; do { console.log(i); i++; } while (i < 5); |
|
for...in loop |
The |
It loops through each enumerable property of an object. | |
Example: var person = { for (var key in person) { |
|
for...of loop |
The |
It provides a simpler shorter syntax compared to other looping structures. |
|
Example: var colors = ['red', 'green', 'blue']; for (var color of colors) { |
Q19. Define closure.
In JavaScript, closure is a combination of a function and the lexical environment within which that function was declared. It has access ti variables in its parent scope and allows a function to access variables from its outer (enclosing) scope even after the outer function has finished executing.
A closure is created when an inner function is returned from an outer function inside the parent scope, and the inner function retains a reference to the variables of the outer function, even if the outer function has already been completed. This allows the inner function within the parent scope to access and manipulate the variables of its parent function, preserving their values.
Closures are powerful because they provide a way to create and access private variables and encapsulate functionality. They are commonly used to create data privacy and to implement modules and factories in JavaScript.
Q20. How to write "hello world" in JavaScript?
“Hello World” is a simple program and is used as an introduction program for beginners. We can print it using three ways:
To write "hello world" in JavaScript, you can use the console.log()
function to output the text to the browser console. Here's an example:
console.log("Hello, world!");
When you run this code in a JavaScript environment that supports the console.log()
function (such as a browser console or a Node.js environment), it will print "Hello, world!" as the output.
If you want to display "hello world" directly on a web page, you can use JavaScript to manipulate the HTML content. Here's an example of how you can achieve that:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<div></div><script src="script.js"></script>
</body>
</html>
JavaScript (script.js):
var outputDiv = document.getElementById("output");
outputDiv.textContent = "Hello, world!";
In this example, the JavaScript code selects the <div>
element with the id "output" using the getElementById()
method and sets its textContent
property to "Hello, world!". This will display "Hello, world!" on the web page inside the <div>
element.
Q21. What are the key differences between Java and JavaScript?
JAVA | JAVASCRIPT |
---|---|
Java is a strongly typed language and variables must be declared first to use in the program. In Java, the type of a variable is checked at compile-time. | JavaScript is a weakly typed language and has a more relaxed syntax and rules. |
Java is an object-oriented programming language. | JavaScript is an object-based scripting language. |
Java applications can run in any virtual machine(JVM) or browser. | JavaScript code used to run only in the browser, but now it can run on the server via Node.js. |
Objects of Java are class-based even we can’t make any program in java without creating a class. | JavaScript Objects are prototype-based. |
Java program has the file extension “.Java” and translates source code into bytecodes which are executed by JVM(Java Virtual Machine). | JavaScript file has the file extension “.js” and it is interpreted but not compiled, every browser has a Javascript interpreter to execute JS code. |
Java is a Standalone language. | contained within a web page and integrates with its HTML content. |
Java has a thread-based approach to concurrency. | Javascript has an event-based approach to concurrency. |
Java supports multithreading. | Javascript doesn’t support multi-threading. |
Q22. What is BOM?
BOM stands for Browser Object Model. It is a JavaScript API provided by web browsers that allows interaction with the browser window, frames, and other browser-specific features. The BOM provides access to various object types and methods that can be used to manipulate and control the browser itself.
The BOM includes owner objects such as:
Window Object |
The |
It provides methods and properties for controlling the browser window, navigating to URLs, opening and closing windows, and handling events related to the window. |
|
Location Object |
The |
It provides properties and methods to manipulate the URL, such as redirecting to a new page, accessing query parameters, or reloading the current page. |
|
History Object |
The |
It provides methods for navigating through the user's history, such as going back or forward to previous pages. |
|
Navigator Object |
The |
It includes properties that reveal details about the browser name, version, platform, and user agent. |
|
Screen Object |
The |
It includes properties for screen dimensions, color depth, and other display-related information. |
The BOM allows JavaScript to interact with the browser, control the window behavior, navigate through history, detect user settings, and perform various browser-specific tasks. However, it's important to note that the BOM is not standardized, and different browsers may have variations in their implementation and available features. Therefore, it's recommended to use BOM-related features judiciously and be aware of cross-browser compatibility issues.
Q23. What is DOM?
DOM stands for Document Object Model. It is a programming interface for web documents, which represents the structure and content of an HTML or XML document as a tree-like model. The DOM provides a way to interact with and manipulate the elements, attributes, and text within a document.
In simple terms, the DOM can be visualized as a representation of the HTML document in memory, organized in a hierarchical structure. Each element, attribute, and text node in the document is represented as a node in the DOM tree.
Key features of the DOM include:
Tree-like Structure |
The DOM represents an HTML document as a hierarchical tree structure, where each element, attribute, and text node is a node in the tree. |
Nodes are connected to each other based on their parent-child relationships, allowing traversal and manipulation of the document structure. |
|
Document Access and Manipulation |
The DOM provides methods and properties to access, create, modify, and delete elements, attributes, and text within the document. |
Developers can use these APIs to dynamically update the content and structure of a web page based on user interactions or other events. |
|
Cross-Language Compatibility |
The DOM is language-neutral, meaning it can be accessed and manipulated using programming languages like JavaScript, Python, Java, etc. |
Different programming languages provide their own DOM APIs to interact with the document structure. |
By using the DOM, web developers can dynamically update the content of web pages, change styles, add or remove elements, handle events, and perform other operations to create interactive and dynamic web applications.
Q24. How to create an array in JavaScript?
There are 3 ways to create an array in JavaScript.
By array literal
By using an Array keyword
By Using Array Constructor
Q25. Explain hoisting in JS.
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that regardless of where variables and functions are declared in the code, they are conceptually moved to the top of their scope and can be used before they are actually declared.
Hoisting applies to both variable declarations and function declarations, but there are some differences in how they are hoisted:
Variable Hoisting |
Variable declarations using the |
Only the declaration is hoisted, not the initialization. The value of the variable is |
|
Function Hoisting |
Function declarations are fully hoisted, meaning both the function declaration and its implementation are moved to the top of the scope. |
Function declarations can be called before they are declared in the code. |
It's important to note that hoisting only applies to declarations, not initializations or assignments. Variables declared with let
and const
are also hoisted, but they are not accessible until the line of code where they are declared.
In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
Q26. Explain "this" keyword.
In JavaScript, the this
keyword refers to the context in which a function is executed. It is a special variable that holds a reference to the object on which a method is being called or the object that is currently being constructed by a constructor function.
The value of this
is determined dynamically at runtime and depends on how a function is invoked. The this
keyword can have different values in different situations:
Global Context |
When |
Function Context |
When a function is called as a standalone function, |
Method Context |
When a function is called as a method of an object, |
Constructor Context |
When a function is used as a constructor function using the |
Event Handler Context: |
When a function is used as an event handler, |
Q27. Given a string, reverse each word in a sentence.
To reverse each word in a sentence, you can follow these steps:
- Split the sentence into an array of words using the
split()
method. - Iterate over each word in the array.
- Reverse each word using various string manipulation techniques such as converting the word into an array, reversing the array, and joining the reversed array back into a string.
- Store the reversed words in a new array.
- Join the reversed words array back into a sentence using the
join()
method. - Return the reversed sentence.
Here's an example JavaScript function that implements this logic:
Output:
olleH, dlrow! woH era ?uoy
Q28. How to empty an array in JS?
There are 4 ways in which the array can be emptied➖
Let us take an array for example a=[1,2,3]
The output for all the following techniques mentioned below is []
Assigning it to a new empty array➖
Assigning the length of the array➖
Using the splice() method➖
Using pop()➖
Q29. Write a function that performs a binary search on a sorted array.
Here's an example of a function that performs a binary search on a sorted array:
Q30. What are the types of Pop up boxes available in JavaScript?
JavaScript provides three types of pop-up boxes or dialog boxes:
-
Alert:
- The
alert()
method displays a simple dialog box with a message and an OK button. - It is commonly used to show informational messages or to alert users of certain conditions.
- The dialog box blocks further execution until the user clicks the OK button.
- Example:
- The
-
Confirm:
- The
confirm()
method displays a dialog box with a message, along with OK and Cancel buttons. - It is used to ask the user for confirmation or to get a yes/no response.
- The function returns a Boolean value (
true
if the user clicks OK andfalse
if the user clicks Cancel). - Example:
- The
-
Prompt:
- The
prompt()
method displays a dialog box with a message, an input field for the user to enter data, and OK/Cancel buttons. - It is used to get user input or to prompt the user for information.
- The method takes an optional default value as a parameter and returns the value entered by the user as a string, or
null
if the user clicks Cancel. - Example:
- The
Q31. Guess the output of the following code.
Explanation:
- The
func1()
function is defined and invoked. - Inside
func1()
, asetTimeout()
function is called with a callback arrow function. The callback function is scheduled to execute after a delay of 3000 milliseconds (3 seconds). - The variable
x
is declared using thevar
keyword and assigned a value of2
.var
declarations are hoisted, so the declaration is moved to the top of the function scope. However, the assignment of2
tox
happens at the line where it is written. - The variable
y
is declared using thelet
keyword and assigned a value of12
.let
declarations are block-scoped and not hoisted, so the declaration and assignment ofy
happen at the same line. - When the callback arrow function inside
setTimeout()
is executed after the delay, it tries to log the values ofx
andy
. - The value of
x
is2
because it was declared usingvar
and is accessible within the function scope. - However, a
Reference Error
occurs when trying to log the value ofy
. This is becausey
is declared usinglet
and is block-scoped to thefunc1()
function block. It is not accessible inside the callback function since it has its own block scope.
Therefore, the code logs the value of x
as 2
, but an error occurs when trying to log the value of y
.
Q32. Guess the output of the following code.
3
3
3
Explanation:
- The
func2()
function is defined and invoked. - Inside
func2()
, afor
loop is used to iterate from0
to2
(3 iterations). - For each iteration of the loop, a
setTimeout()
function is called with a callback arrow function. The callback function is scheduled to execute after a delay of 2000 milliseconds (2 seconds). - The callback function logs the value of
i
. - Since the
setTimeout()
function is asynchronous, the loop continues executing without waiting for the callback functions to execute. - After the loop finishes, the value of
i
is3
because the loop condition (i < 3
) becomes false, and the loop terminates. - As a result, when the callback functions execute after the delay, they access and log the final value of
i
, which is3
. - Therefore, the code logs
3
three times, indicating the value ofi
at the time the callback functions execute.
Q33. Guess the output of the following code.
2
4
3
1
Explanation:
- The code defines an immediately invoked function expression (IIFE) using
(function(){ ... })();
. This allows the code inside the function to be executed immediately. - Inside the IIFE, the following actions occur:
- The first
setTimeout()
function is called with a callback arrow function, which logs1
, and a delay of 2000 milliseconds (2 seconds). This means it will execute after a 2-second delay. - The value
2
is logged to the console immediately. - The second
setTimeout()
function is called with a callback arrow function, which logs3
, and a delay of 0 milliseconds. Despite the delay being set to 0, it is effectively a minimum delay, allowing other tasks in the event loop to be processed before the callback is executed. - The value
4
is logged to the console immediately.
- The first
- Since the second
setTimeout()
function has a delay of 0, it is placed in the event queue and waits for the call stack to clear before executing its callback. - After the IIFE finishes executing, the event loop processes the callback functions waiting in the event queue.
- The callback function from the second
setTimeout()
(with a delay of 0) is processed first and logs3
. - Lastly, after a 2-second delay, the callback function from the first
setTimeout()
executes and logs1
.
Q34. Guess the output of the following code.
11
NaN
2-22
NaN78
Hello78
Explanation:
- The
runFunc()
function is defined and invoked. - Inside
runFunc()
, severalconsole.log()
statements are used to print different expressions. - Let's break down the output line by line:
-
"1" + 1
- The+
operator performs concatenation when one or both operands are strings. In this case,"1"
is a string, and1
is a number. The number1
is coerced into a string and concatenated with"1"
, resulting in the string"11"
. -
"A" - 1
- The-
operator is not defined for string subtraction. JavaScript tries to perform arithmetic operations on the operands. Since"A"
cannot be converted into a number, the operation results inNaN
(Not-a-Number). -
2 + "-2" + "2"
- The+
operator, when used with strings, performs concatenation. The first operation is2 + "-2"
, which concatenates the number2
with the string"-2"
, resulting in"2-2"
. The subsequent concatenation with the string"2"
results in"2-22"
. -
"Hello" - "World" + 78
- The-
operator is not defined for string subtraction. Both"Hello"
and"World"
cannot be converted into numbers, resulting inNaN
. WhenNaN
is involved in any arithmetic operation, the result is alwaysNaN
. The subsequent addition of78
withNaN
still results inNaN
. -
"Hello" + "78"
- Both operands are strings, so the+
operator performs concatenation. It concatenates the string"Hello"
with the string"78"
, resulting in the string"Hello78"
.
Q35. In which location are cookies stored on the hard disk?
Cookies are not stored directly on the hard disk of a user's device. Instead, they are stored by web browsers in a designated storage location specific to each browser. The actual storage location may vary depending on the operating system and browser being used. Here are some common storage locations for cookies:
-
Windows:
- Google Chrome:
C:\Users\{username}\AppData\Local\Google\Chrome\User Data\Default\Cookies
- Mozilla Firefox:
C:\Users\{username}\AppData\Roaming\Mozilla\Firefox\Profiles\{profile_folder}\cookies.sqlite
- Microsoft Edge:
C:\Users\{username}\AppData\Local\Microsoft\Edge\User Data\Default\Cookies
- Google Chrome:
-
macOS:
- Google Chrome:
~/Library/Application Support/Google/Chrome/Default/Cookies
- Mozilla Firefox:
~/Library/Application Support/Firefox/Profiles/{profile_folder}/cookies.sqlite
- Safari:
~/Library/Cookies/Cookies.binarycookies
- Google Chrome:
-
Linux:
- Google Chrome:
~/.config/google-chrome/Default/Cookies
- Mozilla Firefox:
~/.mozilla/firefox/{profile_folder}/cookies.sqlite
- Google Chrome:
Please note that the actual paths may differ based on the version of the browser, user profile, and browser settings. The paths provided here are general examples, and it's always recommended to consult the browser's documentation or settings for the precise location of cookie storage.
Q36. What is a prompt box?
Prompt Box is a popup box available in JavaScript.
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax➖ windows.prompt(”sometxt”,”defaulttxt”);
Example:
Q38. Which symbol is used for comments in JavaScript?
In JavaScript, there are two symbols commonly used for comments:
-
Double Slash (//):
- The double slash
//
is used for single-line comments. - Anything after
//
on the same line is considered a comment and is ignored by the JavaScript interpreter.
- The double slash
-
Slash Asterisk (/* */):
- The slash asterisk
/* */
is used for multi-line comments or block comments. - Anything between
/*
and*/
is considered a comment and is ignored by the JavaScript interpreter, even if it spans multiple lines.
- The slash asterisk
Q39. What is the difference between view state and session state?
View state and session state are both concepts related to managing state in web applications, but they serve different purposes and are used in different contexts:
View State | Session State |
View state is specific to ASP.NET web forms and is used to maintain the state of a web form across postbacks. |
Session state is a server-side mechanism in web development that allows storing and retrieving user-specific data across multiple requests and sessions. |
It is an encoded representation of the state of the controls on a web form, including their values and properties. |
It is used to store data that needs to be persisted and accessed across different pages or interactions during a user session. |
View state is stored as a hidden field in the HTML form and is sent back and forth between the server and the client with each request and response. |
Session state data is stored on the server, usually in memory or a database, and is associated with a unique session identifier (usually stored in a cookie or URL parameter). |
It allows the web form to remember user input and maintain its state during postbacks, enabling the form to restore its data and appearance. |
Session state can store any serializable object or data, such as user preferences, shopping cart contents, or user authentication information. |
View state is primarily used for maintaining state within a single user session and is tied to the individual web form. |
The session state is independent of a specific web form and can be accessed and modified from multiple pages within the same session. |
In summary, view state is specific to ASP.NET web forms and is used to maintain the state of a single web form across postbacks, while session state is a more general mechanism for storing and accessing user-specific data across multiple requests and sessions.
Q40. How can you submit a form using JavaScript?
To submit a form using JavaScript, you can use the submit()
method, which is available on the form element. This method allows you to programmatically trigger the submission of a form.
Here's an example of how you can submit a form using JavaScript:
In this example, we have an HTML form with the id
attribute set to "myForm"
. We then use JavaScript to get a reference to the form element using document.getElementById('myForm')
. Once we have the reference, we can call the submit()
method on the form element to trigger the submission.
By calling form.submit()
, the browser will initiate the form submission process, sending the form data to the specified action
URL using the specified HTTP method (method
attribute). The behavior after form submission will depend on the server-side implementation and the content of the action
URL.
You can trigger the form submission using various events or conditions in your JavaScript code, such as clicking a button, validating form data, or programmatically based on certain conditions.
Q41. What do you mean by NULL in JavaScript?
In JavaScript, null
is a special value that represents the intentional absence of any object value. It is a primitive value that indicates the absence of a value or the absence of an object reference.
Here are some key points about null
in JavaScript:
-
null
is a data type:null
is a primitive data type in JavaScript, specifically representing the absence of an object value. -
It is falsy:
null
is considered a falsy value in JavaScript. When evaluated in a Boolean context (e.g., in anif
statement or as a condition), it is treated asfalse
. -
It is not an object: Despite being a falsy value,
null
is not an object. It is a primitive value. It is distinct from theundefined
value, which represents an uninitialized or missing value. -
Type of
null
is "object": Interestingly, the type of operator in JavaScript returns "object" when applied tonull
. This is a historical quirk in JavaScript and not a true reflection ofnull
being an object. It is considered a mistake in the language's design.
Here's an example illustrating the use of null
:
Q42. What is the strict mode in JavaScript and how can it be enabled?
Strict mode is a feature introduced in ECMAScript 5 (ES5) that enables a stricter set of rules for JavaScript code. It helps in avoiding common mistakes, promotes good coding practices, and makes JavaScript code more robust.
To enable strict mode in JavaScript, you need to add the "use strict";
directive at the beginning of a script or a function. There are two ways to enable strict mode:
- Script-wide strict mode: Add the
"use strict";
directive at the beginning of a script file. When added at the top of a JavaScript file, strict mode applies to the entire file.
"use strict";
// Rest of your JavaScript code
- Function-level strict mode: Add the
"use strict";
directive at the beginning of a function. When added inside a function, strict mode applies only to that specific function.
function myFunction() {
"use strict";// Function-level strict mode applies only to this function
// Rest of your JavaScript code
}
Enabling strict mode introduces the following changes and restrictions to the JavaScript code:
- Variables must be declared before use. Assigning a value to an undeclared variable will throw an error.
- Assigning a value to a read-only global variable or a non-writable property throws an error.
- Deleting variables, functions, or function arguments is not allowed.
- The
this
value in functions is undefined in strict mode when the function is called without an explicitthis
value. - Octal literals (e.g.,
0123
) are not allowed. - Duplicate parameter names in function declarations throw an error.
- The
eval()
function creates a new outer scope and does not have access to the containing scope's variables. - Several potential sources of errors, like using reserved keywords as variable names, are restricted.
By enabling strict mode, you can catch and prevent certain types of errors( type correction) and enforce better coding practices. It is recommended to use strict mode in all JavaScript code to improve code quality and maintainability.
Q43. What is the difference between .call() and .apply()?
Both the .call()
and .apply()
methods in JavaScript are used to invoke a function with a specified this
value and arguments. They allow you to execute a function in the context of a particular object and pass arguments to the function. The main difference between .call()
and .apply()
lies in how the arguments are passed to the function.
The .call()
method:
- Accepts the
this
value as the first argument, followed by the function arguments as individual arguments. - The arguments are passed explicitly and separated by commas.
Example using .call()
:
The .apply()
method:
- Accepts the
this
value as the first argument, followed by an array-like or iterable object containing the function arguments. - The arguments are passed as an array or an array-like object.
Example using .apply()
:
Essentially, the key difference between .call() and .apply() is the way in which the arguments are passed. If you have the function arguments as individual values, you can use .call() and pass them explicitly. If you have the function arguments in an array or array-like object, you can use .apply() and pass the array-like object as a single argument. Both methods allow you to control this value within the function execution context, which can be helpful when working with object-oriented programming or borrowing methods from one object to use with another.
Q44. What is the method of reading and writing in JavaScript
Files can be read and written by using java script functions – fopen(),fread() and fwrite(). The function fopen() takes two parameters – 1. Path and 2. Mode (0 for reading and 3 for writing). The fopen() function returns -1, if the file is successfully opened.
Example:
file=fopen(getScriptPath(),0);
The function fread() is used for reading the source file content.
Example:
str = fread(file,flength(file);
The function fwrite() is used to write the contents to the source file.
Example:
file = fopen("c:\\MyFile.txt", 3);
// opens the source file for writing
fwrite(file, str);
// str is the content that is to be written into a separate file.
Q45. How to print a webpage using javascript?
To print a webpage, we use the print() method. The print method opens a dialog box that you can click and print the page.
The following code can be used➖
Q46. What is the date object in JavaScript?
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
There are four different ways to declare a date, the basic thing is that the date-objects are created by the new Date() operator
new Date() ➖The date constructor creates a Date object which sets the current date and time depending on the browser’s time zone. It does not accept any value.
new Date(milliseconds)➖ This method accepts single parameter milliseconds which indicates any numeric value. This argument is taken as the internal numeric representation of the date in milliseconds.
new Date(dataString) ➖This method accepts a single parameter dataString which indicates any string value. It is a string representation of a date and the return statement returns the data string with the day.
new Date(year, month, date, hour, minute, second, millisecond)➖
Parameters:
This method accepts seven parameters as mentioned above and described below:
year: Integer value which represents the year. This should always specify the year in full, i.e. use 2018, instead of use 18.
month: Integer value which represents the month. The integer values starting from 0 for January to 11 for December.
date: Integer value which represents the date.
hour: Integer value which represents the hour on the 24-hours scale.
minute: Integer value which represents the minute.
second: Integer value which represents the second.
millisecond: Integer value which represents the millisecond.
Q47. How to handle Exception in Java Script?
In JavaScript, you can handle exceptions, also known as errors, using try-catch blocks. The try-catch block allows you to enclose a section of code that may throw an exception and specify how to handle that exception if it occurs.
Here's the basic syntax of a try-catch block:
try {
// Code that may throw an exception
} catch (error) {
// Code to handle the exception
}
Within the try block, you place the code that you want to monitor for exceptions. If an exception occurs within the try block, the catch block is executed. The catch block receives the thrown exception as an argument, which you can then use to handle the exception appropriately.
Here's an example that demonstrates the usage of try-catch block:
In this example, the code within the try block attempts to perform a division by zero, which will throw an exception. Since dividing by zero is an invalid operation, the catch block is executed. The catch block receives the thrown exception as the error
parameter, and the error message along with the exception is logged to the console.
By using try-catch blocks, you can gracefully handle exceptions, prevent them from crashing your program, and provide meaningful error messages or alternative paths of execution. Additionally, you can nest multiple try-catch blocks to handle different types of exceptions or perform more granular error handling.
Q48. What is the purpose of the onError event handler in JavaScript?
The onError
event handler in JavaScript is used to handle errors that occur during the execution of a script or the loading of external resources, such as images, scripts, or stylesheets. It allows you to define a function that will be executed when an error occurs.
The onError
event handler is commonly used in scenarios like:
1. Error handling for scripts:
<script>
function handleScriptError() {
console.log("An error occurred while loading the script.");
}
</script>
<script src="script.js" onError="handleScriptError()"></script>
2. Error handling for images:
<img src="image.png" onError="handleImageError()">
The onError
event handler provides a way to catch and handle errors in a controlled manner. By defining an error handling function and assigning it to the onError
event, you can perform actions such as logging the error, displaying a user-friendly message, or taking corrective measures.
It's important to note that the onError
event handler is not limited to script and image elements. It can also be used with other HTML elements like <audio>
, <video>
, <link>
, and <style>
, as well as various JavaScript APIs that support error events, such as XMLHttpRequest or WebSocket.
Additionally, modern JavaScript provides more robust error-handling mechanisms, such as try-catch blocks and the window.onerror
event handler, which offer greater control and flexibility in handling errors within JavaScript code.
Q49. What would be the result of 3+2+”7″?
In JavaScript, the +
operator is used for both addition and string concatenation. When the +
operator is used with numbers, it performs addition. However, when one or both of the operands are strings, the +
operator concatenates the strings together.
In the expression 3 + 2 + "7"
, the first two operands are numbers (3
and 2
), and the last operand is a string ("7"
).
Here's the step-by-step evaluation of the expression:
3 + 2
evaluates to5
(addition of numbers).5 + "7"
evaluates to"57"
(concatenation of the number5
with the string"7"
).
Therefore, the result of 3 + 2 + "7"
is "57"
. The numeric addition of 3 + 2
results in 5
, and then that result is concatenated with the string "7"
, producing the string "57"
.
Q50. Is JavaScript case-sensitive?
Yes, JavaScript is case-sensitive. This means that JavaScript treats uppercase and lowercase letters as distinct and separate entities. The case of letters in variable names, function names, object properties, and keywords matters and must be used consistently.
For example, in JavaScript, the variables myVariable
, myvariable
, and MYVARIABLE
are considered to be three different variables. Similarly, function names, such as myFunction
and myfunction
, are treated as separate functions.
Q51. What is an anonymous function?
An anonymous function, also known as a function expression, is a function in JavaScript that is defined without a name. Unlike a named function, which is declared with a specific identifier, an anonymous function does not have an explicit name associated with it.
Anonymous functions are typically used when you need a function for a specific task and do not require it to be referenced or called elsewhere in your code. They are commonly used as callback functions, function arguments, or immediately invoked function expressions (IIFE).
Anonymous functions are useful in scenarios where you need a short-lived or one-time function without the need for a specific name. They help in writing more concise code and can be used inline without cluttering the global namespace with unnecessary function names.
It's important to note that anonymous functions can also be assigned to variables or used as arrow functions, providing flexibility in various coding scenarios.
Q52. What is runtime error?
A runtime error, also known as an exception, is an error that occurs during the execution of a program or script. It happens when the program encounters an unexpected condition or behavior that prevents it from continuing its normal execution.
Runtime errors are distinct from compile-time errors, which are detected by the compiler before the program is executed. Runtime errors occur while the program is running and often result from logical errors, invalid data, or unforeseen circumstances.
Here are a few common examples of runtime errors:
-
Division by zero: const result = 10 / 0; // Throws a runtime error (division by zero)
-
Undefined variable: console.log(x); // Throws a runtime error (variable x is not defined)
- Null reference: const obj = null;
console.log(obj.property); // Throws a runtime error (accessing property of null) - Type mismatch: const result = "5" + 2; // Throws a runtime error (concatenating string with a number)
When a runtime error occurs, it interrupts the normal flow of the program and may cause it to terminate prematurely. In many programming languages, including JavaScript, runtime errors can be handled and controlled through the use of exception handling mechanisms, such as try-catch
blocks.
By using try-catch
blocks, you can catch and handle runtime errors gracefully, preventing them from causing the program to crash. This allows you to provide alternative paths of execution or display error messages to the user.
Q53. What is arrow function?
An arrow function, also known as a fat arrow function, is a concise syntax introduced in ECMAScript 2015 (ES6) for creating functions in JavaScript. Arrow functions provide a more compact and streamlined way to write function expressions.
The syntax for an arrow function includes a parameter list (if any), followed by the arrow (=>
) and then the function body. The function body can be either an expression that is implicitly returned or a block of statements enclosed in curly braces ({}
). The arrow functions have a lexical this
binding, meaning that they capture the value of this
from the surrounding context at the time of their creation.
Arrow functions are especially useful when you want to write concise and inline functions or when you need to preserve the lexical this
context. However, it's important to note that arrow functions have some differences compared to traditional function expressions. For example, arrow functions do not have their own this
, arguments
, or super
bindings, and they cannot be used as constructors with the new
keyword. These factors should be considered when deciding whether to use arrow functions in specific scenarios.
Q54. What is a callback function in JavaScript?
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed at a later point in time. The purpose of a callback function is to provide a way to handle asynchronous or event-driven operations, allowing code to be executed when a particular task or event has completed.
Callbacks are commonly used in scenarios such as making asynchronous requests, handling user interactions, and implementing event-driven programming. They allow you to specify what should happen after a particular task or event finishes executing.
Here's an example of a callback function used with setTimeout()
:
In this example, the greet()
function takes two arguments: name
and callback
. It logs a greeting message to the console and then executes the callback
function. The sayGoodbye()
function is defined separately and passed as a callback to greet()
. When greet("Alice", sayGoodbye)
is called, it first prints "Hello, Alice!" and then executes the sayGoodbye()
function, which prints "Goodbye!".
Callbacks provide a way to control the flow of execution in asynchronous or event-driven environments, as they allow you to specify the code to be executed once a certain task or event is completed. This enables handling of results, error handling, and continuation of execution after the asynchronous operation finishes.
Q55. What is a blur function?
In JavaScript, the blur
function is an event handler that is triggered when an element loses focus. When an element, such as an input field or a button, is in focus and the user interacts with another element, such as clicking outside the current element, the blur
event is fired.
The blur
event is commonly used to perform actions or validation when an element loses focus. For example, you might want to validate the input in a form field when the user moves to the next field or clicks outside the field.
The blur
event can be useful for enhancing user experience and providing feedback or performing specific actions when elements lose focus. It is commonly used in form validation scenarios, where you want to validate user input as they move away from an input field.
Q56. What do you understand by cookies in JavaScript?
In JavaScript, cookies are small pieces of data that can be stored on a user's computer by a website. They are used to store information about the user or their interactions with the website. Cookies are primarily used to maintain stateful information across multiple requests or sessions.
When a website sends a response to the user's browser, it can include a "Set-Cookie" header, which contains the data to be stored in a cookie. The browser then stores this data locally. On subsequent requests to the same website, the browser automatically includes the stored cookie data in the "Cookie" header of the request, allowing the website to access and use that information.
Cookies have various properties that can be set, such as the expiration date, path, and domain. These properties determine when and where the cookie is sent back to the server. For example, a cookie can be set to expire after a certain period of time or be restricted to a specific subdomain.
In JavaScript, you can interact with cookies using the document.cookie
property. It provides access to the cookies associated with the current document. The document.cookie
property allows you to read, write, and delete cookies.
Here's an example of how to set a cookie using JavaScript:
It's important to note that cookies have certain limitations, such as their limited storage size and potential security risks (e.g., cross-site scripting vulnerabilities). As a result, alternative methods like browser storage APIs (localStorage, sessionStorage) and server-side session management are often used in modern web development.
Q57. What is Asynchronous testing in JavaScript?
It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously:
So, what the code does is first it logs in Hi
then rather than executing the setTimeout
function it logs in End
and then it runs the setTimeout
function.
At first, as usual, the Hi
the statement got logged in. As we use browsers to run JavaScript, there are web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout
function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code is executed, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript
Q58. What is an Async Function?
An async function is a type of function in JavaScript that enables asynchronous behavior and allows you to write asynchronous code in a more synchronous-like manner. It was introduced in ECMAScript 2017 (ES8) and built upon Promises, providing a simpler and cleaner syntax for handling asynchronous operations.
To define an async function, you use the async
keyword before the function declaration. An async function always returns a Promise, which represents the eventual completion or failure of an asynchronous operation. Within an async function, you can use the await
keyword to pause the execution of the function until a Promise is resolved or rejected.
Using async/await simplifies the handling of asynchronous operations by eliminating the need for nested callbacks or chaining multiple then()
methods. It allows you to write asynchronous code in a more linear and readable way, resembling synchronous code flow. Additionally, async functions provide a convenient way to handle errors by utilizing the try/catch
block.
It's important to note that async functions are non-blocking, meaning that while awaiting a Promise, the execution of the function is paused, allowing other code to run in the meantime. This makes them particularly useful when dealing with time-consuming tasks, such as network requests or source file operations, without blocking the execution of other parts of your code.
Q59. What is event bubbling in JavaScript?
Event bubbling, also known as event propagation, is a mechanism in JavaScript where an event triggered on a nested element is propagated or "bubbled up" through its parent elements in the DOM hierarchy. This means that when an event occurs on an element, such as a click event, the event is first handled by the innermost element and then sequentially propagated to its parent elements, all the way up to the root of the document.
Here's an example to illustrate event bubbling:
In this example, when the button is clicked, the event first triggers the event handler attached to the button. However, after the button's event handler finishes execution, the event continues to propagate up the DOM tree. In this case, the event handler is not defined for the parent elements explicitly. But if there were event handlers defined for the parent elements (such as the divs with IDs "inner" and "outer"), the event would continue to propagate and trigger those event handlers as well.
Event bubbling allows you to handle events at different levels of the DOM hierarchy. It simplifies event handling by allowing you to attach a single event listener to a parent element/ parent object and handle events for its child elements as well. This can be beneficial for managing event delegation and reducing the number of event listeners attached to individual elements. However, it's important to be aware of event bubbling and properly handle event propagation if necessary to prevent unintended behavior or conflicts.
Q60. What is Asynchronous code in JavaScript?
Asynchronous JavaScript: Asynchronous code allows the program to be executed immediately whereas the synchronous code will block further execution of the remaining code until it finishes the current one. This may not look like a big problem but when you see it in a bigger picture you realize that it may lead to delaying the User Interface.
Let us see the example of how Asynchronous JavaScript runs:
Output:
So, what the code does is first it logs in Hi then rather than executing the setTimeout function it logs in End, and then it runs the setTimeout function.
At first, as usual, the Hi statement got logged in. As we use browsers to run JavaScript, there are web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code is executed, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.
Q61. What is rest Syntax or Rest Operator, and how is it opposite to spread operator or spread syntax?
Rest syntax or rest parameter is a feature introduced in ECMAScript 2015 (ES6) that allows you to represent an indefinite number of arguments as an array within a function declaration. It is denoted by using three dots (...
) followed by a parameter name in the function declaration. The rest parameter gathers all the remaining arguments into an array.
Here's an example that demonstrates the use of rest syntax:
In this example, the sum
function uses the rest syntax with the parameter numbers
. It allows you to pass any number of arguments, and they are automatically collected into an array called numbers
. Within the function body, you can then work with this array as needed.
On the other hand, spread syntax or spread operator (also denoted by three dots ...
) is used to expand an array or iterable object into individual elements. It can be used in function calls, array literals, or object literals to spread the elements or properties.
Here's an example of the spread syntax:
const numbers = [1, 2, 3, 4, 5];
console.log(...numbers); // Output: 1 2 3 4 5const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
In the first example, the spread syntax is used within the console.log()
statement to expand the numbers
array into individual elements. This results in each element being printed separately.
In the second example, the spread syntax is used to combine the elements of array1
and array2
into a new array called combinedArray
. The resulting array contains all the elements from array1
followed by all the elements from array2
.
To summarize, the rest syntax is used within a function declaration to collect multiple arguments into an array, while the spread syntax is used to spread an array or iterable object into individual pivot elements or combine multiple forms of arrays/objects into a new array/object.
62. What is a nested function?
A nested function, also known as an inner function, is a function defined within another function. In programming languages that support nested functions, the inner function is enclosed within the body of the outer function. This means that the inner function can only be accessed and called from within the scope of the outer function.
Here's an example in JavaScript to illustrate the concept:
In this JavaScript example, innerFunction()
is defined within outerFunction()
. The inner function can access variables and parameters of the outer function, and it can also have its own local variables. However, it cannot be directly called from outside the scope of the outer function.
Nested functions in JavaScript offer similar benefits as in other programming languages, allowing for code organization, improved readability, and controlled access to functions.
63. What are escape characters in JavaScript?
Escape characters in JavaScript are special characters that are used to represent certain non-printable or reserved characters within a string. They are denoted by a backslash (\
) followed by a specific character or sequence of characters. When encountered in a string, escape characters modify the interpretation or behavior of the following character.
Here are some commonly used escape characters in JavaScript:
- \n: Newline character. Inserts a line break.
- \t: Tab character. Inserts a horizontal tab.
- \r: Carriage return character. Moves the cursor to the beginning of the line.
- **': Single quote character. Used to escape single quotes within a string.
- **": Double quote character. Used to escape double quotes within a string.
- \: Backslash character. Used to escape a literal backslash.
- \uXXXX: Unicode escape sequence. Represents a Unicode character based on its hexadecimal code (XXXX).
64. Explain higher-order functions.
In JavaScript, higher-order functions are functions that can accept other functions as arguments and/or return functions as their results. Essentially, a higher-order function treats functions as first-class citizens, allowing them to be manipulated and operated upon just like any other value.
There are two main ways in which higher-order functions are used:
- Accepting Functions as Arguments: A higher-order function can take one or more functions as arguments. This allows for flexibility and enables the higher-order function to perform operations based on the provided functions. The function definition arguments can be invoked within the higher-order function or used to modify its behavior.
- Returning Functions: A higher-order function can also generate and return a new function. This enables the creation of specialized or partially applied functions based on the provided arguments or conditions.
65. What is a prototype property?
In JavaScript, the prototype property is a property of constructor functions that allows predefined objects created from those constructors to inherit properties and methods. Every JavaScript object has a prototype property, which references the prototype object associated with its constructor function.
The prototype object is essentially a blueprint or template for creating other predefined objects. It contains properties and methods that are shared among all instances created from the constructor function. When a property or method is accessed on an object, JavaScript first checks if the object itself has that property or method. If not found, it looks for it in the prototype object.
66. What does syntax error mean in JavaScript?
In JavaScript, a syntax error occurs when the JavaScript engine encounters code that does not conform to the syntax rules of the language. It means that the code is not written correctly according to the grammar and structure defined by JavaScript.
When a syntax error condition is encountered, the JavaScript engine is unable to interpret and execute the code because it cannot understand the intended meaning due to the violation of syntax rules. As a result, the JavaScript engine throws a syntax error and typically provides an error message that indicates the specific issue it encountered.
67. Explain generator functions.
Generator functions are a special type of function in JavaScript that can be paused and resumed during execution. They allow for the generation of a sequence of values over expiration time, providing a more flexible and efficient way to iterate through data compared to traditional functions.
To define a generator function, you use the function*
syntax:
function* myGenerator() {
// Generator function body
yield value1;
yield value2;
// ...
}
The function*
keyword denotes that the function is a generator function. Inside the generator function, the yield
keyword is used to pause the execution and produce a value. The generator function can then be iterated over using a for...of
loop or by manually calling the next()
method on the generator object.
When a generator function is invoked, it returns a generator object, which serves as an iterator. The generator object has a next()
method that, when called, resumes the execution of the simple function until the next yield
statement is encountered. The next()
method returns an object with two properties: value
(the yielded value) and done
(a boolean indicating whether the generator function has finished).
68. What is a self-invoking function?
A self-invoking function, also known as an Immediately Invoked Function Expression (IIFE), is a JavaScript function that is executed immediately after it is defined. It is a way to encapsulate statement code and create a new scope without polluting the global scope.
The syntax( code snippet) for a self-invoking function is as follows:
(function() {
// Normal Function body or body element
})();
69. What are the types of operators in JavaScript?
In JavaScript, operators are symbols or keywords that perform operations on operands (values or variables). They allow you to perform mathematical calculations, compare values, assign values, and more. JavaScript has several types of operators, including:
-
Arithmetic Operators: These operators perform mathematical calculations on numeric operands.
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Modulus (
%
) - Exponentiation (
**
) - Increment (
++
) - Decrement (
--
) - Comma operator
- Addition (
-
Assignment Operators: These operators assign values to variables.
- Assignment (
=
) - Addition assignment (
+=
) - Subtraction assignment (
-=
) - Multiplication assignment (
*=
) - Division assignment (
/=
) - Modulus assignment (
%=
)
- Assignment (
-
Comparison Operators: These operators compare values and return a Boolean result (
true
orfalse
).- Equal to (
==
) - Not equal to (
!=
) - Strict equal to (
===
) - Strict not equal to (
!==
) - Greater than (
>
) - Less than (
<
) - Greater than or equal to (
>=
) - Less than or equal to (
<=
)
- Equal to (
-
Logical Operators: These operators perform logical operations on Boolean operands.
- Logical AND (
&&
) - Logical OR (
||
) - Logical NOT (
!
)
- Logical AND (
-
Conditional (Ternary) Operator: It is a shorthand way to write conditional statements.
- Conditional (
condition ? value1 : value2
)
- Conditional (
-
Unary Operators: These operators operate on a single operand.
- Unary plus (
+
) - Unary minus (
-
) - Logical NOT (
!
) - Increment (
++
) - Decrement (
--
) - Typeof (
typeof
) - Delete operator (
delete
) - Void (
void
)
- Unary plus (
-
Bitwise Operators: These operators perform bitwise operations on integer operands.
- Bitwise AND (
&
) - Bitwise OR (
|
) - Bitwise XOR (
^
) - Bitwise NOT (
~
) - Left shift (
<<
) - Right shift (
>>
) - Unsigned right shift (
>>>
)
- Bitwise AND (
-
String Operators: These operators are used to concatenate strings.
- String concatenation (
+
)
- String concatenation (
These are the main types of operators in JavaScript. Understanding and utilizing these operators is essential for performing various operations in JavaScript, such as mathematical calculations, logical evaluations, variable assignments, and more.
Summing up...
JavaScript is one of the most versatile languages. One can ace the interview with determination and hard work. JavaScript is one of the highest-paying jobs in the industry.
You need to brush up on your basics and advanced knowledge of javascript, using these interview questions is a great way to land your dream job, in any top technical firm.
All the best!
You might also be interested in reading:
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
Comments
Add comment