Variables, data types, operators in React JS
Course: React JS Training
Topic: Variables, data types, operators
Course Link: React JS Training
Demo Link: Register for a Course Demo
1. Why Variables, Data Types and Operators Matter
Every program you will ever write does three things with values: it stores them, it checks what kind of value they are, and it combines or compares them. Variables handle the storing, data types describe the kind of value, and operators do the combining and comparing. These three ideas are the vocabulary of JavaScript — you cannot read a single line of real code without meeting all three.
This matters double for React work. A React component is mostly JavaScript values in motion: props are values passed in, state is values that change over time, and the UI you see is decided by comparisons such as items.length > 0. Modern React training assumes you already write clean modern JavaScript, and this React preparation checklist makes the same point before your first component. A weak grip on variables and types shows up immediately as confusing bugs, so treat this page as the foundation for conditions, loops, functions and arrays later in this module.
- Variables give a name to a value so you can reuse and change it.
- Data types tell JavaScript (and you) what a value is: text, number, true/false, or "nothing".
- Operators are the symbols that calculate, assign and compare:
+, =, ===, && and friends.
Rule of thumb: if you can store a value, name it, check its type and combine it with another value, you can read almost any line of JavaScript.
2. What Is a Variable? A Simple Definition
A variable is a named container for a value. Think of a labelled storage box: the box holds something (the value) and the label (the name) tells you what is inside. When you write let marks = 87;, JavaScript stores the number 87 in memory and attaches the name marks to it. From then on, the name stands for the value.
const studentName = "Priya"; // a string value named studentName
let marks = 87; // a number value named marks
console.log(studentName); // Priya
console.log(marks); // 87
marks = 91; // the box now holds 91
console.log(marks); // 91
Two points to hold on to:
- The value lives in memory; the name is only a label pointing to it. Reassignment replaces the contents without creating a new label.
- A variable holds one value at a time. Assigning a new value completely replaces the old one.
3. Key Terms Used on This Page
These words appear in every JavaScript lesson, error message and documentation page. Learn them now and everything after gets easier.
- Value — the actual data:
"Priya", 87, true.
- Literal — a value written directly in code, such as
"hello" or 42.
- Identifier — the name you choose for a variable, like
marks.
- Declaration — telling JavaScript a variable exists:
let total;.
- Initialization — giving a variable its first value:
let total = 0;.
- Assignment — storing a value in a variable using
=.
- Reassignment — replacing the current value with a new one.
- Expression — any code that produces a value, like
price * quantity.
- Statement — a complete instruction, usually one line, like
let price = 250;.
- camelCase — the standard naming style: first word lowercase, later words capitalised, e.g.
cartTotal.
- Primitive — a basic, single value such as a string or number.
Naming rule worth memorising: identifiers can contain letters, digits, _ and $, cannot start with a digit, and are case sensitive — total, Total and TOTAL are three different variables.
4. Declaring Variables: let, const and var
JavaScript gives you three keywords to create a variable. Two are modern (let and const); one is legacy (var) and survives only in older code.
Syntax
let score; // declare with let
score = 10; // then assign
let level = 2; // declare and initialize in one line
const city = "Pune"; // const: declare, initialize, never reassign
var old = true; // legacy style, avoid in new code
| Keyword | Can reassign? | Must initialize? | Use it when |
const | No | Yes, on the same line | Almost always — your default choice |
let | Yes | No | The value will genuinely change later |
var | Yes | No | Never in new code; read it only in old projects |
Choosing between const and let
const rate = 18; // a tax rate that never changes
let bill = 500; // a bill that grows as items are added
bill = bill + rate; // fine: bill was declared with let
rate = 20; // TypeError: Assignment to constant variable
One detail that confuses beginners: const locks the name-to-value link, not the contents of the value. For objects and arrays (covered later in this module) you can still change what is inside; you just cannot point the name at a brand-new value.
const user = { name: "Asha" };
user.name = "Usha"; // allowed: changing a property inside
user = {}; // TypeError: cannot reassign a const
Practical habit used across this course: start every variable as const and switch to let only when the code actually needs to reassign it. The code then documents itself — a reader instantly knows which values change.
5. How a Variable Works, Step by Step
Follow one variable through its whole life to see exactly what the engine does.
- Declaration.
let count; reserves the name count. The variable exists but holds the special value undefined.
- Initialization.
count = 1; stores the first real value.
- Reading. Using
count in an expression fetches the current value.
- Reassignment.
count = count + 4; reads the old value, computes a new one, and stores it back under the same name.
- Reading again. Every later use sees the newest value.
let count; // step 1: declared, value is undefined
console.log(count); // undefined
count = 1; // step 2: initialized
console.log(count); // 1
count = count + 4; // steps 3 and 4: read 1, compute 5, store 5
console.log(count); // 5
What happens if you read too early?
With let and const, using the variable before its declaration line throws a ReferenceError. JavaScript calls the gap before the declaration the temporal dead zone — you only need the practical rule: declare first, use after.
console.log(later); // ReferenceError: Cannot access 'later' before initialization
let later = "now";
Old var variables behave differently (they come back as undefined instead of throwing), which is one more reason var is avoided in modern code.
6. The Primitive Data Types
A data type describes what kind of value a variable holds. JavaScript is dynamically typed: you never write the type yourself — the engine figures it out from the value, and the same variable may hold different types over its life. There are seven primitive types: simple, single values that are copied when you assign them.
| Type | What it holds | Example | typeof says |
string | Text in quotes | "Priya" | "string" |
number | Integers and decimals, one type for both | 87, 99.5, -3 | "number" |
boolean | Logical yes/no | true, false | "boolean" |
undefined | Declared but not given a value yet | let x; | "undefined" |
null | Deliberately empty, set by the programmer | let result = null; | "object" (a long-standing quirk) |
symbol | A unique identifier | Symbol("id") | "symbol" |
bigint | Whole numbers beyond the normal number limit | 9007199254740993n | "bigint" |
In day-to-day web work you will constantly use strings, numbers, booleans, undefined and null; symbols and bigints are rare. Anything that is not one of these seven primitives is an object — arrays, functions and dates are all objects, and they get their own pages later in this module.
const course = "React JS Training"; // string
const durationWeeks = 8; // number
const isActive = true; // boolean
let certificate; // undefined for now
let discount = null; // intentionally no discount
console.log(typeof course); // "string"
console.log(typeof durationWeeks); // "number"
console.log(typeof isActive); // "boolean"
console.log(typeof certificate); // "undefined"
7. Checking Types with typeof
typeof is a built-in operator that answers one question: what type is this value? It returns the type name as a string, which makes it perfect for quick checks while learning and for guarding values in real projects.
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof 42.5); // "number" — decimals are numbers too
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" — famous historical quirk
console.log(typeof missing); // "undefined" — name never declared
console.log(typeof function () {}); // "function"
Three quirks worth knowing
typeof null returns "object". This bug from JavaScript's earliest days cannot be fixed without breaking old websites, so it stays. Check for null with value === null instead.
typeof on an undeclared name returns "undefined" instead of crashing — the only operation in the language that is safe on a name that does not exist.
- Functions get their own result
"function", even though technically they are objects.
8. Working with Strings
A string is text wrapped in quotes. JavaScript accepts single quotes, double quotes and backticks; all three create the same kind of value. Pick one style and stay consistent — this course uses single quotes for plain strings.
const single = 'hello';
const double = "hello";
console.log(single === double); // true — same value
Template literals
Backticks have a superpower: they create template literals, which let you drop variables straight into text with ${...} and span multiple lines. This is the modern way to build messages, and React uses the same habit of embedding values inside braces.
const name = "Ravi";
const marks = 91;
const message = `${name} scored ${marks} marks.`;
console.log(message); // Ravi scored 91 marks.
const report = `Result card
Name: ${name}
Marks: ${marks}`;
console.log(report);
Useful string basics
const city = " Mumbai ";
console.log(city.length); // 9 — spaces count
console.log(city.trim()); // "Mumbai" — edge spaces removed
console.log(city.trim().toUpperCase()); // "MUMBAI"
console.log(city.includes("mun")); // false — matching is case sensitive
console.log(city.trim()[0]); // "M" — first character
One trap: adding a string to a number glues them together instead of adding, because + prefers text. "5" + 2 gives "52", not 7. The type conversion section below explains why and how to avoid it.
9. Working with Numbers and Booleans
JavaScript has a single number type for everything numeric: whole numbers, decimals, negative values. There is no separate integer type.
const price = 99.5;
const quantity = 4;
const total = price * quantity;
console.log(total); // 398
console.log(Math.round(7.6)); // 8
console.log((1234.5678).toFixed(2)); // "1234.57" — note: returns a string
The 0.1 + 0.2 surprise
Computers store decimals in binary, and some decimal fractions cannot be stored exactly — the same way one-third cannot be written exactly in decimal digits. The result is a tiny rounding error, not a JavaScript bug:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
// practical fix: round before comparing
const sum = Math.round((0.1 + 0.2) * 100) / 100;
console.log(sum === 0.3); // true
Booleans and truthiness
A boolean is true or false. Comparison operators produce booleans, and conditions (next page in this module) consume them. JavaScript also treats every value as either truthy or falsy whenever it needs a yes/no answer.
- Falsy values (only six):
false, 0, "" (empty string), null, undefined, NaN.
- Everything else is truthy:
"0", " ", [], {}, negative numbers.
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
console.log(5 > 3); // true — comparisons return booleans
10. null, undefined and NaN: The Confusing Trio
Three special values regularly trip up beginners because they all mean "something is not right", but in different ways.
| Value | Meaning in plain words | Where it comes from |
undefined | "No value has been put here yet" | Declared without assignment, missing property, function with no return |
null | "Deliberately empty — I set this on purpose" | Written by the programmer, e.g. resetting a value |
NaN | "This was meant to be a number, but the maths failed" | Failed number conversion or impossible maths |
let pending; // undefined: nothing assigned yet
let cleared = null; // null: intentionally emptied
console.log(pending); // undefined
console.log(cleared); // null
const broken = Number("abc"); // conversion fails
console.log(broken); // NaN
console.log(0 / 0); // NaN
console.log(Number.isNaN(broken)); // true — the reliable check
Checking tips: use value === undefined or value === null for those two, and Number.isNaN(value) for NaN. The odd part about NaN is that it is not equal to anything, including itself: NaN === NaN is false — exactly why the dedicated check exists.
11. Type Conversion and Coercion
Values change type in two ways. Explicit conversion is when you ask for it using functions like Number(), String() and Boolean(). Implicit coercion is when JavaScript changes types on its own because an operator forced it. Coercion is convenient but also the source of many beginner bugs, so learn both.
Explicit conversion
const input = "42";
const n = Number(input); // "42" becomes 42
const s = String(99); // 99 becomes "99"
const b = Boolean(""); // "" becomes false
console.log(n + 8); // 50 — real addition now
console.log(typeof s); // "string"
How implicit coercion works with +
The + operator follows a fixed order of decisions:
- If either side is a string, the other side is converted to a string and the two are glued together.
- Otherwise both sides are treated as numbers and normal maths happens.
console.log("5" + 2); // "52" — string wins, values are glued
console.log("5" - 2); // 3 — minus has no string mode, coerces to number
console.log("5" * "2"); // 10 — both sides coerced to numbers
console.log(true + 1); // 2 — true becomes 1
console.log(1 + " apple"); // "1 apple"
Common conversions at a glance
| Expression | Result | Why |
Number("10") | 10 | Clean numeric text converts fully |
Number("") | 0 | Empty string counts as zero — a classic trap |
Number("12px") | NaN | Extra characters block the conversion |
String(25) | "25" | Number to text always works |
Boolean(0) | false | Zero is falsy |
Boolean("0") | true | Non-empty string is truthy, even "0" |
Course habit: convert explicitly at the edges of your program — form inputs, URLs and saved data always arrive as strings — and let the rest of the code work with clean types.
12. Arithmetic and Assignment Operators
Operators are symbols that act on values. Arithmetic operators calculate; assignment operators store. The humble = you already know; its combined cousins perform a calculation and store the result in one step.
Arithmetic operators
| Operator | Name | Example | Result |
+ | Addition (or string joining) | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
% | Remainder (modulus) | 7 % 2 | 1 |
** | Exponent (power) | 2 ** 10 | 1024 |
The remainder operator % answers "what is left over after whole division?" It is everywhere in real code: even/odd checks (n % 2 === 0), highlighting every third row, or wrapping a counter back to zero.
console.log(10 % 3); // 1 — 3 fits 3 times, 1 left over
console.log(12 % 2 === 0); // true — even number
console.log(7 % 2 === 0); // false — odd number
Assignment operators
| Operator | Example | Same as |
= | x = 5 | Store 5 in x |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
let cartTotal = 500;
cartTotal += 250; // add an item worth 250
cartTotal -= 50; // apply a 50 rupee coupon
console.log(cartTotal); // 700
13. Comparison and Logical Operators
Comparison operators ask questions and answer with a boolean. Logical operators combine boolean answers into a single decision. Together they power every condition, validation and "should this render?" check you will write.
Comparison operators
| Operator | Question it asks | Example | Result |
=== | Equal in value and type? | 5 === 5 | true |
!== | Not equal in value or type? | 5 !== "5" | true |
> | Greater than? | 10 > 3 | true |
< | Less than? | 10 < 3 | false |
>= | Greater than or equal? | 3 >= 3 | true |
<= | Less than or equal? | 2 <= 1 | false |
Always prefer === over ==
The loose equality == converts types before comparing, which produces surprises. Strict equality === compares value and type with no conversion:
| Expression | == result | === result |
5 == "5" / 5 === "5" | true | false |
0 == false / 0 === false | true | false |
null == undefined / null === undefined | true | false |
"" == 0 / "" === 0 | true | false |
Simple rule for this course: use === and !== always, and convert types explicitly when a comparison across types is genuinely needed.
Logical operators
&& (AND) — true only when both sides are truthy.
|| (OR) — true when at least one side is truthy.
! (NOT) — flips a boolean: !true is false.
const isLoggedIn = true;
const hasItems = false;
console.log(isLoggedIn && hasItems); // false — both needed
console.log(isLoggedIn || hasItems); // true — one is enough
console.log(!isLoggedIn); // false
A modern companion to || is the nullish coalescing operator ??, which supplies a default only when the value is null or undefined — useful when 0 or "" are perfectly valid values:
const enteredQty = 0;
console.log(enteredQty || 1); // 1 — || treats 0 as "empty", wrong here
console.log(enteredQty ?? 1); // 0 — ?? keeps the real 0
Putting it together: a small realistic example
Here is a tiny checkout helper using variables, types and operators from this page exactly as they appear in real projects:
const itemPrice = 450; // number
const quantityInput = "3"; // form inputs arrive as strings
const quantity = Number(quantityInput); // explicit conversion
const subtotal = itemPrice * quantity;
const freeShippingFrom = 999;
const shipping = subtotal >= freeShippingFrom ? 0 : 79;
const summary = `${quantity} items, subtotal Rs.${subtotal}, ` +
(shipping === 0 ? "free shipping" : `shipping Rs.${shipping}`);
console.log(subtotal); // 1350
console.log(shipping); // 0
console.log(summary); // 3 items, subtotal Rs.1350, free shipping
Read it line by line: a string was converted to a number explicitly, arithmetic produced the subtotal, a comparison with >= fed a ternary decision, and a template literal built the message. Every piece came from this page, and this same pattern — store, convert, calculate, compare, display — repeats in the conditions, functions and React components ahead.
14. Operator Precedence and Reading Complex Expressions
When an expression mixes several operators, JavaScript does not simply read left to right — it follows precedence rules that decide which operator acts first. Multiplication binds tighter than addition, comparisons bind tighter than logical operators, and parentheses override everything. Knowing this order lets you read any expression with confidence.
| Precedence | Operators | Direction |
| Highest | ( ) parentheses | — |
| High | ** | Right to left |
| Medium-high | *, /, % | Left to right |
| Medium | +, - | Left to right |
| Lower | >, <, >=, <= | Left to right |
| Lower still | ===, !== | Left to right |
| Low | &&, then || | Left to right |
| Lowest | = and friends, ?: | Right to left |
console.log(2 + 3 * 4); // 14 — multiplication happens first
console.log((2 + 3) * 4); // 20 — parentheses change the order
console.log(10 - 4 - 3); // 3 — same level, so left to right
console.log(2 ** 3 ** 2); // 512 — ** runs right to left: 2 ** (3 ** 2)
console.log(1 + 2 + "3"); // "33" — left to right: 3 first, then "33"
console.log("3" + 2 + 1); // "321" — the first string flips everything to text
Two habits keep complex expressions safe. First, add parentheses even when they are not required — (marks >= 35) && (marks <= 100) reads faster than relying on memory of the precedence table. Second, break long calculations into named steps; a variable named percentage is easier to check than a one-liner nobody wants to decode.
15. Ternary, Short-Circuit and Modern Operator Patterns
Beyond the basics, JavaScript has a set of compact operator patterns that appear constantly in professional code — including React codebases. Learn to read them now; you will write them naturally within a few weeks.
The ternary operator
The ternary operator condition ? valueIfTrue : valueIfFalse is a one-line decision that produces a value, which makes it perfect for choosing between two values:
const age = 20;
const category = age >= 18 ? "adult" : "minor";
console.log(category); // adult
const marks = 82;
const result = marks >= 35 ? "Pass" : "Fail";
console.log(result); // Pass
Short-circuit evaluation
&& and || do not always return booleans — they return one of their operands, and they stop evaluating as soon as the answer is known. This behaviour is called short-circuiting, and it is used to write fallbacks and guards in one line:
a || b returns a if a is truthy, otherwise b — the classic "default value" pattern.
a && b returns a if a is falsy, otherwise b — the classic "only if the first is okay" pattern.
let savedName = "";
const displayName = savedName || "Guest"; // "Guest" — empty string is falsy
let token = "abc123";
const status = token && "logged in"; // "logged in" — token is truthy
let missing;
const safe = missing && missing.length; // undefined — right side never runs
The last line shows why short-circuiting is also a safety tool: with &&, the right side is never touched when the left side fails, which prevents errors on missing data.
Reading a chain of ternaries
Ternaries can be chained for multi-way choices. Read them top to bottom: the first condition that matches wins.
const percentage = 85;
const grade = percentage >= 90 ? "A"
: percentage >= 75 ? "B"
: percentage >= 50 ? "C"
: "Reappear";
console.log(grade); // B
Chains deeper than three levels become hard to read — at that point, proper conditionals (next page of this module) are the better tool.
16. Where These Ideas Appear in React Code
Everything on this page reappears in React within days of starting components. A quick preview so you can connect the fundamentals to the goal:
- Props are values with types. A component receives values and must often check them:
typeof props.title === "string".
- State changes through operators. Counters update with
count + 1; totals accumulate with total += price.
- The UI is decided by comparisons. Ternaries and logical operators choose what gets displayed.
function Badge({ count }) {
return (
<span>
{count > 0 ? `${count} new messages` : "Nothing new"}
</span>
);
}
Inside those braces there is nothing new: a comparison with >, a ternary, and a template literal. Master the fundamentals here and JSX will feel like plain JavaScript wearing a different costume.
17. Common Mistakes and the Correct Way
These mistakes account for a large share of beginner bugs. Each one shows the wrong version, why it fails, and the corrected version.
Using = when you meant ===
// wrong — = assigns, it does not compare
let marks = 40;
if (marks = 100) { /* always runs: 100 is truthy, and marks is overwritten */ }
// correct — === compares
let marks = 40;
if (marks === 100) { /* runs only when marks really is 100 */ }
When you reach the conditions page, remember: = stores, === asks. Typing = inside a comparison silently changes your data.
Trusting loose equality
console.log(0 == ""); // true — surprising
console.log(0 === ""); // false — honest
console.log(null == undefined); // true
console.log(null === undefined); // false
== converts types before comparing, so unrelated values can look equal. The correct way is to use === everywhere and convert explicitly when a cross-type comparison is genuinely needed.
Adding a number to numeric text
// wrong — "5" is a string, so + glues
const total = "5" + 5;
console.log(total); // "55"
// correct — convert first
const total = Number("5") + 5;
console.log(total); // 10
Form inputs, prompt() dialogs and saved data always give you strings. Convert at the boundary with Number() before doing maths.
Reading a var variable before its declaration
console.log(value); // undefined — no error, but not the value you expect
var value = 10;
console.log(other); // ReferenceError — fails loudly, which is better
let other = 20;
var silently returns undefined before its line runs, hiding bugs. The correct way is let or const, which fail fast with a ReferenceError and show you the problem immediately.
Comparing NaN with ===
const parsed = Number("abc");
// wrong — NaN is never equal to anything, including itself
console.log(parsed === NaN); // false
// correct — use the dedicated check
console.log(Number.isNaN(parsed)); // true
Forgetting that toFixed returns a string
const price = 99.5;
// wrong — "100" + 1 glues text
console.log(price.toFixed(0) + 1); // "1001"
// correct — convert back to a number
console.log(Number(price.toFixed(0)) + 1); // 101
18. Best Practices for Variables, Data Types and Operators
These habits match how professional teams write modern JavaScript, and they will make your later React code cleaner too:
- Default to
const. Switch to let only when a variable genuinely needs reassignment. Never use var in new code.
- Always compare with
=== and !==. Reserve == for the rare case where you can explain exactly why you want coercion.
- Convert explicitly at the edges. Incoming data (forms, URLs, storage) is text — run it through
Number(), String() or Boolean() once, then work with clean types.
- Use template literals instead of
+ for building text. `Hello, ${name}` is clearer and safer than gluing strings.
- Name constants instead of scattering magic numbers.
const PASS_MARK = 35; documents intent; a bare 35 in ten places does not.
- Check for NaN with
Number.isNaN(), never with ===.
- Use
?? for defaults when 0 or "" are valid values, and || only when any falsy value should fall back.
- Wrap mixed expressions in parentheses and split long calculations into named intermediate variables.
- Use camelCase and descriptive names.
cartTotal beats x; userAge beats ua.
- Keep ternary chains short. Beyond three branches, move to real conditionals.
19. Practical Project: Student Marks Calculator
This mini project uses only what this page taught: variables, types, conversion, validation, arithmetic, comparisons, logical operators, ternaries and template literals. It runs as-is in the browser console or in Node.
Goal
Take three subject marks (as a form would send them — strings), validate them, compute the total and percentage, decide a grade, and print a formatted report.
Working steps
- Collect inputs as strings — exactly how real form data arrives.
- Convert every input with
Number() so maths becomes possible.
- Validate with
Number.isNaN() and && — all three marks must be real numbers.
- Calculate the total and the percentage (out of 300 marks).
- Decide the grade with a comparison chain.
- Build the report with a template literal, guarded by a final ternary.
// Student Marks Calculator
// step 1: inputs, exactly as a form would send them (strings)
const nameInput = "Anita";
const subject1 = "78";
const subject2 = "92";
const subject3 = "85";
// step 2: convert every input to a number
const m1 = Number(subject1);
const m2 = Number(subject2);
const m3 = Number(subject3);
// step 3: validate — every mark must be a real number
const allValid =
!Number.isNaN(m1) &&
!Number.isNaN(m2) &&
!Number.isNaN(m3);
// step 4: calculate
const total = m1 + m2 + m3;
const percentage = Math.round((total / 300) * 100);
// step 5: decide the grade — first matching condition wins
const grade = percentage >= 90 ? "A"
: percentage >= 75 ? "B"
: percentage >= 50 ? "C"
: "Reappear";
// step 6: build the report, with a fallback for invalid input
const report = allValid
? `Student : ${nameInput}
Total marks : ${total} / 300
Percentage : ${percentage}%
Grade : ${grade}`
: "Please enter numbers only.";
console.log(report);
Output
Student : Anita
Total marks : 255 / 300
Percentage : 85%
Grade : B
Try these variations
- Change
subject2 to "nine" — the validation ternary prints the fallback message, because Number("nine") is NaN.
- Raise the marks so the percentage crosses 90 and watch the grade become
A.
- Add a fourth subject: convert it, extend the
&& chain, and change the divisor from 300 to 400.
20. Practice Exercises
- Swap challenge: declare
a = 3 and b = 7, then swap their values using a third variable. Print both afterwards.
- Type explorer: create one variable of each primitive type you have learned, then log
typeof for each. Predict every result before running.
- Even or odd: using only
% and ===, build a string "12 is even" or "7 is odd" with a ternary and a template literal.
- Coercion detective: predict the output of
"5" + 3, "5" - 3, "" + 0, true + true, and null + 1. Run them and explain each result in one sentence.
- Safe divider: write a small block that divides
a by b, but uses a ternary to return "Cannot divide by zero" when b === 0.
- Bug hunt: this code should print 15 but prints
"105". Fix it and explain the mistake: const a = "10"; const b = 5; console.log(a + b);
21. Interview Questions and Answers
What are the differences between var, let and const?
var is the legacy keyword: it allows redeclaration and returns undefined if read before its declaration line. let is the modern redeclarable keyword: it blocks access before declaration (the temporal dead zone) and throws a ReferenceError on early reads. const behaves like let but must be initialized on the same line and can never be reassigned. Modern code defaults to const and uses let only when reassignment is needed.
Which JavaScript types are primitives?
Seven: string, number, boolean, undefined, null, symbol and bigint. Primitives are simple single values. Everything else — arrays, functions, dates, plain objects — is an object.
What is the difference between null and undefined?
undefined means "no value has been placed here yet" and comes from JavaScript itself, for example let x;. null means "deliberately empty" and is set by the programmer, for example let result = null;. A quick check is value === null or value === undefined; note that null == undefined is true with loose equality but false with strict equality.
How is == different from ===?
== converts types before comparing, so 5 == "5" is true. === compares both value and type with no conversion, so 5 === "5" is false. Professional code uses === and !== by default to avoid coercion surprises.
Why does typeof null return "object"?
It is a historical bug from JavaScript's first implementation that cannot be corrected without breaking existing websites, so it has been preserved. The reliable way to detect null is value === null, not typeof.
What is type coercion? Give an example.
Coercion is the automatic conversion of a value from one type to another by JavaScript. With +, a string on either side forces string joining: "5" + 2 gives "52". Arithmetic operators without a string mode coerce to numbers instead: "5" - 2 gives 3. Explicit conversion with Number(), String() and Boolean() avoids the surprises.
What is NaN and how do you check for it?
NaN ("Not a Number") is the number type's failure value, produced when a conversion or calculation cannot produce a real number, such as Number("abc") or 0 / 0. It is not equal to anything, including itself, so the only reliable check is Number.isNaN(value).
Which values are falsy in JavaScript?
Exactly six: false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy, including "0", " ", [] and {}.
What is the ternary operator and when do you use it?
It is a one-line conditional that produces a value: condition ? valueIfTrue : valueIfFalse, for example const label = count > 0 ? `${count} new` : "none";. Use it for short two-way choices, especially when picking a display value; use full conditionals for longer or nested logic.
What is short-circuit evaluation?
Logical operators stop as soon as the result is decided and return one of their operands. a || b returns a when it is truthy, otherwise b — a common default-value pattern. a && b returns a when it is falsy, otherwise b, and the right side is never evaluated when the left side already settles the answer, which also protects against errors on missing data.
What is the temporal dead zone?
It is the span between the start of a block and the line where a let or const variable is declared. Using the variable inside that span throws a ReferenceError. The practical rule is simple: declare first, use after.
Why is 0.1 + 0.2 not exactly 0.3, and how do you handle it?
JavaScript stores numbers in binary floating-point form, and values like 0.1 and 0.2 cannot be represented exactly, so 0.1 + 0.2 yields 0.30000000000000004. For comparisons, round first, for example Math.round((0.1 + 0.2) * 100) / 100 === 0.3, and format money for display with toFixed(2) — remembering it returns a string.
22. Quick Revision Checklist
- A variable is a named container; declare with
const by default, let when reassignment is needed, never var.
- Seven primitives: string, number, boolean, undefined, null, symbol, bigint — everything else is an object.
- Check types with
typeof; remember typeof null says "object".
- Template literals use backticks and
${...} for embedding values.
- One
number type for integers and decimals; beware 0.1 + 0.2.
- Falsy values are exactly six:
false, 0, "", null, undefined, NaN.
undefined = not set yet; null = deliberately empty; NaN = failed maths, check with Number.isNaN().
- Convert explicitly with
Number(), String(), Boolean() — especially on form input.
+ with a string joins text; other arithmetic coerces to numbers.
- Compare with
=== / !==, never == / !=.
% gives the remainder; ** is power; += updates in place.
- Ternary
condition ? a : b for one-line choices; || for defaults, ?? when 0 and "" are valid.
- Precedence: parentheses first, then
**, then * / %, then + -, then comparisons, then logic.
23. Official Documentation and Further Reading
Deepen this module with these course-relevant resources. They show how solid JavaScript fundamentals feed directly into React readiness and interviews:
Conclusion
Variables, data types and operators are the grammar of JavaScript: every function, condition, loop, array and React component you write from here on is built from named values, known types and operators that combine them. In this part you moved from reading expressions to writing them — handling precedence, ternaries and short-circuits, fixing the classic mistakes, and assembling a complete working project from nothing but these pieces. Keep the checklist handy, redo the exercises until the answers feel obvious, and you will be fully prepared for the next page of this module, where conditions and loops turn these values into decisions and repetition.
Learn more in the React JS Training course, or register for a course demo.