JavaScript Basics

contain

Variables

Declaring Variables

Use let for values that change, const for values that stay the same.

// Use let for values that change
let score = 0;
score = 10;  // OK

// Use const for values that don't change
const MAX_SCORE = 100;
MAX_SCORE = 200;  // Error!

// Avoid var (old way)
var oldWay = 'outdated';

Variable Naming

Rules:

  • Start with letter, _, or $
  • No spaces or special characters
  • Case sensitive (myVar ≠ myvar)

Conventions:

  • camelCase for variables: userName, totalScore
  • UPPER_CASE for constants: MAX_SIZE, API_KEY

Data Types

Primitive Types

JavaScript has a few basic data types. You'll use strings, numbers, and booleans most often.

// String
let name = "Alice";
let greeting = 'Hello';
let message = `Hi ${name}`;  // Template literal

// Number (integers and decimals)
let age = 25;
let price = 19.99;

// Boolean
let isActive = true;
let isLoggedIn = false;

// Undefined (no value assigned)
let unknown;

// Null (intentionally empty)
let empty = null;

Checking Types

Use typeof to check what type a value is. Note: arrays return "object" (a JS quirk).

typeof "hello"    // "string"
typeof 42         // "number"
typeof true       // "boolean"
typeof undefined  // "undefined"
typeof null       // "object" (historical bug)
typeof {}         // "object"
typeof []         // "object"

Template Literals

const name = "Alice";
const age = 25;

// Old way (concatenation)
let msg1 = "Hello, " + name + "! You are " + age + ".";

// New way (template literals)
let msg2 = `Hello, ${name}! You are ${age}.`;

// Multi-line strings
let html = `
  <div>
    <h1>${name}</h1>
    <p>Age: ${age}</p>
  </div>
`;

Operators

Arithmetic Operators

Standard math works as expected. % (modulo) gives the remainder, ** is for exponents.

let a = 10, b = 3;

a + b   // 13 (addition)
a - b   // 7  (subtraction)
a * b   // 30 (multiplication)
a / b   // 3.33... (division)
a % b   // 1  (remainder/modulo)
a ** b  // 1000 (exponentiation)

// Shortcuts
a++     // increment by 1
a--     // decrement by 1
a += 5  // same as a = a + 5
a *= 2  // same as a = a * 2

String Operations

Strings have built-in methods for common transformations.

let first = "Hello";
let last = "World";

// Concatenation
first + " " + last  // "Hello World"

// Length
first.length  // 5

// Methods
first.toUpperCase()  // "HELLO"
first.toLowerCase()  // "hello"
first.includes("ell")  // true
first.startsWith("He") // true

Comparison Operators

Always use === (strict equality) in JavaScript to avoid unexpected type conversions.

5 == "5"    // true  (loose equality - converts types)
5 === "5"   // false (strict equality - no conversion)
5 != "5"    // false
5 !== "5"   // true

10 > 5      // true
10 >= 10    // true
5 < 10      // true
5 <= 5      // true

Always use === and !== (strict comparison)

Logical Operators

Combine conditions with && (both must be true), || (either can be true), ! (reverse).

// AND (both must be true)
true && true   // true
true && false  // false

// OR (at least one must be true)
true || false  // true
false || false // false

// NOT (inverts)
!true   // false
!false  // true

// Example
let isAdult = age >= 18;
let canVote = isAdult && isCitizen;

Functions

What is a Function?

A reusable block of code that performs a task:

// Define function
function greet() {
  console.log("Hello!");
}

// Call function
greet();  // prints "Hello!"
greet();  // prints "Hello!" again

Functions with Parameters

Parameters let functions work with different inputs each time you call them.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet("Alice");  // "Hello, Alice!"
greet("Bob");    // "Hello, Bob!"

// Multiple parameters
function add(a, b) {
  console.log(a + b);
}

add(5, 3);  // 8

Return Values

Use return to send a result back. Without it, the function returns undefined.

function add(a, b) {
  return a + b;
}

let sum = add(5, 3);  // sum = 8

// Use the result directly
console.log(add(10, 20));  // 30

// No return = undefined
function sayHi() {
  console.log("Hi");
  // implicitly returns undefined
}

Arrow Functions

Arrow functions are shorthand. AI-generated code uses them often, so learn to recognize them.

// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => {
  return a + b;
};

// Short form (implicit return)
const add = (a, b) => a + b;

// Single parameter (no parentheses needed)
const double = x => x * 2;

Functions as Event Handlers

You can pass any of these function styles to addEventListener.

// Named function
function handleClick() {
  console.log('Clicked!');
}
button.addEventListener('click', handleClick);

// Anonymous function
button.addEventListener('click', function() {
  console.log('Clicked!');
});

// Arrow function
button.addEventListener('click', () => {
  console.log('Clicked!');
});

Objects

Object Basics

Objects group related data together. Access properties with dot notation.

// Create an object
const person = {
  name: "Alice",
  age: 25,
  isStudent: true
};

// Access properties
person.name        // "Alice"
person["age"]      // 25

// Modify properties
person.age = 26;

// Add new properties
person.email = "alice@example.com";

Objects with Methods

Methods are functions inside objects. Use this to access other properties in the same object.

const calculator = {
  add: function(a, b) {
    return a + b;
  },

  // Shorthand
  subtract(a, b) {
    return a - b;
  }
};

calculator.add(5, 3);       // 8
calculator.subtract(10, 4); // 6

Console Practice

Try these in your browser console:

// Variables
let x = 10;
let y = 5;
console.log(x + y);

// Strings
let name = "Your Name";
console.log(`Hello, ${name}!`);

// Functions
function square(n) {
  return n * n;
}
console.log(square(4));

References