Master JavaScript variables, understand different data types, and learn operators for building logic in your programs. Learn variable declarations, type conversion, and arithmetic operations.
Variables are the foundation of programming - they're containers that store data values that can be used throughout your program. JavaScript is a dynamically typed language, meaning variables can hold different types of data and can change type during program execution.
Understanding data types and operators is crucial for building any JavaScript application. From simple calculations to complex data manipulation, these concepts form the building blocks of programming logic.
In this lesson, you'll master JavaScript's type system, learn the best practices for variable declarations, and understand how to use operators to create powerful programming logic that responds to user input and manipulates data effectively.
JavaScript provides three ways to declare variables, each with specific use cases and behaviors. Understanding when and how to use each is essential for writing modern, maintainable code.
1. let - Modern Variable Declaration
let is the modern way to declare variables that can be reassigned:
1let userName = "Alice";
2let age = 25;
3let isActive = true;
4
5// Variables can be reassigned
6userName = "Bob";
7age = 26;
8
9console.log(userName); // "Bob"
10console.log(age); // 26Key Features of let:
2. const - Constants and Immutable References
const is used for values that shouldn't be reassigned:
1const PI = 3.14159;
2const siteName = "My Website";
3const currentYear = 2024;
4
5// This would cause an error:
6// PI = 3.14; // TypeError: Assignment to constant variable
7
8// However, object and array contents can be modified:
9const user = {
10 name: "Alice",
11 age: 25
12};
13
14user.age = 26; // This is allowed - we're modifying the object, not reassigning
15user.city = "New York"; // Adding new properties is also allowed
16
17const colors = ["red", "green", "blue"];
18colors.push("yellow"); // This is allowed - we're modifying the arrayKey Features of const:
3. var - Legacy Variable Declaration (Avoid)
var is the old way of declaring variables and has several issues:
1var oldVariable = "legacy";
2var oldVariable = "redeclared"; // Allowed but problematic
3
4// Function-scoped, not block-scoped
5if (true) {
6 var x = 1;
7}
8console.log(x); // 1 (accessible outside the block)
9
10// Hoisting issues
11console.log(y); // undefined (not an error, but confusing)
12var y = 5;Problems with var:
Best Practices for Variable Declarations:
const by default** for values that won't be reassignedlet when you need to reassign** the variablevar completely** in modern JavaScriptuserName instead of u1// Good examples
2const MAX_USERS = 100;
3const apiUrl = "https://api.example.com";
4let currentUser = null;
5let score = 0;
6
7// Poor examples
8var x = 5; // Use const or let instead
9let u; // Not descriptive
10const data; // Error: const must be initializedVariable Naming Conventions:
firstName, getUserData, isLoggedInMAX_RETRIES, API_BASE_URL (for constants)function, class, return, ifcalculateTotalPrice instead of calcJavaScript has a dynamic type system with several built-in data types. Understanding these types is essential for effective programming and debugging.
Primitive Data Types:
1. String - Text Data
Strings represent textual data and can be created with single quotes, double quotes, or template literals:
1let firstName = "John";
2let lastName = 'Smith';
3let greeting = `Hello, ${firstName} ${lastName}!`; // Template literal
4
5// String properties and methods
6console.log(firstName.length); // 4
7console.log(firstName.toUpperCase()); // "JOHN"
8console.log(firstName.toLowerCase()); // "john"
9
10// String concatenation
11let fullName = firstName + " " + lastName; // "John Smith"
12let modernFullName = `${firstName} ${lastName}`; // Modern approach2. Number - Numeric Data
JavaScript has one number type that handles integers and decimals:
1let age = 25; // Integer
2let price = 19.99; // Decimal
3let negative = -10; // Negative number
4let scientific = 1.5e6; // 1,500,000 (scientific notation)
5
6// Special number values
7let infinity = Infinity;
8let notANumber = NaN; // "Not a Number"
9
10// Number methods
11console.log(price.toFixed(2)); // "19.99"
12console.log(Number.isInteger(age)); // true
13console.log(Number.isNaN(notANumber)); // true3. Boolean - True/False Values
Booleans represent logical values:
1let isActive = true;
2let isComplete = false;
3let hasPermission = Boolean(1); // true (conversion)
4
5// Boolean in conditions
6if (isActive) {
7 console.log("User is active");
8}
9
10// Logical operations
11let canAccess = isActive && hasPermission; // AND operation
12let shouldShow = isActive || isComplete; // OR operation
13let isInactive = !isActive; // NOT operation (negation)4. undefined and null - Empty Values
These represent "no value" but with different meanings:
1let notAssigned; // undefined (declared but not assigned)
2let emptyValue = null; // null (intentionally empty)
3
4console.log(typeof notAssigned); // "undefined"
5console.log(typeof emptyValue); // "object" (this is a known quirk)
6
7// Checking for these values
8if (notAssigned === undefined) {
9 console.log("Variable is undefined");
10}
11
12if (emptyValue === null) {
13 console.log("Variable is intentionally null");
14}Complex Data Types:
5. Arrays - Ordered Lists
Arrays store multiple values in a single variable:
1let fruits = ["apple", "banana", "orange"];
2let numbers = [1, 2, 3, 4, 5];
3let mixed = ["text", 42, true, null]; // Can contain different types
4
5// Array access and modification
6console.log(fruits[0]); // "apple" (first item)
7console.log(fruits.length); // 3
8
9fruits.push("grape"); // Add to end
10fruits.unshift("mango"); // Add to beginning
11let lastFruit = fruits.pop(); // Remove and return last item
12
13// Array methods
14let upperFruits = fruits.map(fruit => fruit.toUpperCase());
15let longFruits = fruits.filter(fruit => fruit.length > 5);6. Objects - Key-Value Pairs
Objects store related data and functionality together:
1let person = {
2 name: "Alice Johnson",
3 age: 30,
4 city: "New York",
5 isEmployed: true,
6 hobbies: ["reading", "coding", "hiking"],
7
8 // Object methods
9 greet: function() {
10 return `Hello, I'm ${this.name}`;
11 },
12
13 // Modern method syntax
14 introduce() {
15 return `I'm ${this.name} and I live in ${this.city}`;
16 }
17};
18
19// Accessing object properties
20console.log(person.name); // Dot notation
21console.log(person["age"]); // Bracket notation
22console.log(person.greet()); // Method call
23
24// Modifying objects
25person.job = "Developer"; // Add new property
26person.age = 31; // Modify existing property
27delete person.city; // Remove propertyType Checking and Conversion:
1// Type checking with typeof
2console.log(typeof "Hello"); // "string"
3console.log(typeof 42); // "number"
4console.log(typeof true); // "boolean"
5console.log(typeof undefined); // "undefined"
6console.log(typeof null); // "object" (quirk)
7console.log(typeof []); // "object"
8console.log(typeof {}); // "object"
9
10// More specific type checking
11console.log(Array.isArray([])); // true
12console.log(person instanceof Object); // true
13
14// Type conversion
15let stringNumber = "42";
16let actualNumber = Number(stringNumber); // 42
17let backToString = String(actualNumber); // "42"
18let booleanValue = Boolean(1); // true
19
20// Automatic type conversion (coercion)
21console.log("5" + 3); // "53" (string concatenation)
22console.log("5" - 3); // 2 (numeric subtraction)
23console.log("5" * "2"); // 10 (numeric multiplication)Best Practices for Data Types:
=== instead of ==** for strict equalityOperators are symbols that perform operations on variables and values. JavaScript provides several categories of operators for different types of operations.
Arithmetic Operators - Mathematical Operations:
1let a = 10;
2let b = 3;
3
4// Basic arithmetic
5let addition = a + b; // 13
6let subtraction = a - b; // 7
7let multiplication = a * b; // 30
8let division = a / b; // 3.333...
9let remainder = a % b; // 1 (modulo - remainder of division)
10
11// Exponentiation (ES2016)
12let power = a ** b; // 1000 (10 to the power of 3)
13
14// Assignment with arithmetic
15let x = 5;
16x += 3; // x = x + 3, now x is 8
17x -= 2; // x = x - 2, now x is 6
18x *= 2; // x = x * 2, now x is 12
19x /= 3; // x = x / 3, now x is 4
20
21// Increment and decrement
22let counter = 0;
23counter++; // Post-increment: use value, then add 1
24++counter; // Pre-increment: add 1, then use value
25counter--; // Post-decrement: use value, then subtract 1
26--counter; // Pre-decrement: subtract 1, then use value
27
28console.log(counter); // Current value depends on operations aboveComparison Operators - Testing Relationships:
1let num1 = 10;
2let num2 = "10";
3let num3 = 5;
4
5// Equality comparisons
6console.log(num1 == num2); // true (loose equality - type conversion)
7console.log(num1 === num2); // false (strict equality - no conversion)
8console.log(num1 != num3); // true (not equal, loose)
9console.log(num1 !== num2); // true (not equal, strict)
10
11// Relational comparisons
12console.log(num1 > num3); // true
13console.log(num1 < num3); // false
14console.log(num1 >= 10); // true
15console.log(num3 <= 5); // true
16
17// String comparisons (lexicographic)
18console.log("apple" < "banana"); // true
19console.log("Apple" < "apple"); // true (uppercase comes first)
20
21// Comparing different types
22console.log(10 > "5"); // true (string converted to number)
23console.log("10" > "5"); // false (string comparison)Logical Operators - Boolean Logic:
1let isLoggedIn = true;
2let hasPermission = false;
3let isAdmin = true;
4
5// AND operator (&&) - both conditions must be true
6let canEdit = isLoggedIn && hasPermission; // false
7let canDelete = isLoggedIn && isAdmin; // true
8
9// OR operator (||) - at least one condition must be true
10let canView = isLoggedIn || hasPermission; // true
11let hasAccess = hasPermission || isAdmin; // true
12
13// NOT operator (!) - reverses the boolean value
14let isGuest = !isLoggedIn; // false
15let needsLogin = !isLoggedIn; // false
16
17// Complex logical expressions
18let canModify = (isLoggedIn && hasPermission) || isAdmin;
19let restrictedAccess = isLoggedIn && !hasPermission && !isAdmin;
20
21// Short-circuit evaluation
22let defaultName = userName || "Guest"; // Use "Guest" if userName is falsy
23let shouldProcess = isLoggedIn && processUserData(); // Only call function if logged inString Operators - Text Manipulation:
1let firstName = "John";
2let lastName = "Doe";
3let age = 30;
4
5// String concatenation with +
6let fullName = firstName + " " + lastName; // "John Doe"
7let greeting = "Hello, " + firstName + "!"; // "Hello, John!"
8
9// Compound assignment with strings
10let message = "Welcome";
11message += " to our website"; // "Welcome to our website"
12message += ", " + firstName; // "Welcome to our website, John"
13
14// Template literals (modern approach)
15let modernGreeting = `Hello, ${firstName} ${lastName}!`;
16let userInfo = `User: ${fullName}, Age: ${age}`;
17let multiLine = `
18 This is a multi-line
19 string using template
20 literals.
21`;
22
23// Mixing strings and numbers
24let result = "The answer is " + 42; // "The answer is 42"
25let calculation = "5" + 3; // "53" (string concatenation)
26let mathResult = "5" * 3; // 15 (numeric operation)Assignment Operators - Storing Values:
1let x = 10; // Basic assignment
2
3// Arithmetic assignment operators
4x += 5; // x = x + 5 (now 15)
5x -= 3; // x = x - 3 (now 12)
6x *= 2; // x = x * 2 (now 24)
7x /= 4; // x = x / 4 (now 6)
8x %= 3; // x = x % 3 (now 0)
9x **= 3; // x = x ** 3 (now 0)
10
11// String assignment
12let text = "Hello";
13text += " World"; // text = text + " World" (now "Hello World")
14
15// Multiple assignment
16let a, b, c;
17a = b = c = 5; // All variables get value 5
18
19// Destructuring assignment (modern JavaScript)
20let [first, second] = [1, 2]; // first = 1, second = 2
21let {name, age} = {name: "Alice", age: 25}; // Extract object propertiesConditional (Ternary) Operator - Inline Conditions:
1let age = 20;
2let isAdult = age >= 18 ? true : false; // Simple ternary
3let status = age >= 18 ? "Adult" : "Minor"; // More practical
4
5// Nested ternary (use sparingly)
6let category = age < 13 ? "Child" : age < 18 ? "Teen" : "Adult";
7
8// Using with functions
9let greeting = isLoggedIn ? getUserGreeting() : "Please log in";
10
11// Alternative to if/else for simple assignments
12let discount = isPremium ? 0.2 : 0.1; // 20% or 10% discount
13let shippingCost = orderTotal > 50 ? 0 : 5.99; // Free shipping over $50Operator Precedence and Associativity:
1// Operator precedence determines order of operations
2let result1 = 2 + 3 * 4; // 14 (multiplication first)
3let result2 = (2 + 3) * 4; // 20 (parentheses override precedence)
4
5// Comparison and logical operators
6let condition = 5 > 3 && 10 < 20; // true (comparison first, then logical)
7let complex = 2 + 3 > 4 && 10 / 2 === 5; // true
8
9// Assignment is right-associative
10let a, b, c;
11a = b = c = 10; // Assigns 10 to c, then b, then a
12
13// Be explicit with parentheses for clarity
14let calculation = (price * quantity) + (tax * price);
15let condition = (age >= 18) && (hasLicense === true);Type Coercion and Operators:
1// Automatic type conversion with operators
2console.log("5" + 2); // "52" (string concatenation)
3console.log("5" - 2); // 3 (numeric subtraction)
4console.log("5" * 2); // 10 (numeric multiplication)
5console.log("10" / "2"); // 5 (numeric division)
6
7// Boolean coercion
8console.log(!""); // true (empty string is falsy)
9console.log(!0); // true (0 is falsy)
10console.log(!null); // true (null is falsy)
11console.log(!"hello"); // false (non-empty string is truthy)
12
13// Comparison coercion
14console.log(0 == false); // true (loose equality)
15console.log(0 === false); // false (strict equality)
16console.log("" == false); // true (loose equality)
17console.log("" === false); // false (strict equality)Best Practices for Operators:
=== and !==** for comparisons to avoid type coercion issues+=, -=) for concisenessJavaScript is dynamically typed, meaning variables can change types during execution, and the language automatically converts types in certain situations. Understanding this behavior is crucial for writing reliable code.
Explicit Type Conversion (Type Casting):
Converting to String:
1// Using String() constructor
2let num = 42;
3let str1 = String(num); // "42"
4let bool = true;
5let str2 = String(bool); // "true"
6
7// Using .toString() method
8let str3 = num.toString(); // "42"
9let str4 = bool.toString(); // "true"
10
11// Template literals (implicit conversion)
12let str5 = `${num}`; // "42"
13let str6 = `The value is ${bool}`; // "The value is true"
14
15// Concatenation with empty string
16let str7 = num + ""; // "42"
17
18console.log(typeof str1); // "string"Converting to Number:
1// Using Number() constructor
2let str = "123";
3let num1 = Number(str); // 123
4let bool = true;
5let num2 = Number(bool); // 1 (true becomes 1, false becomes 0)
6
7// Using parseInt() and parseFloat()
8let str2 = "123.45px";
9let int = parseInt(str2); // 123 (stops at first non-digit)
10let float = parseFloat(str2); // 123.45 (stops at first non-numeric)
11
12// Using unary plus operator
13let num3 = +str; // 123 (quick conversion)
14let num4 = +"456"; // 456
15
16// Special cases
17console.log(Number("")); // 0 (empty string becomes 0)
18console.log(Number(" ")); // 0 (whitespace becomes 0)
19console.log(Number("abc")); // NaN (invalid number)
20console.log(Number(null)); // 0
21console.log(Number(undefined)); // NaN
22
23// Checking for valid numbers
24let userInput = "123abc";
25let converted = parseInt(userInput);
26if (isNaN(converted)) {
27 console.log("Invalid number");
28} else {
29 console.log("Valid number:", converted);
30}Converting to Boolean:
1// Using Boolean() constructor
2console.log(Boolean(1)); // true
3console.log(Boolean(0)); // false
4console.log(Boolean("")); // false (empty string)
5console.log(Boolean("hello")); // true (non-empty string)
6console.log(Boolean([])); // true (empty array is truthy!)
7console.log(Boolean({})); // true (empty object is truthy!)
8
9// Using double NOT operator (common shortcut)
10console.log(!!1); // true
11console.log(!!0); // false
12console.log(!!""); // false
13console.log(!!"hello"); // true
14
15// Falsy values in JavaScript
16let falsyValues = [false, 0, -0, 0n, "", null, undefined, NaN];
17falsyValues.forEach(value => {
18 console.log(`${value} is ${Boolean(value) ? 'truthy' : 'falsy'}`);
19});
20
21// Everything else is truthy
22let truthyValues = [true, 1, -1, "0", "false", [], {}, function() {}];
23truthyValues.forEach(value => {
24 console.log(`${value} is ${Boolean(value) ? 'truthy' : 'falsy'}`);
25});Implicit Type Conversion (Type Coercion):
String Coercion:
1// When using + with strings, everything becomes a string
2console.log("5" + 2); // "52"
3console.log("Hello " + true); // "Hello true"
4console.log("Result: " + null); // "Result: null"
5console.log("Value: " + undefined); // "Value: undefined"
6
7// Template literals always convert to string
8let mixed = `Age: ${25}, Active: ${true}`; // "Age: 25, Active: true"
9
10// Array to string conversion
11console.log("Items: " + [1, 2, 3]); // "Items: 1,2,3"
12console.log("User: " + {name: "John"}); // "User: [object Object]"Numeric Coercion:
1// Mathematical operators (except +) convert to numbers
2console.log("10" - 5); // 5
3console.log("10" * "2"); // 20
4console.log("15" / "3"); // 5
5console.log("10" % "3"); // 1
6
7// Unary operators
8console.log(+"42"); // 42
9console.log(-"42"); // -42
10console.log(+true); // 1
11console.log(+false); // 0
12console.log(+null); // 0
13console.log(+undefined); // NaN
14
15// Comparison operators
16console.log("10" > 5); // true (converts to numbers)
17console.log("10" > "5"); // false (string comparison)
18console.log("a" > 5); // false (NaN comparisons are always false)Boolean Coercion:
1// In conditional contexts, values are converted to boolean
2let value1 = "hello";
3if (value1) { // "hello" is truthy
4 console.log("This runs");
5}
6
7let value2 = 0;
8if (value2) { // 0 is falsy
9 console.log("This doesn't run");
10}
11
12// Logical operators use boolean coercion
13console.log("hello" && "world"); // "world" (both truthy, returns last)
14console.log(0 && "world"); // 0 (first is falsy, returns first)
15console.log("hello" || 0); // "hello" (first is truthy, returns first)
16console.log(0 || "world"); // "world" (first is falsy, returns second)Object and Array Coercion:
1// Objects convert to string via toString() method
2let obj = {
3 name: "John",
4 toString() {
5 return this.name;
6 }
7};
8
9console.log("User: " + obj); // "User: John"
10
11// Arrays convert to string by joining elements
12let arr = [1, 2, 3];
13console.log("Numbers: " + arr); // "Numbers: 1,2,3"
14
15let emptyArr = [];
16console.log("Empty: " + emptyArr); // "Empty: "
17
18// Date objects
19let now = new Date();
20console.log("Current time: " + now); // Converts to date stringComparison and Equality:
1// Loose equality (==) performs type coercion
2console.log(0 == false); // true
3console.log(1 == true); // true
4console.log("" == false); // true
5console.log("0" == false); // true
6console.log(null == undefined); // true
7
8// Strict equality (===) does NOT perform coercion
9console.log(0 === false); // false
10console.log(1 === true); // false
11console.log("" === false); // false
12console.log("0" === false); // false
13console.log(null === undefined); // false
14
15// Best practice: use strict equality
16function compareValues(a, b) {
17 if (a === b) {
18 return "Equal";
19 } else if (a == b) {
20 return "Equal after coercion";
21 } else {
22 return "Not equal";
23 }
24}
25
26console.log(compareValues(0, false)); // "Equal after coercion"
27console.log(compareValues(0, "0")); // "Equal after coercion"Practical Type Conversion Patterns:
1// Safe number conversion with validation
2function toSafeNumber(value, defaultValue = 0) {
3 const converted = Number(value);
4 return isNaN(converted) ? defaultValue : converted;
5}
6
7console.log(toSafeNumber("42")); // 42
8console.log(toSafeNumber("abc")); // 0
9console.log(toSafeNumber("abc", -1)); // -1
10
11// Safe boolean conversion
12function toSafeBoolean(value) {
13 if (typeof value === 'string') {
14 return value.toLowerCase() === 'true';
15 }
16 return Boolean(value);
17}
18
19console.log(toSafeBoolean("true")); // true
20console.log(toSafeBoolean("false")); // false
21console.log(toSafeBoolean(1)); // true
22
23// Input validation and conversion
24function processUserAge(input) {
25 // Convert to number
26 const age = parseInt(input);
27
28 // Validate
29 if (isNaN(age) || age < 0 || age > 150) {
30 throw new Error("Invalid age provided");
31 }
32
33 return age;
34}
35
36// Usage with error handling
37try {
38 let userAge = processUserAge("25");
39 console.log("Age is valid:", userAge);
40} catch (error) {
41 console.log("Error:", error.message);
42}Best Practices for Type Conversion:
Number(), String(), Boolean() instead of relying on coercion===) to avoid unexpected coercionMaster JavaScript variables, data types, and operators with this comprehensive hands-on demonstration. Explore variable declarations, type conversion, and operator behaviors with real-world examples.
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>JavaScript Variables, Data Types & Operators Demo</title>
7 <style>
8 body {
9 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
10 max-width: 900px;
11 margin: 0 auto;
12 padding: 20px;
13 background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
14 color: white;
15 min-height: 100vh;
16 }
17
18 .container {
19 background: rgba(255, 255, 255, 0.1);
20 backdrop-filter: blur(10px);
21 border-radius: 20px;
22 padding: 30px;
23 box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
24 border: 1px solid rgba(255, 255, 255, 0.2);
25 }
26
27 h1 {
28 text-align: center;
29 margin-bottom: 30px;
30 font-size: 2.5rem;
31 text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
32 }
33
34 .section {
35 margin: 25px 0;
36 padding: 20px;
37 background: rgba(255, 255, 255, 0.1);
38 border-radius: 15px;
39 border-left: 4px solid #ffd700;
40 }
41
42 h2 {
43 color: #ffd700;
44 margin-top: 0;
45 font-size: 1.5rem;
46 }
47
48 .interactive-area {
49 background: rgba(255, 255, 255, 0.15);
50 padding: 20px;
51 border-radius: 12px;
52 margin: 15px 0;
53 border: 2px solid rgba(255, 215, 0, 0.3);
54 }
55
56 button {
57 background: linear-gradient(45deg, #ffd700, #ffed4e);
58 color: #333;
59 border: none;
60 padding: 12px 24px;
61 margin: 8px;
62 border-radius: 25px;
63 cursor: pointer;
64 font-weight: bold;
65 font-size: 14px;
66 transition: all 0.3s ease;
67 box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
68 }
69
70 button:hover {
71 transform: translateY(-2px);
72 box-shadow: 0 6px 20px rgba(255, 215, 0, 0.4);
73 }
74
75 input[type="text"], input[type="number"] {
76 padding: 10px 15px;
77 border: 2px solid rgba(255, 255, 255, 0.3);
78 border-radius: 20px;
79 background: rgba(255, 255, 255, 0.1);
80 color: white;
81 font-size: 16px;
82 margin: 5px;
83 backdrop-filter: blur(5px);
84 }
85
86 input::placeholder {
87 color: rgba(255, 255, 255, 0.7);
88 }
89
90 .output {
91 background: rgba(0, 0, 0, 0.2);
92 padding: 15px;
93 border-radius: 10px;
94 margin: 15px 0;
95 font-family: 'Courier New', monospace;
96 min-height: 40px;
97 border-left: 4px solid #4CAF50;
98 font-size: 14px;
99 line-height: 1.4;
100 }
101
102 .code-block {
103 background: rgba(0, 0, 0, 0.3);
104 padding: 15px;
105 border-radius: 8px;
106 font-family: 'Courier New', monospace;
107 font-size: 13px;
108 margin: 10px 0;
109 overflow-x: auto;
110 border: 1px solid rgba(255, 255, 255, 0.1);
111 }
112
113 .highlight {
114 background: rgba(255, 215, 0, 0.2);
115 padding: 2px 6px;
116 border-radius: 4px;
117 font-weight: bold;
118 }
119
120 .success {
121 color: #4CAF50;
122 font-weight: bold;
123 }
124
125 .info {
126 color: #2196F3;
127 font-weight: bold;
128 }
129
130 .warning {
131 color: #FF9800;
132 font-weight: bold;
133 }
134
135 .type-display {
136 display: inline-block;
137 background: rgba(255, 255, 255, 0.2);
138 padding: 4px 8px;
139 border-radius: 12px;
140 margin: 2px;
141 font-size: 12px;
142 font-weight: bold;
143 }
144
145 .grid-demo {
146 display: grid;
147 grid-template-columns: 1fr 1fr;
148 gap: 15px;
149 margin: 15px 0;
150 }
151
152 @media (max-width: 768px) {
153 .grid-demo {
154 grid-template-columns: 1fr;
155 }
156 }
157 </style>
158</head>
159<body>
160 <div class="container">
161 <h1>📊 Variables, Data Types & Operators Lab</h1>
162
163 <div class="section">
164 <h2>1. Variable Declaration Comparison</h2>
165 <p>Compare let, const, and var behavior in modern JavaScript:</p>
166
167 <div class="interactive-area">
168 <h3>Variable Declaration Explorer</h3>
169 <button onclick="demonstrateVariableDeclarations()">🔍 Compare Declarations</button>
170 <button onclick="demonstrateScope()">📦 Show Scope Behavior</button>
171 <div id="variableOutput" class="output">Click a button to explore variable declarations!</div>
172 </div>
173 </div>
174
175 <div class="section">
176 <h2>2. Data Types Investigation</h2>
177 <p>Explore JavaScript's dynamic type system and type checking:</p>
178
179 <div class="interactive-area">
180 <h3>Type System Explorer</h3>
181 <button onclick="demonstrateDataTypes()">📋 Show Data Types</button>
182 <button onclick="demonstrateTypeChecking()">🔍 Type Detection</button>
183 <button onclick="demonstrateComplexTypes()">🎯 Complex Types</button>
184 <div id="typeOutput" class="output">Explore JavaScript's type system!</div>
185 </div>
186 </div>
187
188 <div class="section">
189 <h2>3. Operator Playground</h2>
190 <p>Test different operators and see their results:</p>
191
192 <div class="interactive-area">
193 <h3>Interactive Calculator</h3>
194 <div class="grid-demo">
195 <div>
196 <input type="text" id="operand1" placeholder="First value" value="10">
197 <input type="text" id="operand2" placeholder="Second value" value="3">
198 </div>
199 <div>
200 <button onclick="performArithmetic()">➕ Arithmetic</button>
201 <button onclick="performComparison()">⚖️ Comparison</button>
202 <button onclick="performLogical()">🔗 Logical</button>
203 </div>
204 </div>
205 <div id="operatorOutput" class="output">Enter values and test different operators!</div>
206 </div>
207 </div>
208
209 <div class="section">
210 <h2>4. Type Conversion Laboratory</h2>
211 <p>Experiment with explicit and implicit type conversion:</p>
212
213 <div class="interactive-area">
214 <h3>Type Conversion Tester</h3>
215 <input type="text" id="conversionInput" placeholder="Enter any value..." value="42">
216 <button onclick="demonstrateConversions()">🔄 Convert Types</button>
217 <button onclick="demonstrateCoercion()">⚡ Show Coercion</button>
218 <div id="conversionOutput" class="output">Test type conversion with different values!</div>
219 </div>
220 </div>
221
222 <div class="section">
223 <h2>5. Real-World Data Processing</h2>
224 <p>Apply variables and operators to solve practical problems:</p>
225
226 <div class="interactive-area">
227 <h3>User Data Processor</h3>
228 <div class="grid-demo">
229 <div>
230 <input type="text" id="userName" placeholder="Enter name" value="Alice Johnson">
231 <input type="text" id="userAge" placeholder="Enter age" value="28">
232 </div>
233 <div>
234 <input type="text" id="userSalary" placeholder="Enter salary" value="75000">
235 <input type="text" id="userActive" placeholder="Active (true/false)" value="true">
236 </div>
237 </div>
238 <button onclick="processUserData()">👤 Process User Data</button>
239 <button onclick="calculateTaxes()">💰 Calculate Taxes</button>
240 <div id="processingOutput" class="output">Enter user information to process data!</div>
241 </div>
242 </div>
243
244 <div class="section">
245 <h2>6. Advanced Operator Patterns</h2>
246 <p>Explore advanced operator usage and best practices:</p>
247
248 <div class="interactive-area">
249 <h3>Advanced Patterns</h3>
250 <button onclick="demonstrateTernary()">❓ Ternary Operator</button>
251 <button onclick="demonstrateShortCircuit()">⚡ Short-Circuit Logic</button>
252 <button onclick="demonstratePrecedence()">📊 Operator Precedence</button>
253 <div id="advancedOutput" class="output">Explore advanced operator patterns!</div>
254 </div>
255 </div>
256 </div>
257
258 <script>
259 // Variables, Data Types & Operators - Interactive Demo Script
260
261 // 1. VARIABLE DECLARATIONS
262 function demonstrateVariableDeclarations() {
263 const output = document.getElementById('variableOutput');
264
265 // Demonstrate different declaration types
266 let mutableValue = "Initial";
267 const immutableValue = "Constant";
268 // var deprecatedValue = "Avoid this"; // Commented for best practices
269
270 // Show reassignment capabilities
271 mutableValue = "Changed";
272 // immutableValue = "Error"; // This would cause an error
273
274 output.innerHTML = `290`;
291 }
292
293 function demonstrateScope() {
294 const output = document.getElementById('variableOutput');
295
296 // Block scope demonstration
297 let blockValue = "outer";
298 const results = [];
299
300 if (true) {
301 let blockValue = "inner"; // Different variable
302 const blockConstant = "block-scoped";
303 results.push(`Inside block: ${blockValue}`);
304 results.push(`Block constant: ${blockConstant}`);
305 }
306
307 results.push(`Outside block: ${blockValue}`);
308 // console.log(blockConstant); // This would cause ReferenceError
309
310 output.innerHTML = `326`;
327 }
328
329 // 2. DATA TYPES
330 function demonstrateDataTypes() {
331 const output = document.getElementById('typeOutput');
332
333 // Primitive types
334 const stringValue = "Hello World";
335 const numberValue = 42.5;
336 const booleanValue = true;
337 const undefinedValue = undefined;
338 const nullValue = null;
339 const symbolValue = Symbol('unique');
340 const bigintValue = 123456789012345678901234567890n;
341
342 output.innerHTML = `362`;
363 }
364
365 function demonstrateTypeChecking() {
366 const output = document.getElementById('typeOutput');
367
368 // Various values for type checking
369 const values = [
370 42,
371 "string",
372 true,
373 [],
374 {},
375 function() {},
376 null,
377 undefined,
378 new Date(),
379 /regex/
380 ];
381
382 let typeInfo = values.map(value => {
383 const type = typeof value;
384 const stringRep = value === null ? 'null' :
385 value === undefined ? 'undefined' :
386 typeof value === 'function' ? 'function(){}' :
387 typeof value === 'object' ? JSON.stringify(value) || value.toString() :
388 JSON.stringify(value);
389
390 return `• ${stringRep} → <span class="type-display">${type}</span>`;
391 }).join('<br>');
392
393 output.innerHTML = `408`;
409 }
410
411 function demonstrateComplexTypes() {
412 const output = document.getElementById('typeOutput');
413
414 // Complex type examples
415 const person = {
416 name: "Alice",
417 age: 30,
418 hobbies: ["reading", "coding"],
419 greet() {
420 return `Hello, I'm ${this.name}`;
421 }
422 };
423
424 const numbers = [1, 2, 3, 4, 5];
425 const mixed = ["text", 42, true, null, {id: 1}];
426
427 output.innerHTML = `435`Hello, I'm ${this.name}`; }<br>
436};<br>
437<br>
438// Arrays<br>
439const numbers = [1, 2, 3, 4, 5];<br>
440const mixed = ["text", 42, true, null, {id: 1}];
441 </div>
442 <div class="info">Complex type details:</div>
443 • <strong>Object:</strong> ${JSON.stringify(person, null, 2).replace(/\n/g, '<br> ')}<br>
444 • <strong>Method call:</strong> <span class="highlight">${person.greet()}</span><br>
445 • <strong>Numbers array:</strong> <span class="highlight">[${numbers.join(', ')}]</span> (length: ${numbers.length})<br>
446 • <strong>Mixed array:</strong> <span class="highlight">[${mixed.map(item => typeof item === 'object' && item !== null ? JSON.stringify(item) : item).join(', ')}]</span><br>
447 <br>
448 <div class="info">Array type checking:</div>
449 • Array.isArray(numbers): <span class="highlight">${Array.isArray(numbers)}</span><br>
450 • typeof numbers: <span class="highlight">${typeof numbers}</span>
451 `;
452 }
453
454 // 3. OPERATORS
455 function performArithmetic() {
456 const output = document.getElementById('operatorOutput');
457 const val1 = document.getElementById('operand1').value;
458 const val2 = document.getElementById('operand2').value;
459
460 // Convert to numbers for arithmetic
461 const num1 = parseFloat(val1) || 0;
462 const num2 = parseFloat(val2) || 0;
463
464 output.innerHTML = `484`;
485 }
486
487 function performComparison() {
488 const output = document.getElementById('operatorOutput');
489 const val1 = document.getElementById('operand1').value;
490 const val2 = document.getElementById('operand2').value;
491
492 output.innerHTML = `517`;
518 }
519
520 function performLogical() {
521 const output = document.getElementById('operatorOutput');
522 const val1 = document.getElementById('operand1').value;
523 const val2 = document.getElementById('operand2').value;
524
525 // Convert to boolean for logical operations
526 const bool1 = Boolean(val1);
527 const bool2 = Boolean(val2);
528
529 output.innerHTML = `552`;
553 }
554
555 // 4. TYPE CONVERSION
556 function demonstrateConversions() {
557 const output = document.getElementById('conversionOutput');
558 const input = document.getElementById('conversionInput').value;
559
560 // Explicit conversions
561 const toNumber = Number(input);
562 const toString = String(input);
563 const toBoolean = Boolean(input);
564
565 // Additional conversion methods
566 const parseIntResult = parseInt(input);
567 const parseFloatResult = parseFloat(input);
568
569 output.innerHTML = `593`;
594 }
595
596 function demonstrateCoercion() {
597 const output = document.getElementById('conversionOutput');
598 const input = document.getElementById('conversionInput').value;
599
600 // Implicit conversions (coercion)
601 const stringCoercion = input + "";
602 const numberCoercion = +input;
603 const booleanCoercion = !!input;
604
605 // Arithmetic coercion examples
606 const mathExamples = [
607 { op: `"${input}" + 5`, result: input + 5 },
608 { op: `"${input}" - 5`, result: input - 5 },
609 { op: `"${input}" * 2`, result: input * 2 },
610 { op: `"${input}" / 2`, result: input / 2 }
611 ];
612
613 output.innerHTML = `632`;
633 }
634
635 // 5. REAL-WORLD PROCESSING
636 function processUserData() {
637 const output = document.getElementById('processingOutput');
638
639 // Get user inputs
640 const name = document.getElementById('userName').value;
641 const ageInput = document.getElementById('userAge').value;
642 const salaryInput = document.getElementById('userSalary').value;
643 const activeInput = document.getElementById('userActive').value;
644
645 // Process and validate data
646 const age = parseInt(ageInput);
647 const salary = parseFloat(salaryInput);
648 const isActive = activeInput.toLowerCase() === 'true';
649
650 // Calculate derived information
651 const ageCategory = age < 18 ? 'Minor' : age < 65 ? 'Adult' : 'Senior';
652 const salaryCategory = salary < 30000 ? 'Entry Level' :
653 salary < 70000 ? 'Mid Level' : 'Senior Level';
654
655 // Create user object
656 const user = {
657 name: name,
658 age: age,
659 salary: salary,
660 isActive: isActive,
661 ageCategory: ageCategory,
662 salaryCategory: salaryCategory,
663 annualSalary: salary * 12
664 };
665
666 output.innerHTML = `687`;
688 }
689
690 function calculateTaxes() {
691 const output = document.getElementById('processingOutput');
692 const salaryInput = document.getElementById('userSalary').value;
693 const salary = parseFloat(salaryInput) || 0;
694
695 // Tax calculation logic
696 let taxRate = 0;
697 let taxBracket = '';
698
699 if (salary <= 10000) {
700 taxRate = 0.10;
701 taxBracket = '10% (Low Income)';
702 } else if (salary <= 50000) {
703 taxRate = 0.15;
704 taxBracket = '15% (Middle Income)';
705 } else if (salary <= 100000) {
706 taxRate = 0.25;
707 taxBracket = '25% (High Income)';
708 } else {
709 taxRate = 0.30;
710 taxBracket = '30% (Very High Income)';
711 }
712
713 const monthlyTax = salary * taxRate;
714 const annualTax = monthlyTax * 12;
715 const netMonthlySalary = salary - monthlyTax;
716 const netAnnualSalary = netMonthlySalary * 12;
717
718 output.innerHTML = `743`;
744 }
745
746 // 6. ADVANCED PATTERNS
747 function demonstrateTernary() {
748 const output = document.getElementById('advancedOutput');
749
750 // Examples of ternary operator usage
751 const age = 20;
752 const score = 85;
753 const hasLicense = true;
754
755 const status = age >= 18 ? 'Adult' : 'Minor';
756 const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
757 const canDrive = age >= 16 && hasLicense ? 'Yes' : 'No';
758
759 output.innerHTML = `783`;
784 }
785
786 function demonstrateShortCircuit() {
787 const output = document.getElementById('advancedOutput');
788
789 // Short-circuit evaluation examples
790 const userName = "Alice";
791 const userTitle = "";
792 const userAge = 0;
793
794 const displayName = userName || "Guest";
795 const displayTitle = userTitle || "No Title";
796 const displayAge = userAge || "Age not provided";
797
798 // Function that only runs if condition is true
799 let functionCalled = false;
800 const testFunction = () => {
801 functionCalled = true;
802 return "Function executed";
803 };
804
805 const result1 = false && testFunction(); // Function won't run
806 const result2 = true && testFunction(); // Function will run
807
808 output.innerHTML = `832`;
833 }
834
835 function demonstratePrecedence() {
836 const output = document.getElementById('advancedOutput');
837
838 // Operator precedence examples
839 const a = 5, b = 3, c = 2;
840
841 const result1 = a + b * c; // Multiplication first
842 const result2 = (a + b) * c; // Parentheses override
843 const result3 = a > b && b > c; // Comparison then logical
844 const result4 = a + b > c * 2 && b < a; // Complex precedence
845
846 output.innerHTML = `876`;
877 }
878
879 // Initialize the demo when page loads
880 document.addEventListener('DOMContentLoaded', function() {
881 console.log('📊 Variables, Data Types & Operators Lab Loaded!');
882 console.log('===================================================');
883
884 // Set initial welcome message
885 const welcomeOutput = document.getElementById('variableOutput');
886 welcomeOutput.innerHTML = `896`;
897
898 // Set page title
899 document.title = "📊 JavaScript Variables & Data Types Lab";
900
901 console.log('💡 Pro tip: Open DevTools to see additional logging!');
902 });
903 </script>
904</body>
905</html>This comprehensive demonstration covers all fundamental concepts from Lesson 2:
🎯 Complete Variables, Data Types & Operators Coverage:
1. Variable Declaration Mastery:
2. Data Type System Exploration:
3. Comprehensive Operator Coverage:
4. Type Conversion Mastery:
5. Real-World Data Processing:
6. Advanced Operator Patterns:
7. Professional Development Patterns:
8. Interactive Learning Features:
This interactive laboratory provides hands-on experience with all JavaScript variable and operator concepts, allowing students to experiment with different values, see type conversions in action, and understand the behavior of JavaScript's dynamic type system through practical examples.
Excellent work mastering JavaScript variables, data types, and operators! You now understand how to store and manipulate data effectively. In our next lesson, we'll dive deep into Functions & Scope Management, where you'll learn to create reusable code blocks, understand parameter handling, return values, and master JavaScript's scope system for writing organized, efficient programs.
Your progress is saved in this browser, on this device only.