Javascript Interview questions-part1

Rashmi Mishra
0

 

🔹 Basic JavaScript Concepts

1. What are the different data types available in JavaScript?

JavaScript supports the following data types:

  • Primitive types:
    • String – e.g., "Hello"
    • Number – e.g., 42, 3.14
    • Boolean – true or false
    • Null – intentional absence of value
    • Undefined – variable declared but not assigned
    • BigInt – for large integers
    • Symbol – unique identifiers
  • Non-primitive (Reference) types:
    • Object – collections of key-value pairs
    • Array – ordered list of values
    • Function, Date, RegExp, etc.

2. What is the difference between var, let, and const?

Keyword

Scope

Hoisting

Reassignment

Redeclaration

var

Function

Yes

Yes

Yes

let

Block

No

Yes

No

const

Block

No

No

No

Use let when the value will change and const when it won’t. Avoid var.


3. What are JavaScript functions? How do you define and call one?

Functions are blocks of reusable code.
Define:

function greet(name) {

  return "Hello, " + name;

}

Call:

js

CopyEdit

greet("Alice");


4. What is a callback function? Can you give an example?

A callback is a function passed as an argument to another function.
Example:

function sayHi(callback) {

  console.log("Hi");

  callback();

}

sayHi(() => console.log("Callback executed!"));


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

  • == compares values with type coercion.
  • === compares values without type coercion (strict).

Example:

'5' == 5    // true 

'5' === 5   // false


6. What is null vs undefined?

  • null: Manually assigned to a variable to indicate “no value.”
  • undefined: A variable declared but not yet assigned a value.

let a = null;

let b;

console.log(a); // null

console.log(b); // undefined


7. How does the typeof operator work?

It returns the data type of a variable or expression.

typeof 123         // "number" 

typeof "hello"     // "string" 

typeof undefined   // "undefined" 

typeof null        // "object" (a known JS quirk)


8. What is a JavaScript object? How do you create one?

An object is a collection of key-value pairs.

let person = {

  name: "Alice",

  age: 25,

  greet: function () {

    return "Hi!";

  }

};


9. What is an array in JavaScript? How do you loop through an array?

An array is an ordered collection:

let fruits = ["apple", "banana", "cherry"];

Loop using:

js

CopyEdit

for (let i = 0; i < fruits.length; i++) {

  console.log(fruits[i]);

}


10. What are template literals? Give an example.

They allow embedding variables using backticks ` and ${}:

let name = "Alice";

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


🔹 Control Structures and Loops

11. What are the different types of loops in JavaScript?

  • for
  • while
  • do...while
  • for...in (loops through object keys)
  • for...of (loops through iterable values)

12. What is the difference between for, while, and do...while loops?

  • for: Best for known iteration counts.
  • while: Continues as long as condition is true.
  • do...while: Executes at least once before checking condition.

13. How does an if...else condition work in JavaScript?

if (x > 0) {

  console.log("Positive");

} else {

  console.log("Not positive");

}


14. What is a switch statement and when would you use it?

Used for multiple conditions on a single value.

switch (day) {

  case "Mon": console.log("Work"); break;

  case "Sun": console.log("Rest"); break;

  default: console.log("Unknown");

}


🔹 DOM Manipulation

15. What is the DOM in JavaScript?

DOM (Document Object Model) is a tree structure representing HTML elements. JS can read/write content and style.


16. How do you select an element by ID or class name in JavaScript?

document.getElementById("id");

document.getElementsByClassName("class");

document.querySelector(".class");


17. How can you change the content or style of an HTML element using JavaScript?

let el = document.getElementById("demo");

el.innerHTML = "New Content";

el.style.color = "blue";


18. How do you add an event listener to a button click?

button.addEventListener("click", () => {

  alert("Clicked!");

});


19. How would you create a dynamic list of items in JavaScript?

let items = ["A", "B", "C"];

let ul = document.createElement("ul");

items.forEach(item => {

  let li = document.createElement("li");

  li.textContent = item;

  ul.appendChild(li);

});

document.body.appendChild(ul);


🔹 Functions and Scope

20. What is the difference between function declaration and function expression?

  • Declaration is hoisted:

function greet() {}

  • Expression is not:

let greet = function() {};


21. What is lexical scope in JavaScript?

Variables are accessible where they are physically written:

function outer() {

  let a = 1;

  function inner() {

    console.log(a); // has access

  }

}


22. What is a closure in JavaScript? Can you give an example?

A closure is a function that remembers the scope where it was created:

function outer() {

  let count = 0;

  return function() {

    count++;

    return count;

  };

}

let counter = outer();

counter(); // 1

counter(); // 2


23. What is the difference between global scope and local scope?

  • Global: Defined outside functions, accessible anywhere.
  • Local: Defined inside functions, accessible only there.

🔹 Project-Oriented Questions

24. Can you explain how you would build a simple to-do list app in JavaScript?

1.   Create an input and button.

2.   On button click, read input and add to an array.

3.   Render list using DOM.

4.   Optionally, allow deleting and marking complete.


25. How would you implement form validation using JavaScript?

  • Use addEventListener("submit", ...)
  • Check values using JS logic (e.g. empty, regex)
  • Show error messages using innerHTML

26. How can you store and retrieve data from localStorage or sessionStorage?

localStorage.setItem("name", "Alice");

let name = localStorage.getItem("name");

localStorage.removeItem("name");


27. What is the use of JSON.stringify() and JSON.parse()?

  • JSON.stringify(obj) → converts object to string
  • JSON.parse(string) → converts JSON string back to object
    Useful for storing data in localStorage.

28. How can you make a button show/hide content on a web page using JavaScript?

button.addEventListener("click", () => {

  let el = document.getElementById("content");

  el.style.display = (el.style.display === "none") ? "block" : "none";

});


29. How would you fetch data from an API using fetch()?

fetch("https://api.example.com/data")

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(err => console.error(err));


🔹 Beginner Debugging and Error Handling

30. What are common errors in JavaScript and how do you fix them?

  • Syntax errors (missing ; or }) → Fix code structure
  • Type errors (e.g., undefined.length) → Check for undefined
  • Reference errors → Declare variables properly

31. How do you debug JavaScript code in the browser?

  • Use Developer Tools (F12)
  • Use console.log()
  • Set breakpoints in Sources tab

32. What is the console.log() function used for?

Used to print output to the console for testing/debugging:

console.log("This is a test");


33. How do you handle exceptions using try...catch?

try {

  let result = riskyFunction();

} catch (error) {

  console.error("Something went wrong:", error);

}

 

Post a Comment

0Comments

Post a Comment (0)