Learn JavaScript from Scratch, Part 2: Variables and Data Types

Learn JavaScript from Scratch, Part 2: Variables and Data Types - CodingHumans

JavaScript variables are how your program remembers things: a user's name, a score, whether a menu is open. In this part you'll learn how to create variables with let and const, which data types JavaScript has, and the classic beginner traps like null vs undefined.

This is Part 2 of Learn JavaScript from Scratch, continuing from Part 1.

1. What a variable is

A variable is a named box for a value. You create it once, put something inside, and use the name everywhere else:

let score = 0;        // create a box called score, put 0 in it
score = score + 10;   // take the value out, add 10, put it back
console.log(score);   // 10

Names matter. score, userName and isMenuOpen explain themselves; x and temp2 don't. JavaScript names use camelCase, can't start with a digit, and are case-sensitive: Name and name are two different variables.

2. let, const and var

There are three keywords that create variables. You only need two of them:

KeywordCan be reassigned?When to use
constNoDefault. Most values never change after creation
letYesCounters, flags, anything that will be reassigned
varYesDon't use it. The old pre-2015 way with confusing scoping rules (we'll see exactly why in Part 13)
const name = "CodingHumans";
name = "Sita";        // TypeError: Assignment to constant variable

let count = 1;
count = 2;            // fine
Rule of thumb: write const first. If the code later needs to reassign it, change it to let. You'll be surprised how rarely that happens.

One subtlety: const means the box can't be re-pointed, not that the value is frozen. A const array can still have items pushed into it — more on that in Part 6.

3. The 7 data types you actually need

TypeExampleUsed for
string"hello", 'hi', `hi ${name}`Text
number42, 3.14, -7All numbers — there is no separate integer type
booleantrue, falseYes/no answers
undefinedlet a;"No value was ever put here"
nulllet user = null;"Intentionally empty"
object{ name: "CodingHumans" }, arraysCollections of values (Parts 6–7)
function() => {}Reusable code (Part 5)

(For completeness: bigint and symbol also exist, but you can learn JavaScript for months before needing them.)

Strings deserve two quick notes. First, single and double quotes are identical — pick one style and stay consistent. Second, backticks make template literals, the modern way to build text from variables:

const user = "CodingHumans";
console.log("Hello, " + user + "!");   // old way
console.log(`Hello, ${user}!`);        // template literal - same result, easier to read

4. Dynamic typing and typeof

In Java or C you declare what type a variable holds. JavaScript is dynamically typed: the variable is just a box, and the value carries the type. The same box can hold a number now and a string later (allowed, but usually a bad idea):

let data = 42;
console.log(typeof data);   // "number"
data = "forty-two";
console.log(typeof data);   // "string"

typeof tells you the type of a value. Two famous quirks to memorise, because interviewers love them:

typeof null          // "object"  - a 30-year-old bug kept for compatibility
typeof undefined     // "undefined"
typeof [1, 2, 3]     // "object"  - arrays are objects (use Array.isArray instead)

5. null vs undefined

Both mean "nothing here", and the difference is who put the nothing there:

  • undefined — JavaScript's own "nothing yet": a declared variable with no value, a missing function argument, an object property that doesn't exist.
  • null — your deliberate "empty on purpose": you assign it yourself to say "there is no user right now".
let user;              // undefined - never assigned
let selected = null;   // null - you chose "nothing selected"
console.log(user == null);   // true  (== treats them as equal)
console.log(user === null);  // false (=== does not - Part 3 explains)

6. Common mistakes (and the interview note)

  • Using a variable before creating it → ReferenceError. Declare first, use after.
  • Forgetting quotes: let city = Delhi; looks for a variable called Delhi. Text needs quotes: "Delhi".
  • Reassigning a const → TypeError. If it must change, it should have been let.
  • Expecting precise decimals: 0.1 + 0.2 is 0.30000000000000004. All languages with binary floating point do this; compare with a tolerance or work in paise/cents.
Interview note: "Difference between let, const and var?" and "null vs undefined?" are two of the most common first-round JavaScript questions. The tables above are exactly the answers they're looking for — plus hoisting, which we'll add in Part 13.

Practice: test what you learned

Q1. Which keyword should be your default for creating variables in modern JavaScript?

a) var, because it works everywhere

b) const, switching to let only when you need to reassign

c) let, switching to const only for maths constants

d) No keyword - just write the name

Q2. What does typeof null return?

a) "null"

b) "undefined"

c) "object"

d) "empty"

Q3. let a; - what is the value of a?

a) undefined

b) null

c) 0

d) An error is thrown

Q4. Which line creates valid text in a variable?

a) let city = Delhi;

b) let city = (Delhi);

c) let 2city = "Delhi";

d) let city = "Delhi";

Q5. What does `Hi ${name}` (with backticks) do, if name is "Asha"?

a) Prints the literal text Hi ${name}

b) Creates the string "Hi Asha" - backticks allow ${} placeholders

c) Throws a syntax error

d) Creates an array of two strings

Q6. What happens here? const x = 5; x = 6;

a) x becomes 6

b) x stays 5 and the line is skipped

c) A TypeError: assignment to constant variable

d) x becomes "6"

FAQ

Should I ever use var?

In new code, no. var exists so that 20 years of old websites keep working. let and const do everything var does, with saner scoping rules - Part 13 shows exactly what var does differently and why it causes bugs.

Does JavaScript have integers and floats like other languages?

No - there is one number type (a 64-bit float) used for both 7 and 7.5. For whole numbers bigger than about 9 quadrillion there is BigInt, which you will rarely need as a beginner.

Why does 0.1 + 0.2 not equal 0.3 exactly?

Computers store numbers in binary, and 0.1 and 0.2 have no exact binary form - like 1/3 has no exact decimal form. The tiny error is normal in nearly every language; handle money in whole paise/cents.

Is a const object really constant?

const only locks which object the name points to. The object's own contents can still change - you can push into a const array. To freeze contents you would use Object.freeze, which we meet later.

Learning with others? Join the CodingHumans WhatsApp community to get each new part of Learn JavaScript as soon as it goes live.

Comments

Answered 0/0Correct 0