JavaScript: Data Types and Variables (Part 1)

JavaScript 101: Your First Step into the World of Code (Part 1)

Welcome to the start of your programming journey! If you've ever wondered how websites go from being static pages to interactive, dynamic experiences, you're in the right place. The magic behind it all is a powerful language called JavaScript.

This series is designed for absolute beginners. We'll start from scratch, and by the end of this first post, you'll not only understand what JavaScript is but also write your very first lines of code.

Ready? Let's get our laptops ready and dive in!

What You'll Learn in This Session:

  • Why we need JavaScript and where it's used.

  • How to write and see the output of your first program.

  • The basic "ingredients" of code: Primitive Data Types.

  • How to store information using Variables (varlet, and const).

  • The do's and don'ts of naming your variables.


Why Do We Even Need JavaScript?

Imagine you're building a house.

  • HTML (HyperText Markup Language) is the frame and structure. It builds the walls, the roof, and the rooms. It's the skeleton of a webpage.

  • CSS (Cascading Style Sheets) is the paint and decoration. It adds colors, sets the fonts, and arranges the furniture. It makes the webpage look good.

  • JavaScript (JS) is the electricity and plumbing. It makes the house functional. It powers the lights when you flip a switch, makes the water run when you turn a tap, and opens the garage door when you press a button.

On a website, JavaScript is what handles the interactivity:

  • Showing a pop-up when you click a button.

  • Validating a form to make sure you entered a proper email address.

  • Loading new posts on a social media feed without reloading the page.

  • Creating complex animations and browser-based games.

In short, HTML and CSS create a static view. JavaScript brings it to life.


Your First Program: "Hello, World!"

Before we build complex things, we need to learn how to communicate. In programming, our first step is often to make the computer say "Hello, World!". But where do we see this message?

We'll use the browser's developer console. It's a built-in tool in browsers like Chrome, Firefox, and Edge that lets us "peek under the hood" of a website and run JavaScript code directly.

How to open the console:

  • Right-click anywhere on a webpage.

  • Select "Inspect" or "Inspect Element".

  • A new panel will open. Click on the "Console" tab.

Now, let's write our first command: console.log(). This command is like telling the computer, "Hey, write whatever I put inside these parentheses into your logbook."

Activity: Write Your First Program

  1. Open the console in your browser.

  2. Type the following line and press Enter:

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

You should see the text Hello, World! printed back to you in the console.

Congratulations, you've just executed your first JavaScript program! Now, try it with your own name:

console.log("My name is Alex");

console.log() is the single most important tool for a developer. It helps us check the value of things in our code, debug problems, and understand what's happening at every step.


The Ingredients of Code: Data Types

Think about filling out a patient registration form online.

You're asked for different kinds of information:

  • Patient's Name: This is text (e.g., "John Doe").

  • Date of Birth: This involves numbers and symbols (e.g., "10/25/1990").

  • Marital Status: This is a choice between options, like "Single" or "Married". We could represent this as a simple yes or no decision (e.g., IsMarried? true).

In programming, we need to handle these different kinds of information. These are called data types. For now, we'll focus on the three most basic, or primitive, data types. Primitives are fundamental values that cannot be broken down further.

  1. Numbers: Used for mathematical calculations. They can be whole numbers (integers) or have decimals.

    • Examples: 100, -55, 3.14

  2. Strings: Used for text. A string is any sequence of characters wrapped in quotes (" or ').

    • Examples: "hello", 'JavaScript is fun', "123" (This is text, not a number, because of the quotes!)

  3. Booleans: Used for logical operations. A boolean can only have one of two values: true or false. They are perfect for answering yes/no questions.

    • Examples: true, false

Let's try logging these different types in the console:

console.log(42);                // Logs a number
console.log("I am a string!");   // Logs a string
console.log(true);              // Logs a boolean

Storing Information: Meet Variables!

Imagine you're at a grocery store with a shopping cart.

  • Without a variable: To get the total, you'd have to pick up every single item again and add up their prices: $1500 + $800 + $300 + $800. This is inefficient, especially for a big cart!

  • With a variable: You keep a running total. You start at $0. You add the camera ($1500), and your total is now $1500. You add the hard drive ($800), and your total becomes $2300. You only need to remember one thing: the current total.

That "current total" is a variable.

A variable is a named container used to store, change, and access information. Think of it as a labeled box where you can put data.

We use three steps with variables:

  1. Declaration: Creating the empty, labeled box.

  2. Assignment: Putting something inside the box.

  3. Reassignment: Replacing the contents of the box with something new.

The Three Keywords: var, let, and const

To create (declare) a variable, we use special keywords. Let's look at the three ways to do this in JavaScript.

1. var (The Old Way)

var is the original way to declare variables.

// 1. Declaration (Create an empty box named 'age')
var age;
console.log(age); // Output: undefined (the box is empty)

// 2. Assignment (Put the number 25 in the 'age' box)
age = 25;
console.log(age); // Output: 25

// 3. Reassignment (Replace 25 with 30)
age = 30;
console.log(age); // Output: 30

However, var has a problem. Imagine a very long program (200+ lines). You might accidentally re-declare the same variable:

// Line 7
var temp = 10;

// ... lots of other code ...

// Line 150 (by mistake)
var temp = "hello"; // This works, but it can cause confusing bugs!

var allows you to completely re-declare a variable, which can hide mistakes. To solve this, modern JavaScript introduced let and const.

2. let (The Modern, Flexible Way)

let is an improved version of var. It allows you to reassign a value, but it prevents you from re-declaring it in the same scope.

// Declaration and Assignment
let score = 100;
console.log(score); // Output: 100

// Reassignment is allowed
score = 150;
console.log(score); // Output: 150

// Now, let's try to re-declare it
let score = 200; // This will cause an ERROR!
// SyntaxError: Identifier 'score' has already been declared

This error is a good thing! It stops you from making a common mistake.

3. const (The Constant, Unchanging Way)

What if you have a value that should never change, like the value of Pi or the number of days in a week? For this, we use const.

const stands for "constant." When you declare a variable with const, you must assign it a value immediately, and you can never change it.

const daysInWeek = 7;
console.log(daysInWeek); // Output: 7

// Let's try to reassign it
daysInWeek = 8; // This will cause an ERROR!
// TypeError: Assignment to constant variable.

This is extremely useful for making your code safer and more predictable.

Quick Summary: var vs. let vs. const

KeywordCan be Re-declared?Can be Re-assigned?
var✅ Yes✅ Yes
let❌ No✅ Yes
const❌ No❌ No

Best Practice: In modern JavaScript, you should almost always use const by default. If you know you'll need to change the value later, use let. Try to avoid using var.

The Rules of the Name Game: Naming Variables

You can't name your variables just anything. There are a few rules:

Do's:

  • Variable names can start with a letter, an underscore (, or a dollar sign (.

  • After the first character, you can use letters, numbers, underscores, or dollar signs.

Don'ts:

  • You cannot start a variable name with a number. (let 1stPlace = "Alex"; is invalid).

  • You cannot use JavaScript's reserved keywords (like letconstvarfunction, etc.). (let const = 10; is invalid).

Best Practice: Use camelCase
For readability, it's a convention to write variable names using camelCase. This means the first word is lowercase, and every subsequent word starts with an uppercase letter.

  • let firstName = "Jane"; (Good)

  • const itemsInCart = 5; (Good)

  • let firstname = "Jane"; (Okay, but less readable)

  • let items_in_cart = 5; (Also okay, called snake_case, but camelCase is more common in JS)


Knowledge Check

Test what you've learned! What will the console log for each of these?

  1. let color = "blue";
    color = "green";
    console.log(color);
  2. const user = "admin";
    user = "guest";
    console.log(user);
  3. var x = 10;
    var x = 20;
    console.log(x);

Answers: 1. 

Conclusion & What's Next

Fantastic work! You've taken your very first, and most important, step.

Today, you learned:

  • JavaScript makes web pages interactive.

  • console.log() is your best friend for seeing what's happening in your code.

  • Data comes in different types, like NumbersStrings, and Booleans.

  • Variables are labeled boxes for storing data, created with let (for things that change) and const (for things that don't).

In our next session, we'll start performing actions with our data. We'll explore mathematical operators, how to combine strings, and start making decisions in our code.

Keep practicing in the console, and see you in Part 2


Comments

Popular posts from this blog

JavaScript : Acing the Interview - The Ultimate Q&A Guide (Part 11)

JavaScript : Loops and Arrays (Part 4)