Session 2.1 – JavaScript Basics: Variables and Operators

Module 2: JavaScript & AJAX | Duration: 1 hr

Learning Objectives

By the end of this session, students will be able to:

  • Understand the fundamentals of JavaScript and its role in web development
  • Declare and use variables with var, let, and const keywords
  • Identify and work with different JavaScript data types
  • Apply various operators including arithmetic, comparison, and logical operators
  • Perform type conversion and coercion in JavaScript

Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. It enables interactive web pages and is an essential part of web applications.

What is JavaScript?

JavaScript is a versatile, event-driven scripting language that runs in web browsers, allowing developers to create dynamic content, control multimedia, animate images, and much more. Unlike HTML and CSS, which define the structure and style of web pages, JavaScript adds behavior and interactivity.

Client-Side

Runs directly in the user's browser without server interaction

Dynamic

Can modify page content and respond to user actions in real-time

Versatile

Used for both frontend and backend development (Node.js)

JavaScript Variables

Variables are containers for storing data values. In JavaScript, you can declare variables using three keywords: var, let, and const.

Variable Declaration Methods

// Using var (old way - function scoped)
var name = "John Doe";
var age = 25;

// Using let (modern - block scoped)
let city = "New York";
let isStudent = true;

// Using const (constant - cannot be reassigned)
const PI = 3.14159;
const MAX_SIZE = 100;
Keyword Scope Reassignable Hoisting When to Use
var Function Yes Yes (undefined) Legacy code (avoid in modern JS)
let Block Yes No When value will change
const Block No No For constants or objects that won't be reassigned
Best Practice

Use const by default. Use let only when you need to reassign a variable. Avoid var in modern JavaScript development.

JavaScript Data Types

JavaScript is a dynamically typed language, meaning variables can hold values of any type without type declaration.

Primitive Data Types

// Number - integers and floating-point numbers
let integer = 42;
let float = 3.14;
let negative = -10;

// String - text data
let singleQuote = 'Hello';
let doubleQuote = "World";
let templateLiteral = `Hello ${singleQuote}`;

// Boolean - true or false
let isActive = true;
let isCompleted = false;

// Undefined - variable declared but not assigned
let notAssigned;
console.log(notAssigned); // undefined

// Null - intentional absence of value
let emptyValue = null;

// Symbol (ES6) - unique identifier
let sym = Symbol('description');

// BigInt (ES2020) - large integers
let bigNumber = 1234567890123456789012345678901234567890n;

Reference Data Types

// Object - collection of key-value pairs
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

// Array - ordered collection
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];

// Function - reusable code block
function greet(name) {
    return `Hello, ${name}!`;
}
Type Checking Demo
// Using typeof operator
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" (historical bug)
console.log(typeof {name: "John"}); // "object"
console.log(typeof [1, 2, 3]);    // "object"
console.log(typeof function(){}); // "function"

JavaScript Operators

1. Arithmetic Operators

Perform mathematical calculations on numeric values.

let a = 10, b = 3;

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

// Increment and Decrement
let x = 5;
console.log(++x);     // Pre-increment: 6
console.log(x++);     // Post-increment: 6 (then becomes 7)
console.log(--x);     // Pre-decrement: 6
console.log(x--);     // Post-decrement: 6 (then becomes 5)

2. Assignment Operators

let num = 10;

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

3. Comparison Operators

let x = 5, y = "5";

// Equality operators
console.log(x == y);    // true (loose equality - type coercion)
console.log(x === y);   // false (strict equality - no type coercion)
console.log(x != y);    // false (loose inequality)
console.log(x !== y);   // true (strict inequality)

// Relational operators
console.log(5 > 3);     // true
console.log(5 < 3);     // false
console.log(5 >= 5);    // true
console.log(5 <= 4);    // false

4. Logical Operators

let age = 25;
let hasLicense = true;

// AND operator (&&) - both conditions must be true
console.log(age >= 18 && hasLicense);  // true

// OR operator (||) - at least one condition must be true
console.log(age < 18 || hasLicense);   // true

// NOT operator (!) - inverts the boolean value
console.log(!hasLicense);              // false

// Logical assignment (ES2021)
let value = null;
value ??= 10;  // Assigns 10 if value is null or undefined
console.log(value);  // 10

5. String Operators

// Concatenation operator
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName);  // "John Doe"

// Concatenation assignment
let greeting = "Hello";
greeting += " World";
console.log(greeting);  // "Hello World"

// Template literals (modern approach)
let name = "Alice";
let age = 30;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);

6. Ternary (Conditional) Operator

// Syntax: condition ? valueIfTrue : valueIfFalse
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status);  // "Adult"

// Can be nested (but use sparingly)
let score = 85;
let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" : "F";
console.log(grade);  // "B"

Type Conversion and Coercion

Implicit Type Coercion

JavaScript automatically converts types in certain situations.

// String concatenation
console.log("5" + 3);       // "53" (number to string)
console.log("5" - 3);       // 2 (string to number)
console.log("5" * "2");     // 10 (both to numbers)

// Boolean context
console.log(5 + true);      // 6 (true becomes 1)
console.log(5 + false);     // 5 (false becomes 0)

// Truthy and Falsy values
// Falsy: false, 0, "", null, undefined, NaN
// Everything else is truthy
if ("hello") {
    console.log("This runs!");  // Non-empty string is truthy
}

Explicit Type Conversion

// To String
let num = 123;
let str1 = String(num);           // "123"
let str2 = num.toString();        // "123"
let str3 = "" + num;              // "123"

// To Number
let str = "456";
let num1 = Number(str);           // 456
let num2 = parseInt(str);         // 456 (integer)
let num3 = parseFloat("3.14");    // 3.14 (float)
let num4 = +str;                  // 456 (unary plus)

// To Boolean
let bool1 = Boolean(1);           // true
let bool2 = Boolean(0);           // false
let bool3 = Boolean("hello");     // true
let bool4 = Boolean("");          // false
let bool5 = !!"test";             // true (double negation)
Common Pitfalls
// Be careful with these
console.log(typeof NaN);          // "number" (Not a Number is a number type!)
console.log(NaN === NaN);         // false (NaN is not equal to itself)
console.log(0.1 + 0.2 === 0.3);   // false (floating-point precision)
console.log([] + []);             // "" (empty string)
console.log([] + {});             // "[object Object]"
console.log({} + []);             // 0 (or "[object Object]" depending on context)

Practical Examples

Example 1: Simple Calculator

// Basic calculator function
function calculate(num1, num2, operator) {
    let result;

    switch(operator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num2 !== 0 ? num1 / num2 : "Cannot divide by zero";
            break;
        default:
            result = "Invalid operator";
    }

    return result;
}

console.log(calculate(10, 5, '+'));   // 15
console.log(calculate(10, 5, '-'));   // 5
console.log(calculate(10, 5, '*'));   // 50
console.log(calculate(10, 5, '/'));   // 2

Example 2: Temperature Converter

// Convert Celsius to Fahrenheit and vice versa
function celsiusToFahrenheit(celsius) {
    return (celsius * 9/5) + 32;
}

function fahrenheitToCelsius(fahrenheit) {
    return (fahrenheit - 32) * 5/9;
}

const tempC = 25;
const tempF = 77;

console.log(`${tempC}°C = ${celsiusToFahrenheit(tempC)}°F`);
console.log(`${tempF}°F = ${fahrenheitToCelsius(tempF).toFixed(2)}°C`);

Example 3: Age Calculator

// Calculate age from birth year
function calculateAge(birthYear) {
    const currentYear = new Date().getFullYear();
    const age = currentYear - birthYear;

    // Determine life stage
    let stage;
    if (age < 13) {
        stage = "Child";
    } else if (age < 20) {
        stage = "Teenager";
    } else if (age < 60) {
        stage = "Adult";
    } else {
        stage = "Senior";
    }

    return `Age: ${age}, Life Stage: ${stage}`;
}

console.log(calculateAge(2000));  // Age: 25, Life Stage: Adult
console.log(calculateAge(2010));  // Age: 15, Life Stage: Teenager

Session Summary

Key Points
  • JavaScript is a client-side scripting language that adds interactivity to web pages
  • Variables can be declared using var, let, or const
  • JavaScript has primitive types (number, string, boolean, undefined, null, symbol, bigint) and reference types (objects, arrays, functions)
  • Operators include arithmetic, assignment, comparison, logical, and string operators
  • Type conversion can be implicit (coercion) or explicit (using conversion functions)
  • Best practices: Use const by default, use === for comparison, and be aware of type coercion
Next Session Preview

In the next session, we will explore Control Structures and Loops, including if-else statements, switch cases, for loops, while loops, and loop control statements.