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

  1. A variable is a labelled box
  2. let and const
  3. Naming rules
  4. The five basic data types
  5. Arithmetic operators
  6. % and Math.floor — the two most useful operators
  7. Useful Math functions
  8. Joining text, and a common + mistake
  9. Converting between text and numbers
  10. Shorthand operators: += and ++
  11. Traced: swapping two variables
  12. Practice questions (8)
  13. 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

JavaScript
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.14159
  • let is 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. Write let only 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:
JavaScript
const pi = 3.14159;pi = 3;   // TypeError: Assignment to constant variable.
Which one to use

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 (2nd is not allowed, second is fine).
  • Names are case-sensitive: total and Total are different boxes.
  • You cannot use reserved words. These are words that already have a meaning in JavaScript, such as let, if and for.
  • The usual JavaScript style is camelCase: the first word is small and each new word starts with a capital letter, like maxValue or studentCount. Short names like i, n and sum are 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):

JavaScript
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
TypeExamplesUsed in DSA for
number0, -4, 3.14Counts, sums, positions, answers
string"abc", 'hello'Text problems: palindromes, anagrams
booleantrue, falseYes/no answers: “is it sorted?”, “found it?”
undefineda box that was made but has nothing put in itSpotting bugs: you read something that was never set
nullnull“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:

JavaScript
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:

JavaScript
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
Dry run · 17 ÷ 5 like at school
QuestionExpressionAnswer
How many whole 5s fit in 17?Math.floor(17 / 5)3
What is left over?17 % 52
Check: 3 × 5 + 215 + 217 ✓
Remember these three lines
  • n % 2 === 0 means n is even (Lesson 3).
  • n % 10 gives 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:

JavaScript
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 ** 10
floor vs trunc for negative numbers

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

JavaScript
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 = 5

Be careful. If either side of + is a string, JavaScript joins instead of adding. It works from left to right, one + at a time:

JavaScript
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 first
Why this matters in real code

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

JavaScript
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));  // string

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

JavaScript
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); // 24

Traced: 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:

step 1 / 7
Set up
Start

No boxes exist yet.

▶let a = 5;2let b = 9;3let temp = a;4a = b;5b = temp;6console.log(a, b);
Variables
— none yet —
Console
(nothing printed yet)
The highlighted row in Variables is the box that just changed. temp exists only to remember a's old value. · interactive

Practice questions

Q1Area and perimeter of a rectangleEasy

Given a length and a width, print the area (length × width) and the perimeter (2 × (length + width)).

Example 1
Input: length = 5, width = 3
Output:
Area: 15
Perimeter: 16
Explanation: Area = 5 × 3 = 15. Perimeter = 2 × (5 + 3) = 2 × 8 = 16.
Example 2
Input: length = 10, width = 10
Output:
Area: 100
Perimeter: 40
Explanation: Area = 10 × 10 = 100. Perimeter = 2 × (10 + 10) = 40.
Stuck? Open one hint at a time
Hint 1
Store the length and the width in two variables first.
Hint 2
Area is length * width. Perimeter is 2 * (length + width) — keep the brackets.
Show all 3 solutions with explanations
Approach 1A variable for each result
The idea
  1. Store the inputs in two variables, length and width.
  2. Calculate area and perimeter into their own variables.
  3. Print both.
JavaScript
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: 16
How it works

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

Approach 2Calculate inside console.log
The idea

Skip the result variables and put the calculations straight into the print statements.

JavaScript
const length = 5;const width = 3;console.log("Area:", length * width);             // Area: 15console.log("Perimeter:", 2 * (length + width));  // Perimeter: 16
How it works

JavaScript calculates the expression first, then prints the result. The code is shorter, but you cannot reuse the results later.

Approach 3Build the text with a template literal
The idea

A template literal is text between backticks. Use ${…} inside it to place values in a sentence.

JavaScript
const length = 5;const width = 3;console.log(`Area: ${length * width}, Perimeter: ${2 * (length + width)}`);// Area: 15, Perimeter: 16
How it works

JavaScript calculates everything inside ${ } and puts the result into the text. This is the clearest way to print a sentence that contains several values.

Which approach should you use?

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.

Q2Swap two numbersEasy

Swap the values of a and b, then print them.

Example 1
Input: a = 5, b = 9
Output: a = 9 b = 5
Explanation: After the swap, a holds the value b had (9) and b holds the value a had (5).
Example 2
Input: a = -1, b = 0
Output: a = 0 b = -1
Explanation: The same exchange works for any two numbers, including negatives and zero.
Stuck? Open one hint at a time
Hint 1
Try a = b; b = a; on paper. What is in b at the end, and why?
Hint 2
Before you overwrite a, its value has to be saved somewhere.
Hint 3
Use a third variable: temp = a, then a = b, then b = temp.
Show all 3 solutions with explanations
Approach 1A temporary variable
The idea
  1. Copy a into a spare variable, temp.
  2. Copy b into a. The old value of a is gone from a, but temp still has it.
  3. Copy temp into b.
JavaScript
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
How it works
Dry run · a = 5, b = 9
Lineabtemp
temp = a595
a = b995
b = temp955
Approach 2Array destructuring
The idea

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

JavaScript
let a = 5;let b = 9;[a, b] = [b, a];console.log("a =", a, "b =", b); // a = 9 b = 5
How it works

The 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.)

Approach 3Arithmetic, without a third variable
The idea

Store the sum in a. Then get each original value back by subtracting.

JavaScript
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 = 5
How it works

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

Which approach should you use?

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.

Q3Minutes to hours and minutesEasy

Convert a number of minutes into hours and remaining minutes.

Example 1
Input: 135
Output: 2 hours 15 minutes
Explanation: Two whole hours are 120 minutes. 135 − 120 leaves 15 minutes.
Example 2
Input: 60
Output: 1 hours 0 minutes
Explanation: Exactly one hour, with nothing left over.
Example 3
Input: 45
Output: 0 hours 45 minutes
Explanation: Less than an hour: zero whole hours, and all 45 minutes are left over.
Stuck? Open one hint at a time
Hint 1
How many whole groups of 60 fit into the number? That is the number of hours.
Hint 2
Math.floor(total / 60) gives the whole groups. What gives the amount left over?
Show all 2 solutions with explanations
Approach 1Math.floor and %
The idea
  1. Hours = how many whole 60s fit: Math.floor(total / 60).
  2. Minutes = what is left over: total % 60.
JavaScript
const total = 135;const hours = Math.floor(total / 60); // 2const minutes = total % 60;           // 15console.log(hours + " hours " + minutes + " minutes"); // 2 hours 15 minutes
How it works
Dry run · total = 135
StepValue
135 / 602.25
Math.floor(2.25) → hours2
135 % 60 → minutes15
Approach 2Math.floor, then subtract
The idea

After finding the hours, subtract the minutes that those hours use up. What remains is the minutes.

JavaScript
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 minutes
How it works

This gives the same answer as %. It also shows what the remainder really means: the part that did not fit into a whole hour.

Which approach should you use?

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.

Q4Last digit, and the number without itEasy

Given a positive whole number, print its last digit and the number with the last digit removed.

Example 1
Input: 4729
Output:
Last digit: 9
Rest: 472
Explanation: 4729 ÷ 10 = 472 remainder 9. The remainder is the last digit. The whole part is the rest of the number.
Example 2
Input: 50
Output:
Last digit: 0
Rest: 5
Explanation: 50 ÷ 10 = 5 remainder 0.
Stuck? Open one hint at a time
Hint 1
Think about dividing by 10. What happens to each digit?
Hint 2
The remainder of dividing by 10 is the last digit. The whole part of the division is the rest.
Show all 3 solutions with explanations
Approach 1% 10 and Math.floor(n / 10)
The idea
  1. n % 10 is the remainder after dividing by 10, which is the last digit.
  2. Math.floor(n / 10) removes the last digit.
JavaScript
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: 472
How it works

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

Approach 2Subtract the last digit, then divide
The idea

Once you know the last digit, subtracting it leaves a number ending in 0, which divides by 10 exactly.

JavaScript
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: 472
How it works

4729 − 9 = 4720, and 4720 / 10 = 472 exactly, so no rounding is needed.

Approach 3Treat the number as text
The idea

Turn the number into a string (text) with String(n), then take its last character.

JavaScript
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: 472
How it works

s[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.

Which approach should you use?

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.

Q5Sum of the digits of a 3-digit numberEasy

Find the sum of the digits of a three-digit number.

Example 1
Input: 472
Output: 13
Explanation: The digits are 4, 7 and 2. 4 + 7 + 2 = 13.
Example 2
Input: 905
Output: 14
Explanation: 9 + 0 + 5 = 14.
Stuck? Open one hint at a time
Hint 1
You already know how to get the last digit (n % 10) and remove it (Math.floor(n / 10)).
Hint 2
Do “add the last digit, then remove it” three times.
Show all 3 solutions with explanations
Approach 1Take the last digit three times
The idea

Add the last digit to a running total, remove that digit, and repeat until all three digits are used.

JavaScript
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
How it works
Dry run · n = 472
Linenn % 10sum
start472—0
sum += n % 1047222
n = floor(n/10)47—2
sum += n % 104779
n = floor(n/10)4—9
sum += n % 104413
Approach 2Calculate each digit directly
The idea
  1. Hundreds digit: Math.floor(n / 100).
  2. Tens digit: Math.floor(n / 10) % 10.
  3. Ones digit: n % 10.
JavaScript
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); // 13
How it works

Each digit has its own formula, so the original number is never changed. This works only because we know the number has exactly three digits.

Approach 3Read the digits as text
The idea

Convert the number to a string, then turn each character back into a number.

JavaScript
const s = String(472);   // "472"const sum = Number(s[0]) + Number(s[1]) + Number(s[2]);console.log(sum); // 13
How it works

s[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.

Which approach should you use?

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.

Q6Predict the + resultsEasy

Predict each output before running:

JavaScript
console.log("5" + 3);console.log("5" - 3);console.log(5 + 3 + "5");console.log("5" + 3 + 5);
Example 1
Input: console.log("5" + 3);
Output: 53
Explanation: One side is text, so + joins: "5" and "3" become "53".
Example 2
Input: console.log(5 + 3 + "5");
Output: 85
Explanation: JavaScript works left to right: 5 + 3 = 8 first (two numbers), then 8 + "5" joins to "85".
Stuck? Open one hint at a time
Hint 1
Work from left to right, one + at a time.
Hint 2
At each +, ask: is either side text? If yes, it joins. If both are numbers, it adds. - always subtracts.
Show all 2 solutions with explanations
Approach 1Apply the rule one + at a time
The idea

Work out each expression from left to right. At every step, decide whether + adds or joins.

JavaScript
console.log("5" + 3);     // 53console.log("5" - 3);     // 2console.log(5 + 3 + "5"); // 85console.log("5" + 3 + 5); // 535
How it works
Dry run · four expressions
ExpressionStep 1Step 2Result
"5" + 3text + number → join—53
"5" - 3- only subtracts: 5 - 3—2
5 + 3 + "5"5 + 3 = 88 + "5" → join85
"5" + 3 + 5"5" + 3 = "53""53" + 5 → join535
Approach 2Convert the text first
The idea

If you want maths, turn the text into a number with Number() before using +.

JavaScript
console.log(Number("5") + 3);     // 8console.log(5 + 3 + Number("5")); // 13
How it works

With every value a number, + always adds. This is how you avoid the problem in real code, where input often arrives as text.

Q7Average of three numbersEasy

Print the average of three numbers (the total divided by how many numbers there are).

Example 1
Input: 4, 8, 9
Output: 7
Explanation: 4 + 8 + 9 = 21, and 21 / 3 = 7.
Example 2
Input: 1, 2, 2
Output: 1.6666666666666667
Explanation: 1 + 2 + 2 = 5, and 5 / 3 is not a whole number, so the decimal part is kept.
Stuck? Open one hint at a time
Hint 1
The average is the total divided by how many numbers there are.
Hint 2
Add first, then divide. Use brackets so the division happens last.
Show all 2 solutions with explanations
Approach 1Add, then divide
The idea

Add the three numbers inside brackets, then divide by 3.

JavaScript
const a = 4, b = 8, c = 9;const average = (a + b + c) / 3;console.log(average); // 7
How it works

Without the brackets, a + b + c / 3 divides only c by 3, because division happens before addition. That gives 15 instead of 7.

Approach 2Keep a separate total
The idea

Store the total in its own variable first. Then the division is easy to read.

JavaScript
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 text
How it works

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

Which approach should you use?

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.

Q8Seconds to hours, minutes and secondsMedium

Convert a number of seconds into hours, minutes and seconds.

Example 1
Input: 3725
Output: 1h 2m 5s
Explanation: One hour is 3600 seconds, leaving 125. 125 seconds is 2 minutes (120) and 5 seconds.
Example 2
Input: 59
Output: 0h 0m 59s
Explanation: Less than a minute: no whole hours, no whole minutes, 59 seconds.
Stuck? Open one hint at a time
Hint 1
Start with the biggest unit. How many whole hours (3600 seconds each) fit into the total?
Hint 2
Find how many seconds are left after the hours. From those, take out the whole minutes (60 seconds each).
Hint 3
Whatever is left after the minutes is the seconds.
Show all 2 solutions with explanations
Approach 1Math.floor and % twice
The idea
  1. Hours = Math.floor(total / 3600). Seconds left = total % 3600.
  2. Minutes = Math.floor(left / 60). Seconds = left % 60.
JavaScript
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
How it works
Dry run · total = 3725
VariableHowValue
hoursMath.floor(3725 / 3600)1
afterHours3725 % 3600125
minutesMath.floor(125 / 60)2
seconds125 % 605
Approach 2Convert everything to minutes first
The idea
  1. Total minutes = Math.floor(total / 60). Seconds = total % 60.
  2. Hours = Math.floor(totalMinutes / 60). Minutes = totalMinutes % 60.
JavaScript
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 5s
How it works

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

Which approach should you use?

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

Make it stick — close this page, then
  1. Write from memory: how to get the last digit of n, and n without its last digit.
  2. Without running it, say what 1 + 2 + "3" and "1" + 2 + 3 print, and why they differ.
  3. 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