JavaScript 1: An Introduction, The Console, Variables, and Data Types
Storing information, checking it, and changing the page
What JavaScript Is
Front-end web development has three layers. You already know two of them. Each layer has one job, and keeping them separate is what makes a site maintainable.
| Layer | Language | Its job |
|---|---|---|
| Structure and content | HTML | What things are: headings, paragraphs, images, forms |
| Presentation | CSS | What things look like: color, type, layout, spacing |
| Behavior | JavaScript | What things do: calculate, respond, change, validate |
JavaScript is written in plain text, so any editor can produce it. Unlike Java or C++, it is never compiled into a separate program file. Every browser contains a JavaScript engine that reads your code and runs it directly, which is why you can save a file and refresh to see the result a second later.
This course uses vanilla JavaScript, which means plain JavaScript with no library or framework added on top. Libraries like React and jQuery are themselves written in JavaScript, so everything here is the foundation they are built on.
Things to Know Before You Write Any
These are the rules to remember, which will help you avoid problems. You do not have to memorize them now, but come back to this list when something is not working, because the answer is often here.
- JavaScript is case sensitive.
firstName,firstname, andFirstNameare three completely different names. This is the single most common source of typos, and the error message will only tell you that something "is not defined." - Code runs top to bottom, one line at a time. A line cannot use a value that a later line creates. Order matters.
- An error stops everything below it. When the script hits a problem it quits on the spot, so the rest of your lines never run. If half your page works and half does not, look for a red message about the line where it stopped.
- Every statement ends with a semicolon. Modern browsers will often guess correctly if you forget, but the guess is sometimes wrong. Type the semicolon.
- Spaces, tabs, and blank lines are ignored. Indent your code however makes it readable; JavaScript does not care. Inside quotes is the exception, where every space you type is part of the text.
- Quotes have to match.
"text"and'text'both work, but"text'does not. Nearly every "unexpected end of input" error is a missing closing quote, bracket, or brace. - Names use camelCase. Start lowercase, capitalize each word after the
first:
firstName,totalPrice,isLoggedIn. No spaces, no dashes, and never start with a number. - Some words are reserved. You cannot name something
let,const,function,class,if,for, orreturn, because JavaScript already uses them. - Comments are ignored by the browser.
//comments out the rest of a line;/* */comments out everything between the markers. Use them for notes, and for switching off a line while you test. - JavaScript is not Java. They are unrelated languages. The name was a marketing decision in 1995 and it has confused people ever since.
- Save, then refresh. Changes do nothing until the file is saved and the browser reloads it. If a change seems to have no effect, check that you saved, or that you are seeing a live view using Live Server or something similar. If it still seems stuck, hold Shift while clicking reload to bypass the browser's cache.
Reading Dot Notation
You will see dots all through JavaScript, starting with your very first line,
console.log(). A dot connects a thing to something that belongs to it. Read
it like an apostrophe-s: console.log is "the console's log."
console.log("Hi"); // the console's log action
document.title // the page's title
Whatever comes after the dot is one of two kinds of thing:
- An action, called a method. It always has parentheses. In
console.log("Hi")the method islog, the action the console can perform, and whatever you put inside the parentheses is what you hand it: here, the text"Hi". - A value, called a property. No parentheses. It is information the
thing holds:
document.titleis the text in the page's title tag.
Dots can also chain, one after another. The pre-written lines that put your results on this page look like this:
document.querySelector("#out-first") // find a box
.textContent = firstName; // set its text
Read it left to right: the page, its search action, the box it finds, and that box's text. In Section 5 you write a line like this yourself.
console log("Hi"),
with a space instead of a dot, is an error that stops the script. Write it as one
unbroken word, console.log, the way every example on this page does.
Old Code vs. Current Practice
JavaScript is thirty years old, and a lot of tutorials online have not aged well. Everything in the left column still runs, so you will meet it in older code. Everything in the right column is what you should write.
| Task | Older approach | What we use |
|---|---|---|
| Test what your code is doing | alert("checking") |
console.log("checking") |
| Create a variable | var total = 0; |
let total = 0; or const |
| Combine text and a variable | "Hi, " + name + "!" |
`Hi, ${name}!` |
- Section 1 is typed in the browser's console, not the file, so you can see the difference between the two.
- Sections 2 to 5 are typed in the file. In the script at the
bottom, find
ENTER SECTION 2 CODE HERE, and so on. Section 2 takes two lines. - The code for each section is in a gold box below it. Type it, save, and refresh. Your result appears on the page under that section.
- Go in order. A mistake in one section stops everything after it.
- The gold-box code is a picture, so you have to type it. That is on purpose: typing is how you learn the punctuation and syntax. The dark code panels are text you can copy.
1. The Console and Your First Line
Opening the browser's message window, and running your first line of JavaScript inside it.
Opening the Console
The console is a message window built into every browser, and you cannot work on JavaScript without it. Open it now and leave it open.
| Browser | How to open it |
|---|---|
| Chrome / Edge, Windows | F12 or Ctrl + Shift + J |
| Chrome / Edge, Mac | Command + Option + J |
| Firefox | F12, or Command + Option + K |
| Safari | Settings → Advanced → Show Develop menu, then Command + Option + C |
| Any browser | Right-click the page, choose Inspect, click the Console tab |
A panel opens with several tabs across the top. Elements shows the live HTML; Console is the one you want.
What the Console Does
- Shows your messages. Anything your script sends with
console.log()appears as a line of plain text. - Shows your errors. Problems appear in red with a file name and line number on the right. Click the line number to jump straight to it.
- Runs a quick test. Click next to the
>symbol, type something, press Enter. Try2 + 2. - Clears on demand. The circle-with-a-slash icon empties it, which makes it obvious which messages came from your latest refresh.
- Your code editor is where your work goes. Every typed line after Section 1 goes into the script at the bottom of the page, then you save and refresh. This is permanent.
- The console prompt is a scratchpad. It runs once and disappears on refresh. It never touches your file.
file:/// instead of
http://, and browsers apply extra security rules to those. A message
about "'file:' URLs are treated as unique security origins" is the browser
describing its own policy, not a mistake in your code.
Where the Script Goes
Your JavaScript can sit inside a <script> tag in the page, or in a
separate .js file. Either way, one rule governs everything: the
script must run after the HTML it touches exists.
The browser reads your page top to bottom. If the script comes first, the elements it
wants have not been built yet, so it finds nothing and reports an error. Putting the
tag just before </body> guarantees the page is finished first.
console.log() appears on the page
itself. That is the point. It is a private channel between you and your code, so you
can leave notes in while you test without a visitor ever seeing them.
// The script tag goes at the bottom of the
// body, after all the HTML it works with.
<script>
console.log("Hello");
</script>
</body>
// Or link to a separate file, which is what a
// real production site would do.
<script src="js/main.js"></script>
</body>
// ----- your first line of JavaScript -----
console.log("Hello from JavaScript!");
// console the browser's message window
// .log( ) prints what is inside the ( )
// "Hello..." text, so it goes inside quotes
// ; marks the end of the instruction
// ----- comments -----
// two slashes hide the rest of this line
/* a slash-star pair hides
everything in between,
across as many lines as you want */
Section 1 Code — in the console this time, not the file
Click in the Console next to the > prompt, type this line, and press Enter:
What each part of this line does:
Your message appears right under what you typed. Now refresh the page and look again: it is gone. The console prompt runs a line once and keeps nothing.
One message does come back every time:
This message comes from the file. You did not type that one. It was
already written in the script at the bottom of this page. Anything saved in the
file runs again on every refresh; anything typed at the console prompt runs once
and is gone. Sections 2 to 5 all go in the file.
2. Variables: let and const
Creating a name that holds a value, and choosing which keyword to create it with.
Naming and Storing Values
A variable is a named container that holds a value so you can use it again later. Instead of typing your course name in nine places, you store it once and refer to the name. Change what is in the container and all nine places update.
Two words you will see constantly: to declare a variable is to
create the name, and to assign is to put a value into it.
const firstName = "Mark"; does both at once.
let favoriteColor; declares without assigning, which is where
undefined comes from.
You create one with either const or let. The difference is
whether the value will ever be replaced.
const
Use const when the value is set once and never reassigned: a name, a tax
rate, a course code. This is your default. Reaching for it first is a habit worth
building, because it lets the browser catch accidental changes for you.
let
Use let when the value genuinely needs to change: a running total, a
click count, a score. You will use it much less often than const.
var
You will see var constantly in older code and older tutorials. It works,
but it has scoping behavior that causes subtle bugs, which is exactly why
let and const replaced it. Recognize it; do not write it.
Scope: Where a Variable Exists
A variable only exists inside the curly braces { } it was created in.
That region is called its scope. Every variable in this file is
written outside any braces, so every line can see every variable, which is why
nothing here has to worry about it yet.
This is also the real reason var was replaced: var ignores
curly braces and leaks out into the surrounding code, while let and
const stay where you put them.
= as "gets," not "equals."
let total = 0; means "total gets zero." The equals sign is an
instruction to store something, not a question about whether two things match.
console.log(firstName) prints what the container holds:
Mark. console.log("firstName") prints the word
firstName, because quotes mean "this is text, take it
literally."
Neither one is an error, so the only clue is that the output looks wrong. When you
want a variable's value, leave the quotes off.
// ----- const: set once, never changed -----
const firstName = "Mark";
// const a value that is never replaced
// firstName the name we picked for it
// = put the value into that name
// "Mark" the value; quotes mean text
const courseName = "GDS 46";
// same idea: text that stays the same all page
// ----- let: a value we may change -----
let gradYear = 2027;
// let a value we may replace later
// 2027 a number, so no quotes around it
gradYear = 2028;
// changing it later needs no let or const,
// because the name already exists
// ----- what const protects you from -----
// firstName = "Sam";
//
// TypeError: Assignment to constant variable.
// The browser refuses. That is the point.
Section 2 Code — in the file, not the console
In your code editor, find ENTER SECTION 2 CODE HERE in the script and type these two lines on the blank lines below it:
What each part of this line does:
Use your own first and last name inside the quotes. Keep the
variable names firstName and lastName spelled exactly as
shown, because later sections use them. Save, refresh, and your values appear in
the box below.
What your variables hold
- firstName
- Waiting for Section 2 code...
- lastName
- Waiting for Section 2 code...
Two lines already written at the bottom of the script copy your values into this box.
3. Data Types and typeof
The four kinds of value you will meet, and how to ask JavaScript which one you have.
What Kind of Value Is This?
Every value in JavaScript has a type. The type decides what you can do with it: you can multiply numbers, but multiplying two pieces of text is meaningless. Four types cover nearly everything you will write.
String
Text, always wrapped in matching quotes. Single or double both work, as long as you
close with the one you opened with. "46" with quotes is a string, not a
number, and that difference will matter shortly.
Number
Any numeric value, whole or decimal, positive or negative. No quotes, and no commas
inside them: write 1000, never 1,000.
Boolean
Exactly two possible values, true and false, written without
quotes. Booleans answer yes-or-no questions: is the user logged in, is the box
checked, is the field empty.
Undefined
What you get when a variable has been declared but never given a value. It is not an
error, just an empty container. Seeing undefined in your console usually
means a value did not arrive where you expected.
let variable can
hold a string one moment and a number the next.
typeof is a diagnostic tool. When something is
misbehaving, logging typeof yourVariable is often the fastest way to
find out why, because the answer is frequently "that is a string, not a number."
// ----- boolean -----
const isEnrolled = true;
// true one of only two boolean values
// note: no quotes, or it would be text
// ----- undefined -----
let favoriteColor;
// the name exists, but nothing is in it,
// so its value right now is undefined
// ----- typeof: ask what something is -----
console.log(typeof firstName);
// typeof reports the kind of value
// firstName the variable we are asking about
// prints string
console.log(typeof gradYear); // number
console.log(typeof isEnrolled); // boolean
// ----- a value changes the answer -----
favoriteColor = "teal";
// no let this time: the name already exists,
// we are only putting something into it now
console.log(typeof favoriteColor);
// prints string, because it is no longer empty
Section 3 Code — in the file, not the console
In your code editor, find ENTER SECTION 3 CODE HERE in the script and type this line on the blank line below it:
What each part of this line does:
No quotes around true. With quotes it would be the text "true", a
string, not a boolean. Save, refresh, and the box below shows what
typeof reports for three different values.
What typeof reports
- typeof firstName
- Waiting for Section 3 code...
- typeof isEnrolled
- Waiting for Section 3 code...
- typeof 2027
- Waiting for Section 3 code...
4. Template Literals
Building a sentence out of text and variables, without gluing pieces together.
Combining Text and Variables
Most of the time you do not want a variable's raw value. You want it wrapped in a
sentence: not Mark, but Hello, Mark! Welcome to GDS 46.
The Old Way
For years the only option was concatenation: joining pieces with
+ signs. It works, but it gets ugly fast. You have to track which pieces
need quotes, which do not, and where the spaces go. A missing space inside the quotes
produces Hello,Mark, and a missing quote breaks the script.
The Modern Way
A template literal uses backticks instead of quotes and drops
variables in with ${ }. You write the sentence the way it should read
and mark the holes where values go. Spaces work exactly as typed, because it is one
continuous string rather than glued fragments.
~. If your output prints
literally as ${firstName} instead of your name, you used a regular
quote. This trips up nearly everyone the first time.
${ }, not just a
variable name. `Total: ${price * 2}` does the math first and drops the
result in. Keep it simple though: if the expression gets long, calculate it on its
own line and put only the variable in the template.
// ----- the old way: joining with + -----
const oldWay = "Hello, " + firstName + "!";
// "Hello, " text, with a space at the end
// + glues the pieces together
// firstName the variable, outside the quotes
// "!" more text
// result Hello, Mark!
console.log(oldWay);
// ----- the modern way: template literal -----
const greeting =
`Hello, ${firstName}! Welcome to ${courseName}.`;
// ` ` backticks, not regular quotes
// ${firstName} drops that value in here
// everything else typed exactly as it should read
// result Hello, Mark! Welcome to GDS 46.
console.log(greeting);
// ----- ${ } can do math too -----
const price = 20;
console.log(`Two cost ${price * 2} dollars.`);
// the math happens first, then the answer is
// dropped in: Two cost 40 dollars.
Section 4 Code — in the file, not the console
In your code editor, find ENTER SECTION 4 CODE HERE in the script and type this line on the blank line below it:
What each part of this line does:
Watch the backticks at each end, and type a real space between the two
${ } placeholders. Save, refresh, and your sentence appears in the box
below.
Your greeting
- greeting
- Waiting for Section 4 code...
5. Changing the Page: A Background Color
Reaching into the HTML from your script and changing how an element looks.
Reaching Into the Page
So far your code has stored values and reported on them. This section changes how the page looks. It takes one line, and it reads left to right just like the dot notation in the intro.
Find the Element
document is the whole page. .querySelector() is its
search action: it finds the first element that matches a CSS
selector, the same selectors you write in a stylesheet.
"#color-box" finds the element with id="color-box",
which sits just below this section, waiting.
Change Its Style
.style is the element's own CSS, and
.backgroundColor is one property inside it. The value is any CSS
color, in quotes: a hex code like
"#ff6b6b", a name like "teal", or
"rgb(255, 107, 107)".
background-color as "background minus
color." So the dash goes and the next letter is capitalized:
backgroundColor, fontSize,
borderRadius.
# or a typo in the id.
// ----- find a box, change its color -----
document.querySelector("#color-box")
.style.backgroundColor = "#ff6b6b";
// document the whole page
// .querySelector() finds the first match
// "#color-box" the element with that id
// .style the element's own CSS
// .backgroundColor background-color in CSS
// = "#ff6b6b" any CSS color, in quotes
// ----- CSS names become camelCase -----
// background-color becomes backgroundColor
// font-size becomes fontSize
// border-radius becomes borderRadius
// ----- any CSS color works -----
"gold"
"#ff6b6b"
"rgb(255, 107, 107)"
Section 5 Code — in the file, not the console
In your code editor, find ENTER SECTION 5 CODE HERE in the script and type this line on the blank line below it:
What each part of this line does:
Pick your own color: replace "#ff6b6b" with any hex code or color name, keeping the quotes. Save, refresh, and the box below changes.
Quick Reference
| You want to... | Write |
|---|---|
| Read dot notation | thing.action() or thing.value |
| Send yourself a test message | console.log("message"); |
| Store a value that will not change | const name = "Mark"; |
| Store a value that will change | let count = 0; |
| Find out what type a value is | typeof count |
| Combine text and variables | `Hi, ${name}!` |
| Find an element on the page | document.querySelector("#id") |
| Change its background color | element.style.backgroundColor = "#ff6b6b"; |