Code / JavaScript from Zero / Unit 1: Values and variables

Numbers and types संख्याएँ और टाइप

Lesson 2 of 15 · about 12 minutes · typeof, maths operators, % and rounding.

⚡ 0 XP

Step 1 of 2

Every value has a type

42number"chai"stringtrueboolean

JavaScript values come in types. The three you will use most:

  • number: 15, 99.5, -3 (no quotes)
  • string (text): "Jaipur", "15" (with quotes)
  • boolean: only true or false

typeof tells you the type: typeof 15 is "number", but typeof "15" is "string"! The quotes make it text. That matters: "15" + 1 gives "151" (text joined), while 15 + 1 gives 16.

Example
console.log(typeof 15);       // number
console.log(typeof "15");     // string
console.log(typeof true);     // boolean
console.log("15" + 1, 15 + 1); // 151 16

🎯 Challenge: Fix the types +10 XP

A student form has three values. Make age a number (fix the quotes), keep city a string, and create isStudent as a boolean. Then print the typeof of each one, one per line.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • age is a number
  • city is a string
  • isStudent is a boolean
  • The console shows number, string and boolean
Lesson notes (text version)

1. Every value has a type

JavaScript values come in types. The three you will use most:

  • number: 15, 99.5, -3 (no quotes)
  • string (text): "Jaipur", "15" (with quotes)
  • boolean: only true or false

typeof tells you the type: typeof 15 is "number", but typeof "15" is "string"! The quotes make it text. That matters: "15" + 1 gives "151" (text joined), while 15 + 1 gives 16.

                console.log(typeof 15);       // number
console.log(typeof "15");     // string
console.log(typeof true);     // boolean
console.log("15" + 1, 15 + 1); // 151 16
              

Challenge: Fix the types

A student form has three values. Make age a number (fix the quotes), keep city a string, and create isStudent as a boolean. Then print the typeof of each one, one per line.

2. Maths, remainder and rounding

JavaScript is a calculator: + add, - subtract, * multiply, / divide.

Two more you will love:

  • % gives the remainder: 17 % 5 is 2 (17 = 5 × 3 + 2)
  • Math.floor(x) rounds down, Math.ceil(x) rounds up, Math.round(x) rounds to the nearest whole number

Example: ₹100 shared by 3 friends. 100 / 3 is 33.333…. Each pays Math.floor(100 / 3) = ₹33, and 100 % 3 = ₹1 is left over.

                console.log(7 / 2);           // 3.5
console.log(7 % 2);           // 1
console.log(Math.floor(3.9)); // 3
console.log(Math.ceil(3.1));  // 4
console.log(Math.round(3.5)); // 4
              

Challenge: Split the dhaba bill

Five friends ate at a dhaba. The bill is ₹1234. Everyone pays whole rupees: set share to the bill divided by friends, rounded down, and set leftover to the rupees that are left (use %). The last line prints Each pays ₹246, leftover ₹4.

Search by task, format or tool name.