Class 5: JavaScript Basics: Variables, data types, operators.

Welcome to Class 5, where we will explore the fundamentals of JavaScript, focusing on variablesdata types, and operators. This class is the foundation of JavaScript programming and will help you build the skills needed for more advanced topics.

1. Variables in JavaScript

What are Variables?

Variables are containers that store data values. They allow you to store, update, and retrieve data throughout your program.

Declaring Variables

In JavaScript, you can declare variables using the following keywords:

  1. var: The old way of declaring variables (not recommended due to scoping issues).
  2. let: Used to declare variables that can be reassigned.
  3. const: Used to declare variables that cannot be reassigned (constant values).

Syntax

let variableName = value;  
const constantName = value;  
var oldVariable = value; // Not recommended  

Examples

let age = 25; // Can be updated later  
const name = "John"; // Cannot be updated  
var isAlive = true; // Old variable declaration  

Rules for Variable Names

  1. Must start with a letter, underscore (_), or dollar sign ($).
  2. Cannot contain spaces or special characters.
  3. Must not be a reserved keyword (e.g., letconstif).

2. Data Types in JavaScript

What are Data Types?

Data types specify the kind of data that can be stored in a variable. JavaScript has two main categories of data types:

  • Primitive Data Types: Simple values.
  • Non-Primitive Data Types: Complex structures.

Primitive Data Types

  1. string: Represents text.const name = "Alice";
  2. number: Represents both integers and floating-point numbers.let age = 30; // Integer let price = 19.99; // Float
  3. boolean: Represents true or false.let isLoggedIn = true;
  4. undefined: A variable that has been declared but not assigned a value.let x; console.log(x); // undefined
  5. null: Represents an intentional absence of a value.let emptyValue = null;
  6. symbol: Represents unique identifiers.let id = Symbol("uniqueId");

Non-Primitive Data Types

  1. Object: A collection of key-value pairs.const person = { name: "John", age: 30 };
  2. Array: An ordered collection of values.const fruits = ["apple", "banana", "cherry"];

Checking Data Types

You can use the typeof operator to check the data type of a variable.

console.log(typeof "Hello"); // string  
console.log(typeof 42); // number  
console.log(typeof true); // boolean  
console.log(typeof undefined); // undefined  
console.log(typeof null); // object (this is a known JavaScript quirk)  
console.log(typeof { key: "value" }); // object  
console.log(typeof ["apple", "banana"]); // object (arrays are objects)  

3. Operators in JavaScript

What are Operators?

Operators are symbols or keywords that perform operations on variables or values.

Types of Operators

  1. Arithmetic Operators
    Perform mathematical operations.let a = 10; let b = 3; console.log(a + b); // Addition: 13 console.log(a - b); // Subtraction: 7 console.log(a * b); // Multiplication: 30 console.log(a / b); // Division: 3.3333 console.log(a % b); // Modulus (Remainder): 1 console.log(a ** b); // Exponentiation: 1000 (10^3)
  2. Assignment Operators
    Assign values to variables.let x = 10; // Assign x += 5; // Add and assign (x = x + 5) x -= 2; // Subtract and assign (x = x - 2) x *= 3; // Multiply and assign (x = x * 3) x /= 2; // Divide and assign (x = x / 2)

3. Comparison Operators
Compare two values and return a boolean (true or false).

let a = 5;  
let b = 10;  

console.log(a == b); // Equal to: false  
console.log(a != b); // Not equal to: true  
console.log(a === b); // Strict equal to (checks value and type): false  
console.log(a !== b); // Strict not equal to: true  
console.log(a < b); // Less than: true  
console.log(a > b); // Greater than: false  
console.log(a <= b); // Less than or equal to: true  
console.log(a >= b); // Greater than or equal to: false  

4. Logical Operators
Combine or invert boolean values.

let x = true;  
let y = false;  

console.log(x && y); // AND: false (both must be true)  
console.log(x || y); // OR: true (at least one must be true)  
console.log(!x); // NOT: false (inverts the value)  

5. String Operators
Concatenate or manipulate strings.

let firstName = "John";  
let lastName = "Doe";  

console.log(firstName + " " + lastName); // Concatenation: "John Doe"  

6. Unary Operators
Operate on a single value.

let x = 5;  
console.log(++x); // Increment: 6  
console.log(--x); // Decrement: 5  
console.log(typeof x); // Returns the type of x: "number"  

7. Ternary Operator
A shorthand for conditional statements.

let age = 18;  
let canVote = age >= 18 ? "Yes" : "No";  
console.log(canVote); // "Yes"  

4. Practical Examples

Example 1: Basic Arithmetic

let radius = 5;  
const pi = 3.14159;  
  
let area = pi * radius ** 2;  
console.log("Area of circle:", area);  

Example 2: Conditional Logic with Ternary Operator

let score = 85;  
let grade = score >= 60 ? "Pass" : "Fail";  
console.log("Grade:", grade);  

Example 3: String Manipulation

let greeting = "Hello";  
let name = "Alice";  
  
console.log(greeting + ", " + name + "!"); // "Hello, Alice!"  

Example 4: Logical Operators

let isAdult = true;  
let hasID = false;  
  
if (isAdult && hasID) {  
  console.log("You can enter.");  
} else {  
  console.log("Access denied.");  
}  

5. Key Takeaways

  1. Use let and const for declaring variables (avoid var).
  2. Understand and use primitive and non-primitive data types.
  3. Operators are the building blocks of logic in JavaScript:
    • Arithmetic for math.
    • Comparison for decision-making.
    • Logical for combining conditions.

Homework

  1. Create a program to calculate the area and perimeter of a rectangle.
  2. Write a program to check whether a number is even or odd using the % operator.
  3. Create a program that outputs a greeting based on the time of day using the ternary operator.

This concludes Class 5: JavaScript Basics! You should now have a solid understanding of variables, data types, and operators.