0% found this document useful (0 votes)
1 views24 pages

Basic JavaScript

The document provides a comprehensive overview of JavaScript, covering its definition, differences from Java, data types, variable declarations, ES6+ features, functions, asynchronous JavaScript, and the 'this' keyword. It also discusses DOM manipulation, global variables, and various JavaScript concepts like hoisting, lexical scope, and higher-order functions. Additionally, it includes examples and explanations of common JavaScript functionalities and interview questions.

Uploaded by

priyakush1002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views24 pages

Basic JavaScript

The document provides a comprehensive overview of JavaScript, covering its definition, differences from Java, data types, variable declarations, ES6+ features, functions, asynchronous JavaScript, and the 'this' keyword. It also discusses DOM manipulation, global variables, and various JavaScript concepts like hoisting, lexical scope, and higher-order functions. Additionally, it includes examples and explanations of common JavaScript functionalities and interview questions.

Uploaded by

priyakush1002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

✅ Basic JavaScript

1. What is JavaScript? How is it different from Java?

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.

 JavaScript: Interpreted, dynamically typed, runs in browsers.

 Java: Compiled, statically typed, runs on JVM.

2. What are the different data types in JavaScript?


 Primitive: String, Number, Boolean, Null, Undefined, Symbol, BigInt

 Non-primitive: Object, Array, Function

3. Difference between var, let, and const?


 var: Function-scoped, can be re-declared and updated.

 let: Block-scoped, can be updated but not re-declared in the same scope.

 const: Block-scoped, cannot be updated or re-declared.

4. Primitive vs Non-primitive data types?


 Primitive: Immutable values, stored directly (e.g., 42, 'hello').

 Non-primitive: Mutable objects, stored by reference (e.g., arrays, objects).

5. == vs ===?
 ==: Compares values after type coercion.

 ===: Compares values and types (strict equality).

5 == "5" // true

5 === "5" // false

🟩 ES6+ Features

6. Arrow Functions vs Regular Functions


Arrow functions are shorter and do not bind this.
const greet = name => `Hello, ${name}`;

7. Template Literals Example


let name = 'Priya';

console.log(`Hello, ${name}!`);

8. Default Parameters

function greet(name = 'Guest') {

return `Hello, ${name}`;

9. Destructuring
const person = { name: 'Priya', age: 22 };

const { name, age } = person;

10. Spread vs Rest Operator


 Spread: Expands arrays/objects

 Rest: Collects remaining elements

const arr = [1, 2];

const newArr = [...arr, 3];

function sum(...nums) {

return nums.reduce((a, b) => a + b);

11. Object Shorthand Properties


const name = 'Priya';

const user = { name }; // same as { name: name }

🟩 Array Methods

12. map() vs forEach()


 map(): Returns a new array
 forEach(): Executes for each element, no return

13. filter() Example


[1, 2, 3].filter(num => num > 1); // [2, 3]

14. reduce() Use Case


To calculate a single value like sum:

[1, 2, 3].reduce((acc, val) => acc + val, 0); // 6

15. find() Return


Returns the first matching element:

[1, 2, 3].find(num => num > 1); // 2

16. Output of [1, 2, 3].map(num => num * 2)


[2, 4, 6]

🟩 Functions & Scope

17. Callback Function


function greet(name, callback) {

console.log("Hi " + name);

callback();

18. Closure Example


function outer() {

let count = 0;

return function inner() {

return ++count;

19. Hoisting
Variables (var) and functions are hoisted.
console.log(a); // undefined

var a = 10;

20. Lexical Scope


Inner functions access variables from outer functions.

21. Function Declaration vs Expression


 Declaration: Hoisted

function greet() {}

 Expression: Not hoisted

const greet = function() {};

🟩 Asynchronous JavaScript
22. Promise
An object representing future completion or failure.

const promise = new Promise((resolve, reject) => {

resolve("Success");

});

23. async/await

async function getData() {

const res = await fetch(url);

const data = await res.json();

24. Event Loop


Handles async operations via call stack + task queue.

25. Microtask vs Macrotask

 Microtask: Promise.then

 Macrotask: setTimeout

26. Output:
console.log("A");

setTimeout(() => console.log("B"), 0);

console.log("C");

// Output: A C B

🟩 this Keyword

27. What is this?


Represents the object that is executing the function.

28. Arrow vs Regular Function this


Arrow functions don’t bind their own this.

29. this in Global Scope


In browser: this refers to window.

console.log(this); // window

🟩 DOM & Browser

30. Selecting DOM Elements


document.getElementById('id')

document.querySelector('.class')

. Are JavaScript and Java related?

Java is an object-oriented programming language, while JavaScript is a client-side scripting


language. Both of them are different from each other. Here are main difference point
between them:

Java JavaScript

Statically typed, compiled and then interpreted Dynamically typed, interpreted

Runs on JVM (Java Virtual Machine) Runs in a browser or Node.js

Class-based inheritance Prototype-based inheritance


Java JavaScript

Compiled into bytecode and then bytcdode is run


Interpreted directly by browser
by the interpreter

Single-threaded, async with event


Multi-threading and concurrency supported
loop

Strongly typed Weakly typed

Supports object-oriented but


Fully object-oriented
more flexible

Automatic garbage collection


Automatic garbage collection (JVM)
(browser)

2. What are Data Types in 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

5. What is the use of the isNaN function?

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.

6. Which is faster in JavaScript and ASP script?

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.

7. What is negative infinity?

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.

8. Is it possible to break JavaScript Code into several lines?

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:

console.log("A Online Computer Science Portal\n for Geeks")

The code-breaking line is avoid by JavaScript which is not preferable.

let gfg= 10, GFG = 5,


Geeks =
gfg + GFG;

9. What are "truthy" and "falsy" values in JavaScript

 Falsy: false, 0, "" (empty string), null, undefined, NaN.

 Truthy: Everything else (e.g., any non-empty string, any non-zero number, objects,
arrays).

10. What are undeclared and undefined variables?


 Undefined: It occurs when a variable is declare but not assign any value. Undefined is
not a keyword.

 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.

11. Write a JavaScript code for adding new elements dynamically.

<html>

<head>

</head>

<body>

<button onclick="create()">

Click Here!

</button>

<script>

function create() {

let geeks = document.createElement('geeks');

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:

let petName = "Rocky"; // Global Variable

myFunction();

function myFunction() {

console.log("Inside myFunction - Type of petName:", typeof petName);

console.log("Inside myFunction - petName:", petName);

console.log("Outside myFunction - Type of petName:", typeof petName);

console.log("Outside myFunction - petName:", petName);

Output

Inside myFunction - Type of petName: string

Inside myFunction - petName: Rocky

Outside myFunction - Type of petName: string

Outside myFunction - petName: Rocky

It is difficult to debug and test the code that relies on global variables.

13. What do you mean by NULL in JavaScript?

The NULL value represents that no value or no object. It is known as empty value/object.

14. How to delete property-specific values?

The delete keyword deletes the whole property and all the values at once like

let gfg={Course: "DSA", Duration:30};


delete gfg.Course;

15. What is the difference between null and undefined in JavaScript?

A deeper comparison between the two special values, null (intentional absence of value)
and undefined (uninitialized variables).

16. What is a prompt box?


The prompt box is a dialog box with an optional message prompting the user to input some
text. It is often used if the user wants to input a value before entering a page. It returns a
string containing the text entered by the user, or null.

17. What is the 'this' keyword in JavaScript?

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.

19. What is the difference between ViewState and SessionState?

 ViewState: It is specific to a single page in a session.

 SessionState: It is user specific that can access all the data on the web pages.

20. How to submit a form using JavaScript?

You can use document.form[0].submit()method to submit the form in JavaScript.

21. Does JavaScript support automatic type conversion?

Yes, JavaScript supports automatic type conversion.

22. What is a template literal in JavaScript?

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.

23. What is a higher-order function in JavaScript?

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

24. What are all the looping structures in JavaScript?

 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.

25. What is lexical scope in JavaScript?

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.

let outer = "I am outside!";

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.

27. Explain how to read and write a file using JavaScript?

The readFile() functions is used for reading operation.

readFile( Path, Options, Callback)

The writeFile() functions is used for writing operation.

writeFile( Path, Data, Callback)

28. What is called Variable typing in JavaScript?

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";

29. What is hoisting in JavaScript?

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.

30. How to convert the string of any base to integer in JavaScript?

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.

32. What are the types of Pop up boxes available in JavaScript?

There are three types of pop boxes available in JavaScript.

 Alert

 Confirm

 Prompt

33. What is the use of void(0) ?

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

export const greet = () => "Hello";

// In file2.js

import { greet } from './file1';

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?

In Node.js, the setImmediate() function schedules a callback to be executed in the next


iteration of the event loop, specifically after the current event loop phase (which includes
I/O events). It's commonly used for deferring tasks to be executed once the current
operation completes.

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.

JavaScript Interview Questions for Experienced

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:

 Improved Readability : Async/await makes asynchronous code look like synchronous


code, making it easier to read and maintain.

 Simplified Error Handling : With try/catch, error handling is more straightforward


compared to .catch() with promises or callback-based error handling.

 Avoids callback hell : It eliminates deeply nested callbacks, reducing complexity in


asynchronous logic.

Disadvantages of async/await:

 Requires modern JavaScript : It’s supported in ES2017 and above, so older


environments may need transpiling.

 Limited concurrency control : Unlike promises with .all() or .race(), async/await can
be less flexible for handling multiple parallel tasks.

39. How to explain closures in JavaScript and when to use it?

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;

let get_func_inner = foo();

console.log(get_func_inner());

console.log(get_func_inner());

console.log(get_func_inner());

Output

40. What is the difference between call() and apply() methods ?

Both methods are used in a different situation

 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.

41. How to target a particular frame from a hyperlink in JavaScript ?

This can be done by using the target attribute in the hyperlink. Like

<a href="/geeksforgeeks.htm" target="newframe">New Page</a>

42. Write the errors shown in JavaScript?

There are three different types of errors in JavaScript.

 Syntax error : A syntax error is an error in the syntax of a sequence of characters or


tokens that are intended to be written in a particular programming language.

 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.

43. What is the difference between JavaScript and Jscript?

JavaScript

 It is a scripting language developed by Netscape.

 It is used to design client and server-side applications.

 It is completely independent of Java language.

JScript

 It is a scripting language developed by Microsoft.

 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:

 getElementById() Method: It is used to get the element by its id name.

 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.

45. What is an event bubbling in JavaScript?

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.

46. Explain the concept of memoization in JavaScript?

Memoization in JavaScript is an optimization technique that stores the results of expensive


function calls and reuses them when the same inputs occur again. This reduces the number
of computations by caching the results. Memoization is typically implemented using an
object or a map to store function arguments and their corresponding results. When the
function is called with the same arguments, the cached result is returned instead of
recalculating it. This improves performance, especially for functions with repeated calls and
expensive computations.

47. What is the difference between == and === in JavaScript?


In JavaScript, == is the loose equality operator, which compares two values for equality after
performing type coercion if necessary. This means it converts the operands to the same type
before comparing.

=== is the strict equality operator, which compares both the values and their types, without
performing type conversion.

48. Explain the concept of promises and how they work.

A Promise in JavaScript is an object that represents the result of an asynchronous operation.


It can be in one of three states: pending, fulfilled (resolved), or rejected. You create a
promise using new Promise(), passing an executor function with resolve and reject callbacks.
When the operation succeeds, resolve() is called; if it fails, reject() is used. Promises are
handled with .then() for success and .catch() for failure. They can be chained to handle
sequences of asynchronous tasks in a more readable way.

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).

JavaScript MCQ Coding Interview Questions

53. Which of the following is a JavaScript data type?

Options:

1. number

2. string

3. boolean

4. All of the above

Answer:

Explanation:

 JavaScript has several built-in data types, and number, string, and boolean are all
valid types.

 A number represents numeric values, a string represents sequences of characters,


and a boolean represents either true or false. All of these are fundamental data types
in JavaScript.

54. What is the result of the following code?

let a = [1, 2, 3];

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 (==).

 In JavaScript, arrays are reference types, meaning each array is a reference to an


object in memory.

 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.

55. What is the output of the following code?

console.log([] + []);

Options:

1. null

2. undefined

3. ''

4. []

Answer :

Explanation:

 The + operator concatenates two empty arrays, which results in an empty string '' .

56. What will be the output of the following code?

(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:

 Inside the IIFE, b = 5 is treated as a global variable (since no var , let ,


or const keyword is used).

 However, a is declared with var and is local to the function, so it is undefined outside.

57. What will be logged in the console?

console.log(1 < 2 < 3);


console.log(3 > 2 > 1);

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.

58. What will be the output of the following code?


const obj1 = { a: 1 };
const obj2 = { a: 1 };
console.log(obj1 == obj2);
console.log(obj1 === obj2);

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.

59. What will be the result of the following code?

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.

 x + 1 becomes 11 + 1 = 12, and the final expression x * 2 evaluates to 11 * 2 = 22,


which is assigned to y.
60. What will be the output of this asynchronous JavaScript code?

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:

 The synchronous code runs first, logging 'A' and 'D'.

 Promise callbacks (microtasks) are executed before setTimeout (macrotasks). So 'C' is


logged before 'B'.

61. What will be the output of this recursive function?

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:

 The function works recursively:


o foo(3) → 3 + foo(2)

o foo(2) → 2 + foo(1)

o foo(1) → 1 + foo(0)

o foo(0) → 1

 So, the total is 3 + 2 + 1 + 1 = 7.

62. What will be printed in the following code?

let a = [1, 2, 3];


let b = a;
b.push(4);
console.log(a);
console.log(b);

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.

63. What will be logged by the following code?

function test() {
console.log(this);
}
test.call(null);

Options:

1. null
2. undefined

3. Window or global object

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).

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy