JavaScript Output Based Questions
1. What is the output of 3 + 2 + "7" ?
The output is "57".
Explanation: JavaScript evaluates expressions from left to right.
- First, it performs addition on the numbers:
3 + 2 = 5. - Then, it encounters the string
"7". When a number is added to a string, JavaScript performs string concatenation. - Thus,
5 + "7"results in the string"57".
2. What is the output of below logic ?
const a = 1 < 2 < 3;
const b = 1 > 2 > 3;
console.log(a, b); // true, false
Output: true, false
Explanation:
- In JavaScript, the comparison operators < and > have left-to-right associativity. So, 1 < 2 < 3 is evaluated as (1 < 2) < 3, which becomes true < 3. When comparing a boolean value ( true ) with a number ( 3 ), JavaScript coerces the boolean to a number, which is 1. So, true < 3 evaluates to 1 < 3, which is true.
- Similarly, 1 > 2 > 3 is evaluated as (1 > 2) > 3, which becomes false > 3. When comparing a boolean value ( false ) with a number ( 3 ), JavaScript coerces the boolean to a number, which is 0. So, false > 3 evaluates to 0 > 3, which is false.
- That's why console.log(a, b) prints true false.
3. Guess the ouput ?
const p = { k: 1, l: 2 };
const q = { k: 1, l: 2 };
let isEqual = p == q;
let isStrictEqual = p === q;
console.log(isEqual, isStrictEqual)
OutPut:
- False,False
Explanation:
- In JavaScript, when you compare objects using == or ===, you're comparing their references in memory, not their actual contents. Even if two objects have the same properties and values, they are considered unequal unless they reference the exact same object in memory.
- isEqual will be false because p and q are two different objects in memory, even though they have the same properties and values.
- isStrictEqual will also be false for the same reason. The === operator checks for strict equality, meaning it not only compares values but also ensures that the objects being compared reference the exact same memory location.
- So, console.log(isEqual, isStrictEqual) will output false false.
4. Guess the output ?
a) 2+2 = ?
b) "2"+"2" = ?
c) 2+2-2 = ?
d) "2"+"2"-"2" = ? (tricky remember this)
e) 4+"2"+2+4+"25"+2+2 ?
OutPut:
// a) 2+2 = ?
console.log(2 + 2); // Output: 4
// b) "2"+"2" = ?
console.log("2" + "2"); // Output: "22" (string concatenation)
// c) 2+2-2 = ?
console.log(2 + 2 - 2); // Output: 2
// d) "2"+"2"-"2" = ?
console.log("2" + "2" - "2"); // Output: 20 (string "22" is coerced to a number, then subtracted by the number 2)
// e) 4+"2"+2+4+"25"+2+2
console.log(4+"2"+2+4+"25"+2+2); // "42242522"
Explanation:
- a & c: Standard numeric addition and subtraction.
- b: When using + with a string, JavaScript performs concatenation.
- d: The - operator does not exist for strings, so JavaScript coerces the string "22" into the number 22 before subtracting 2.
- e: Evaluation happens left-to-right. Once a string is encountered during addition, all subsequent additions are treated as string concatenations:
4 + "2" -> "42" + 2 -> "422" + 4 -> "4224"and so on.
5. What is the output of below logic ?
let a = 'jscafe'
a[0] = 'c'
console.log(a)
Output:
- "jscafe"
Explanation:
- Strings are immutable in javascript so we cannot change individual characters by index where as we can create a new string with desired modification as below.
- a = "cscafe" // outputs "cscafe"
6. Output of below logic ?
var x=10;
function foo(){
var x = 5;
console.log(x)
}
foo();
console.log(x)
Output: 5 and 10
Explanation:
In JavaScript, this code demonstrates variable scoping. When you declare a variable inside a function using the var keyword, it creates a new variable scoped to that function, which may shadow a variable with the same name in an outer scope. Here's what happens step by step:
- var x = 10; : Declares a global variable x and initializes it with the value 10.
- function foo() { ... } : Defines a function named foo.
- var x = 5; : Inside the function foo, declares a local variable x and initializes it with the value 5. This x is scoped to the function foo and is different from the global x.
- console.log(x); : Logs the value of the local variable (which is 5) to the console from within the foo function.
- foo(); : Calls the foo function.
- console.log(x); : Logs the value of the global variable (which is still 10) to the console outside the foo function.
7. Guess the output ?
console.log("Start");
setTimeout(() => {
console.log("Timeout");
});
Promise.resolve().then(() => console.log("Promise"));
console.log("End");
Output:
- Start, End, Promise, Timeout.
Explanation:
- "Start" is logged first because it's a synchronous operation.
- Then, "End" is logged because it's another synchronous operation.
- "Promise" is logged because Promise.resolve().then() is a microtask and will be executed before the next tick of the event loop.
- Finally, "Timeout" is logged. Even though it's a setTimeout with a delay of 0 milliseconds, it's still a macrotask and will be executed in the next tick of the event loop after all microtasks have been executed.
8. This code prints 6 everytime. How to print 1,2,3,4,5,6 ? (Most asked)
function x(){
for(var i=1;i<=5;i++){
setTimeout(()=>{
console.log(i)
}, i*1000)
}
}
x();
OutPut:
Solution: Either use let or closure
function x() {
function closur(x) {
// Set a timeout to log the value of x after x seconds
setTimeout(() => {
console.log(x);
}, x * 1000);
}
// Loop from 1 to 5
for (var i = 1; i <= 5; i++) {
// Call the closure function with the current value of i
closur(i);
}
}
// Call the outer function x
x();
Explanation:
- The function we have written defines an inner function closur which is supposed to log the value of x after x seconds. The outer function x calls this inner function for values from 1 to 5.
- The code will log the values 1 to 5 after 1 to 5 seconds respectively. Here's an explanation of how it works:
- The outer function x is called.
- Inside x, a loop runs from i=1 to i=6.
- For each iteration of the loop, the inner function closur is called with the current value of i.
- Inside closur, a setTimeout is set to log the value of x after x seconds.
Each call to closur(i) creates a new closure that captures the current value of i and sets a timeout to log that value after i seconds.
When you run this code, the output will be:
- 1 (after 1 second)
- 2 (after 2 seconds)
- 3 (after 3 seconds)
- 4 (after 4 seconds)
- 5 (after 5 seconds)
This happens because each iteration of the loop calls closur with a different value of i, and each setTimeout inside closur is set to log that value after i seconds.
9. What will be the output or below code ?
function x(){
let a = 10;
function d(){
console.log(a);
}
a = 500;
return d;
}
var z = x();
z();
OutPut: 500 - Closures concept
Explanation:
In JavaScript, this code demonstrates lexical scoping and closure. Let's break it down:
- function x() { ... } : Defines a function named x.
- let a = 10; : Declares a variable a inside the function x and initializes it with the value 10.
- function d() { ... } : Defines a nested function named d inside the function x.
- console.log(a); : Logs the value of the variable a to the console. Since d is defined within the scope of x, it has access to the variable a defined in x.
- a = 500; : Changes the value of the variable a to 500.
- return d; : Returns the function d from the function x.
- var z = x(); : Calls the function x and assigns the returned function d to the variable z.
- z(); : Calls the function d through the variable z.
When you run this code, it will log the value of a at the time of executing d, which is 500, because d retains access to the variable a even after x has finished executing. This behavior is possible due to closure, which allows inner functions to access variables from their outer scope even after the outer function has completed execution.
10. What's the output of below logic ?
getData1()
getData();
function getData1(){
console.log("getData11")
}
var getData = () => {
console.log("Hello")
}
Output:
- Uncaught TypeError: getData is not a function
Explanation:
In JavaScript, function declarations are hoisted to the top of their scope, while variable declarations using var are also hoisted but initialized with undefined. Here's what happens in your code:
- getData1() is a function declaration and getData() is a variable declaration with an arrow function expression assigned to it.
- When the code runs:
- getData1() is a function declaration, so it's hoisted to the top and can be called anywhere in the code.
- getData is declared using var, so it's also hoisted to the top but initialized with undefined.
- The arrow function assigned to getData is not hoisted because it's assigned to a variable.
- When getData() is invoked:
- It will throw an error because getData is undefined, and you cannot call undefined as a function.
Modification needed for code:
var getData = () => {
console.log("Hello")
}
getData1(); // This will log "getData11"
getData(); // This will log "Hello"
11. Whats the output of below code ?
function func() {
try {
console.log(1)
return
} catch (e) {
console.log(2)
} finally {
console.log(3)
}
console.log(4)
}
func()
Output: 1 & 3
Explanation:
- The function func() is defined.
- Inside the try block:
- console.log(1) is executed, printing 1 to the console.
- return is encountered, which immediately exits the function.
- The finally block is executed:
- console.log(3) is executed, printing 3 to the console.
Since return is encountered within the try block, the control exits the function immediately after console.log(1). The catch block is skipped because there are no errors, and the code in the finally block is executed regardless of whether an error occurred or not. So, when you run this code, it will only print 1 and 3 to the console.
12. What's the output of below code ?
const nums = [1, 2, 3, 4, 5, 6, 7];
nums.forEach((n) => {
if(n%2 === 0) {
break;
}
console.log(n);
});
Output:
- Uncaught SyntaxError: Illegal break statement
Explanation:
- Many of you might have thought the output to be 1, 2, 3, 4, 5, 6, 7.
- But "break" statement works only loops like for, while, do...while and not for map(), forEach().
- They are essentially functions by nature which takes a callback and not loops.
13. Whats the output of below code ?
let a = true;
setTimeout(() => {
a = false;
}, 2000)
while(a) {
console.log('-- inside whileee -- ');
}
Output: Infinite loop
Explanation:
This code snippet creates an infinite loop. Let's break it down:
- let a = true;: This declares a variable a and initializes it to true.
- setTimeout(() => { a = false; }, 2000);: This sets up a timer to execute a function after 2000 milliseconds (2 seconds). The function assigned to setTimeout will set the value of a to false after the timeout.
- while(a) { console.log('-- inside whileee -- '); }: This is a while loop that continues to execute as long as the condition a is true. Inside the loop, it prints -- inside whileee -- .
The issue here is that the while loop runs indefinitely because there's no opportunity for the JavaScript event loop to process the setTimeout callback and update the value of a. So, even though a will eventually become false after 2 seconds, the while loop will not terminate because it doesn't yield control to allow other tasks, like the callback, to execute.
To fix this, you might consider using asynchronous programming techniques like Promises, async/await, or handling the setTimeout callback differently.
14. Whats the output of below code ?
setTimeout(() => console.log(1), 0);
console.log(2);
new Promise(res => {
console.log(3)
res();
}).then(() => console.log(4));
console.log(5);
Output: 2, 3, 5, 4, 1
Explanation:
This code demonstrates the event loop in JavaScript. Here's the breakdown of what happens:
- setTimeout(() => console.log(1), 0);: This schedules a callback function to be executed after 0 milliseconds. However, due to JavaScript's asynchronous nature, it doesn't guarantee that it will execute immediately after the current synchronous code block.
- console.log(2);: This immediately logs 2 to the console.
- new Promise(res => { console.log(3); res(); }).then(() => console.log(4));: This creates a new Promise. The executor function inside the Promise logs 3 to the console and then resolves the Promise immediately with res(). The .then() method is chained to the Promise, so once it's resolved, it logs 4 to the console.
- console.log(5);: This logs 5 to the console.
When you run this code, the order of the output might seem a bit counterintuitive: 2, 3, 5, 4, 1.
Here's why:
- console.log(2); is executed first because it's synchronous code.
- Then, the Promise executor is executed synchronously, so console.log(3); is logged.
- After that, console.log(5); is executed.
- Once the current synchronous execution is done, the event loop picks up the resolved Promise and executes its .then() callback, logging 4.
- Finally, the callback passed to setTimeout is executed, logging 1. Although it was scheduled to run immediately with a delay of 0 milliseconds, it's still processed asynchronously and placed in the event queue, after the synchronous code has finished executing.
15. Output of below logic ?
async function foo() {
console.log("A");
await Promise.resolve();
console.log("B");
await new Promise(resolve => setTimeout(resolve, 0));
console.log("C");
}
console.log("D");
foo();
console.log("E");
Output: D, A, E, B, C
Explanation:
- The main context logs "D" because it is synchronous and executed immediately.
- The foo() function logs "A" to the console since it's synchronous and executed immediately.
- await Promise.resolve();: This line awaits the resolution of a Promise. The Promise.resolve() function returns a resolved Promise immediately. The control is temporarily returned to the caller function (foo()), allowing other synchronous operations to execute.
- Back to the main context: console.log("E");: This line logs "E" to the console since it's a synchronous operation. The foo() function is still not fully executed, and it's waiting for the resolution of the Promise inside it.
- Inside foo() (resumed execution): console.log("B");: This line logs "B" to the console since it's a synchronous operation.
- await new Promise(resolve => setTimeout(resolve, 0));: This line awaits the resolution of a Promise returned by the setTimeout function. Although the delay is set to 0 milliseconds, the setTimeout callback is pushed into the callback queue, allowing the synchronous code to continue.
- Back to the main context: The control is still waiting for the foo() function to complete.
- Inside foo() (resumed execution): The callback from the setTimeout is picked up from the callback queue, and the promise is resolved. This allows the execution of the next await.
- console.log("C");: This line logs "C" to the console since it's a synchronous operation. foo() function completes.
16. Guess the output ?
let output = (function(x){
delete x;
return x;
})(3);
console.log(output);
Output: 3
Explanation:
- The code defines an immediately invoked function expression (IIFE) that takes a parameter x.
- Inside the function, delete x; is called. However, delete operator is used to delete properties from objects, not variables. When you try to delete a variable, it doesn't actually delete the variable itself, but it's syntactically incorrect and may not have any effect depending on the context (in strict mode, it throws an error). So, delete x; doesn't do anything in this case.
- Finally, the function returns x. Since 3 was passed as x when calling the function, it returns 3.
- The returned value is assigned to the variable output.
- console.log(output); then logs the value of output, which is 3.
17. Guess the output of below code ?
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000 + i);
}
Output: 3 3 3
Explanation:
This might seem counterintuitive at first glance, but it's due to how JavaScript handles closures and asynchronous execution. Here's why:
- The for loop initializes a variable i to 0.
- It sets up a timeout for 1000 milliseconds plus the current value of i, which means the timeouts will be 1000, 1001, and 1002 milliseconds.
- After setting up the timeouts, the loop increments i.
- The loop checks if i is still less than 3. Since it's now 3, the loop exits.
- When the timeouts execute after their respective intervals, they access the variable i from the outer scope. At the time of execution, i is 3 because the loop has already finished and incremented i to 3. So, all three timeouts log 3.
18. Guess the output ?
let output = (function(x){
delete x;
return x;
})(3);
console.log(output);
Output: 3
Explanation:
- The code defines an immediately invoked function expression (IIFE) that takes a parameter x.
- Inside the function, delete x; is called. However, delete operator is used to delete properties from objects, not variables. When you try to delete a variable, it doesn't actually delete the variable itself, but it's syntactically incorrect and may not have any effect depending on the context (in strict mode, it throws an error). So, delete x; doesn't do anything in this case.
- Finally, the function returns x. Since 3 was passed as x when calling the function, it returns 3.
- The returned value is assigned to the variable output.
- console.log(output); then logs the value of output, which is 3.
19. Guess the output ?
let c = 0;
let id = setInterval(() => {
console.log(c++)
}, 200)
setTimeout(() => {
clearInterval(id)
}, 2000)
Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Explanation:
This JavaScript code sets up an interval that increments the value of c every 200 milliseconds and logs its value to the console. After 2 seconds (2000 milliseconds), it clears the interval.
Here's what each part does:
- let c = 0;: Initializes a variable c and sets its initial value to 0.
- let id = setInterval(() => { console.log(c++) }, 200);: Sets up an interval that executes a function every 200 milliseconds. The function logs the current value of c to the console and then increments c.
- setTimeout(() => { clearInterval(id) }, 2000);: Sets a timeout function that executes after 2000 milliseconds (2 seconds). This function clears the interval identified by id, effectively stopping the logging of c.
This code essentially logs the values of c at 200 milliseconds intervals until 2 seconds have passed, at which point it stops logging.
20. What would be the output of following code ?
function getName1(){
console.log(this.name);
}
Object.prototype.getName2 = () => {
console.log(this.name);
}
let personObj = {
name: "Tony",
print: getName1
}
personObj.print();
personObj.getName2();
Output: Tony undefined
Explanation:
getName1() function works fine because it's being called from personObj, so it has access to this.name property. But while calling getName2 which is defined under Object.prototype using an arrow function, it doesn't have its own this context; instead, it uses the lexical this (which is the global object/window). Since there is no name property on the global object, it returns undefined.
If you want it to log a value from the prototype, you would need to define it as follows:
Object.prototype.name = "Steve";
personObj.getName2(); // logs "Steve"
21. What would be the output of following code ?
function test() {
console.log(a);
console.log(foo());
var a = 1;
function foo() {
return 2;
}
}
test();
Output: undefined and 2
Explanation:
In JavaScript, this code will result in undefined being logged for console.log(a) and 2 being logged for console.log(foo()). This is due to variable hoisting and function declaration hoisting.
Here's what's happening step by step:
- The test function is called.
- Inside test:
- console.log(a) is executed. Since a is declared later in the function using var, it's hoisted to the top of the function scope but not initialized yet. So, a is undefined at this point.
- console.log(foo()) is executed. The foo function is a declaration, so it's fully hoisted to the top of the scope and available even before its definition.
- var a = 1; declares and initializes a with the value 1.
Therefore, when console.log(a) is executed, a is undefined due to hoisting, and when console.log(foo()) is executed, it logs 2, the return value of the foo function.
22. What is the output of below logic ?
function job() {
return new Promise((resolve, reject) => {
reject()
})
}
let promise = job();
promise.then(() => {
console.log("1111111111")
}).then(() => {
console.log("2222222222")
}).catch(() => {
console.log("3333333333")
}).then(() => {
console.log("4444444444")
})
Output:
3333333333
4444444444
Explanation:
In this code, a Promise is created with the job function. Inside the job function, a Promise is constructed with the executor function that immediately rejects the Promise.
Then, the job function is called and assigned to the variable promise.
After that, a series of then and catch methods are chained to the promise:
- The first then method is chained to the promise, but it is not executed because the Promise is rejected, so the execution jumps to the catch method.
- The catch method catches the rejection of the Promise and executes its callback, logging "3333333333".
- Another then method is chained after the catch method. Despite the previous rejection, this then method will still be executed because it's part of the Promise chain, regardless of previous rejections or resolutions. It logs "4444444444".
23. Guess the output ?
var a = 1;
function data() {
if (!a) {
var a = 10;
}
console.log(a);
}
data();
console.log(a);
Output: 10 and 1
Explanation:
This code demonstrates how hoisting works inside a function scope:
- Inside the data function, the declaration var a is hoisted to the top of the function's scope.
- This means that even before the if statement, a local variable a exists but is undefined.
- The check if (!a) evaluates to if (!undefined), which is true.
- The local variable a is then assigned the value 10.
- console.log(a) inside the function logs the local value, 10.
- console.log(a) outside the function logs the global variable a, which remains 1.
24. Tests your array basics
function guessArray() {
let a = [1, 2];
let b = [1, 2];
console.log(a == b);
console.log(a === b);
}
guessArray();
Output: false false
Explanation:
In JavaScript, when you compare two arrays using the == or === operators, you're comparing their references, not their contents. So, even if two arrays have the same elements, they will not be considered equal unless they refer to the exact same object in memory.
In your guessArray function, a and b are two separate arrays with the same elements, but they are distinct objects in memory. Therefore, a == b and a === b will both return false, indicating that a and b are not the same object.
If you want to compare the contents of the arrays, you'll need to compare each element individually.
25. Test your basics on comparison ?
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b);
console.log(a === b);
console.log(b === c);
Output: true false false
Explanation:
new Number() is a built-in function constructor. Although it looks like a number, it's not really a number; it has a bunch of extra features and is an object.
- When we use the == operator (Equality operator), it only checks whether it has the same value. They both have the value of 3, so it returns true.
- However, when we use the === operator (Strict equality operator), both value and type should be the same. It's not: new Number(3) is not a number, it's an object. Both return false.
26. Guess the output ?
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
Output: NaN
Explanation:
The provided code snippet demonstrates the behavior of variable hoisting and function scope in JavaScript. Let's analyze the code step-by-step to understand the output:
- Global Scope: var x = 23; A global variable x is declared and initialized with the value 23.
- First IIFE: var x = 43; A new function scope is created. Inside this function, a local variable x is declared and initialized with the value 43. This shadows the global x.
- Second IIFE (Nested function, named random): Another function scope is created inside the first IIFE. The function random is invoked immediately.
- Inside the random function:
- x++;
- console.log(x);
- var x = 21;
- Here, variable hoisting comes into play. The declaration var x = 21; is hoisted to the top of the function random, but not its initialization. Thus, the code is interpreted as:
var x; // x is hoisted, but not initialized (undefined)
x++; // undefined + 1 = NaN
console.log(x); // logs NaN
x = 21;
- Initially, x is undefined because the hoisted declaration of x does not include its initialization.
- x++ attempts to increment x when it is still undefined. In JavaScript, undefined++ results in NaN (Not a Number).
- Therefore, console.log(x); outputs NaN.
27. Answer below queries on typeOf operator in javascript ?
typeof [1,2,3,4] // Returns object
typeof null // Returns object
typeof NaN // Returns number
typeof 1234n // Returns bigint
typeof 3.14 // Returns number
typeof Symbol() // Returns symbol
typeof "John" // Returns string
typeof 33 // Returns number
typeof true // Returns boolean
typeof undefined // Returns undefined
Explanation:
The typeof operator in JavaScript is used to determine the data type of a value or a variable. It returns a string representing the type.
- Arrays and null are historically treated as objects in JavaScript.
- NaN is technically a number (Not a Number).
- 1234n represents a BigInt.
- Symbol() is a unique and immutable primitive value.
28. Can you find is there any security issue in the javascript code?
const data = await fetch("api");
const div = document.getElementById("todo");
div.innerHTML = data;
Explanation:
The provided JavaScript code seems straightforward, but there's a potential security issue related to how it handles data from the API response.
- Cross-Site Scripting (XSS):
The code directly assigns the fetched data (data) to the innerHTML property of the div element. If the data fetched from the API contains untrusted or user-controlled content (such as user-generated content or content from a third-party API), it could potentially contain malicious scripts. Assigning such data directly to innerHTML can lead to XSS vulnerabilities, as it allows execution of arbitrary scripts in the context of the page.
To mitigate this security risk, you should properly sanitize or escape the data before assigning it to innerHTML, or consider using safer alternatives like textContent or creating DOM elements programmatically.
Example using DOMPurify:
const data = await fetch("api");
const div = document.getElementById("todo");
data.text().then(text => {
div.innerHTML = DOMPurify.sanitize(text);
});
By using DOMPurify.sanitize(), you can ensure that any potentially harmful content is removed or escaped, reducing the risk of XSS attacks.