JavaScript Interview Guide (4+ Years Experience)
1. What are the different data types in JavaScript?
JavaScript has primitive and reference data types:
- Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt
- Reference: Object, Array, Function
2. What is the difference between == and ===?
- == (abstract equality) compares values after type coercion.
- === (strict equality) compares both value and type.
Example:
console.log(5 == '5'); // true (type conversion happens)
console.log(5 === '5'); // false (different types)
3. What is undefined vs null?
- undefined: Variable declared but not assigned a value.
- null: A deliberate assignment indicating an empty value.
Example:
let a; console.log(a); // undefined
let b = null; console.log(b); // null
4. What are closures in JavaScript?
A closure is a function that remembers variables from its parent scope, even after the parent has
executed.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
5. What is hoisting in JavaScript?
JavaScript moves function and variable declarations to the top of their scope before execution.
Example:
console.log(x); // undefined (due to hoisting)
var x = 5;
6. What is the this keyword in JavaScript?
- In global scope, this refers to the window object.
- In methods, this refers to the calling object.
Example:
console.log(this); // Window (global)
const obj = { name: 'JS', print: function() { console.log(this.name); } };
obj.print(); // 'JS'
7. What is the difference between let, const, and var?
- var: Function-scoped, can be redeclared, hoisted with undefined.
- let: Block-scoped, cannot be redeclared.
- const: Block-scoped, cannot be reassigned.
Example:
var a = 10;
let b = 20;
const c = 30;
8. What is the event loop in JavaScript?
The event loop allows JavaScript to handle asynchronous code without blocking execution.
Example:
console.log('Start');
setTimeout(() => console.log('Async Task'), 0);
console.log('End');
// Output: Start -> End -> Async Task
9. What is the difference between async and await?
- async: Declares a function that returns a promise.
- await: Pauses execution until the promise resolves.
Example:
async function fetchData() {
let data = await fetch('https://api.example.com');
console.log(data);
}
10. How do you prevent XSS attacks?
- Use Content Security Policy (CSP).
- Escape user input in HTML.
- Avoid using innerHTML.