Q2JavaScript fundamentals
What is the difference between let, const, and var?
Interview question about what is the difference between let, const, and var?.
Answer
let and const are block-scoped; var is function-scoped. let can be reassigned, const cannot be rebound, but const objects can still be mutated.
Syntax
let count = 0;
count++;
const user = { name: 'Asha' };
user.name = 'Mina';
Key Points
- Prefer const by default
- Use let for reassignment
- Avoid var in modern code
Q3JavaScript fundamentals
What are JavaScript primitive types?
Interview question about what are javascript primitive types?.
Answer
The primitive types are string, number, bigint, boolean, undefined, symbol, and null. Objects, arrays, and functions are reference values.
Syntax
const title = 'Engineer';
const score = 9.5;
const big = 123n;
const active = true;
const absent = null;
Key Points
- typeof null is historically object
- Primitives are immutable values
- Use bigint for large integers
Q4JavaScript fundamentals
What is the difference between == and ===?
Interview question about what is the difference between == and ===?.
Answer
== may coerce types before comparison; === compares without type conversion. Strict equality is usually more predictable.
Syntax
5 == '5'; // true
5 === '5'; // false
Key Points
- Prefer === and !==
- Know coercion in legacy code
- NaN !== NaN
Q5JavaScript fundamentals
What are truthy and falsy values?
Interview question about what are truthy and falsy values?.
Answer
Falsy values include false, 0, -0, 0n, empty string, null, undefined, and NaN. Empty arrays and empty objects are truthy.
Syntax
if (items.length) console.log('Has items');
const label = input ?? 'Default';
Key Points
- Empty arrays are truthy
- ?? only defaults null/undefined
- 0 and empty string can be valid values
Q6JavaScript fundamentals
What is type coercion?
Interview question about what is type coercion?.
Answer
Type coercion converts values between types. It can happen implicitly through operators or explicitly with Number, String, and Boolean.
Syntax
Number('42'); // 42
String(42); // '42'
'5' + 2; // '52'
Key Points
- + may concatenate strings
- Validate conversion results
- Prefer explicit conversion
Q7JavaScript fundamentals
How are null and undefined different?
Interview question about how are null and undefined different?.
Answer
undefined often indicates a missing or uninitialized value; null is commonly assigned intentionally to represent absence. Use each consistently in your application.
Syntax
let result;
console.log(result); // undefined
const selectedUser = null;
Key Points
- Optional properties may be undefined
- JSON handles them differently
- Use domain-specific states when useful
Q8JavaScript fundamentals
What is NaN and how do you test for it?
Interview question about what is nan and how do you test for it?.
Answer
NaN represents an invalid numeric result. It is not equal to itself, so use Number.isNaN for reliable checking without coercion.
Syntax
const value = Number('hello');
Number.isNaN(value); // true
Key Points
- Number.isNaN does not coerce
- Global isNaN does
- Validate external input
Q9JavaScript fundamentals
What are template literals?
Interview question about what are template literals?.
Answer
Template literals use backticks and support interpolation and multiline text. They do not automatically sanitize HTML or SQL.
Syntax
const name = 'Asha';
const greeting = `Hello, ${name}!`;
Key Points
- Use ${} for expressions
- Do not interpolate untrusted input into SQL
- HTML output still needs safe handling
Q10JavaScript functions
What are arrow functions?
Interview question about what are arrow functions?.
Answer
Arrow functions provide concise syntax and capture this lexically. They have no own this or arguments and cannot be used as constructors.
Syntax
const double = n => n * 2;
const greet = name => `Hi ${name}`;
Key Points
- Useful for callbacks
- Not always suitable for object methods
- Cannot be called with new
Q11JavaScript functions
What are default parameters?
Interview question about what are default parameters?.
Answer
Default parameters apply when an argument is omitted or undefined, not when it is null, false, zero, or an empty string.
Syntax
function greet(name = 'Guest') { return `Hi ${name}`; }
greet(); // Hi Guest
Key Points
- Defaults can be expressions
- null does not trigger the default
- Use ?? for nullish fallback
Q12JavaScript functions
What is a callback?
Interview question about what is a callback?.
Answer
A callback is a function passed to another function to be called later or during an operation. Callbacks can be synchronous or asynchronous.
Syntax
function run(task, done) { done(task()); }
run(() => 2 + 3, value => console.log(value));
Key Points
- Common in events and array methods
- Legacy Node APIs use error-first callbacks
- Promises help flatten async flows
Q13JavaScript arrays
How do map, filter, and forEach differ?
Interview question about how do map, filter, and foreach differ?.
Answer
map transforms every item and returns an array; filter returns matching items; forEach performs side effects and returns undefined.
Syntax
const nums = [1, 2, 3];
nums.map(n => n * 2);
nums.filter(n => n > 1);
nums.forEach(console.log);
Key Points
- map/filter do not mutate the source
- Avoid side effects in map
- for...of supports break
Q14JavaScript arrays
What are destructuring and spread syntax?
Interview question about what are destructuring and spread syntax?.
Answer
Destructuring extracts values from arrays or objects. Spread expands iterable items or enumerable object properties; copies are shallow.
Syntax
const [first, ...rest] = [10, 20, 30];
const next = { ...user, active: false };
Key Points
- Nested references remain shared
- Later spread properties override earlier ones
- Useful for immutable updates
Q15JavaScript objects
What is optional chaining?
Interview question about what is optional chaining?.
Answer
Optional chaining ?. stops a property access or call when the left side is null or undefined and returns undefined rather than throwing.
Syntax
const city = response?.user?.address?.city;
const label = city ?? 'Unknown';
Key Points
- Useful for optional data
- Does not validate required fields
- Combine with nullish coalescing
Q16JavaScript scope
What is lexical scope?
Interview question about what is lexical scope?.
Answer
Lexical scope means variables are resolved based on where code is written. Inner functions can access variables from enclosing scopes.
Syntax
function makeGreeting(name) {
return () => `Hello ${name}`;
}
Key Points
- Scope follows source structure
- Closures retain lexical bindings
- Avoid accidental globals
Q17JavaScript scope
What is a closure?
Interview question about what is a closure?.
Answer
A closure is a function that retains access to variables in its surrounding scope even after the outer function returns.
Syntax
function counter() { let n = 0; return () => ++n; }
const next = counter();
next(); // 1
Key Points
- Useful for encapsulation
- Retains bindings, not frozen snapshots
- Can keep referenced data alive
Q18JavaScript modules
What are ES modules?
Interview question about what are es modules?.
Answer
ES modules use import and export to define dependencies and expose values. Module scope is separate from global scope.
Syntax
export const PI = 3.14;
export function area(r) { return PI * r * r; }
import { area } from './math.js';
Key Points
- Named and default exports differ
- Use consistent conventions
- Runtime configuration affects module loading
Q19JavaScript errors
How do try, catch, and finally work?
Interview question about how do try, catch, and finally work?.
Answer
try wraps potentially failing code, catch handles thrown errors, and finally runs regardless of success or failure.
Syntax
try { riskyOperation(); }
catch (error) { console.error(error); }
finally { cleanup(); }
Key Points
- Catch errors you can handle
- Do not silently swallow errors
- Use finally for cleanup
Q20JavaScript JSON
How do JSON.stringify and JSON.parse work?
Interview question about how do json.stringify and json.parse work?.
Answer
stringify converts supported values to JSON text; parse converts JSON text back into JavaScript values. JSON does not preserve all JavaScript types.
Syntax
const text = JSON.stringify({ name: 'Mina' });
const data = JSON.parse(text);
Key Points
- Validate untrusted parsed data
- BigInt is not serializable by default
- Functions and undefined properties are omitted
Q21TypeScript fundamentals
What is TypeScript?
Interview question about what is typescript?.
Answer
TypeScript adds a static type system and tooling to JavaScript. Its types are erased from emitted JavaScript and do not validate runtime data automatically.
Syntax
type User = { id: number; name: string };
const user: User = { id: 1, name: 'Asha' };
Key Points
- Type-checking is primarily compile-time
- Runtime validation is separate
- Can target different JS versions
Q22TypeScript fundamentals
How do you type function parameters and returns?
Interview question about how do you type function parameters and returns?.
Answer
Parameter annotations define accepted inputs; return annotations document and check outputs. Inference can reduce unnecessary annotations.
Syntax
function add(a: number, b: number): number { return a + b; }
Key Points
- Avoid any when possible
- Use inference for local values
- Public APIs benefit from clear contracts
Q23TypeScript fundamentals
How do any and unknown differ?
Interview question about how do any and unknown differ?.
Answer
any disables most checking; unknown can hold any value but must be narrowed before use. Prefer unknown for untrusted data.
Syntax
let input: unknown = JSON.parse(raw);
if (typeof input === 'string') console.log(input.toUpperCase());
Key Points
- any spreads unsafety
- Narrow unknown with guards
- Validate external data
Q24TypeScript fundamentals
What are union types?
Interview question about what are union types?.
Answer
A union allows a value to match one of several types. Narrow it before accessing members not shared by every variant.
Syntax
type Id = string | number;
function formatId(id: Id) { return typeof id === 'number' ? `#${id}` : id.toUpperCase(); }
Key Points
- Use discriminated unions for states
- Narrow with runtime checks
- Avoid unnecessarily broad unions
Q25TypeScript fundamentals
What is the difference between interface and type?
Interview question about what is the difference between interface and type?.
Answer
Interfaces primarily describe object contracts and can merge declarations; type aliases can describe unions, tuples, primitives, and object shapes.
Syntax
interface User { id: number; name: string }
type Status = 'pending' | 'done';
Key Points
- Both use structural typing
- Interfaces can be extended
- Choose consistent project conventions
Q26TypeScript fundamentals
What is type inference?
Interview question about what is type inference?.
Answer
TypeScript infers types from initializers, expressions, and context. Explicit annotations are useful at public boundaries or when inference is too broad.
Syntax
const count = 3; // number
const names = ['Asha', 'Mina']; // string[]
Key Points
- Avoid needless annotations
- Annotate public contracts
- Check inference for empty arrays
Q27TypeScript fundamentals
What are optional and readonly properties?
Interview question about what are optional and readonly properties?.
Answer
Optional properties may be absent; readonly properties cannot be reassigned through that type. readonly is a compile-time restriction and is shallow by default.
Syntax
type Config = { readonly id: string; timeoutMs?: number };
Key Points
- Compiler options affect undefined semantics
- Readonly is not deep immutability
- Use optional only when absence is meaningful
Q28TypeScript configuration
What is tsconfig.json?
Interview question about what is tsconfig.json?.
Answer
tsconfig.json controls compiler options such as target, module format, strictness, included files, and path aliases.
Syntax
{
"compilerOptions": { "target": "ES2022", "module": "ESNext", "strict": true, "noEmit": true }
}
Key Points
- Enable strict checks for new projects
- Build tools may transpile without type checking
- Align config with runtime
Q29JavaScript objects
What are Map and Set?
Interview question about what are map and set?.
Answer
Map stores key-value pairs with keys of any type; Set stores unique values. Both preserve insertion order.
Syntax
const scores = new Map(); scores.set('Asha', 95);
const ids = new Set([1, 1, 2]);
Key Points
- Map is designed for key-value lookup
- Set stores unique values
- Plain objects suit record-like string keys
Q30JavaScript language
What is the difference between slice and splice?
Interview question about what is the difference between slice and splice?.
Answer
slice returns a shallow selected copy without mutating the array; splice mutates the array by removing, replacing, or inserting items.
Syntax
const a = [1, 2, 3, 4];
a.slice(1, 3); // [2,3]
a.splice(1, 1, 9); // changes a
Key Points
- slice end index is exclusive
- splice mutates source
- Use immutable updates when appropriate
Q31JavaScript language
What are primitive and reference values?
Interview question about what are primitive and reference values?.
Answer
Primitive values represent single immutable values; objects are accessed through references. Assigning an object variable copies the reference, not the object.
Syntax
const a = { count: 1 };
const b = a;
b.count = 2;
console.log(a.count); // 2
Key Points
- Multiple variables can reference one object
- Shallow copies retain nested references
- Mutation can affect other consumers