Part 1 · Lesson 2 · 16 min read
Variables and Data Types
Named boxes for values: numbers, strings and booleans, and the operators that combine them — including % and Math.floor, which appear in almost every DSA problem.
On this page
- A variable is a labelled box
- let and const
- Naming rules
- The five basic data types
- Arithmetic operators
- % and Math.floor — the two most useful operators
- Useful Math functions
- Joining text, and a common + mistake
- Converting between text and numbers
- Shorthand operators: += and ++
- Traced: swapping two variables
- Practice questions (8)
- Make it stick
A variable is a labelled box
Programs need to remember things: a score, a name, a running total. A variable is a named place in the computer's memory that holds one value. Think of a box with a label on it. You put a value in the box (a value is a piece of data, such as 21 or "Asha"). Later you use the label to get the value back, or to replace it with a new one.
In every DSA problem you will keep a few variables: the answer so far, a counter, the position you are looking at. A dry run means tracking what is in each box, line by line.
let and const
let age = 21; // make a box called age, put 21 in itconsole.log(age); // 21age = 22; // replace what is in the box (no "let" the second time)console.log(age); // 22const pi = 3.14159; // a box that can never be given a new valueconsole.log(pi); // 3.14159letis a keyword (a special word in JavaScript) that makes a box whose value you can change later. Putting a new value in a box is called assignment. Writeletonly the first time. After that, just use the name.const(short for “constant”) is a keyword that makes a box that cannot be given a new value. Trying to put something new in it is an error:
const pi = 3.14159;pi = 3; // TypeError: Assignment to constant variable.Use const by default. Use let when the value must change, for example a counter, a total or the current position. You may see var in old code. It is the old way to make a variable, and its rules can surprise you, so do not use it. One more detail: const stops you from putting a new value in the box. It does not stop a list or object inside the box from being changed. You will see this later with arrays.
Naming rules
- Use letters, digits,
_and$only. A name cannot start with a digit (2ndis not allowed,secondis fine). - Names are case-sensitive:
totalandTotalare different boxes. - You cannot use reserved words. These are words that already have a meaning in JavaScript, such as
let,ifandfor. - The usual JavaScript style is camelCase: the first word is small and each new word starts with a capital letter, like
maxValueorstudentCount. Short names likei,nandsumare normal in DSA code.
The five basic data types
A data type (or just type) is the kind of a value. It decides what you can do with the value. For example, you can add two numbers, but you cannot add two pieces of text in the same way. The typeof operator tells you the type of a value. These five types are enough for now (JavaScript has a few more, which you do not need yet):
let count = 7; // number (whole or decimal, one type for both)let price = 99.5; // numberlet name = "Asha"; // string (text, in quotes)let isOpen = true; // boolean (only true or false)let score; // undefined (made, but nothing put in yet)let winner = null; // null ("empty on purpose")console.log(typeof count); // numberconsole.log(typeof name); // stringconsole.log(typeof isOpen); // booleanconsole.log(typeof score); // undefined| Type | Examples | Used in DSA for |
|---|---|---|
number | 0, -4, 3.14 | Counts, sums, positions, answers |
string | "abc", 'hello' | Text problems: palindromes, anagrams |
boolean | true, false | Yes/no answers: “is it sorted?”, “found it?” |
undefined | a box that was made but has nothing put in it | Spotting bugs: you read something that was never set |
null | null | “No answer” on purpose, e.g. “no repeating character” |
Difference in one line: undefined means “nothing was put here yet” (JavaScript sets it), and null means “I chose to put nothing here” (you set it). A small surprise: typeof null gives "object". This is an old mistake in JavaScript that was never fixed.
Arithmetic operators
An operator is a symbol that does something with values, such as + or *. The values it works on are called operands. An expression is any piece of code that produces a value, like 7 + 2. The arithmetic operators do maths:
console.log(7 + 2); // 9console.log(7 - 2); // 5console.log(7 * 2); // 14console.log(7 / 2); // 3.5 (normal division keeps the decimal)console.log(7 % 2); // 1 (remainder)console.log(2 ** 5); // 32 (power: 2 × 2 × 2 × 2 × 2)console.log(2 + 3 * 4); // 14 (* before +, like school maths)console.log((2 + 3) * 4); // 20 (brackets first)The order is the same as in school maths. First brackets, then **, then * / %, then + -. Operators at the same level go from left to right. When in doubt, add brackets. They cost nothing and make your meaning clear.
% and Math.floor — the two most useful operators
% is the modulo operator. It gives the remainder of a division (the part that is left over). For example, 17 % 5 is 2, because 5 fits into 17 three times (15) and 2 is left. Math.floor(x) is a function that rounds down to a whole number. So Math.floor(a / b) means “how many whole times b fits in a”. Together they answer three questions you will meet over and over:
let n = 4729;console.log(n % 10); // 9 the LAST digitconsole.log(Math.floor(n / 10)); // 472 n WITHOUT its last digitconsole.log(n % 100); // 29 the last two digitsconsole.log(10 % 2); // 0 remainder 0 → 10 is evenconsole.log(7 % 2); // 1 remainder 1 → 7 is oddconsole.log(15 % 5); // 0 remainder 0 → 15 is divisible by 5console.log(Math.floor(17 / 5)); // 3 how many whole 5s fit in 17console.log(17 % 5); // 2 what is left over| Question | Expression | Answer |
|---|---|---|
| How many whole 5s fit in 17? | Math.floor(17 / 5) | 3 |
| What is left over? | 17 % 5 | 2 |
| Check: 3 × 5 + 2 | 15 + 2 | 17 ✓ |
n % 2 === 0means n is even (Lesson 3).n % 10gives the last digit of n.Math.floor(n / 10)gives n with its last digit removed (Lesson 5 repeats this in a loop).
These examples use positive whole numbers. With a negative number, the result of % takes the sign of the left number. For example, -7 % 2 is -1, not 1.
Useful Math functions
Math is a built-in JavaScript object (a ready-made group of tools) that holds maths functions. A function is a named set of steps. You call it by writing its name, then brackets with the values to give it, like Math.max(4, 9, 2). It gives back a result. These functions appear constantly in DSA answers:
console.log(Math.abs(-7)); // 7 distance from zeroconsole.log(Math.min(4, 9, 2)); // 2 smallestconsole.log(Math.max(4, 9, 2)); // 9 largestconsole.log(Math.round(2.5)); // 3 nearest whole numberconsole.log(Math.floor(2.9)); // 2 round downconsole.log(Math.ceil(2.1)); // 3 round upconsole.log(Math.trunc(-2.9)); // -2 drop the decimal partconsole.log(Math.sqrt(49)); // 7 square rootconsole.log(Math.pow(2, 10)); // 1024 same as 2 ** 10Math.floor(-2.9) is −3 (it always rounds down, towards smaller numbers), while Math.trunc(-2.9) is −2 (it just removes the decimal part). For positive numbers they give the same answer.
Joining text, and a common + mistake
A string is a value that is text. + between two strings joins them into one string. A newer and clearer way to build text is a template literal. It is a string written between backticks `…` that can hold ${…} placeholders. JavaScript replaces each placeholder with the value inside it.
let first = "Asha";let city = "Pune";console.log("Hi " + first); // Hi Ashaconsole.log(first + " lives in " + city); // Asha lives in Puneconsole.log(`${first} lives in ${city}`); // Asha lives in Pune (template literal)console.log(`2 + 3 = ${2 + 3}`); // 2 + 3 = 5Be careful. If either side of + is a string, JavaScript joins instead of adding. It works from left to right, one + at a time:
console.log(5 + 3); // 8 number + number → addconsole.log("5" + 3); // 53 string + anything → JOINconsole.log(5 + 3 + "5");// 85 left to right: 5 + 3 = 8, then 8 + "5" = "85"console.log("5" + 3 + 5);// 535 "5" + 3 = "53", then "53" + 5 = "535"console.log("5" - 3); // 2 - only means subtract, so "5" becomes 5console.log(Number("42") + 1); // 43 convert text to a number firstInput from a web form, a file or a test program often arrives as text. "5" + 3 quietly gives "53" with no error, and every later step is wrong. Convert with Number(x) first.
Converting between text and numbers
Input often arrives as text, and output often needs to be text. So you need to convert between the two (this is called type conversion). These functions do it:Number turns text into a number, parseInt reads a whole number from the start of some text, and String turns a value into text.
console.log(Number("42")); // 42 text → numberconsole.log(Number("4x")); // NaN "Not a Number": the text is not a valid numberconsole.log(parseInt("42px")); // 42 reads digits from the start, stops at the first non-digitconsole.log(String(42)); // 42 number → textconsole.log((42).toString(2)); // 101010 the number written in binaryconsole.log(typeof String(42)); // stringNaN means “Not a Number”. It is a special number value that appears when a conversion or calculation fails. Check for it with Number.isNaN(x). Do not use x === NaN, because NaN is not equal to anything, even to itself.
Shorthand operators: += and ++
Updating a variable using its own value is very common, so JavaScript has short forms. += adds a value to the variable. ++ adds 1 (this is called incrementing), and -- subtracts 1. You will use += and ++ in nearly every loop.
let total = 10;total += 5; // same as total = total + 5 → 15total -= 3; // total = total - 3 → 12total *= 2; // total = total * 2 → 24total++; // total = total + 1 → 25total--; // total = total - 1 → 24console.log(total); // 24Traced: swapping two variables
A common first question is to swap the values in a and b. The obvious attempt a = b; b = a; fails. After the first line both boxes hold 9, and the 5 is gone. You need a spare box. Step through it:
No boxes exist yet.
▶let a = 5;2let b = 9;3let temp = a;4a = b;5b = temp;6console.log(a, b);Practice questions
Given a length and a width, print the area (length × width) and the perimeter (2 × (length + width)).
Area: 15 Perimeter: 16
Area: 100 Perimeter: 40
Hint 1
Hint 2
length * width. Perimeter is 2 * (length + width) — keep the brackets.Show all 3 solutions with explanations
- Store the inputs in two variables,
lengthandwidth. - Calculate
areaandperimeterinto their own variables. - Print both.
const length = 5;const width = 3;const area = length * width;const perimeter = 2 * (length + width);console.log("Area:", area); // Area: 15console.log("Perimeter:", perimeter); // Perimeter: 16Naming each result makes the code easy to read and to check. The brackets in 2 * (length + width) matter: without them, 2 * length + width multiplies first and gives 13, which is wrong.
Skip the result variables and put the calculations straight into the print statements.
const length = 5;const width = 3;console.log("Area:", length * width); // Area: 15console.log("Perimeter:", 2 * (length + width)); // Perimeter: 16JavaScript calculates the expression first, then prints the result. The code is shorter, but you cannot reuse the results later.
A template literal is text between backticks. Use ${…} inside it to place values in a sentence.
const length = 5;const width = 3;console.log(`Area: ${length * width}, Perimeter: ${2 * (length + width)}`);// Area: 15, Perimeter: 16JavaScript calculates everything inside ${ } and puts the result into the text. This is the clearest way to print a sentence that contains several values.
Approach 1 is the best habit: clear names, each value calculated once. Use a template literal (Approach 3) whenever you print a sentence with values inside it.
Swap the values of a and b, then print them.
Hint 1
a = b; b = a; on paper. What is in b at the end, and why?Hint 2
a, its value has to be saved somewhere.Hint 3
temp = a, then a = b, then b = temp.Show all 3 solutions with explanations
- Copy
ainto a spare variable,temp. - Copy
bintoa. The old value ofais gone froma, buttempstill has it. - Copy
tempintob.
let a = 5;let b = 9;let temp = a; // temp = 5a = b; // a = 9b = temp; // b = 5console.log("a =", a, "b =", b); // a = 9 b = 5| Line | a | b | temp |
|---|---|---|---|
| temp = a | 5 | 9 | 5 |
| a = b | 9 | 9 | 5 |
| b = temp | 9 | 5 | 5 |
Destructuring is a short way to take values out of a list and put them into variables. It lets JavaScript assign two variables at once: [a, b] = [b, a].
let a = 5;let b = 9;[a, b] = [b, a];console.log("a =", a, "b =", b); // a = 9 b = 5The right side, [b, a], is built first from the current values: [9, 5]. Then the first value goes into a and the second into b. (You will learn about arrays, which are lists written in square brackets, in Lesson 8.)
Store the sum in a. Then get each original value back by subtracting.
let a = 5;let b = 9;a = a + b; // a = 14b = a - b; // b = 14 - 9 = 5a = a - b; // a = 14 - 5 = 9console.log("a =", a, "b =", b); // a = 9 b = 5This is sometimes asked as a puzzle (“swap without a temporary variable”). It only works for numbers, and it is harder to read, so people do not use it in real code.
Know Approach 1 by heart. The same swap happens inside sorting algorithms (Lesson 16). Approach 2 is the short form you will see in modern JavaScript. Mention Approach 3 only if the interviewer asks.
Convert a number of minutes into hours and remaining minutes.
Hint 1
Hint 2
Math.floor(total / 60) gives the whole groups. What gives the amount left over?Show all 2 solutions with explanations
- Hours = how many whole 60s fit:
Math.floor(total / 60). - Minutes = what is left over:
total % 60.
const total = 135;const hours = Math.floor(total / 60); // 2const minutes = total % 60; // 15console.log(hours + " hours " + minutes + " minutes"); // 2 hours 15 minutes| Step | Value |
|---|---|
| 135 / 60 | 2.25 |
| Math.floor(2.25) → hours | 2 |
| 135 % 60 → minutes | 15 |
After finding the hours, subtract the minutes that those hours use up. What remains is the minutes.
const total = 135;const hours = Math.floor(total / 60); // 2const minutes = total - hours * 60; // 135 - 120 = 15console.log(hours + " hours " + minutes + " minutes"); // 2 hours 15 minutesThis gives the same answer as %. It also shows what the remainder really means: the part that did not fit into a whole hour.
Approach 1 is the standard pair, so remember it: Math.floor for “how many whole groups” and % for “how much is left”. It solves every unit-conversion question.
Given a positive whole number, print its last digit and the number with the last digit removed.
Last digit: 9 Rest: 472
Last digit: 0 Rest: 5
Hint 1
Hint 2
Show all 3 solutions with explanations
n % 10is the remainder after dividing by 10, which is the last digit.Math.floor(n / 10)removes the last digit.
const n = 4729;const last = n % 10;const rest = Math.floor(n / 10);console.log("Last digit:", last); // Last digit: 9console.log("Rest:", rest); // Rest: 472Dividing by 10 moves every digit one place to the right: 4729 becomes 472.9. Math.floor drops the .9. The expression % 10 gives the last digit, 9.
Once you know the last digit, subtracting it leaves a number ending in 0, which divides by 10 exactly.
const n = 4729;const last = n % 10; // 9const rest = (n - last) / 10; // 4720 / 10 = 472console.log("Last digit:", last); // Last digit: 9console.log("Rest:", rest); // Rest: 4724729 − 9 = 4720, and 4720 / 10 = 472 exactly, so no rounding is needed.
Turn the number into a string (text) with String(n), then take its last character.
const n = 4729;const s = String(n); // "4729"const last = Number(s[s.length - 1]); // 9const rest = Number(s.slice(0, s.length - 1)); // 472console.log("Last digit:", last); // Last digit: 9console.log("Rest:", rest); // Rest: 472s[s.length - 1] is the last character. (The number in square brackets is a position, counted from 0. s.length is the number of characters.) s.slice(0, s.length - 1) is everything before the last character. Strings are covered in Lesson 9. This works, but it converts back and forth between numbers and text.
Use Approach 1. Interviewers expect the % 10 and Math.floor(n / 10) pair. Lesson 5 builds on it to visit every digit of any number.
Find the sum of the digits of a three-digit number.
Hint 1
n % 10) and remove it (Math.floor(n / 10)).Hint 2
Show all 3 solutions with explanations
Add the last digit to a running total, remove that digit, and repeat until all three digits are used.
let n = 472;let sum = 0;sum += n % 10; // + 2n = Math.floor(n / 10); // n = 47sum += n % 10; // + 7n = Math.floor(n / 10); // n = 4sum += n % 10; // + 4console.log(sum); // 13| Line | n | n % 10 | sum |
|---|---|---|---|
| start | 472 | — | 0 |
| sum += n % 10 | 472 | 2 | 2 |
| n = floor(n/10) | 47 | — | 2 |
| sum += n % 10 | 47 | 7 | 9 |
| n = floor(n/10) | 4 | — | 9 |
| sum += n % 10 | 4 | 4 | 13 |
- Hundreds digit:
Math.floor(n / 100). - Tens digit:
Math.floor(n / 10) % 10. - Ones digit:
n % 10.
const n = 472;const hundreds = Math.floor(n / 100); // 4const tens = Math.floor(n / 10) % 10; // 47 % 10 = 7const ones = n % 10; // 2console.log(hundreds + tens + ones); // 13Each digit has its own formula, so the original number is never changed. This works only because we know the number has exactly three digits.
Convert the number to a string, then turn each character back into a number.
const s = String(472); // "472"const sum = Number(s[0]) + Number(s[1]) + Number(s[2]);console.log(sum); // 13s[0] is the character "4", which is text. Number turns it into the number 4. Without Number, + would join the characters into "472" instead of adding them.
Approach 1 is the one to learn. It repeats the same two lines, and in Lesson 5 a loop does that repetition for a number of any length. Approach 2 is short when the number of digits is fixed.
Predict each output before running:
console.log("5" + 3);console.log("5" - 3);console.log(5 + 3 + "5");console.log("5" + 3 + 5);Hint 1
+ at a time.Hint 2
+, ask: is either side text? If yes, it joins. If both are numbers, it adds. - always subtracts.Show all 2 solutions with explanations
Work out each expression from left to right. At every step, decide whether + adds or joins.
console.log("5" + 3); // 53console.log("5" - 3); // 2console.log(5 + 3 + "5"); // 85console.log("5" + 3 + 5); // 535| Expression | Step 1 | Step 2 | Result |
|---|---|---|---|
| "5" + 3 | text + number → join | — | 53 |
| "5" - 3 | - only subtracts: 5 - 3 | — | 2 |
| 5 + 3 + "5" | 5 + 3 = 8 | 8 + "5" → join | 85 |
| "5" + 3 + 5 | "5" + 3 = "53" | "53" + 5 → join | 535 |
If you want maths, turn the text into a number with Number() before using +.
console.log(Number("5") + 3); // 8console.log(5 + 3 + Number("5")); // 13With every value a number, + always adds. This is how you avoid the problem in real code, where input often arrives as text.
Print the average of three numbers (the total divided by how many numbers there are).
Hint 1
Hint 2
Show all 2 solutions with explanations
Add the three numbers inside brackets, then divide by 3.
const a = 4, b = 8, c = 9;const average = (a + b + c) / 3;console.log(average); // 7Without the brackets, a + b + c / 3 divides only c by 3, because division happens before addition. That gives 15 instead of 7.
Store the total in its own variable first. Then the division is easy to read.
const a = 1, b = 2, c = 2;const total = a + b + c; // 5const average = total / 3;console.log(average); // 1.6666666666666667console.log(Math.round(average)); // 2 nearest whole numberconsole.log(average.toFixed(2)); // 1.67 two decimal places, as textWhen an answer must be a whole number, use Math.round (nearest) or Math.floor (round down). toFixed(2) gives the number as text with two decimal places, for display.
Both are correct. Approach 2 is easier to read and lets you format the result in different ways. Always check whether a question wants the exact value, a rounded value, or a whole number.
Convert a number of seconds into hours, minutes and seconds.
Hint 1
Hint 2
Hint 3
Show all 2 solutions with explanations
- Hours =
Math.floor(total / 3600). Seconds left =total % 3600. - Minutes =
Math.floor(left / 60). Seconds =left % 60.
const total = 3725;const hours = Math.floor(total / 3600); // 1const afterHours = total % 3600; // 125 seconds leftconst minutes = Math.floor(afterHours / 60); // 2const seconds = afterHours % 60; // 5console.log(`${hours}h ${minutes}m ${seconds}s`); // 1h 2m 5s| Variable | How | Value |
|---|---|---|
| hours | Math.floor(3725 / 3600) | 1 |
| afterHours | 3725 % 3600 | 125 |
| minutes | Math.floor(125 / 60) | 2 |
| seconds | 125 % 60 | 5 |
- Total minutes =
Math.floor(total / 60). Seconds =total % 60. - Hours =
Math.floor(totalMinutes / 60). Minutes =totalMinutes % 60.
const total = 3725;const totalMinutes = Math.floor(total / 60); // 62const seconds = total % 60; // 5const hours = Math.floor(totalMinutes / 60); // 1const minutes = totalMinutes % 60; // 2console.log(`${hours}h ${minutes}m ${seconds}s`); // 1h 2m 5sThis uses only the number 60, which some people find easier to remember. 3725 seconds is 62 minutes and 5 seconds. 62 minutes is 1 hour and 2 minutes.
Both use the same idea: Math.floor for whole units and % for the remainder. They only use a different order. Choose the one you can explain clearly.
Make it stick
- Write from memory: how to get the last digit of
n, andnwithout its last digit. - Without running it, say what
1 + 2 + "3"and"1" + 2 + 3print, and why they differ. - Swap two variables using a temp variable, then explain why
a = b; b = a;fails.
Revisit schedule: solve two of the questions again tomorrow, again in 3 days, and once more in a week — without looking at the answers. Each time it will feel easier. That is the memory forming.
Next lesson: making decisions with if / else (running some code only when a condition is true). You will solve even or odd, largest of three, and other common interview questions.
Published by Jainik · Last updated · How these lessons are made
Keep learning
Related series