Basic JavaScript
Basic JavaScript
JavaScript is a high-level, interpreted scripting language used for adding interactive behavior
to web pages. Java is an object-oriented, compiled language used for building standalone
applications.
let: Block-scoped, can be updated but not re-declared in the same scope.
5. == vs ===?
==: Compares values after type coercion.
5 == "5" // true
🟩 ES6+ Features
console.log(`Hello, ${name}!`);
8. Default Parameters
9. Destructuring
const person = { name: 'Priya', age: 22 };
function sum(...nums) {
🟩 Array Methods
callback();
let count = 0;
return ++count;
19. Hoisting
Variables (var) and functions are hoisted.
console.log(a); // undefined
var a = 10;
function greet() {}
🟩 Asynchronous JavaScript
22. Promise
An object representing future completion or failure.
resolve("Success");
});
23. async/await
Microtask: Promise.then
Macrotask: setTimeout
26. Output:
console.log("A");
console.log("C");
// Output: A C B
🟩 this Keyword
console.log(this); // window
document.querySelector('.class')
Java JavaScript
JavaScript data types are categorized into two parts i.e. primitive and non-primitive types.
Primitive Data Type: The predefined data types provided by JavaScript language are
known as primitive data type. Primitive data types are also known as in-built data
types.
o Numbers
o Strings
o Boolean
o Symbol
o Undefined
o Null
o BigInt
Non-Premitive Data Type: The data types that are derived from primitive data types
are known as non-primitive data types. It is also known as derived data types or
reference data types.
o Objects
o Functions
o Arrays
The number isNan function determines whether the passed value is NaN (Not a number)
and is of the type "Number". In JavaScript, the value NaN is considered a type of number. It
returns true if the argument is not a number, else it returns false.
JavaScript is faster compared to ASP Script. JavaScript is a client-side scripting language and
does not depend on the server to execute. The ASP script is a server-side scripting language
always dependable on the server.
The negative infinity is a constant value represents the lowest available value. It means that
no other number is lesser than this value. It can be generate using a self-made function or by
an arithmetic operation. JavaScript shows the NEGATIVE_INFINITY value as -Infinity.
Yes, it is possible to break the JavaScript code into several lines in a string statement. It can
be broken by using the '\n' (backslash n).
Example:
Truthy: Everything else (e.g., any non-empty string, any non-zero number, objects,
arrays).
Undeclared: It occurs when we try to access any variable which is not initialize or
declare earlier using the var or const keyword. If we use 'typeof' operator to get the
value of an undeclare variable, we will face the runtime error with the return value
as "undefined". The scope of the undeclare variables is always global.
<html>
<head>
</head>
<body>
<button onclick="create()">
Click Here!
</button>
<script>
function create() {
geeks.textContent = "Geeksforgeeks";
geeks.setAttribute('class', 'note');
document.body.appendChild(geeks);
</script>
</body>
</html>
12. What are global variables? How are these variables declared, and what are the
problems associated with them?
In contrast, global variables are the variables that define outside of functions. These
variables have a global scope, so they can be used by any function without passing them to
the function as parameters.
Example:
myFunction();
function myFunction() {
Output
It is difficult to debug and test the code that relies on global variables.
The NULL value represents that no value or no object. It is known as empty value/object.
The delete keyword deletes the whole property and all the values at once like
A deeper comparison between the two special values, null (intentional absence of value)
and undefined (uninitialized variables).
Functions in JavaScript are essential objects. Like objects, it can be assign to variables, pass
to other functions, and return from functions. And much like objects, they have their own
properties. 'this' stores the current execution context of the JavaScript program. Thus, when
it use inside a function, the value of 'this' will change depending on how the function is
defined, how it is invoked, and the default execution context.
18. Explain the working of timers in JavaScript. Also explain the drawbacks of using the
timer, if any.
The timer executes some specific code at a specific time or any small amount of code in
repetition to do that you need to use the
functions setTimout, setInterval, and clearInterval. If the JavaScript code sets the timer to 2
minutes and when the times are up then the page displays an alert message "times up".
The setTimeout() method calls a function or evaluates an expression after a specified
number of milliseconds.
SessionState: It is user specific that can access all the data on the web pages.
A template literal in JavaScript is a way to define strings that allow embedded expressions
and multi-line formatting. It uses backticks (`) instead of quotes and supports ${} for
embedding variables or expressions inside the string.
A higher-order function in JavaScript is a function that either takes one or more functions as
arguments, or returns a function as its result. These functions allow for more abstract and
reusable code, enabling functional programming patterns
For example, map() and filter() are higher-order functions because they take callback
functions as arguments.
JavaScript Intermediate Interview Questions
while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as
a repeating if statement.
for loop: A for loop provides a concise way of writing the loop structure. Unlike a
while loop, for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
do while: A do-while loop is similar to while loop with the only difference that it
checks the condition after executing the statements, and therefore is an example of
Exit Control Loop.
Lexical scope in JavaScript refers to the way variables are resolved based on their location in
the source code. A variable's scope is determined by the position of the code where it is
defined, and it is accessible to any nested functions or blocks. This means that functions
have access to variables in their own scope and the outer (lexical) scopes, but not to
variables in inner scopes.
function inner() {
console.log(outer);
inner();
In this example, inner() can access the outer variable because of lexical scoping.
26. How does lexical scoping work with the this keyword in JavaScript?
In JavaScript, lexical scoping primarily applies to variable resolution, while the behavior of
the this keyword is determined by how a function is called, not by its position in the code.
The value of this is dynamically determined at runtime based on the function’s context (e.g.,
whether it’s called as a method, in a global context, or with call, apply, or bind).
const obj = {
name: "JavaScript",
greet: function () {
console.log(this.name);
}
};
obj.greet(); // "JavaScript"
Here, this refers to obj because the function is called as a method of the object. Lexical
scoping affects variable lookups but doesn’t alter how this behaves.
The variable typing is the type of variable used to store a number and using that same
variable to assign a “string”.
Geeks = 42;
Geeks = "GeeksforGeeks";
Hoisting in JavaScript is the behavior where variable and function declarations are moved to
the top of their containing scope during compilation, before the code is executed. This
means you can reference variables and functions before they are declared in the code.
However, only declarations are hoisted, not initializations.
console.log(a); // undefined
var a = 5;
In this case, the declaration of a is hoisted, but its value (5) is not assigned until the code
execution reaches that line. Hoisting applies differently for var, let, const, and function
declarations.
In JavaScript, parseInt() function is used to convert the string to an integer. This function
returns an integer of base which is specified in second argument of parseInt() function. The
parseInt() function returns Nan (not a number) when the string doesn’t contain number.
31. Explain how to detect the operating system on the client machine?
To detect the operating system on the client machine, one can simply use
navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is
a read-only property and it returns the string that represents the version information of the
browser.
Alert
Confirm
Prompt
The void(0) is used to call another method without refreshing the page during the calling
time parameter “zero” will be passed.
34. What are JavaScript modules, and how do you import/export them?
JavaScript modules allow you to split your code into smaller, reusable pieces. They enable
the export of variables, functions, or objects from one file and the import of them into
another. To export an element, you use export (either named or default). To import it, you
use import.
// In file1.js
// In file2.js
console.log(greet());
Modules help organize code and avoid global namespace pollution. They are natively
supported in modern JavaScript through import and export statements.
36. What is the role of the setImmediate function in Node.js, and how is it different from
setTimeout?
The key difference between setImmediate() and setTimeout() is that setImmediate() runs
after the current event loop iteration, following I/O events but before any timers (such
as setTimeout()). On the other hand, setTimeout() schedules tasks to run after a specified
delay, which might not be precise if the event loop is busy, meaning it can be delayed by I/O
or other tasks. While setTimeout() schedules tasks with a minimum
delay, setImmediate() executes as soon as the event loop reaches a free point in the "check"
phase, after I/O events have been processed.
37. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program or a
function in a “strict” operating context. This strict context prevents certain actions from
being taken and throws more exceptions. The statement “use strict” instructs the browser to
use the Strict mode, which is a reduced and safer feature set of JavaScript.
38. What are the advantages and disadvantages of using async/await over traditional
callbacks or promises?
Advantages of async/await:
Disadvantages of async/await:
Limited concurrency control : Unlike promises with .all() or .race(), async/await can
be less flexible for handling multiple parallel tasks.
The closure is created when a child functions to keep the environment of the parent’s scope
even after the parent’s function has already executed. The Closure is a locally declared
variable related to a function. The closure will provide better control over the code when
using them.
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());
Output
call() Method: It calls the method, taking the owner object as argument. The
keyword this refers to the ‘owner’ of the function or the object it belongs to. We can
call a method that can be used on different objects.
apply() Method: The apply() method is used to write methods, which can be used on
different objects. It is different from the function call() because it takes arguments as
an array.
This can be done by using the target attribute in the hyperlink. Like
Logical error: It is the most difficult error to be traced as it is the error on the logical
part of the coding or logical error is a bug in a program that causes to operate
incorrectly and terminate abnormally.
Runtime Error : A runtime error is an error that occurs during the running of the
program, also known as an exception.
JavaScript
JScript
It is used to design active online content for the word wide Web.
44. How many ways an HTML element can be accessed in JavaScript code?
There are four possible ways to access HTML elements in JavaScript which are:
getElementsByClass() Method: It is used to get all the elements that have the given
classname.
getElementsByTagName() Method: It is used to get all the elements that have the
given tag name.
querySelector() Method: This function takes CSS style selector and returns the first
selected element.
Consider a situation an element is present inside another element and both of them handle
an event. When an event occurs in bubbling, the innermost element handles the event first,
then the outer, and so on.
=== is the strict equality operator, which compares both the values and their types, without
performing type conversion.
49. What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new object but copies references to the original nested objects,
meaning changes to the nested objects affect both the original and the copy. A deep copy,
on the other hand, creates a new object and recursively copies all nested objects, ensuring
that the original and the copy are completely independent. In a shallow copy, nested objects
are shared, while in a deep copy, they are fully duplicated.
50. Explain the concept of the event loop and the call stack in JavaScript. How does
JavaScript handle asynchronous code execution?
In JavaScript, the event loop manages the execution of code, handling both synchronous and
asynchronous operations. The call stack stores function calls and executes them in a Last In,
First Out (LIFO) order. When asynchronous code (e.g., setTimeout, promises) is encountered,
it’s offloaded to the callback queue once its execution context is ready. The event loop
continuously checks the call stack and moves tasks from the callback queue to the stack
when it’s empty, allowing asynchronous code to run without blocking the main thread.
51. What are Web Workers, and how do you use them to run scripts in the background?
Web Workers are JavaScript threads that run in the background, separate from the main
thread, allowing long-running scripts to be executed without blocking the user interface. You
can create a Web Worker using the Worker constructor, passing a JavaScript file as an
argument. Once created, the worker can perform tasks asynchronously, and you can
communicate with it via postMessage and onmessage events, ensuring the main thread
remains responsive.
52. Explain the concept of "debouncing" and "throttling" in JavaScript. How can these
techniques optimize performance?
Debouncing and throttlingare techniques used to optimize performance by limiting the
frequency of function executions in response to events like scrolling or resizing.
Debouncing ensures that a function is only executed after a certain amount of idle
time, i.e., it delays the execution until the event stops triggering for a specified time
(e.g., for search input).
Throttling limits the number of times a function can be executed in a given period,
ensuring it runs at regular intervals (e.g., during scroll or window resizing).
Options:
1. number
2. string
3. boolean
Answer:
Explanation:
JavaScript has several built-in data types, and number, string, and boolean are all
valid types.
let b = a;
b[0] = 100;
console.log(a);
Options:
1. [100, 2, 3]
2. [1, 2, 3]
3. [100, 100, 100]
4. undefined
Answer :
Explanation :
The code snippet represents two arrays [100, 2, 3] and [1, 2, 3] being compared using
the equality operator (==).
Since the two arrays are different objects in memory, the comparison results in false,
which evaluates to undefined when logged. Therefore, the result is undefined.
console.log([] + []);
Options:
1. null
2. undefined
3. ''
4. []
Answer :
Explanation:
The + operator concatenates two empty arrays, which results in an empty string '' .
(function() {
var a = b = 5;
})();
console.log(typeof a);
console.log(typeof b);
Options:
1. typeof a: "undefined"
typeof b: "number"
2. typeof a: "number"
typeof b: "number"
3. typeof a: "undefined"
typeof b: "undefined"
4. typeof a: "number"
typeof b: "undefined"
Answer:
Explanation:
However, a is declared with var and is local to the function, so it is undefined outside.
Options:
1. true, true
2. true, false
3. false, true
4. false, false
Answer:
Explanation:
1 < 2 < 3 is evaluated as (1 < 2) < 3, which becomes true < 3. In JavaScript, true is
treated as 1, so 1 < 3 is true.
3 > 2 > 1 becomes (3 > 2) > 1, which results in true > 1. Since true is 1, the
comparison becomes 1 > 1, which is false.
Options:
1. true, true
2. true, false
3. false, true
4. false, false
Answer:
Explanation:
In JavaScript, objects are compared by reference, not by value. Since obj1 and obj2
point to different memory locations, both == and === comparisons return false.
let x = 10;
let y = (x++, x + 1, x * 2);
console.log(y);
Options :
1. 22
2. 12
3. 21
4. 20
Answer:
22
Explanation:
The comma operator ( , ) evaluates all expressions but returns the value of the last
one.
x++ increments x to 11, but the result of this expression is the original 10.
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
Options:
1. A D B C
2. A B C D
3. A D C B
4. A C D B
Answer:
Explanation:
function foo(num) {
if (num === 0) return 1;
return num + foo(num - 1);
}
console.log(foo(3));
Options:
1. 3
2. 6
3. 7
4. 10
Answer:
Explanation:
o foo(2) → 2 + foo(1)
o foo(1) → 1 + foo(0)
o foo(0) → 1
Options:
1. [1, 2, 3]
[1, 2, 3, 4]
2. [1, 2, 3, 4]
[1, 2, 3, 4]
3. [1, 2, 3]
[1, 2, 3]
4. [1, 2, 3, 4]
[1, 2, 3]
Answer:
Explanation:
In JavaScript, arrays are reference types. Both a and b point to the same array in
memory. Modifying b also affects a.
function test() {
console.log(this);
}
test.call(null);
Options:
1. null
2. undefined
4. TypeError
Answer:
Explanation:
In non-strict mode, calling a function with this set to null defaults to the global object
(Window in browsers or global in Node.js).