Class 5: JavaScript Basics: Variables, data types, operators.
Welcome to Class 5, where we will explore the fundamentals of JavaScript, focusing on variables, data 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:
var: The old way of declaring variables (not recommended due to scoping issues).let: Used to declare variables that can be reassigned.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
- Must start with a letter, underscore (
_), or dollar sign ($). - Cannot contain spaces or special characters.
- Must not be a reserved keyword (e.g.,
let,const,if).
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
string: Represents text.const name = "Alice";number: Represents both integers and floating-point numbers.let age = 30; // Integer let price = 19.99; // Floatboolean: Representstrueorfalse.let isLoggedIn = true;undefined: A variable that has been declared but not assigned a value.let x; console.log(x); // undefinednull: Represents an intentional absence of a value.let emptyValue = null;symbol: Represents unique identifiers.let id = Symbol("uniqueId");
Non-Primitive Data Types
- Object: A collection of key-value pairs.
const person = { name: "John", age: 30 }; - 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
- 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) - 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
- Use
letandconstfor declaring variables (avoidvar). - Understand and use primitive and non-primitive data types.
- Operators are the building blocks of logic in JavaScript:
- Arithmetic for math.
- Comparison for decision-making.
- Logical for combining conditions.
Homework
- Create a program to calculate the area and perimeter of a rectangle.
- Write a program to check whether a number is even or odd using the
%operator. - 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.