Basics of JavaScript
Basics of JavaScript Interview with follow-up questions
1. What are the different data types available in JavaScript?
JavaScript values fall into two camps: primitives and objects.
There are 7 primitive types (immutable, compared by value):
- string, number, boolean, undefined, null, symbol (ES6), and bigint (ES2020, for integers beyond
Number.MAX_SAFE_INTEGER, e.g.123n).
Everything else is an object (compared by reference) — plain objects, plus arrays, functions, Date, Map, Set, etc.
You check a type with typeof, but interviewers love the two gotchas:
typeof null; // "object" ← legacy bug, kept for compatibility
typeof function(){}; // "function" (functions are callable objects)
typeof []; // "object" → use Array.isArray() for arrays
Other things to mention: NaN is a number and NaN !== NaN (use Number.isNaN), and Object.is(-0, +0) is false while === says true. number is a 64-bit float, so use bigint when you need exact large integers.
Follow-up 1
Can you explain the difference between null and undefined?
In JavaScript, null and undefined are both special values that represent the absence of a value.
- null is a value that represents the intentional absence of any object value. It is a primitive value that is assigned to a variable to indicate that it has no value or that it is empty.
- undefined is a value that represents an uninitialized, missing, or non-existent value. It is a primitive value that is automatically assigned to a variable that has been declared but has not been assigned a value.
In summary, null is an assignment value that indicates no value or empty value, while undefined is a default value that indicates a variable has not been assigned a value.
Follow-up 2
What is the typeof operator used for?
The typeof operator in JavaScript is used to determine the data type of a value or variable.
For example:
typeof 42; // returns 'number'
typeof 'Hello'; // returns 'string'
typeof true; // returns 'boolean'
typeof undefined; // returns 'undefined'
typeof null; // returns 'object' (this is a known bug in JavaScript)
typeof [1, 2, 3]; // returns 'object'
typeof {name: 'John', age: 30}; // returns 'object'
Follow-up 3
How does JavaScript handle type conversions?
JavaScript has two types of type conversions:
Implicit type conversion: JavaScript automatically converts values from one data type to another when needed. For example, when performing operations between different data types, JavaScript will convert one or both values to a common data type.
Explicit type conversion: JavaScript provides several built-in functions and operators to explicitly convert values from one data type to another. For example, the Number(), String(), and Boolean() functions can be used to convert values to the corresponding data types.
Here are some examples of type conversions:
var num = 42;
var str = String(num); // explicit conversion to string
console.log(str); // '42'
var bool = Boolean(''); // explicit conversion to boolean
console.log(bool); // false
var sum = '10' + 5; // implicit conversion to string
console.log(sum); // '105'
var difference = '10' - 5; // implicit conversion to number
console.log(difference); // 5
Follow-up 4
What is the difference between double equals (==) and triple equals (===) in JavaScript?
In JavaScript, the double equals (==) and triple equals (===) are comparison operators used to compare values.
Double equals (==): It compares the values on both sides of the operator after performing type coercion if necessary. It allows for loose equality comparison, meaning that it can convert values of different types to a common type before comparing them.
Triple equals (===): It compares the values on both sides of the operator without performing any type coercion. It checks for strict equality, meaning that it does not convert values of different types.
Here are some examples:
console.log(42 == '42'); // true (loose equality, converts string to number)
console.log(42 === '42'); // false (strict equality, different types)
console.log(0 == false); // true (loose equality, converts boolean to number)
console.log(0 === false); // false (strict equality, different types)
2. What are variables in JavaScript and how are they declared?
Variables are named containers for values, declared with let, const, or the legacy var. The modern default is const by default, let when you need to reassign, and var essentially never in new code.
const PI = 3.14159; // can't be reassigned
let count = 0; // block-scoped, reassignable
count += 1;
The differences interviewers probe:
- Scope:
let/constare block-scoped ({}, loops,if);varis function-scoped, which leaks out of blocks and causes classic loop-closure bugs. - Hoisting / TDZ:
varis hoisted and initialized toundefined, so reading it early is silently allowed.let/constare hoisted too but sit in the Temporal Dead Zone until the declaration runs — reading early throws aReferenceError. - Redeclaration & globals:
varallows redeclaration and, at top level, attaches to the global object (window);let/constdo neither. const≠ immutable: it only blocks reassignment of the binding.const obj = {}; obj.x = 1is fine — the object is still mutable.
Follow-up 1
What is the difference between var, let and const?
The main difference between var, let, and const is the scope and reassignment behavior. var has function scope and can be reassigned and redeclared within its scope. let has block scope and can be reassigned but not redeclared within its scope. const also has block scope but cannot be reassigned or redeclared once it is declared. Here's an example:
var x = 1;
let y = 2;
const z = 3;
if (true) {
var x = 4; // This reassigns the value of x
let y = 5; // This creates a new block-scoped variable y
const z = 6; // This creates a new block-scoped constant z
}
console.log(x); // Output: 4
console.log(y); // Output: 2
console.log(z); // Output: 3
In the example above, the var variable x is reassigned within the if statement, while the let variable y creates a new block-scoped variable with a different value. The const variable z also creates a new block-scoped constant with a different value.
Follow-up 2
What is hoisting in JavaScript?
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions before they are declared in your code. However, only the declarations are hoisted, not the initializations. Here's an example:
console.log(x); // Output: undefined
var x = 10;
console.log(y); // Output: ReferenceError: y is not defined
let y = 20;
In the example above, the var variable x is hoisted to the top of its scope, so it is accessible but has an initial value of undefined. The let variable y is not hoisted, so trying to access it before its declaration results in a ReferenceError.
Follow-up 3
Can you explain the concept of scope in JavaScript?
Scope in JavaScript refers to the visibility and accessibility of variables, functions, and objects in some particular part of your code during runtime. JavaScript has function scope and block scope. Function scope means that variables declared within a function are only accessible within that function or any nested functions. Block scope means that variables declared within a block (e.g., within a loop or conditional statement) are only accessible within that block. Here's an example:
function example() {
var x = 1; // Function-scoped variable
if (true) {
let y = 2; // Block-scoped variable
console.log(x); // Output: 1
console.log(y); // Output: 2
}
console.log(x); // Output: 1
console.log(y); // Output: ReferenceError: y is not defined
}
example();
In the example above, the variable x is function-scoped and accessible within the example function and any nested functions. The variable y is block-scoped and only accessible within the if statement block.
Follow-up 4
What happens if you try to use a variable that has not been declared?
If you try to use a variable that has not been declared, JavaScript will throw a ReferenceError and your code will stop executing. This is because JavaScript requires variables to be declared before they can be used. Here's an example:
console.log(x); // Output: ReferenceError: x is not defined
3. What are arrays in JavaScript and how can you manipulate them?
Arrays are ordered, zero-indexed objects that hold an ordered collection of values (of any mixed types). You create them with literals and read with bracket or at() notation:
const fruits = ["apple", "banana", "cherry"];
fruits[0]; // "apple"
fruits.at(-1); // "cherry" ← at() supports negative indexing
The key distinction interviewers want is mutating vs non-mutating methods:
- Mutating (change the original):
push/pop,shift/unshift,splice,sort,reverse,fill. - Non-mutating (return a new array):
map,filter,reduce,slice,concat,flat/flatMap, and spread[...arr].
Since ES2023 there are immutable copies of the in-place methods — toSorted(), toReversed(), toSpliced(), and with(i, val) — which return a new array instead of mutating. These are ideal for React/immutable state:
const nums = [3, 1, 2];
const sorted = nums.toSorted(); // [1,2,3], nums unchanged
const updated = nums.with(0, 99); // [99,1,2], nums unchanged
Also worth knowing: find/findIndex and their findLast/findLastIndex counterparts, and Array.from / Array.of for construction.
Follow-up 1
What are some methods you can use to manipulate arrays in JavaScript?
There are several methods you can use to manipulate arrays in JavaScript:
push(): Adds one or more elements to the end of an array.
pop(): Removes the last element from an array and returns that element.
shift(): Removes the first element from an array and returns that element.
unshift(): Adds one or more elements to the beginning of an array.
splice(): Adds or removes elements from an array at a specified index.
slice(): Returns a shallow copy of a portion of an array into a new array.
concat(): Joins two or more arrays and returns a new array.
sort(): Sorts the elements of an array in place.
reverse(): Reverses the order of the elements in an array.
forEach(): Executes a provided function once for each array element.
map(): Creates a new array with the results of calling a provided function on every element in the array.
Follow-up 2
How do you add and remove elements from an array?
To add elements to an array, you can use the push() method to add elements to the end of the array, or the unshift() method to add elements to the beginning of the array.
To remove elements from an array, you can use the pop() method to remove the last element from the array, or the shift() method to remove the first element from the array. You can also use the splice() method to remove elements from a specific index in the array.
Follow-up 3
What is the difference between an array and an object in JavaScript?
In JavaScript, arrays and objects are both types of objects, but they have some key differences:
Arrays are ordered collections of data, while objects are unordered collections of key-value pairs.
Arrays use numeric indices to access and manipulate elements, while objects use string keys.
Arrays have a length property that represents the number of elements in the array, while objects do not.
Arrays have built-in methods for manipulating and iterating over elements, while objects do not.
Arrays are best suited for storing and manipulating ordered collections of data, while objects are best suited for storing and accessing data using descriptive keys.
Follow-up 4
How can you iterate over an array in JavaScript?
There are several ways to iterate over an array in JavaScript:
- for loop: You can use a traditional for loop to iterate over an array by using the array's length property and accessing each element using its index.
var array = [1, 2, 3, 4, 5];
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
- forEach() method: You can use the forEach() method to execute a provided function once for each element in the array.
var array = [1, 2, 3, 4, 5];
array.forEach(function(element) {
console.log(element);
});
- for...of loop: You can use a for...of loop to iterate over the values of an array.
var array = [1, 2, 3, 4, 5];
for (var element of array) {
console.log(element);
}
- map() method: You can use the map() method to create a new array with the results of calling a provided function on every element in the array.
var array = [1, 2, 3, 4, 5];
var newArray = array.map(function(element) {
return element * 2;
});
console.log(newArray);
4. What are conditionals in JavaScript and how are they used?
Conditionals let a program branch — running different code depending on whether an expression is truthy. The main forms are if/else if/else, the ternary ?:, and switch:
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";
const label = isAdmin ? "Admin" : "User"; // ternary, returns a value
The gotcha interviewers chase is truthiness. A condition coerces to boolean, and the falsy values are exactly: false, 0, -0, 0n, "", null, undefined, and NaN — everything else (including [] and {}) is truthy.
Modern code often replaces small conditionals with operators:
- Nullish coalescing
??for defaults only onnull/undefined(unlike||, which also fires on0/""). - Optional chaining
?.to guard property access:user?.address?.city. - Logical assignment
??=,||=,&&=for conditional assignment.
Use switch for many discrete cases, but remember each case falls through without a break.
Follow-up 1
What is the syntax for an if-else statement in JavaScript?
The syntax for an if-else statement in JavaScript is as follows:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Follow-up 2
What is the ternary operator and how is it used?
The ternary operator is a shorthand way of writing an if-else statement in JavaScript. It allows you to write a single line of code to perform a conditional operation. The syntax for the ternary operator is as follows:
condition ? expression1 : expression2
If the condition is true, expression1 is evaluated and returned. If the condition is false, expression2 is evaluated and returned.
Follow-up 3
What is the switch statement and how is it used?
The switch statement is used to perform different actions based on different conditions. It evaluates an expression and executes the code block associated with the matching case. If no matching case is found, the code block associated with the default case is executed. The syntax for the switch statement is as follows:
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
// code to be executed if expression does not match any case
}
Follow-up 4
Can you explain the concept of truthy and falsy values in JavaScript?
In JavaScript, truthy and falsy values are values that are considered true or false when evaluated in a boolean context. The following values are considered falsy:
- false
- 0
- "" (empty string)
- null
- undefined
- NaN
All other values are considered truthy. When using conditionals, these truthy and falsy values can be used to determine the flow of the program. For example, if a variable is assigned a falsy value, the corresponding code block in an if-else statement will not be executed.
5. What are functions in JavaScript and how are they declared?
Functions are reusable, callable blocks of code. JavaScript has three main forms, and interviewers want you to know how they differ:
// 1. Declaration — hoisted, can be called before its definition
function greet(name) {
return `Hello, ${name}!`;
}
// 2. Expression — assigned to a variable, NOT hoisted
const greet2 = function (name) {
return `Hello, ${name}!`;
};
// 3. Arrow function — concise, lexical `this`
const greet3 = (name) => `Hello, ${name}!`;
Key follow-ups:
- Hoisting: declarations are fully hoisted; expressions/arrows are only as available as their
const/letbinding (TDZ applies). - Arrow functions have no own
this,arguments, orsuper—thisis taken lexically from where they're defined, which is why they're great for callbacks but wrong for object methods or constructors (they can't benew-ed). - Functions are first-class: you can pass them as arguments, return them, and store them — the basis for callbacks, closures, and higher-order functions.
- They support default (
name = "world") and rest (...args) parameters.
Follow-up 1
What is the difference between a function declaration and a function expression?
In JavaScript, a function declaration is a statement that defines a named function and hoists it to the top of the current scope. It can be called before it is defined. On the other hand, a function expression is an assignment of a function to a variable or a constant. It is not hoisted and can only be called after it is defined. Here's an example:
// Function declaration
function greet(name) {
console.log('Hello, ' + name + '!');
}
// Function expression
const greet = function(name) {
console.log('Hello, ' + name + '!');
};
Follow-up 2
What is a callback function?
A callback function is a function that is passed as an argument to another function and is invoked inside that function. It allows for asynchronous and event-driven programming in JavaScript. Callback functions are commonly used in scenarios like handling AJAX requests, event handling, and timeouts. Here's an example:
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(function() {
const data = 'Some data';
callback(data);
}, 1000);
}
function processData(data) {
console.log('Processed data:', data);
}
fetchData(processData);
Follow-up 3
What are arrow functions and how do they differ from regular functions?
Arrow functions are a concise syntax for writing functions in JavaScript. They were introduced in ES6. Unlike regular functions, arrow functions do not have their own this value, arguments object, or super keyword. They also cannot be used as constructors with the new keyword. Arrow functions are often used in scenarios where a short, anonymous function is needed. Here's an example:
// Regular function
function multiply(a, b) {
return a * b;
}
// Arrow function
const multiply = (a, b) => a * b;
Follow-up 4
Can you explain the concept of closures in JavaScript?
In JavaScript, a closure is a function that has access to its own scope, the scope in which it is defined, and the scope of its outer function. It allows a function to access and manipulate variables from its outer function even after the outer function has finished executing. Closures are often used to create private variables and encapsulate functionality. Here's an example:
function outer() {
const message = 'Hello';
function inner() {
console.log(message);
}
return inner;
}
const closure = outer();
closure(); // Output: Hello
6. What is the difference between ES Modules and CommonJS?
With modern tooling and Node, interviewers expect you to know both module systems. CommonJS (CJS) is Node's original system; ES Modules (ESM) is the standardized, browser-native system and the modern default.
| CommonJS | ES Modules | |
|---|---|---|
| Syntax | require() / module.exports |
import / export |
| Loading | synchronous, runtime | static, parsed before execution |
| Binding | copy of the value | live binding (read-only view of the export) |
this at top level |
module.exports |
undefined |
| Tree-shaking | hard | easy (static structure) |
Top-level await |
no | yes |
// ESM
import { sum } from './math.js';
export const PI = 3.14159;
Key points/gotchas: because ESM imports are static, you can't conditionally import at the top level (use dynamic import() which returns a Promise); ESM is always strict mode; in Node you opt into ESM via "type": "module" in package.json or the .mjs extension; mixing the two needs care (require of ESM is limited, though newer Node added some interop). Tree-shaking and browser-native loading are why ESM won.
Live mock interview
Mock interview: Basics of JavaScript
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.