πŸŽ“ Velnov

🟨 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.

Key concepts in this topic

letvarBlock scopeconstObject.freezeMutabilityScopeHoistingBest practicesSyntaxErrorPrimitivestypeofnullGotchasundefined== vs ===numberbigintNaNisNaNNumber.isNaNCoercionBooleansCase sensitivity

Jump to: Easy Β· Medium Β· Hard

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
  1. A var
  2. B let
  3. C const
  4. 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?

  1. A const by default, let when the value must change, avoid var
  2. B var everywhere
  3. C let everywhere
  4. 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?

  1. A 7 - string, number, boolean, null, undefined, symbol, bigint
  2. B 3 - string, number, boolean
  3. C 2 - number and object
  4. 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"
  1. A "string"
  2. B "text"
  3. C "str"
  4. 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"
  1. A One - 'number' covers both integers and decimals
  2. B Two - int and float
  3. C Three - int, float, double
  4. 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?

  1. A true and false
  2. B True and False
  3. C 1 and 0 only
  4. 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?

  1. A camelCase - firstName, totalPrice
  2. B snake_case - first_name
  3. C PascalCase - FirstName
  4. 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
  1. A No - const prevents REASSIGNMENT, not mutation. user.name = "Ben" works fine
  2. B Yes - this throws an error
  3. C It silently does nothing
  4. 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
  1. A let is BLOCK-scoped ({ }); var is FUNCTION-scoped and leaks out of blocks
  2. B let is faster
  3. C var cannot hold numbers
  4. 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;

  1. A SyntaxError - a const must be initialised when declared
  2. B x becomes undefined
  3. C x becomes null
  4. 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
  1. A undefined means 'no value assigned yet' (JS sets it); null means 'deliberately empty' (you set it)
  2. B They are identical
  3. C null is a string
  4. 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"
  1. A 'Not a Number' - the result of an invalid maths operation, and its type is "number"
  2. B A string meaning error
  3. C null in disguise
  4. 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
  1. A Global isNaN() converts its argument first, so isNaN("abc") is true; Number.isNaN("abc") is false (it is a string, not NaN)
  2. B They are identical
  3. C Number.isNaN is deprecated
  4. 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);

  1. A undefined
  2. B null
  3. C 0
  4. 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
  1. A 2ndPlace
  2. B _private
  3. C $element
  4. 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(){});

  1. A "function"
  2. B "object"
  3. C "method"
  4. 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?

  1. A A variable can hold any type and change type at any time - the type belongs to the value, not the variable
  2. B Types must be declared upfront
  3. C Types cannot change ever
  4. 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);

  1. A 5 - primitives are copied BY VALUE
  2. B 10
  3. C undefined
  4. 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
  1. A The number 42
  2. B The string "42"
  3. C NaN
  4. 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")?

  1. A Number gives NaN (strict); parseInt gives 12 (reads digits until it hits a non-digit)
  2. B Both give 12
  3. C Both give NaN
  4. 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"
  1. A Converts the number to the text "42"
  2. B Keeps it a number
  3. C Returns NaN
  4. 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;

  1. A It silently creates a GLOBAL variable - a common source of bugs (strict mode throws instead)
  2. B SyntaxError
  3. C It creates a local variable
  4. 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
  1. A "object" - a famous historic BUG in JavaScript that can never be fixed
  2. B "null"
  3. C "undefined"
  4. 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);

  1. A true false - loosely equal but different types
  2. B true true
  3. C false false
  4. 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
  1. A false - NaN is the only value not equal to itself
  2. B true
  3. C undefined
  4. 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
  1. A "object" - arrays are objects in JavaScript
  2. B "array"
  3. C "list"
  4. 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
  1. A 10 - objects are copied BY REFERENCE, so a and b point to the same object
  2. B 5
  3. C undefined
  4. 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
  1. A Creating a unique identifier that never clashes with another key - often used as a hidden object property
  2. B Mathematical symbols
  3. C Currency formatting
  4. 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"
  1. A Integers larger than Number.MAX_SAFE_INTEGER - written with an n suffix: 9007199254740993n
  2. B Very long strings
  3. C Large arrays
  4. 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;
  1. A undefined - var declarations are hoisted, but the assignment is not
  2. B 5
  3. C ReferenceError
  4. 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

Practice β€œVariables & Data Types” as a quiz