Welcome To JS Tutorial!

1. Introduction & Setup

JavaScript is one of the main technologies used to build modern websites. HTML creates the structure of a page, CSS controls the design, and JavaScript adds behavior. When you click a button, open a menu, submit a form, load data without refreshing the page, or see moving sliders, JavaScript is usually working behind the scenes.

It is a beginner friendly language because every web browser already supports it. You do not need to install a heavy compiler to begin. You can write code in a simple text editor, save the file, and open your webpage in Chrome, Edge, Firefox, or any modern browser.

JavaScript is also used outside browsers. Developers use it for backend servers with Node.js, mobile apps, desktop apps, browser extensions, games, and automation tools. This means learning JavaScript gives you many career paths.

When you are new, focus on browser JavaScript first. Learn how code connects with HTML, how to handle clicks, how to change page content, and how to solve simple logic problems. That foundation helps with everything later.

How JavaScript Works in the Browser

When a browser loads your page, it reads HTML from top to bottom. Then it loads CSS for design. After that, it can run JavaScript code. JavaScript can read page elements, change text, add styles, remove items, create new elements, and react to user actions.

This is why many developers place the script tag near the end of the body section. It allows the page structure to load first, then JavaScript runs after the elements exist.

Linking an External JavaScript File

Most real projects keep JavaScript in a separate file. This keeps your HTML cleaner and easier to maintain.

<body>
    <h1 id="title">Welcome to CBS Docs</h1>
    <p>Learn JavaScript step by step.</p>

    <script src="main.js"></script>
</body>

Explanation:

  • <h1 id="title"> creates a heading on the page.
  • <script src="main.js"> tells the browser to load the file named main.js.
  • The browser reads that file and runs the code inside it.
  • Keeping code in a separate file makes editing easier.

Your First JavaScript File

Create a file named main.js and write this:

console.log("JavaScript is connected!");
alert("Welcome to the website");

Explanation:

  • console.log() prints text inside the browser developer console.
  • alert() shows a popup message.
  • If you see both working, your JavaScript file is connected correctly.

Using JavaScript Inside HTML

You can also write code directly inside script tags. This is useful for quick testing, but large projects usually use external files.

<script>
console.log("Inline JavaScript");
</script>

Explanation:

  • The code is written directly inside the HTML file.
  • Good for small tests.
  • External files are better for organized projects.

Opening the Developer Console

The console is one of the most useful tools for beginners. It helps you test code and view errors.

In most browsers:

  • Press F12
  • Or right click the page and choose Inspect
  • Open the Console tab

If your code has mistakes, errors usually appear there. Reading errors is a skill every developer needs.

Statements and Semicolons

JavaScript code runs line by line. Each instruction is called a statement.

console.log("Line one");
console.log("Line two");

Explanation:

  • Each line runs in order.
  • Semicolons are often optional, but using them is a good habit.
  • They make code easier to read.

Comments in JavaScript

Comments are notes for humans. They are ignored by the browser.

// This is a single line comment

/*
This is a
multi line comment
*/

Explanation:

  • Use comments to explain logic.
  • Helpful when revisiting old code.
  • Do not overuse comments for obvious things.

Case Sensitivity

JavaScript is case sensitive. This means these names are different:

userName
username
UserName

Be careful with spelling and letter case.

Common Beginner Mistakes

  • Wrong file path in the script src.
  • Trying to run JavaScript before HTML loads.
  • Misspelling variable names.
  • Forgetting quotes around text.
  • Ignoring console errors.

Best Beginner Practice

Create a small folder with these files:

  • index.html
  • style.css
  • main.js

Then test small examples daily. Write a button click event, change text, show time, or calculate totals. Small practice builds strong skill.

Simple Real Example

const heading = document.getElementById("title");
heading.innerText = "JavaScript Loaded Successfully";

Explanation:

  • getElementById() finds the element with id title.
  • innerText changes the visible text.
  • The page heading updates instantly.

Why Setup Matters

Many students rush into advanced topics, but setup is important. If you understand files, script linking, console tools, and how the browser runs code, later topics become easier.

Strong basics save time. When something breaks, you know where to check first.

What to Learn Next

After setup, move to variables, data types, operators, conditions, loops, functions, arrays, objects, DOM manipulation, and asynchronous JavaScript. These topics form the core of real web development.

Keep coding by hand. Reading alone is not enough. The more examples you type yourself, the faster you improve.

2. Variables & Data Types

Variables are one of the first and most important ideas in JavaScript. A variable is a named container used to store data. Instead of repeating values again and again, you save them inside variables and reuse them anywhere in your code.

Think of a variable like a labeled box. The label is the variable name, and the value inside the box is the data. You can store numbers, text, true or false values, lists, objects, and much more.

Without variables, writing programs would be difficult because every value would need to be typed manually each time.

Why Variables Matter

Variables help when you build websites and apps. For example:

  • Store a user's name after login
  • Store product prices in a cart
  • Store marks in a student result system
  • Store theme settings like dark mode
  • Store API data from another server

Once data is stored in a variable, your program can read it, update it, compare it, and display it.

Creating Variables in JavaScript

Modern JavaScript mainly uses three keywords:

  • let
  • const
  • var (older style)

Today, most developers use let and const.

let age = 22;
const siteName = "CBS Docs";
var city = "Islamabad";

Explanation:

  • let age = 22; creates a variable that can change later.
  • const siteName creates a fixed value.
  • var city is older syntax. Still works, but less preferred in modern code.

let vs const

This is one of the most common beginner questions.

let score = 10;
score = 15;

const country = "Pakistan";
// country = "UK";

Explanation:

  • score changes from 10 to 15 because it uses let.
  • country cannot be changed because it uses const.
  • If you try to change a const value, JavaScript gives an error.

Use const by default. Use let only when you know the value must change.

Variable Naming Rules

JavaScript has naming rules:

  • Names can contain letters, numbers, underscore, and dollar sign.
  • Names cannot start with a number.
  • Names are case sensitive.
  • Spaces are not allowed.
let userName = "Ali";
let totalMarks = 450;
let _price = 99;
let $data = "ok";

Wrong Examples:

let 2name = "Ali";
let user name = "Ali";

Use clear names so your code is easier to understand.

Best Naming Style

JavaScript commonly uses camelCase naming.

let firstName = "Sohaib";
let studentMarks = 90;
let cartTotalPrice = 1500;

The first word starts small, next words start with capital letters.

What Are Data Types

Data type means the kind of value stored in a variable. JavaScript supports many types. Beginners should first learn these:

  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • Object
  • Array

1. String

Strings are text values.

let name = "Sohaib";
let message = 'Welcome';
let course = `JavaScript`;

Explanation:

  • Strings use quotes.
  • Double quotes and single quotes both work.
  • Backticks are useful for template strings.

2. Number

Numbers are used for math values.

let age = 22;
let price = 499.99;
let result = -10;

JavaScript uses one number type for integers and decimals.

3. Boolean

Boolean values are only true or false.

let isLoggedIn = true;
let isAdmin = false;

Used in conditions and decision making.

4. Undefined

If a variable is created but no value is assigned, it becomes undefined.

let userName;
console.log(userName);

Output will be undefined.

5. Null

Null means empty on purpose.

let selectedUser = null;

This means there is no value right now, but maybe later.

6. Array

Arrays store multiple values in one variable.

let colors = ["red", "blue", "green"];

7. Object

Objects store related data with keys and values.

let student = {
    name: "Ali",
    marks: 88
};

Checking Data Types

You can use typeof to inspect data types.

console.log(typeof "Hello");
console.log(typeof 100);
console.log(typeof true);

Output:

  • string
  • number
  • boolean

Changing Variable Values

let counter = 1;
counter = 2;
counter = 3;

The latest assigned value replaces the old one.

Using Variables Together

let firstName = "Muhammad";
let lastName = "Sohaib";

let fullName = firstName + " " + lastName;
console.log(fullName);

Explanation:

  • Two text values are joined together.
  • The output becomes Muhammad Sohaib.

Math With Variables

let price = 1000;
let tax = 100;
let total = price + tax;

console.log(total);

Output is 1100.

Real Website Example

let userName = "Ali";
let loginCount = 5;
let isMember = true;

console.log("Welcome " + userName);

This can be used on a dashboard after login.

Common Beginner Mistakes

  • Using quotes around numbers when number type is needed.
  • Trying to change a const variable.
  • Misspelling variable names.
  • Using unclear names like x, y, z everywhere.
  • Forgetting that JavaScript is case sensitive.

Good Practice Tips

  • Use const by default.
  • Use let when values change.
  • Use meaningful names.
  • Keep names short but clear.
  • Test values using console.log().

Mini Practice Task

const studentName = "Ayesha";
let marks = 85;
let passed = true;

console.log(studentName);
console.log(marks);
console.log(passed);

Try changing marks to another number and test again.

Summary

Variables store data. Data types define what kind of data is stored. These ideas are used in every JavaScript project. If you understand variables well, learning conditions, loops, arrays, functions, and DOM work becomes much easier.

Practice by creating your own variables daily. Store names, prices, scores, and settings. Repetition builds confidence.

3. Operators & Math Logic

Think of variables as the nouns of your code, holding your data. If variables are the nouns, operators are the verbs. They are the action-makers. Operators are special symbols that allow you to perform calculations, manipulate data, combine strings, and make complex decisions by comparing different values.

Whether you are calculating the final price in an e-commerce shopping cart, determining if a user is old enough to access a website, or simply moving a character across a screen in a game, you are relying heavily on operators. Let's break down the different families of operators and how they govern the logic of your applications.


1. Arithmetic Operators: The Math You Already Know (Mostly)

At its core, your computer is just a really fast calculator. Arithmetic operators allow you to perform standard mathematical operations on numbers. You are likely already familiar with the basics: addition (+), subtraction (-), multiplication (*), and division (/).

let basePrice = 1200;
let discount = 200;
let quantity = 3;

// Basic Math
let finalPrice = basePrice - discount;     // 1000
let totalCost = finalPrice * quantity;     // 3000
let splitCost = totalCost / 2;             // 1500

However, programming introduces a few specialized math operators that are incredibly powerful for everyday logic:

The Modulo Operator (%)

The modulo operator divides two numbers and returns the remainder. Think back to elementary school math before you learned about decimals. If you divide 10 by 3, the answer is 3 with a remainder of 1. In code, 10 % 3 equals 1.

let totalSlices = 10;
let people = 3;

let slicesPerPerson = Math.floor(totalSlices / people); // 3 slices each
let leftoverSlices = totalSlices % people;              // 1 slice left over!

Why is Modulo useful? It is the secret weapon for figuring out if a number is even or odd (e.g., number % 2 === 0 means it's even). It's also used heavily in game development and UI design for looping through arrays or keeping items in a grid.

Exponentiation (**)

Instead of relying on clunky math library functions, modern code lets you use double asterisks to raise a base number to an exponent power.

let area = 5 ** 2; // 5 squared = 25
let cube = 3 ** 3; // 3 cubed = 27

Increment (++) and Decrement (--)

You will often need to add or subtract exactly 1 from a variable—especially when counting items or running loops. The increment and decrement operators are elegant shortcuts for this.

let lives = 3;
lives--; // Player took damage! lives is now 2

let score = 0;
score++; // Player collected a coin! score is now 1

2. Assignment Operators: Updating State

In programming, the single equals sign (=) does not mean "these two things are mathematically equal." Instead, it is the Assignment Operator. It means "take the value on the right, and put it into the variable on the left."

Because updating a variable based on its own current value is so common, we have Compound Assignment Operators. They combine an arithmetic operator with the assignment operator to save you keystrokes and make your code cleaner.

let balance = 500;
let deposit = 150;

// The long, repetitive way:
// balance = balance + deposit;

// The clean, professional way:
balance += deposit; // Adds 150 to the current balance, making it 650

balance -= 50;  // Subtracts 50, making it 600
balance *= 2;   // Multiplies by 2, making it 1200
balance /= 4;   // Divides by 4, making it 300

Line-by-line breakdown:

  • balance += deposit;: Grabs the current value of balance (500), adds deposit (150) to it, and stores the new total (650) right back into balance.
  • This pattern works for virtually every math operator, including modulo (%=).

3. Comparison Operators: Asking the Computer Questions

If you want your program to make decisions, it needs to compare data. Comparison operators always result in a boolean value: either true or false. They are the backbone of if/else statements.

let userAge = 25;
let legalAge = 18;

console.log(userAge > legalAge);  // true (Greater than)
console.log(userAge < 13);        // false (Less than)
console.log(userAge >= 25);       // true (Greater than or equal to)

The Great Gotcha: Strict Equality (===) vs Loose Equality (==)

When asking "Are these two things equal?", many programming languages use a double equals sign. However, in modern web development, you should almost always use the Strict Equality Operator (===).

The loose equality operator (==) tries to be "helpful" by converting the data types before comparing them. This is called type coercion, and it leads to notorious, hard-to-find bugs.

let stringNumber = "5";
let realNumber = 5;

// LOOSE Equality (Avoid this!)
console.log(stringNumber == realNumber);  // true... wait, what? 

// STRICT Equality (Always use this!)
console.log(stringNumber === realNumber); // false. This is correct!

The Golden Rule: Always use === for checking equality, and !== for checking inequality. It ensures that both the value and the data type are exactly the same, making your code predictable and safe.


4. Logical Operators: Combining Conditions

Real-world decisions are rarely based on a single factor. Usually, several things must be true at once, or at least one of several things must be true. Logical operators allow you to chain comparisons together.

The AND Operator (&&)

With the AND operator, all conditions must be true for the final result to be true. If even one condition is false, the whole thing collapses into false.

let hasTicket = true;
let isVip = false;

// Will they get into the VIP lounge?
let canEnterVip = hasTicket && isVip; // false, because they aren't VIP

The OR Operator (||)

The OR operator is much more forgiving. As long as at least one of the conditions is true, the final result is true. It only returns false if absolutely everything is false.

let knowsPassword = false;
let hasAdminKeycard = true;

// Will the safe open?
let safeUnlocks = knowsPassword || hasAdminKeycard; // true, the keycard worked!

The NOT Operator (!)

The NOT operator is the contrarian of the group. It simply flips a boolean value to its opposite. True becomes false, and false becomes true. It is incredibly useful for checking if something is missing, empty, or disabled.

let isGameOver = false;

// "If NOT game over, keep playing"
if (!isGameOver) {
    console.log("Keep fighting!");
}

5. The String Concatenation Operator (The Dual-Purpose +)

We already discussed the + operator for doing math, but it leads a double life. If you use the + operator with strings (text), it acts as a "glue," sticking the text together. This is called concatenation.

let greeting = "Hello";
let userName = "Alice";
let welcomeMessage = greeting + ", " + userName + "!"; // "Hello, Alice!"

Warning - The Coercion Trap: What happens if you try to add a string and a number together? The computer panics, converts the number into text, and glues them together.

let score = 100;
let bonus = "50";

let total = score + bonus; 
console.log(total); // "10050" (It glued them, it didn't do math!)

This is why understanding data types and how operators interact with them is a critical skill for any developer.


6. Operator Precedence (Order of Operations)

Just like in your middle school algebra class, programming languages follow a strict order of operations (often remembered as PEMDAS or BODMAS). Multiplication and division happen before addition and subtraction.

let result = 10 + 5 * 2; // Result is 20, NOT 30!

The multiplication (5 * 2 = 10) happens first, and then the addition (10 + 10). If you want to force the addition to happen first, you use grouping parentheses (), which possess the highest precedence of all operators.

let correctedResult = (10 + 5) * 2; // Result is 30. The parentheses execute first.

By mastering these operators—Arithmetic, Assignment, Comparison, and Logical—you gain the fundamental tools required to build complex algorithms, manage application state, and write intelligent, decision-making code.