JS Output Questions

User
Ask me output questions of js !
from east to complex , 50 questions !
Assistant
User wants to practice JavaScript output questions from easy to complex (50 questions).
Assistant
Great! Here's a set of 50 JavaScript **output-based** questions, ordered from **easy to complex**, to help you master JS step-by-step. Try to guess the output before checking it!

### 🟒 Easy Level (1–15)
1.

console.log(typeof "Hello");

2.

console.log(2 + "2");

3.

console.log(2 - "2");

4.

console.log(true + false);

5.

console.log("5" == 5);

6.

console.log("5" === 5);

7.

let a;
console.log(a);

8.

console.log(0.1 + 0.2 == 0.3);

9.

console.log(typeof null);

10.

console.log(typeof NaN);

11.

console.log(Boolean(""));

12.

console.log([1, 2] + [3, 4]);

13.

console.log(3 > 2 > 1);

14.

console.log("10" - - "5");

15.

console.log(!!"false" == !!"true");

### 🟑 Intermediate Level (16–35)
16.

let x = [1, 2, 3];
x[10] = 11;
console.log(x.length);

17.

let y = 1;
y++;
console.log(y++);

18.

console.log(typeof typeof 1);

19.

console.log([] == ![]);

20.

console.log(+"");

21.

console.log(new Array(3).toString());

22.

console.log([..."hello"]);

23.

const foo = () => arguments;
console.log(foo(1, 2, 3));

24.

(function() {
  var a = b = 3;
})();
console.log(typeof b);

25.

let a = [1, 2, 3];
let b = a;
a = [4, 5, 6];
console.log(b);

26.

console.log(1 < 2 < 3);
console.log(3 > 2 > 1);

27.

let a = 0;
console.log(a++);
console.log(++a);

28.

console.log(null + 1);

29.

const obj = { name: "Neeraj" };
Object.freeze(obj);
obj.name = "Tiwari";
console.log(obj.name);

30.

let arr = [1, 2, 3];
arr.length = 0;
console.log(arr[0]);

31.

(function(a){
  return (function(){
    console.log(a);
    a = 5;
  })();
})(10);

32.

var x = 1;
function test() {
  console.log(x);
  var x = 2;
}
test();

33.

console.log(typeof (function() {}));

34.

(function(){
  console.log(this);
})();

35.

console.log([] + {});
console.log({} + []);

### πŸ”΄ Advanced Level (36–50)
36.

let x = (function(){
  let a = b = 5;
})();
console.log(typeof b);

37.

console.log(typeof (1 + "2" - "3"));

38.

setTimeout(() => console.log(1), 0);
Promise.resolve().then(() => console.log(2));
console.log(3);

39.

var a = 10;
(function(){
  console.log(a);
  var a = 5;
})();

40.

let a = 1;
let b = a++;
console.log(a, b);

41.

let obj = {
  a: 1,
  b: 2,
  get c() {
    return this.a + this.b;
  }
};
console.log(obj.c);

42.

let obj = {a: 1};
let clone = {...obj};
obj.a = 5;
console.log(clone.a);

43.

let a = () => {
  return
  {
    name: "John"
  };
};
console.log(a());

44.

let a = () => ({
  name: "John"
});
console.log(a());

45.

console.log((() => 10)());

46.

let x = [1, 2, 3];
x.length = 5;
console.log(x[3]);

47.

let a = [1, 2, 3];
let b = [...a];
a[0] = 99;
console.log(b[0]);

48.

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

49.

let obj = {
  name: "Neeraj",
  say: function() {
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
};
obj.say();

50.

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}

Let me know when you're ready for the **answers** or if you want them in quiz format (one-by-one with explanations).

User
1. string
2. 22
3. 0
4. 1 (but why)?????
5. true
6. false
7.undefined
8. false (but why)?????
9. object
10. number
11. false (but why)?????
12. no idea
13. no idea
14. no idea
15. no idea
Assistant
Great effort! Let's go through the ones you're unsure about with clear **explanations**, starting from **4, 8, 11 to 15**.

### **4. `console.log(true + false);` β†’ `1`**
– `true` is coerced to `1`
– `false` is coerced to `0`
– So: `1 + 0 = 1`

### **8. `console.log(0.1 + 0.2 == 0.3);` β†’ `false`**
– In **JavaScript**, `0.1 + 0.2` is **not exactly** `0.3` due to **floating point precision**.
– `0.1 + 0.2` equals `0.30000000000000004`
– So `0.30000000000000004 == 0.3` β†’ `false`

### **11. `console.log(Boolean(""));` β†’ `false`**
– An **empty string `""`** is one of JavaScript’s **falsy values**.
– Other falsy values: `0`, `NaN`, `null`, `undefined`, and `false` itself.

### **12. `console.log([1, 2] + [3, 4]);` β†’ `'1,23,4'`**
– Arrays are converted to strings when used with `+`.
– `[1, 2].toString()` β†’ `'1,2'`
– `[3, 4].toString()` β†’ `'3,4'`
– `'1,2' + '3,4'` β†’ `'1,23,4'`

### **13. `console.log(3 > 2 > 1);` β†’ `false`**
– Step-by-step:
1. `3 > 2` β†’ `true`
2. `true > 1` β†’ `Number(true)` is `1`, so `1 > 1` β†’ `false`

### **14. `console.log("10" – – "5");` β†’ `15`**
– `"10"` and `"5"` are strings, but `- -` forces **numeric coercion**:
– `"10"` β†’ `10`
– `"5"` β†’ `5`
– `10 – -5` = `10 + 5` = `15`

### **15. `console.log(!!"false" == !!"true");` β†’ `true`**
– `"false"` is a **non-empty string**, which is **truthy**
– `"true"` is also **truthy**
– So:
– `!!"false"` β†’ `true`
– `!!"true"` β†’ `true`
– Hence: `true == true` β†’ `true`

Would you like to continue from **question 16 onward**, or should I quiz you with random ones from what you’ve done?

User
Api fetch try catch !
Assistant
Here's a simple and clear example of using **`fetch` with `try…catch`** to handle API requests in JavaScript.

### βœ… Basic Example

“`js
async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com

User
Api fetch try catch in react!
Assistant
Here’s a complete and clean example of how to **fetch API data with `try-catch` in React** using `useEffect` and `useState`.

### βœ… Basic Example with `fetch`

import React, { useEffect, useState } from 'react';

function Users() {
  const [users, setUsers] = useState([]);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchUsers();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          {user.name} β€” {user.email}
        </li>
      ))}
    </ul>
  );
}

export default Users;

### πŸ” Key Points:

– `try` block is used to handle fetch logic.
– `catch` catches **network** or **parsing** errors.
– `finally` ensures `loading` is set to `false` regardless of success or failure.
– `!response.ok` ensures **HTTP errors** (like 404, 500) are also caught.

Let me know if you want the same thing using **Axios**, or need to add **POST requests**, headers, or authentication tokens.

User
import React , {useState , useEffect} from 'react';

const ApiFetch= ()=>{
const [users, setUsers] = useState([]);
const [loading , setLoading] = useState(true);
const [error , setError] = useState(null);

useEffect(()=>{
const fetchApi = async ()=>{
try{
const response = await fetch('https://jsonplaceholder.typicode.com/users')
if(!response.ok){
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
setUsers(data)

}
catch(err){
setError(err.message)
}
finally{
setLoading(false)
}
}
fetchApi()
}, [])
if (loading) return loading……
if (error) return Error: {error}
return
API Fetch
{users.map((user)=>{
return {user.name}
})}

}
export default ApiFetch;

is it correct?

Assistant
βœ… Yes, your code is **perfectly correct** and clean!

You are:
– Using `useEffect` properly to call the API on mount.
– Handling **loading**, **error**, and **successful data** states.
– Using `try-catch-finally` correctly.
– Returning JSX with conditions.

### πŸ’‘ Optional Small Improvements (Just for Best Practices):

1. **Add a dependency array comment** (to clarify intention):

useEffect(() => {
  // fetches only on first render
}, []);

2. **Optional loading spinner** or placeholder could be added instead of `"loading…"` string.

3. (Optional) You could extract the `fetchApi` function outside `useEffect` if you want to reuse it (e.g., in a refresh button later).

### βœ… Final Code is Fully Functional:

import React, { useState, useEffect } from 'react';

const ApiFetch = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchApi = async () => {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        const data = await response.json();
        setUsers(data);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchApi();
  }, []);

  if (loading) return <p>Loading......</p>;
  if (error) return <p style={{ color: 'red' }}>Error: {error}</p>;

  return (
    <>
      <h1>API Fetch</h1>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </>
  );
};

export default ApiFetch;

Let me know if you want to implement:
– Pagination
– Search/filter
– Button to refetch data
– POST/PUT/DELETE requests with fetch or Axios

Leave a Comment

Your email address will not be published. Required fields are marked *