Values, Variables, and Types
Table of Contents
- Values and Variables
- const and let
- Why Not var
- The Primitive Types
- Strings and Template Strings
- typeof, null, and undefined
- Coercion Pitfalls
- Try It Yourself
1. Values and Variables
A value is a piece of data: the number 42, the text "Dara", the
answer true. A variable is a name that points to a value, so you can
use it again later. Think of a labeled box: the label is the name, and
what is inside is the value.
Create a file js/values.js and run it with node js/values.js as you
read. Here is the whole idea in three lines:
const name = "Dara Sok";
const age = 22;
console.log(name, age);
This prints Dara Sok 22. The word const creates the variable, name is its
label, = stores the value on its right into the name on its left, and
; ends the statement. The = sign here is assignment, not "equals"
as in mathematics.
Variable names can contain letters, digits, _ and $, but cannot start
with a digit and cannot be a reserved word like const. By convention, JavaScript
uses camelCase: firstName, projectCount. Names are case-sensitive,
so age and Age are different variables.
2. const and let
JavaScript has two modern ways to create a variable:
| Keyword | Can be reassigned? | Use it for |
|---|---|---|
const | No | Values that do not change (most of your variables) |
let | Yes | Values that must change later |
const city = "Phnom Penh";
let projectCount = 3;
projectCount = 4; // fine: let can change
console.log(projectCount); // 4
city = "Siem Reap"; // TypeError: Assignment to constant variable.
Run this and the last line stops the program with a TypeError. That is
useful: the error tells you that you tried to change something that was
meant to stay fixed.
A good habit: start with const, and switch to let only when you
find that the value must change. Code is easier to read when most names
never change.
Note that const stops reassignment, not every kind of change. When a
const points to an array or object, you can still change what is inside
it. Chapter 6 explains this.
3. Why Not var
Older code uses a third keyword, var. You will see it in old tutorials,
so you should recognize it, but you should not write it. It has surprising
behavior:
if (true) {
var leaked = "I am visible outside the block";
}
console.log(leaked); // works, which is surprising
if (true) {
let contained = "I stay inside the block";
}
console.log(contained); // ReferenceError: contained is not defined
var ignores the curly braces { } of a block, so a variable can
"leak" out to code that should not see it. let and const are block
scoped: they exist only inside the { } where you made them. Chapter 5
covers scope in more detail. The rule for this series is simple: use
const and let, never var.
4. The Primitive Types
Every value has a type. The simplest types are called primitives: single, unchangeable values.
| Type | Example | Meaning |
|---|---|---|
string | "Dara" | Text |
number | 42, 3.14 | Any number, whole or decimal |
boolean | true, false | Yes or no |
null | null | "Nothing here", set on purpose |
undefined | undefined | "No value has been given yet" |
bigint | 9007199254740993n | Whole numbers too large for number |
symbol | Symbol("id") | A unique identifier (rarely needed by beginners) |
You will use the first five constantly. bigint is for very large
integers; you write it with a trailing n. symbol is used mostly by
libraries, so you can skip it for now.
JavaScript has only one type for ordinary numbers. Whole numbers and
decimals are both number, so there is no separate "integer" type to
choose.
Values that are not primitives are objects, such as arrays and records. They get their own chapter (chapter 6).
5. Strings and Template Strings
A string is text inside quotes. This series uses double quotes:
const greeting = "Hello";
const length = greeting.length; // 5
const loud = greeting.toUpperCase(); // "HELLO"
console.log(length, loud);
To combine text with values, you can use +:
const firstName = "Dara";
const projects = 3;
console.log("Hi, " + firstName + "! You have " + projects + " projects.");
This works, but becomes hard to read quickly. A template string is
easier. It uses backticks (`, usually the key left of 1) and puts
variables inside ${ }:
console.log(`Hi, ${firstName}! You have ${projects} projects.`);
Both lines print Hi, Dara! You have 3 projects. You can put any
expression inside ${ }, such as ${projects + 1}. Template strings can
also span several lines, which is helpful later for building HTML.
6. typeof, null, and undefined
The typeof operator tells you the type of a value:
console.log(typeof "Dara"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof 10n); // "bigint"
console.log(typeof null); // "object" <-- a famous mistake
That last line is a bug from the first version of JavaScript in 1995. It
cannot be fixed now without breaking old websites. Remember that null
is not an object, even though typeof says so.
null and undefined both mean "no value", but they are used differently:
undefinedis what JavaScript gives you when a value is missing. A variable declared without a value, a missing object property, and a function that returns nothing all giveundefined.nullis what you write when you want to say "there is deliberately nothing here".
let nickname;
console.log(nickname); // undefined: no value assigned yet
nickname = null;
console.log(nickname); // null: we decided there is no nickname
A simple rule: let JavaScript produce undefined, and use null only
when you choose to show an empty value.
7. Coercion Pitfalls
JavaScript will sometimes convert a value from one type to another to make an operation work. This is called coercion. It is convenient but can produce surprises. Know these four:
1. The + operator joins text if either side is a string.
console.log("5" + 1); // "51" (text, not 6)
console.log("5" - 1); // 4 (minus converts "5" to a number)
2. Decimal arithmetic is not exact. Computers store decimals in binary, and some values cannot be stored exactly. This is true in almost every language, not only JavaScript:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
For money, many developers store whole cents (1999 for $19.99) and
convert at the end.
3. NaN means "Not a Number". You get it when a calculation makes no
sense. Its type is still number, and it is not equal even to itself:
const result = Number("hello");
console.log(result); // NaN
console.log(typeof result); // "number"
console.log(result === NaN); // false
console.log(Number.isNaN(result)); // true <-- the right way to check
4. Convert on purpose, not by accident. Use these functions instead of relying on coercion:
console.log(Number("42")); // 42
console.log(Number("")); // 0
console.log(parseInt("42px")); // 42
console.log(String(42)); // "42"
console.log(Boolean("")); // false
Use Number() when the whole text should be a number, and parseInt() when
the number is at the start of other text. When data comes from a form
field, it is always a string, so convert it before doing arithmetic.
8. Try It Yourself
- Declare and print. In
js/values.js, createconstvariables for your name, your age, and whether you are a student (a boolean). Print all three with oneconsole.log. - Meet the error. Declare
const country = "Cambodia";and try to assign a new value to it. Read the error. Then changeconsttoletand see that the error goes away. - Use a template string. Build the sentence
Dara Sok lives in Phnom Penh and has 3 projects.from three variables using one template string, then do it again with+and compare. - Check the types. Print
typeoffor"7",7,7n,null,undefined, and[]. Which results surprise you? - Predict, then run. Without running it, guess the output of
"3" + 4,"3" * 4,true + 1, andNumber("12abc"). Run them and explain each answer. - Fix the decimal problem. Show that
0.1 + 0.2 === 0.3isfalse. Then compareMath.abs(0.1 + 0.2 - 0.3) < Number.EPSILONand explain, in one sentence, what this comparison checks.
Next, we'll make decisions with these values: comparing them, combining conditions, and running different code depending on the result. Continue with Operators and Conditions.
Buy Me a Coffee
Found this tutorial helpful? Consider buying me a coffee to support more free content!