JavaScript Basics

Table of Contents

  1. What is JavaScript?
  2. Adding JavaScript to HTML5
  3. JavaScript Syntax & Variables
  4. Data Types
  5. Different Ways of Printing Output
  6. Different Ways of Getting User Input
  7. Operators
  8. Conditional Statements
  9. Loops
  10. Comments
  11. Best Practices

What is JavaScript?

JavaScript is a dynamic, high-level programming language that makes websites interactive and dynamic. Originally created to add interactivity to web pages, JavaScript has evolved into one of the most popular programming languages in the world.

Key Features:

  • Client-side scripting: Runs in the browser
  • Interpreted language: No compilation needed
  • Dynamically typed: Variables can change types
  • Case-sensitive: myVariable and myvariable are different
  • Object-oriented and functional: Supports multiple programming paradigms

What Can JavaScript Do?

  • Make websites interactive (buttons, forms, animations)
  • Validate user input before sending to server
  • Create dynamic content that changes without page reload
  • Build web applications, mobile apps, and even desktop applications
  • Handle user events (clicks, scrolls, keyboard input)

Adding JavaScript to HTML5

There are three main ways to include JavaScript in your HTML document:

1. Inline JavaScript

JavaScript code written directly in HTML attributes:

<!DOCTYPE html>
<html>
<head>
    <title>Inline JavaScript</title>
</head>
<body>
    <button onclick="alert('Hello World!')">Click Me</button>
    <p onmouseover="this.style.color='red'" onmouseout="this.style.color='black'">
        Hover over me!
    </p>
</body>
</html>

2. Internal JavaScript

JavaScript code written inside <script> tags within the HTML document:

<!DOCTYPE html>
<html>
<head>
    <title>Internal JavaScript</title>
</head>
<body>
    <h1 id="heading">Welcome</h1>
    
    <script>
        // JavaScript code goes here
        console.log("Hello from internal script!");
        document.getElementById("heading").style.color = "blue";
    </script>
</body>
</html>

3. External JavaScript

JavaScript code written in separate .js files and linked to HTML:

HTML File (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>External JavaScript</title>
    <script src="script.js"></script>
</head>
<body>
    <h1>Check the console!</h1>
</body>
</html>

JavaScript File (script.js):

console.log("Hello from external script!");
alert("Welcome to my website!");

Best Practice:

Use external JavaScript files for better organization, reusability, and maintenance.


JavaScript Syntax & Variables

Basic Syntax Rules:

  • Statements end with semicolon ; (optional but recommended)
  • Case-sensitive: Name and name are different
  • Whitespace is ignored (use for readability)
  • Code blocks are enclosed in curly braces {}

Variables

Variables are containers that store data values.

Declaration Methods:

// 1. var (old way - avoid in modern JavaScript)
var oldVariable = "I'm old school";

// 2. let (modern way - block scoped)
let modernVariable = "I'm modern";

// 3. const (for constants - cannot be reassigned)
const PI = 3.14159;

Variable Naming Rules:

  • Must start with letter, underscore _, or dollar sign $
  • Cannot start with numbers
  • Cannot use reserved keywords (like function, if, class)
  • Use camelCase convention: firstName, userAge, isLoggedIn
// Valid variable names
let firstName = "John";
let user_age = 25;
let $price = 99.99;
let _private = "secret";

// Invalid variable names
// let 123name = "invalid";     // starts with number
// let class = "invalid";       // reserved keyword
// let user-name = "invalid";   // contains hyphen

Data Types

JavaScript has two categories of data types:

Primitive Data Types

1. Number

let age = 25;           // Integer
let price = 99.99;      // Decimal
let negative = -10;     // Negative number
let infinity = Infinity; // Special number value
let notANumber = NaN;   // Not a Number

2. String

let singleQuotes = 'Hello World';
let doubleQuotes = "Hello World";
let backticks = `Hello World`;        // Template literals
let multiLine = `This is
a multi-line
string`;

// String concatenation
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;   // "John Doe"
let templateName = `${firstName} ${lastName}`; // "John Doe"

3. Boolean

let isActive = true;
let isCompleted = false;
let isLoggedIn = Boolean(1);    // true
let isEmpty = Boolean(0);       // false

4. Undefined

let notAssigned;
console.log(notAssigned);       // undefined

let user = {name: "John"};
console.log(user.age);          // undefined

5. Null

let data = null;                // Intentionally empty
let response = null;            // Will be filled later

Non-Primitive Data Types

1. Object

let person = {
    name: "John",
    age: 30,
    isStudent: false
};

console.log(person.name);       // "John"
console.log(person["age"]);     // 30

2. Array (Special type of object)

let numbers = [1, 2, 3, 4, 5];
let fruits = ["apple", "banana", "orange"];
let mixed = [1, "hello", true, null];

console.log(numbers[0]);        // 1
console.log(fruits.length);     // 3

Type Checking

console.log(typeof 42);         // "number"
console.log(typeof "Hello");    // "string"
console.log(typeof true);       // "boolean"
console.log(typeof undefined);  // "undefined"
console.log(typeof null);       // "object" (this is a known quirk)
console.log(typeof {});         // "object"
console.log(typeof []);         // "object"

Different Ways of Printing Output

1. console.log() – Developer Console

Most common for debugging and development:

console.log("Hello World!");
console.log(42);
console.log(true);

let name = "Alice";
console.log("User name is:", name);
console.log(`Welcome ${name}!`);

// Multiple values
console.log("Name:", name, "Age:", 25);

2. alert() – Browser Alert Box

Shows popup dialog:

alert("Welcome to our website!");
alert("Your order has been placed!");

let message = "Thank you for visiting!";
alert(message);

3. document.write() – Write to HTML Document

Writes directly to the HTML page:

document.write("Hello World!");
document.write("<h1>Welcome!</h1>");
document.write("<p>Today is " + new Date() + "</p>");

Note: Avoid document.write() in modern web development.

4. innerHTML – Update HTML Elements

Change content of specific HTML elements:

<p id="demo">Original content</p>

<script>
document.getElementById("demo").innerHTML = "New content!";
document.getElementById("demo").innerHTML = "<strong>Bold text</strong>";
</script>

5. innerText – Update Text Content

Change only the text (no HTML):

document.getElementById("demo").innerText = "Plain text only";

Different Ways of Getting User Input

1. prompt() – Simple Input Dialog

Shows input dialog box:

let userName = prompt("Enter your name:");
console.log("Hello " + userName);

let age = prompt("Enter your age:");
let ageNumber = parseInt(age);      // Convert string to number
console.log("You are " + ageNumber + " years old");

// With default value
let city = prompt("Enter your city:", "New York");

2. confirm() – Yes/No Dialog

Shows confirmation dialog:

let isConfirmed = confirm("Are you sure you want to delete?");
console.log(isConfirmed);           // true or false

if (isConfirmed) {
    console.log("Item deleted!");
} else {
    console.log("Action cancelled");
}

3. HTML Form Elements

More user-friendly input methods:

<!DOCTYPE html>
<html>
<body>
    <input type="text" id="userInput" placeholder="Enter your name">
    <button onclick="getUserInput()">Submit</button>
    <p id="result"></p>

    <script>
        function getUserInput() {
            let input = document.getElementById("userInput").value;
            document.getElementById("result").innerHTML = "Hello " + input + "!";
        }
    </script>
</body>
</html>

4. Different Input Types

<!-- Text input -->
<input type="text" id="name" placeholder="Your name">

<!-- Number input -->
<input type="number" id="age" min="1" max="120">

<!-- Email input -->
<input type="email" id="email" placeholder="your@email.com">

<!-- Password input -->
<input type="password" id="password">

<!-- Checkbox -->
<input type="checkbox" id="newsletter"> Subscribe to newsletter

<!-- Radio buttons -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

<!-- Select dropdown -->
<select id="country">
    <option value="us">United States</option>
    <option value="uk">United Kingdom</option>
    <option value="ca">Canada</option>
</select>

Operators

1. Arithmetic Operators

let a = 10;
let b = 3;

console.log(a + b);     // 13 (Addition)
console.log(a - b);     // 7  (Subtraction)
console.log(a * b);     // 30 (Multiplication)
console.log(a / b);     // 3.33 (Division)
console.log(a % b);     // 1  (Modulus - remainder)
console.log(a ** b);    // 1000 (Exponentiation)

// Increment and Decrement
let count = 5;
count++;                // count = 6 (post-increment)
++count;                // count = 7 (pre-increment)
count--;                // count = 6 (post-decrement)
--count;                // count = 5 (pre-decrement)

2. Assignment Operators

let x = 10;

x += 5;                 // x = x + 5 → x = 15
x -= 3;                 // x = x - 3 → x = 12
x *= 2;                 // x = x * 2 → x = 24
x /= 4;                 // x = x / 4 → x = 6
x %= 4;                 // x = x % 4 → x = 2

3. Comparison Operators

let a = 10;
let b = "10";

console.log(a == b);    // true  (equal value, different types)
console.log(a === b);   // false (equal value and type)
console.log(a != b);    // false (not equal value)
console.log(a !== b);   // true  (not equal value or type)
console.log(a > 5);     // true  (greater than)
console.log(a < 20);    // true  (less than)
console.log(a >= 10);   // true  (greater than or equal)
console.log(a <= 10);   // true  (less than or equal)

4. Logical Operators

let age = 25;
let hasLicense = true;

// AND operator (&&)
if (age >= 18 && hasLicense) {
    console.log("Can drive");
}

// OR operator (||)
if (age < 18 || !hasLicense) {
    console.log("Cannot drive");
}

// NOT operator (!)
let isMinor = !(age >= 18);
console.log(isMinor);           // false

Conditional Statements

1. if Statement

let age = 18;

if (age >= 18) {
    console.log("You are an adult");
}

2. if…else Statement

let temperature = 25;

if (temperature > 30) {
    console.log("It's hot outside");
} else {
    console.log("It's not too hot");
}

3. if…else if…else Statement

let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else if (score >= 60) {
    console.log("Grade: D");
} else {
    console.log("Grade: F");
}

4. switch Statement

let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of work week");
        break;
    case "Tuesday":
    case "Wednesday":
    case "Thursday":
        console.log("Midweek");
        break;
    case "Friday":
        console.log("TGIF!");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Invalid day");
}

5. Ternary Operator

let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status);            // "adult"

// Multiple conditions
let weather = "sunny";
let activity = weather === "sunny" ? "go to beach" : 
               weather === "rainy" ? "stay inside" : 
               "go for a walk";

Loops

1. for Loop

// Basic for loop
for (let i = 0; i < 5; i++) {
    console.log("Count:", i);
}

// Loop through numbers with step
for (let i = 0; i <= 10; i += 2) {
    console.log(i);             // 0, 2, 4, 6, 8, 10
}

// Reverse loop
for (let i = 10; i >= 0; i--) {
    console.log(i);
}

2. while Loop

let count = 0;

while (count < 5) {
    console.log("Count:", count);
    count++;
}

// User input validation
let password;
while (password !== "secret") {
    password = prompt("Enter password:");
}
console.log("Access granted!");

3. do…while Loop

let number;

do {
    number = parseInt(prompt("Enter a number between 1-10:"));
} while (number < 1 || number > 10);

console.log("Valid number:", number);

4. Loop Control Statements

break Statement

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;                  // Exit the loop
    }
    console.log(i);             // Prints: 0, 1, 2, 3, 4
}

continue Statement

for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue;               // Skip even numbers
    }
    console.log(i);             // Prints: 1, 3, 5, 7, 9
}

Comments

Single-line Comments

// This is a single-line comment
let name = "John";              // Comment at end of line

// Use comments to explain complex logic
// Calculate area of circle
let radius = 5;
let area = Math.PI * radius * radius;

Multi-line Comments

/*
This is a multi-line comment
It can span multiple lines
Use for longer explanations
*/

let price = 99.99;

/*
TODO: Add the following features:
- Tax calculation
- Discount application  
- Currency conversion
*/

Best Practices for Comments:

  • Explain why, not what
  • Keep comments up-to-date
  • Don’t over-comment obvious code
  • Use comments for complex logic
  • Add TODO comments for future improvements

Best Practices

1. Variable Naming

// Good
let firstName = "John";
let userAge = 25;
let isLoggedIn = true;
let MAX_ATTEMPTS = 3;

// Bad
let a = "John";
let xyz = 25;
let flag = true;

2. Use const and let

// Good
const PI = 3.14159;
let userScore = 0;

// Avoid
var oldStyle = "avoid this";

3. Consistent Indentation

// Good
if (age >= 18) {
    console.log("Adult");
    if (hasLicense) {
        console.log("Can drive");
    }
}

// Bad
if(age>=18){
console.log("Adult");
if(hasLicense){
console.log("Can drive");
}
}

4. Use Semicolons

// Good
let name = "John";
console.log(name);

// Works but not recommended
let name = "John"
console.log(name)

5. Error Handling

let userInput = prompt("Enter a number:");
let number = parseInt(userInput);

if (isNaN(number)) {
    console.log("Please enter a valid number");
} else {
    console.log("Number is:", number);
}

6. Use Template Literals

let name = "Alice";
let age = 25;

// Good
let message = `Hello ${name}, you are ${age} years old`;

// Old way
let message = "Hello " + name + ", you are " + age + " years old";

Quick Reference Cheat Sheet

Variables

const PI = 3.14;        // Constant
let score = 100;        // Variable

Data Types

typeof "text"           // "string"
typeof 42               // "number"  
typeof true             // "boolean"
typeof undefined        // "undefined"
typeof null             // "object"

Input/Output

console.log("text");
alert("message");
let input = prompt("Enter:");

Conditions

if (condition) { }
else if (condition) { }
else { }

condition ? true_value : false_value;

Loops

for (let i = 0; i < 10; i++) { }
while (condition) { }
do { } while (condition);

Conclusion

You’ve now learned the fundamental building blocks of JavaScript! These basics form the foundation for everything else you’ll learn in web development.

Next Steps:

  • Practice writing small programs using these concepts
  • Experiment with combining different features
  • Start building simple interactive web pages
  • Learn about Arrays, Functions, and DOM manipulation

Remember: Practice makes perfect! The more you code, the more comfortable you’ll become with JavaScript syntax and logic.

Happy coding! 🎉

Leave a Reply

Your email address will not be published. Required fields are marked *