A Quick Tour of JavaScript, Part 1: Values, Variables, Objects, Arrays and Operators
A fast, hands-on first pass through JavaScript: let and const, numbers, strings, booleans, null and undefined, objects and arrays, optional chaining, arithmetic, comparison and logical operators, and the === vs == question, all with runnable examples you can change.
kvi5hnuCode Sprout team member7 min readOn this page
This article and the next one take you on a quick tour of the whole language. The goal is not to explain everything (the rest of the course does that) but to give you a working picture, so that later chapters have something to hang on. Every example is runnable: press Run, then change something and run it again.
We'll use one small theme throughout: a music playlist.
Variables and values
A variable is a name for a value. Declare one with let if you'll reassign it later, or with const if you won't:
let plays = 0; // a variable we will change
plays = plays + 1; // reassign it
plays += 1; // shorter form of the same thing
const title = "Blue in Green"; // a constant: it can't be reassigned
console.log(plays);
console.log(title);
try {
title = "Something else"; // not allowed
} catch (err) {
console.log(err.name + ": " + err.message);
}
2
Blue in Green
TypeError: Assignment to constant variable.
Use const by default and let when the value must change. That makes code easier to read: when you see const, you know the name keeps the same value everywhere. You'll also see the older keyword var in existing code. It behaves differently in subtle ways (part 3 explains them), and modern code avoids it.
JavaScript variables have no fixed type. The value has a type, and the same variable may hold different types over time:
let value; // declared but not assigned yet
console.log(typeof value, value);
value = 42; console.log(typeof value, value); // integers...
value = 3.75; console.log(typeof value, value); // ...and fractions are both "number"
value = "jazz"; console.log(typeof value, value); // text in double quotes
value = 'jazz'; console.log(typeof value, value); // or single quotes
value = `${2 + 2} beats`; console.log(typeof value, value); // or backticks, with ${} inside
value = true; console.log(typeof value, value); // true or false
value = null; console.log(typeof value, value); // "intentionally empty"
value = 10n ** 20n; console.log(typeof value, value); // whole numbers of any size
undefined undefined
number 42
number 3.75
string jazz
string jazz
string 4 beats
boolean true
object null
bigint 100000000000000000000n
A few things to notice already:
- There's a single
numbertype for both integers and fractions. Very large whole numbers needbigint, written with annsuffix. undefinedmeans "no value assigned yet";nullmeans "deliberately empty". Thetypeof nullresult,"object", is a famous mistake from 1995 that can never be fixed without breaking old code.- Backtick strings, called template literals, insert the value of any expression between
${and}.
Objects: named values grouped together
An object groups related values, called properties, under names:
const song = {
title: "So What",
artist: "Miles Davis",
seconds: 562,
liked: false,
};
console.log(song.title); // dot notation
console.log(song["artist"]); // bracket notation, with a string
song.liked = true; // change a property
song.genre = "jazz"; // add a new one
delete song.seconds; // remove one
const key = "genre";
console.log(song[key]); // brackets accept any expression
console.log(song);
console.log(song.album); // a missing property is undefined, not an error
So What
Miles Davis
jazz
{ title: 'So What', artist: 'Miles Davis', liked: true, genre: 'jazz' }
undefined
Notice that song is declared with const, yet we changed its properties. const stops you from making song refer to a different object; it doesn't freeze the object itself. Part 6 covers objects in depth, including how to freeze one.
Reading a property of undefined or null is an error, and that's one of the most common crashes in JavaScript. The optional chaining operator ?. stops early instead of crashing:
const track = { title: "Freddie Freeloader", stats: { plays: 12 } };
const other = { title: "Flamenco Sketches" }; // no stats object
console.log(track.stats.plays); // 12
console.log(other.stats?.plays); // undefined: stops at the missing stats
console.log(other.stats?.plays ?? 0); // ?? supplies a default for null/undefined
try {
console.log(other.stats.plays); // no ?. here
} catch (err) {
console.log(err.name + ": " + err.message);
}
12
undefined
0
TypeError: Cannot read properties of undefined (reading 'plays')
The ?? operator, nullish coalescing, gives the right-hand value when the left side is null or undefined. The two operators work well together.
Values and references
Primitive values (numbers, strings, booleans) are copied when you assign them. Objects aren't: a variable holds a reference to the object, so assigning it to another variable gives you two names for the same object.

let a = 5;
let b = a; // copies the number
b = 6;
console.log(a, b);
const original = { x: 1 };
const alias = original; // copies the reference: same object
alias.x = 2;
console.log(original.x, original === alias);
const copy = { ...original }; // a new object with the same properties
copy.x = 3;
console.log(original.x, copy.x, original === copy);
5 6
2 true
2 3 false
=== on objects compares references: two separate objects are never equal, even with identical contents. To get an independent copy, create a new object, for example with spread syntax { ...original }. That copy is shallow; article 21 covers copying and comparing in depth.
Arrays: ordered lists
An array is an ordered list of values, numbered from 0:
const playlist = ["So What", "Blue in Green", "All Blues"];
console.log(playlist[0]); // first element
console.log(playlist.length); // how many
console.log(playlist[playlist.length - 1]); // last element
console.log(playlist.at(-1)); // also the last element (ES2022)
playlist.push("Flamenco Sketches"); // add at the end
playlist[1] = "Blue in Green (take 2)"; // replace an element
console.log(playlist);
console.log(playlist.includes("All Blues")); // is it there?
console.log(playlist.indexOf("All Blues")); // where is it?
console.log(playlist[10]); // past the end: undefined
So What
3
All Blues
All Blues
[
'So What',
'Blue in Green (take 2)',
'All Blues',
'Flamenco Sketches'
]
true
2
undefined
Arrays and objects can contain each other, which is how real data usually looks:
const library = {
owner: "Ravi",
albums: [
{ name: "Kind of Blue", year: 1959, tracks: ["So What", "Blue in Green"] },
{ name: "Time Out", year: 1959, tracks: ["Take Five"] },
],
};
console.log(library.albums.length);
console.log(library.albums[1].name);
console.log(library.albums[0].tracks[1]);
console.log(library.albums.map(album => album.name).join(" / "));
2
Time Out
Blue in Green
Kind of Blue / Time Out
The last line is a preview of array methods: map builds a new array by applying a function to each element, and join glues the elements into one string. Part 7 covers dozens of these methods.
Operators
Operators combine values into new values. Arithmetic works as you'd expect, with one twist: + also joins strings.
console.log(7 + 2, 7 - 2, 7 * 2, 7 / 2); // division gives fractions
console.log(7 % 2); // remainder
console.log(2 ** 10); // exponent
console.log(0.1 + 0.2); // floating point: not exactly 0.3!
console.log("7" + 2); // + with a string joins: "72"
console.log("7" - 2); // - converts to numbers: 5
console.log(1 / 0, -1 / 0, 0 / 0); // no exception: Infinity and NaN
let count = 5;
count++; // add 1
count *= 2; // multiply and assign
console.log(count);
9 5 14 3.5
1
1024
0.30000000000000004
72
5
Infinity -Infinity NaN
12
0.1 + 0.2 is not exactly 0.3 because numbers are stored in binary floating point, as in most languages. NaN means "not a number" and is what you get from undefined math such as 0 / 0. Both are explained in part 3.
Comparison operators produce true or false:
const minutes = 9;
console.log(minutes > 5, minutes <= 5);
console.log(minutes === 9, minutes !== 9);
console.log("apple" < "banana"); // strings compare alphabetically (by code unit)
console.log("Zebra" < "apple"); // uppercase letters sort before lowercase!
console.log(9 === "9"); // strict equality: different types, so false
console.log(9 == "9"); // loose equality converts first: true
console.log(null == undefined, null === undefined);
console.log(NaN === NaN); // NaN is not equal to anything, even itself
true false
true false
true
true
false
true
true false
false
Logical operators combine conditions: && (and), || (or) and ! (not).
const plays = 12, liked = true;
console.log(plays > 10 && liked); // both true
console.log(plays > 100 || liked); // at least one true
console.log(!liked);
// && and || return one of their operands, not just true/false:
console.log("" || "untitled"); // "" counts as false, so the right side wins
console.log(0 ?? 5, 0 || 5); // ?? only replaces null/undefined; || replaces any falsy value
true
true
false
untitled
0 5
That last line matters in real code: count || 5 turns a legitimate count of 0 into 5, while count ?? 5 keeps the 0. Values that act like false in conditions are called falsy: false, 0, -0, 0n, "", null, undefined and NaN. Everything else, including "0", [] and {}, is truthy.
Common questions
Should I use semicolons?
JavaScript inserts missing semicolons automatically in most places, so many codebases omit them, and many others write them everywhere. Both work. There are a few traps either way, which article 8 explains. This course writes semicolons. Pick one style and let a formatter like Prettier enforce it.
Single quotes, double quotes or backticks?
All three create strings. Single and double quotes are identical; pick one and stay consistent (a formatter will do it for you). Use backticks when you need ${} interpolation or a string spanning several lines.
Why does console.log show strings with quotes in one place and without in another?
When you log a string directly, console.log("jazz"), it prints the text: jazz. When the string is inside an object or array, Node shows it in quotes so you can tell '42' from 42. Browsers do the same.
If const objects can be changed, what's the point of const?
It protects the binding: the name will always refer to the same object. That rules out a whole class of bugs where a variable is accidentally reassigned, and it tells readers they don't have to look for reassignments. To prevent changes inside an object, use Object.freeze (part 6) or immutable patterns (part 7).
Summary
- Declare variables with
constby default andletwhen they change. Values, not variables, have types:number,bigint,string,boolean,undefined,null,symbolandobject. - Objects map names to values:
obj.nameorobj["name"]. Missing properties areundefined. Use?.to read safely through possibly missing objects and??for defaults. - Arrays are ordered and zero-indexed, with
length,push,at,includesand many more methods. +adds numbers but joins strings. Floating-point results can be slightly off (0.1 + 0.2).- Compare with
===/!==.&&,||and??return one of their operands, and??differs from||for0and"".
Practice Questions
What does console.log(typeof typeof 42) print?
Answer
string. typeof 42 is the string "number", and the typeof of any string is "string".
Does this throw?
const scores = [90, 75];
scores.push(60);
Answer
No. push changes the array's contents, which const allows. Only scores = [...] (reassigning the name) would throw a TypeError.
What do "3" + 4 + 5 and 3 + 4 + "5" evaluate to?
Answer
"345" and "75". + works left to right. In the first, "3" + 4 is the string "34", and then "34" + 5 is "345". In the second, 3 + 4 is the number 7, then 7 + "5" is "75".
A function receives volume, which may be 0. Why is volume || 50 a bug, and what should you write?
Answer
0 is falsy, so volume || 50 replaces a deliberate volume of 0 with 50. Write volume ?? 50, which only falls back when volume is null or undefined.
What does user.address?.city evaluate to when user is { name: "Ana" }, and what about when user itself is undefined?
Answer
For { name: "Ana" }, user.address is undefined, so ?. stops and the result is undefined. If user is undefined, user.address throws a TypeError before ?. is reached; you'd need user?.address?.city.
Previous: Running JavaScript: Browser DevTools Console, Node.js REPL and Script Files
Next: A Quick Tour of JavaScript, Part 2: Functions, Control Flow and Classes

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.