JavaScript Basics: Variables, Data Types, and Operators

Week 1, Day 5 - Lecture 1

Welcome to JavaScript!

If HTML is the skeleton and CSS is the skin and clothes, JavaScript is the brain and muscles of a website. It makes things interactive, dynamic, and alive! JavaScript brings websites to life by responding to user actions, manipulating content, and communicating with servers.

graph TD A[JavaScript] --> B[Client-Side] A --> C[Server-Side] B --> D[Browser Interactions] B --> E[DOM Manipulation] B --> F[Event Handling] C --> G[Node.js] C --> H[APIs] C --> I[Databases] style A fill:#f9f,stroke:#333,stroke-width:2px style B fill:#9cf,stroke:#333,stroke-width:2px style C fill:#fc9,stroke:#333,stroke-width:2px

Adding JavaScript to HTML

Inline JavaScript

<button onclick="alert('Hello!')">Click me</button>

👎 Not recommended: Hard to maintain, violates separation of concerns

Internal JavaScript

<script>
    console.log('Hello, JavaScript!');
</script>

👍 Better: Good for small scripts or page-specific code

External JavaScript

<script src="script.js"></script>

<!-- With modern attributes -->
<script src="script.js" defer></script>
<script src="script.js" async></script>
<script type="module" src="script.js"></script>

👍👍 Best practice: Reusable, cacheable, maintainable

Variables in JavaScript

Variables are like labeled boxes where you store data. JavaScript has three ways to declare variables:

var (Old way - avoid)

var name = "John";
var age = 25;
var isStudent = true;

// Problems with var
var x = 1;
if (true) {
    var x = 2; // Same variable!
    console.log(x); // 2
}
console.log(x); // 2 (leaked out of block)

let (Block-scoped variable)

let name = "John";
let age = 25;
let isStudent = true;

// let respects block scope
let x = 1;
if (true) {
    let x = 2; // Different variable
    console.log(x); // 2
}
console.log(x); // 1

// Can be reassigned
let count = 0;
count = 1; // OK

const (Block-scoped constant)

const PI = 3.14159;
const MAX_SIZE = 100;

// Cannot be reassigned
const x = 1;
// x = 2; // Error!

// But objects/arrays can be modified
const user = { name: "John" };
user.name = "Jane"; // OK
user.age = 30; // OK
// user = {}; // Error!
graph TD A[Variable Declaration] --> B[var] A --> C[let] A --> D[const] B --> E[Function scope] B --> F[Hoisting issues] B --> G[Avoid using] C --> H[Block scope] C --> I[Can reassign] C --> J[Modern standard] D --> K[Block scope] D --> L[Cannot reassign] D --> M[Preferred for constants] style B fill:#fdd,stroke:#333,stroke-width:2px style C fill:#dfd,stroke:#333,stroke-width:2px style D fill:#ddf,stroke:#333,stroke-width:2px

Data Types

JavaScript has several data types, divided into primitive and object types:

Primitive Types

1. Number

let integer = 42;
let float = 3.14;
let negative = -10;
let exponential = 1.5e3; // 1500
let notANumber = NaN;
let infinity = Infinity;

// Checking for NaN
console.log(isNaN(NaN)); // true
console.log(Number.isNaN(NaN)); // true (better)

// Number methods
let num = 3.14159;
console.log(num.toFixed(2)); // "3.14"
console.log(parseInt("42")); // 42
console.log(parseFloat("3.14")); // 3.14

2. String

let single = 'Hello';
let double = "World";
let backticks = `Hello, ${name}!`; // Template literal

// String methods
let text = "JavaScript";
console.log(text.length); // 10
console.log(text.toUpperCase()); // "JAVASCRIPT"
console.log(text.toLowerCase()); // "javascript"
console.log(text.substring(0, 4)); // "Java"
console.log(text.includes("Script")); // true
console.log(text.split("")); // ["J", "a", "v", "a", ...]

// Template literals
let firstName = "John";
let lastName = "Doe";
let fullName = `${firstName} ${lastName}`;
let multiline = `
    This is a
    multiline string
`;

3. Boolean

let isTrue = true;
let isFalse = false;

// Truthy and falsy values
// Falsy: false, 0, "", null, undefined, NaN
// Everything else is truthy

if ("") {
    console.log("This won't run");
}

if ("hello") {
    console.log("This will run");
}

4. Undefined

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

function noReturn() {
    // No return statement
}
console.log(noReturn()); // undefined

5. Null

let emptyValue = null;
console.log(emptyValue); // null

// Checking for null
if (emptyValue === null) {
    console.log("Value is null");
}

6. Symbol (ES6)

let sym1 = Symbol("description");
let sym2 = Symbol("description");
console.log(sym1 === sym2); // false (always unique)

// Used for object properties
const obj = {
    [Symbol("key")]: "value"
};

7. BigInt (ES11)

let bigNumber = 9007199254740991n;
let anotherBig = BigInt(9007199254740991);

console.log(bigNumber + 1n); // Works!
// console.log(bigNumber + 1); // Error! Can't mix types

Object Types

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

// Array
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "two", true, null];

// Function
function greet(name) {
    return `Hello, ${name}!`;
}

// Date
let now = new Date();

// RegExp
let pattern = /[a-z]+/;

Type Conversion and Coercion

Explicit Conversion

// To String
String(123); // "123"
(123).toString(); // "123"
String(true); // "true"

// To Number
Number("123"); // 123
Number("abc"); // NaN
Number(true); // 1
Number(false); // 0
+"123"; // 123 (unary plus)

// To Boolean
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
!!value; // Double NOT trick

Implicit Coercion

// String coercion
"5" + 3; // "53"
"5" - 3; // 2 (converts to number!)

// Number coercion
"5" * "2"; // 10
"5" / "2"; // 2.5
true + 1; // 2

// Boolean context
if ("hello") { /* runs */ }
if (0) { /* doesn't run */ }

Operators

Arithmetic Operators

let a = 10, 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.333... (division)
console.log(a % b);  // 1  (modulus/remainder)
console.log(a ** b); // 1000 (exponentiation)

// Increment/Decrement
let x = 5;
console.log(x++); // 5 (post-increment)
console.log(x);   // 6
console.log(++x); // 7 (pre-increment)
console.log(x--); // 7 (post-decrement)
console.log(--x); // 5 (pre-decrement)

Assignment Operators

let x = 10;

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

Comparison Operators

console.log(5 == "5");   // true  (loose equality)
console.log(5 === "5");  // false (strict equality)
console.log(5 != "5");   // false (loose inequality)
console.log(5 !== "5");  // true  (strict inequality)
console.log(5 > 3);      // true
console.log(5 < 3);      // false
console.log(5 >= 5);     // true
console.log(5 <= 4);     // false

// Always use === and !== to avoid type coercion issues!

Logical Operators

// AND (&&)
console.log(true && true);   // true
console.log(true && false);  // false
console.log(false && true);  // false
console.log(false && false); // false

// OR (||)
console.log(true || true);   // true
console.log(true || false);  // true
console.log(false || true);  // true
console.log(false || false); // false

// NOT (!)
console.log(!true);  // false
console.log(!false); // true

// Short-circuit evaluation
let value = null;
let defaultValue = value || "default"; // "default"

let user = { name: "John" };
let name = user && user.name; // "John"

// Nullish coalescing (??)
let count = 0;
console.log(count || 10);  // 10 (wrong!)
console.log(count ?? 10);  // 0 (correct!)

Ternary Operator

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

// Nested ternary (use sparingly)
let score = 85;
let grade = score >= 90 ? "A" :
            score >= 80 ? "B" :
            score >= 70 ? "C" :
            score >= 60 ? "D" : "F";
console.log(grade); // "B"

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 {});           // "object"
console.log(typeof []);           // "object"
console.log(typeof function(){}); // "function"
console.log(typeof Symbol());     // "symbol"
console.log(typeof 42n);          // "bigint"

// Better type checking
Array.isArray([]);            // true
Array.isArray({});            // false
value instanceof Date;        // true/false
Object.prototype.toString.call(value); // "[object Type]"

Best Practices

mindmap root((JavaScript Best Practices)) Variables Use const by default Use let when needed Avoid var Meaningful names Comparisons Use === not == Use !== not != Be explicit Type Safety Check types when needed Handle edge cases Validate input Code Style Consistent formatting Clear naming Comments for clarity

Naming Conventions

// Variables and functions: camelCase
let firstName = "John";
let getUserName = function() {};

// Constants: UPPER_SNAKE_CASE
const MAX_SIZE = 100;
const API_KEY = "abc123";

// Classes: PascalCase
class UserProfile {}
class ShoppingCart {}

// Private properties: underscore prefix
let _privateVar = "secret";

// Boolean variables: is/has prefix
let isActive = true;
let hasPermission = false;

Common Pitfalls

// Type coercion surprises
console.log(1 + "2");        // "12" (string)
console.log("1" + 2);        // "12" (string)
console.log(1 - "2");        // -1 (number)
console.log("1" - 2);        // -1 (number)

// Floating point precision
console.log(0.1 + 0.2);      // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false!

// NaN comparisons
console.log(NaN === NaN);    // false
console.log(Number.isNaN(NaN)); // true (use this!)

// Null vs undefined
let obj = { name: undefined };
console.log(obj.name);       // undefined
console.log(obj.age);        // undefined
console.log("name" in obj);  // true
console.log("age" in obj);   // false

Assignment: JavaScript Basics

  1. Create a JavaScript file with:
    • Variables of each data type
    • Examples of type conversion
    • Demonstrations of each operator
    • Comments explaining each section
  2. Build a simple calculator:
    • Prompt user for two numbers
    • Perform basic arithmetic operations
    • Handle edge cases (division by zero)
    • Display results with proper formatting
  3. Create a type checker function:
    • Accept any value as input
    • Return detailed type information
    • Handle arrays, null, and other edge cases
    • Test with various inputs
  4. Write a temperature converter:
    • Convert between Celsius and Fahrenheit
    • Validate input
    • Format output to 2 decimal places
    • Handle invalid input gracefully

Bonus: Create a mini quiz that tests JavaScript knowledge using prompts and alerts!