Home / Web Basics / Intro to JavaScript

Lesson 5 of 6

Intro to JavaScript

Estimated time: 2.5–3 hours

What You Will Learn

  • What JavaScript is and why it is the third essential language of the web
  • Where JavaScript runs and how to use the browser console
  • How to output messages with console.log()
  • How to create variables with let and const
  • The basic data types: strings, numbers, and booleans
  • How to work with strings and do simple math
  • How to write comments in your code

What is JavaScript?

Welcome to one of the most exciting lessons in this course — you are about to learn your first real programming language! Up to this point, you have been working with HTML and CSS. Those two languages are incredibly important, but they have a limitation: they can only describe things. HTML describes the structure of a page, and CSS describes how it looks. Neither one can actually do anything on its own.

That is where JavaScript comes in. JavaScript (often shortened to JS) is the third essential language of the web, and it is the one that brings your pages to life. Here is how the three languages work together:

Think about every interactive thing you have ever done on a website. Clicking a "Like" button on social media? JavaScript. A dropdown menu that opens when you hover over it? JavaScript. A form that tells you "Please enter a valid email address" before you submit it? JavaScript. A live chat widget in the bottom corner of a page? JavaScript. The autocomplete suggestions that appear as you type in a search bar? Also JavaScript.

Every modern website on the internet uses JavaScript. It is the most widely used programming language in the world, and learning it opens the door to building truly interactive, dynamic web experiences. This is where things get really fun.

Tip Do not confuse JavaScript with Java — they are completely different languages! Despite the similar names, they have almost nothing in common. JavaScript was named during a time when Java was popular, and the creators thought the similar name would help with marketing. It is one of the most confusing naming decisions in tech history.

Where JavaScript Runs

Here is something important to understand: unlike HTML and CSS, which simply describe things for the browser to display, JavaScript is a programming language that can actually do things. It can make decisions, perform calculations, remember information, respond to what the user does, and change the page in real time.

JavaScript runs right inside your web browser — the same program you use to visit websites every day. Chrome, Firefox, Safari, Edge — they all have a built-in JavaScript engine that reads and executes your code. This means you do not need to install anything special to start writing JavaScript. Your browser is already set up and ready to go.

Every browser also has a secret tool that developers use all the time: the browser console. The console is like a behind-the-scenes window where you can see messages from your JavaScript code, test out small pieces of code, and debug problems. You will be using it a lot in this lesson.

Note In the code editors throughout this lesson, when you click Run, your JavaScript output will appear in the Console tab of the output pane (not the Preview tab). Make sure to click on the Console tab after running your code to see the results!

Your First JavaScript: console.log

Let us write your very first line of JavaScript! We are going to use a command called console.log(). This is the most fundamental tool in JavaScript — it lets you "print" or output a message so you can see it. Think of it as JavaScript's way of talking to you.

The word console refers to the browser console we just talked about, and .log() means "write this message to the console." You put whatever you want to display inside the parentheses.

Try It Yourself

Click Run below, then click the Console tab in the output area to see your message. After that, try changing the text inside the quotes to say something different — maybe your own name or a greeting!

console.log("Hello, Lansing!");

Congratulations — you just ran your first JavaScript program! Let us break down what happened:

You can log multiple messages by writing multiple console.log() lines. Each one will appear on its own line in the console:

console.log("Welcome to Coders Farm!");
console.log("Today we are learning JavaScript.");
console.log("This is going to be great!");
Tip You will use console.log() constantly as a developer — not just for learning, but as a debugging tool. When something in your code is not working right, the first thing most developers do is add console.log() statements to figure out what is going on. It is your best friend.

Variables

Imagine you are filling out a name tag at a Coders Farm meetup. You write your name on the tag, and from that point on, anyone can look at the tag to know who you are. A variable in JavaScript works the same way — it is a labeled container that holds a value. You give it a name, put something inside it, and then you can use that name later to refer to the value.

In JavaScript, you create variables using two keywords: let and const.

let — A Variable That Can Change

Use let when the value might need to change later. For example, a person's score in a game, the current temperature, or the number of items in a shopping cart — these can all change over time.

let score = 0;
console.log("Starting score:", score);

score = 10;
console.log("After earning points:", score);

score = 25;
console.log("After bonus round:", score);

const — A Variable That Stays the Same

Use const (short for "constant") when the value should never change after you set it. For example, a person's birthday, the number of days in a week, or the name of your city — these are fixed values.

const city = "Lansing";
const state = "Michigan";
console.log("I live in " + city + ", " + state);

// Try uncommenting the line below to see what happens:
// city = "Detroit";

If you uncomment that last line and click Run, you will see an error in the Console — JavaScript will not let you reassign a const variable. That is the whole point! It protects values that should not change.

Tip A good rule of thumb: start with const for everything. If you later realize you need to change the value, switch it to let. This habit helps you write safer, more predictable code. You will rarely need a value to change as often as you might think.

Try It Yourself

Create your own variables below! Make a const for your name and a let for your favorite number. Log both to the console. Then change your favorite number and log it again.

const myName = "Your Name Here";
let favoriteNumber = 7;

console.log("My name is", myName);
console.log("My favorite number is", favoriteNumber);

// Now change favoriteNumber and log it again:
favoriteNumber = 42;
console.log("Actually, my new favorite number is", favoriteNumber);

Data Types

Not all values in JavaScript are the same. A person's name is different from their age, which is different from whether or not they are a student. JavaScript organizes values into different data types. Let us look at the three most important ones for beginners.

Strings — Text

A string is any piece of text. You create a string by wrapping text in quotes — either double quotes ("hello") or single quotes ('hello'). Both work exactly the same way.

let greeting = "Hello, world!";
let name = 'Maria';
let address = "123 Main Street, Lansing, MI";

Numbers

A number is exactly what you would expect — a numeric value. Numbers do not use quotes. JavaScript handles both whole numbers (integers) and decimal numbers the same way.

let age = 25;
let temperature = 72.5;
let population = 112644;  // Lansing's approximate population

Booleans — True or False

A boolean is the simplest data type — it can only be one of two values: true or false. Booleans are incredibly useful for making decisions in your code (which we will explore in the next lesson).

let isStudent = true;
let hasGraduated = false;
let livesInMichigan = true;

Checking Types with typeof

JavaScript has a handy tool called typeof that tells you what type a value is. This is really useful when you are not sure what kind of data you are working with.

Try It Yourself

Run the code below and check the Console tab to see the type of each value. Then try adding your own variables and checking their types!

let name = "Maria";
let age = 25;
let isStudent = true;

console.log(typeof name);       // "string"
console.log(typeof age);        // "number"
console.log(typeof isStudent);  // "boolean"

// Two special types worth knowing about:
let nothing = null;
let notDefined;

console.log(typeof nothing);     // "object" (a known quirk in JS!)
console.log(typeof notDefined);  // "undefined"

You might notice that typeof null says "object" instead of "null" — that is actually a famous bug in JavaScript that has existed since the very beginning of the language in 1995! It was never fixed because too many websites already depended on it. Do not worry about null and undefined too much right now — just know they exist and represent "empty" or "missing" values.

String Operations

Strings are one of the data types you will work with most often, so let us learn some useful things you can do with them.

Concatenation — Joining Strings Together

You can join two or more strings together using the + operator. This is called concatenation (a fancy word that just means "putting things together").

let firstName = "Alex";
let lastName = "Johnson";

// Join them together with a space in between
let fullName = firstName + " " + lastName;
console.log(fullName);  // "Alex Johnson"

// You can concatenate as many strings as you want
console.log("Welcome, " + fullName + "! Glad you are here.");

Template Literals — A Better Way to Build Strings

Concatenation with + works fine, but it can get messy when you have a lot of pieces to join. JavaScript has a cleaner way called template literals. Instead of regular quotes, you use backticks (`) — the key to the left of the number 1 on your keyboard. Inside a template literal, you can insert variables directly using ${variableName}.

let name = "Maria";
let age = 28;
let city = "Lansing";

// With concatenation (the old way):
console.log("My name is " + name + ", I am " + age + " years old, and I live in " + city + ".");

// With template literals (the modern way):
console.log(`My name is ${name}, I am ${age} years old, and I live in ${city}.`);

Both lines produce the exact same output, but the template literal version is much easier to read and write. You will see template literals used constantly in modern JavaScript.

Useful String Properties and Methods

Strings come with built-in tools that let you do useful things. Here are two you will use often:

Try It Yourself

Run the code below to see string properties and methods in action. Try changing the message to your own text and see how the results change!

let message = "Hello, Lansing!";

// .length tells you how many characters are in the string
console.log(message.length);  // 15

// .toUpperCase() converts everything to capital letters
console.log(message.toUpperCase());  // "HELLO, LANSING!"

// .toLowerCase() converts everything to lowercase letters
console.log(message.toLowerCase());  // "hello, lansing!"

// You can chain them together with other operations
let shout = message.toUpperCase();
console.log(`${shout} has ${shout.length} characters.`);

Simple Math

JavaScript is great at math. You can use it as a powerful calculator right in your code. Here are the basic math operators:

Try It Yourself

Run the code to see math in action. Try changing the numbers or adding your own calculations!

// Basic math operations
console.log("Addition:", 10 + 5);        // 15
console.log("Subtraction:", 20 - 8);     // 12
console.log("Multiplication:", 6 * 7);   // 42
console.log("Division:", 100 / 4);       // 25
console.log("Remainder:", 17 % 5);       // 2

// You can use variables in math too!
let pricePerItem = 4.99;
let quantity = 3;
let total = pricePerItem * quantity;
console.log(`${quantity} items at $${pricePerItem} each = $${total}`);

// JavaScript follows the normal order of operations (PEMDAS)
let result = 2 + 3 * 4;
console.log("2 + 3 * 4 =", result);  // 14 (not 20!)

// Use parentheses to change the order
let result2 = (2 + 3) * 4;
console.log("(2 + 3) * 4 =", result2);  // 20

The modulus operator (%) might seem strange at first, but it is actually very useful. It gives you the remainder after dividing two numbers. For example, 17 % 5 equals 2 because 17 divided by 5 is 3 with a remainder of 2. Programmers use modulus for things like checking if a number is even or odd (number % 2 equals 0 if the number is even).

Comments

As your code gets longer, it becomes important to leave notes for yourself (and for other people who might read your code). JavaScript lets you write comments — text that the computer completely ignores. Comments are only for humans to read.

There are two types of comments:

// This is a single-line comment.
// Everything after // on the same line is ignored by JavaScript.

let name = "Alex";  // You can also put comments at the end of a line

/*
  This is a multi-line comment.
  It starts with /* and ends with the closing characters.
  Everything between them is ignored.
  Great for longer explanations!
*/

console.log("Comments do not appear in the output!");
console.log("Only console.log messages show up here.");

Good comments explain why you did something, not what you did. For example, // Calculate the total price including Michigan sales tax is a helpful comment. But // Set x to 5 right above let x = 5; does not add any useful information — anyone can already see that from the code itself.

Tip Comments are also a great way to temporarily "turn off" a line of code without deleting it. Just put // in front of the line and JavaScript will skip it. Developers call this "commenting out" a line. You already saw this trick earlier with the const reassignment example!

Interactive Exercise: Build a Greeting

Time to put everything together! In this exercise, you will create variables for your name, age, and city, then use them to build and log a personalized greeting message. This combines variables, strings, template literals, and console.log() — all the key skills from this lesson.

Try It Yourself

Replace the placeholder values below with your own information, then click Run and check the Console tab to see your personalized greeting. Try adding more variables and making the greeting even more detailed!

// Step 1: Create variables for your personal info
const myName = "Your Name";
let myAge = 25;
const myCity = "Lansing";

// Step 2: Log each piece of info
console.log("Name:", myName);
console.log("Age:", myAge);
console.log("City:", myCity);

// Step 3: Build a greeting using template literals
let greeting = `Hi, my name is ${myName}. I am ${myAge} years old and I live in ${myCity}, Michigan!`;
console.log(greeting);

// Step 4: Try some fun extras!
console.log(`My name has ${myName.length} letters.`);
console.log(`In 10 years, I will be ${myAge + 10} years old.`);
console.log(greeting.toUpperCase());

If your console shows all the messages with your personalized info, you just completed your first real JavaScript program! That is a genuinely big deal — be proud of yourself.

Knowledge Check

Let us see how well you absorbed the material. Give each question a try — there is no pressure, and you can review the lesson and try again as many times as you like.

1. What is the role of JavaScript on a web page?

Correct! HTML handles structure, CSS handles style, and JavaScript handles behavior and interactivity. It is the language that makes web pages respond to user actions, perform calculations, and update content dynamically.

2. What is the difference between let and const?

That is right! let creates a variable whose value can be changed (reassigned) later, while const creates a variable whose value is fixed and cannot be reassigned. Both can hold any data type — the difference is about whether the value can change, not what type of value it holds.

3. What will console.log(typeof 42) output?

Exactly! The typeof operator returns "number" for any numeric value, whether it is a whole number like 42 or a decimal like 3.14. JavaScript does not distinguish between integers and decimals — they are all just "number."

Lesson Summary

Amazing work — you just took your first steps into the world of programming! Here is everything you learned in this lesson:

In the next lesson, we will build on these fundamentals and dive into JavaScript basics like conditionals (making decisions in your code), functions (reusable blocks of code), and working with the DOM (using JavaScript to actually change things on the page). You are off to a great start — see you there!

Finished this lesson?

← Previous: CSS Selectors & Layout Next: JavaScript Basics →