JavaScript Fundamentals: Building Blocks

7 min read

Course: JavaScript

Topic: JavaScript Fundamentals: Building Blocks

Hey there, future JavaScript wizard! 🧙‍♂️ Welcome to the very first step in your journey. Before you can build amazing websites and complex applications, you need to know the absolute basics, the LEGO® bricks of the programming world.

Imagine you're building a smart to-do list application. This app needs to remember your tasks, know how many tasks are left, and check if a task is completed. To do any of that, you first need to learn how to store and manage information. That's exactly what we're covering today!


1. Variables: Storing Data with let and const 📥

The Problem: Your program needs a way to store and remember values. If a user adds a new task called "Buy groceries," how does your application remember that piece of text? You need a named container for it.

The Solution: Variables! A variable is just that: a named storage location in the computer's memory that holds a value. You can think of it like a labeled box where you can keep a piece of information.

In modern JavaScript, we have two primary ways to create (or "declare") these boxes: let and const.

const (The Constant)

Use const when you know the value inside the box should not change after you've set it. It's like writing the label on the box with a permanent marker.

Industry Standard: The modern best practice is to use const by default for all your variables. This makes your code more predictable and prevents accidental changes, which is a common source of bugs.

javascript
// A variable for the name of our app. It's not going to change.
const appName = "My Awesome To-Do App";

// The user's birth year. This also won't change.
const birthYear = 1995;

console.log(appName); // Output: My Awesome To-Do App

If you try to change a const variable, JavaScript will give you an error. This is a good thing! It's protecting you from yourself.

javascript
const appName = "My Awesome To-Do App";
appName = "Another App"; // 💥 TypeError: Assignment to constant variable.

let (The Changeable)

Use let only when you know you will need to change, or "reassign," the value later on. Think of this as a box with a label written in pencil—you can erase it and write something new.

javascript
// A variable to keep track of the number of active tasks. This will change.
let activeTasks = 3;
console.log(activeTasks); // Output: 3

// A user completes a task, so we update the value.
activeTasks = 2;
console.log(activeTasks); // Output: 2

A Funny Bit of History: Before let and const were introduced in 2015, JavaScript only had var. var has some quirky behaviors (like "hoisting" and function-scoping) that could lead to confusing bugs. Think of var as that old, rusty tool in the back of the shed. It did the job, but we have much safer and more reliable tools now. You'll still see it in older codebases, but for new projects, stick with let and const.


2. Primitive Data Types: Strings, Numbers, and Booleans 🧱

The Problem: Your app needs to store different kinds of information. The name of a task is text, the count of tasks is a number, and the status of a task (done or not done) is a simple "yes" or "no". How do you tell JavaScript to handle these different types of data?

The Solution: Data Types! JavaScript has several "primitive" data types, which are the most basic building blocks of data. All primitives are immutable, meaning the value itself cannot be changed, only the variable holding it can be reassigned. For now, we'll focus on the three most common ones.

String 📝

A string is used to represent text. You create a string by wrapping text in single quotes ('...'), double quotes ("..."), or backticks (`...`).

Industry Standard: Most teams pick one style (single or double quotes) and stick with it for consistency. The choice is yours!

javascript
const taskName = "Buy groceries";
const userGreeting = "Hello, world!";

Number 🔢

The number type is for... well, numbers! This includes integers (like 10) and floating-point numbers (like 3.14). Unlike some other languages, JavaScript doesn't have different types for integers and decimals; it's all just Number.

javascript
const totalTasks = 5;
const priceOfMilk = 2.99;

Boolean ✅ / ❌

A boolean has only two possible values: true or false. It’s perfect for representing on/off switches, yes/no decisions, or any other two-state situation.

javascript
const isTaskCompleted = false;
const isUserLoggedIn = true;

You can check the type of a variable using the typeof operator.

javascript
const taskName = "Buy groceries";
console.log(typeof taskName); // Output: "string"

const totalTasks = 5;
console.log(typeof totalTasks); // Output: "number"

const isTaskCompleted = false;
console.log(typeof isTaskCompleted); // Output: "boolean"

3. Basic Operators: Math, Assignment, and String Concatenation ⚙️

The Problem: Okay, you can store data. Now what? How do you perform calculations, assign values, or join pieces of text together?

The Solution: Operators! Operators are the symbols that perform actions on your variables and values.

Assignment Operator =

You've already been using this one! The single equals sign (=) is the assignment operator. It takes the value on the right and assigns it to the variable on the left.

javascript
let currentTaskCount = 0; // Assigns 0 to currentTaskCount

Math (Arithmetic) Operators ➕➖✖️➗

These work just like they do in a calculator.

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
javascript
let apples = 5;
let oranges = 3;

let totalFruit = apples + oranges; // totalFruit is 8
let fruitDifference = apples - oranges; // fruitDifference is 2

let pricePerApple = 0.5;
let totalCost = apples * pricePerApple; // totalCost is 2.5

String Concatenation +

You can also use the + operator to join strings together. This is called concatenation.

javascript
const firstName = "John";
const lastName = "Doe";

// Note the " " string in the middle to add a space!
const fullName = firstName + " " + lastName;

console.log(fullName); // Output: "John Doe"

This works, but it can get messy very quickly. What if you wanted to build a more complex sentence?

javascript
const username = "CodeNinja88";
const itemsInCart = 3;
const total = 45.50;

const message = "Hello, " + username + "! You have " + itemsInCart + " items in your cart. Your total is $" + total + ".";

console.log(message); // Hello, CodeNinja88! You have 3 items in your cart. Your total is $45.50.

Yikes. That's hard to read and easy to mess up (did you forget a space?). This is a perfect setup for our next concept...


4. Template Literals: Dynamic and Readable Strings ✨

The Problem: As you saw above, building strings with variables using the + operator is clunky, error-prone, and hard to read. There must be a better way!

The Solution: Template Literals!
Introduced in ES6 (the 2015 update to JavaScript), template literals are a modern and much cleaner way to create strings. They are defined using backticks (`) instead of quotes.

The superpower of template literals is string interpolation. This allows you to embed expressions directly inside the string using the ${expression} syntax.

Let's refactor that messy message from before:

javascript
const username = "CodeNinja88";
const itemsInCart = 3;
const total = 45.50;

const message = `Hello, ${username}! You have ${itemsInCart} items in your cart. Your total is $${total}.`;

console.log(message); // Hello, CodeNinja88! You have 3 items in your cart. Your total is $45.50.

Look at that! So much cleaner and more readable. You write the string exactly how you want it to look and just pop in the variables where they belong.

Another cool feature is that template literals can be multi-line.

javascript
const multiLineMessage = `
This is line 1.
This is line 2.
And this is line 3!
`;

console.log(multiLineMessage);
// Output:
// This is line 1.
// This is line 2.
// And this is line 3!

Trying to do that with regular strings is a headache. With template literals, it's effortless.


Further Reading & References 📚

  • MDN Web Docs on JavaScript Grammar and types: A comprehensive look at all data types in JavaScript.
  • let vs. const: A deep dive into the differences and best practices.
  • Basic Operators: The full list of arithmetic and assignment operators.
  • Template Literals (Template Strings): The official documentation on this amazing feature.

Challenge

You are a developer for an e-commerce platform, and you need to generate a dynamic receipt. Your task is to write a script that creates a formatted, multi-line receipt summary string.

Requirements:

  1. Declare the following constants with the specified values and data types:

    • customerName: A string with the value "Alex".
    • itemCount: A number with the value 5.
    • itemPrice: A number with the value 19.99.
    • taxRate: A number with the value 0.07 (representing 7%).
  2. Perform the following calculations and store each result in a new const:

    • Calculate the subtotal by multiplying itemCount by itemPrice. Name this constant subtotal.
    • Calculate the tax amount by multiplying the subtotal by the taxRate. Name this constant taxAmount.
    • Calculate the final total cost by adding the subtotal and taxAmount. Name this constant totalCost.
  3. Create a final constant named receiptSummary. This constant must hold a single multi-line string generated using a template literal.

  4. The receiptSummary string must use string interpolation to embed the values of customerName, itemCount, subtotal, taxAmount, and totalCost. The final string must exactly match the format shown in the expected output, including all text, spacing, and line breaks.

Expected result

Your code should result in a final constant, receiptSummary, that holds a multi-line string. When this string is logged or displayed, it should look exactly like this:

apache
Customer: Alex
Items Purchased: 5

Subtotal: $99.95
Tax: $6.9965
Total Cost: $106.9465

Ensure all variables are declared with const and that the final string is created using a template literal with embedded expressions for the dynamic values.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.