π¨ JavaScript Β· Topic 2 of 20
Variables & Data Types β JavaScript Questions with Answers
30 practice questions on Variables & Data Types, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
7 easy Β· 15 medium Β· 8 hard Β· Part of JavaScript: The language of the web - basics to advanced, 20 topics.
Easy questions (7)
Q1. easy
Which keyword declares a block-scoped variable that CANNOT be reassigned?
const PI = 3.14159;
// PI = 3; // TypeError!
let count = 0;
count = 1; // fine
- A var
- B let
- C const
- D static
Answer: C β const
const creates a block-scoped binding that cannot be reassigned. let is block-scoped but reassignable; var is function-scoped and reassignable.
letvarBlock scope
Q4. easy
Which declaration style is recommended by default in modern JavaScript?
- A const by default, let when the value must change, avoid var
- B var everywhere
- C let everywhere
- D No declaration keyword at all
Answer: A β const by default, let when the value must change, avoid var
Start with const - it signals 'this will not be reassigned' and prevents accidental changes. Switch to let only when you genuinely reassign. var is legacy.
Best practicesconst
Q6. easy
How many PRIMITIVE data types does JavaScript have?
- A 7 - string, number, boolean, null, undefined, symbol, bigint
- B 3 - string, number, boolean
- C 2 - number and object
- D Unlimited
Answer: A β 7 - string, number, boolean, null, undefined, symbol, bigint
The seven primitives are string, number, boolean, null, undefined, symbol and bigint. Everything else (objects, arrays, functions) is an object.
Primitivestypeof
Q7. easy
What does typeof "hello" return?
console.log(typeof "hi"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
- A "string"
- B "text"
- C "str"
- D "String"
Answer: A β "string"
typeof returns a lowercase string naming the type: "string", "number", "boolean", "undefined", "object", "function", "symbol", "bigint".
typeof
Q11. easy
How many NUMBER types does JavaScript have for everyday maths?
console.log(typeof 5); // "number"
console.log(typeof 5.5); // "number"
- A One - 'number' covers both integers and decimals
- B Two - int and float
- C Three - int, float, double
- D Four
Answer: A β One - 'number' covers both integers and decimals
Unlike many languages, JavaScript has a single number type (64-bit floating point). 5 and 5.5 are both 'number'. (bigint exists separately for huge integers.)
numberbigint
Q15. easy
Which are the two boolean values?
- A true and false
- B True and False
- C 1 and 0 only
- D yes and no
Answer: A β true and false
JavaScript booleans are lowercase true and false. (True with a capital T is an undefined variable and causes a ReferenceError.)
BooleansCase sensitivity
Q18. easy
What naming convention is standard for JavaScript variables?
- A camelCase - firstName, totalPrice
- B snake_case - first_name
- C PascalCase - FirstName
- D kebab-case - first-name
Answer: A β camelCase - firstName, totalPrice
Variables and functions use camelCase; classes use PascalCase; true constants are sometimes ALL_CAPS. kebab-case is impossible (the hyphen means subtraction).
ConventionsStyle
Medium questions (15)
Q2. medium
Does const make an OBJECT immutable?
const user = { name: "Ana" };
user.name = "Ben";
const user = { name: "Ana" };
user.name = "Ben"; // allowed
// user = {}; // TypeError: Assignment to constant
- A No - const prevents REASSIGNMENT, not mutation. user.name = "Ben" works fine
- B Yes - this throws an error
- C It silently does nothing
- D It converts the object to a string
Answer: A β No - const prevents REASSIGNMENT, not mutation. user.name = "Ben" works fine
const locks the binding, not the contents. You cannot do user = {} (reassignment), but you can change properties. Use Object.freeze(user) if you truly need immutability.
- Same applies to const arrays: push() works, reassigning does not.
constObject.freezeMutability
Q3. medium
What is the main difference between let and var?
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1 - leaked out!
// console.log(b); // ReferenceError
- A let is BLOCK-scoped ({ }); var is FUNCTION-scoped and leaks out of blocks
- B let is faster
- C var cannot hold numbers
- D There is no difference
Answer: A β let is BLOCK-scoped ({ }); var is FUNCTION-scoped and leaks out of blocks
A var declared inside an if or for block is visible throughout the whole function; a let exists only inside its { } block. Modern code prefers let/const to avoid surprising leaks.
ScopeHoisting
Q5. medium
What happens?
const x;
- A SyntaxError - a const must be initialised when declared
- B x becomes undefined
- C x becomes null
- D It works fine
Answer: A β SyntaxError - a const must be initialised when declared
Because const can never be reassigned, it must be given its value immediately: 'Missing initializer in const declaration'. let x; is perfectly legal (x is undefined).
constSyntaxError
Q9. medium
What is the difference between null and undefined?
let a;
console.log(a); // undefined - never assigned
let b = null; // I deliberately set it empty
- A undefined means 'no value assigned yet' (JS sets it); null means 'deliberately empty' (you set it)
- B They are identical
- C null is a string
- D undefined only appears in errors
Answer: A β undefined means 'no value assigned yet' (JS sets it); null means 'deliberately empty' (you set it)
JavaScript gives undefined to variables you declared but never assigned, and to missing function arguments. null is a value YOU assign to say 'intentionally nothing here'.
nullundefined
Q12. medium
What is NaN?
console.log(Number("abc")); // NaN
console.log(typeof NaN); // "number"
- A 'Not a Number' - the result of an invalid maths operation, and its type is "number"
- B A string meaning error
- C null in disguise
- D A syntax error
Answer: A β 'Not a Number' - the result of an invalid maths operation, and its type is "number"
NaN appears when a numeric operation makes no sense, such as Number("abc") or 0/0. Confusingly, typeof NaN is "number".
NaNisNaN
Q14. medium
Why prefer Number.isNaN() over the older global isNaN()?
isNaN("abc"); // true (coerced)
Number.isNaN("abc"); // false (it's a string)
Number.isNaN(NaN); // true
- A Global isNaN() converts its argument first, so isNaN("abc") is true; Number.isNaN("abc") is false (it is a string, not NaN)
- B They are identical
- C Number.isNaN is deprecated
- D isNaN only works on numbers
Answer: A β Global isNaN() converts its argument first, so isNaN("abc") is true; Number.isNaN("abc") is false (it is a string, not NaN)
The old isNaN() coerces: isNaN("hello") is true even though "hello" is a string. Number.isNaN() checks strictly for the actual NaN value - almost always what you want.
NaNCoercion
Q16. medium
What is the output?
let x;
console.log(x);
- A undefined
- B null
- C 0
- D ReferenceError
Answer: A β undefined
A declared but unassigned variable holds undefined. (Using a variable that was never DECLARED gives a ReferenceError instead.)
undefinedDeclaration
Q17. medium
Which variable name is INVALID in JavaScript?
let _private = 1; // ok
let $el = 2; // ok
let name2 = 3; // ok
// let 2ndPlace; // SyntaxError
- A 2ndPlace
- B _private
- C $element
- D firstName
Answer: A β 2ndPlace
Names cannot start with a digit. They may start with a letter, underscore or dollar sign, and may contain digits after the first character. Reserved words (let, class, return) are also forbidden.
IdentifiersNaming rules
Q20. medium
What is the output?
console.log(typeof function(){});
- A "function"
- B "object"
- C "method"
- D "undefined"
Answer: A β "function"
Functions are technically objects, but typeof gives the special result "function" - useful for checking whether a value can be called.
Functionstypeof
Q21. medium
What does 'dynamically typed' mean for JavaScript?
- A A variable can hold any type and change type at any time - the type belongs to the value, not the variable
- B Types must be declared upfront
- C Types cannot change ever
- D Only numbers are allowed
Answer: A β A variable can hold any type and change type at any time - the type belongs to the value, not the variable
let x = 5; then x = "hello"; is perfectly legal. Flexible, but type mistakes only show up at runtime - which is why TypeScript (typed JavaScript) is popular for large projects.
Dynamic typingTypeScript
Q22. medium
What is the output?
let a = 5;
let b = a;
a = 10;
console.log(b);
- A 5 - primitives are copied BY VALUE
- B 10
- C undefined
- D Error
Answer: A β 5 - primitives are copied BY VALUE
Primitive values (number, string, boolean...) are copied. b received a snapshot of 5 and is unaffected when a changes later.
Value vs referencePrimitives
Q24. medium
What does Number("42") return, and what type is it?
Number("42"); // 42
parseInt("42px"); // 42 - stops at the letters
Number("42px"); // NaN - stricter
- A The number 42
- B The string "42"
- C NaN
- D undefined
Answer: A β The number 42
Number() converts a string to a number. Alternatives: parseInt("42"), parseFloat("4.2"), or the unary plus +"42".
Type conversionparseInt
Q25. medium
What is the difference between Number("12px") and parseInt("12px")?
- A Number gives NaN (strict); parseInt gives 12 (reads digits until it hits a non-digit)
- B Both give 12
- C Both give NaN
- D parseInt gives NaN
Answer: A β Number gives NaN (strict); parseInt gives 12 (reads digits until it hits a non-digit)
parseInt is forgiving - it parses leading digits and ignores the rest, useful for CSS values like "12px". Number() demands the whole string be a valid number.
parseIntNumber()
Q26. medium
What does String(42) do?
String(42); // "42"
(42).toString(); // "42"
`${42}`; // "42"
- A Converts the number to the text "42"
- B Keeps it a number
- C Returns NaN
- D Throws an error
Answer: A β Converts the number to the text "42"
String() converts any value to its string form. Alternatives: (42).toString() and template literals `${42}`.
Type conversiontoString
Q30. medium
What happens if you assign to a variable that was never declared (without strict mode)?
myVar = 10;
- A It silently creates a GLOBAL variable - a common source of bugs (strict mode throws instead)
- B SyntaxError
- C It creates a local variable
- D Nothing happens
Answer: A β It silently creates a GLOBAL variable - a common source of bugs (strict mode throws instead)
Sloppy mode creates an accidental global, which can clash with other code. This is exactly what "use strict" (and ES modules) prevent by throwing a ReferenceError.
GlobalsStrict mode
Hard questions (8)
Q8. hard
What is the output?
console.log(typeof null);
console.log(typeof null); // "object" (bug)
console.log(value === null); // the correct check
- A "object" - a famous historic BUG in JavaScript that can never be fixed
- B "null"
- C "undefined"
- D "empty"
Answer: A β "object" - a famous historic BUG in JavaScript that can never be fixed
typeof null returns "object" due to a bug in the very first JavaScript implementation. Fixing it would break countless websites, so it stays. To test for null, use: value === null.
- A classic interview question.
nulltypeofGotchas
Q10. hard
What is the output?
console.log(null == undefined, null === undefined);
- A true false - loosely equal but different types
- B true true
- C false false
- D false true
Answer: A β true false - loosely equal but different types
With == (loose), null and undefined are considered equal to each other (a special rule). With === (strict), the types differ (object vs undefined), so it is false.
== vs ===nullundefined
Q13. hard
What is the output?
console.log(NaN === NaN);
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true - correct test
- A false - NaN is the only value not equal to itself
- B true
- C undefined
- D SyntaxError
Answer: A β false - NaN is the only value not equal to itself
By specification, NaN never equals anything including itself. To test for it use Number.isNaN(value) (or Object.is(value, NaN)).
NaNNumber.isNaN
Q19. hard
What is the output?
console.log(typeof []);
console.log(typeof []); // "object"
console.log(Array.isArray([])); // true - correct test
- A "object" - arrays are objects in JavaScript
- B "array"
- C "list"
- D "undefined"
Answer: A β "object" - arrays are objects in JavaScript
typeof cannot distinguish arrays from plain objects - both give "object". Use Array.isArray(value) to test for an array.
ArraysArray.isArray
Q23. hard
What is the output?
let a = { n: 5 };
let b = a;
a.n = 10;
console.log(b.n);
let b = { ...a }; // shallow copy - independent
let c = structuredClone(a); // deep copy
- A 10 - objects are copied BY REFERENCE, so a and b point to the same object
- B 5
- C undefined
- D Error
Answer: A β 10 - objects are copied BY REFERENCE, so a and b point to the same object
Objects (and arrays) are assigned by reference: b is another name for the same object. Changing it through a is visible through b. Copy with { ...a } or structuredClone(a).
Reference typesCopying objects
Q27. hard
What is a Symbol used for?
const id = Symbol("id");
console.log(Symbol("a") === Symbol("a")); // false - always unique
- A Creating a unique identifier that never clashes with another key - often used as a hidden object property
- B Mathematical symbols
- C Currency formatting
- D Emoji support
Answer: A β Creating a unique identifier that never clashes with another key - often used as a hidden object property
Symbol() always produces a unique value, even with the same description. Used for object keys that must not collide with normal keys, and for built-in behaviours like Symbol.iterator.
SymbolUnique keys
Q28. hard
What is BigInt for?
const big = 9007199254740993n;
console.log(typeof big); // "bigint"
- A Integers larger than Number.MAX_SAFE_INTEGER - written with an n suffix: 9007199254740993n
- B Very long strings
- C Large arrays
- D Big decimal precision
Answer: A β Integers larger than Number.MAX_SAFE_INTEGER - written with an n suffix: 9007199254740993n
Regular numbers lose precision above 2^53-1. BigInt handles arbitrarily large integers. Note: you cannot mix BigInt and Number in maths without converting.
BigIntMAX_SAFE_INTEGER
Q29. hard
What happens?
console.log(x);
var x = 5;
console.log(x); // undefined
var x = 5;
console.log(y); // ReferenceError
let y = 5;
- A undefined - var declarations are hoisted, but the assignment is not
- B 5
- C ReferenceError
- D null
Answer: A β undefined - var declarations are hoisted, but the assignment is not
JavaScript hoists the var declaration to the top of the scope, so x exists but holds undefined until the assignment runs. With let or const the same code throws a ReferenceError (temporal dead zone).
HoistingTDZ