JavaScript Basics

Detailed explanations & code examples are in the JavaScript (.js) file

Click the { } button at the bottom right to view it

Master the Fundamentals: Output, Variables, Operators, Input & More

Topic 1: Output & Comments

JavaScript has multiple ways to display output and document your code with comments

3 Ways to Show Output in JavaScript:
// console.log() - prints to browser console
console.log("Hello, World!");

// window.alert() - shows a popup box
window.alert("This is an alert!");

// document.getElementById() - changes HTML element text
document.getElementById("myH1").textContent = "Hello";

Comments

2 Types of Comments:
Single-line: // This is a comment - anything after // is ignored
Multi-line: /* This spans multiple lines */ - use for longer explanations

Why use comments? To explain your code to yourself and others. Good code is well-commented!
Method Where Output Goes Best Used For
console.log() Browser Console (F12) Debugging, testing values
window.alert() Popup dialog box Simple notifications (use rarely)
document.getElementById().textContent Inside an HTML element Displaying results on the webpage

Output to HTML:

The JS file ran document.getElementById().textContent on page load:

Loading...

Examples in JS File:

Topic 2: Variables

Variables are named containers that store data values - like labelled boxes that hold information

3 Ways to Declare Variables:
let - Can be changed later. Use this most of the time
const - Cannot be changed (covered in Topic 6)
var - Old way, avoid using it in modern JavaScript
let fullName = "Umer Azmi";   // String - text, always in quotes
let age = 23;               // Number - no quotes needed
let isStudent = false;      // Boolean - only true or false

// Template literals - use backticks `` and ${} to embed variables
console.log(`Hello, my name is ${fullName}`);
console.log(`I am ${age} years old`);

JavaScript Data Types

Data Type Example Description
String "Hello" or 'Hello' Text - must be wrapped in quotes
Number 42 or 3.14 Any number - integers and decimals
Boolean true or false Only two possible values
Undefined let x; Variable declared but not assigned a value
Null let x = null; Intentionally empty / no value
Template Literals ` `
Use backticks (not quotes!) to create strings that can include variables:
`Hello, my name is ${fullName} and I am ${age} years old`

The ${} syntax is called string interpolation - it inserts the variable's value directly into the string.

Variables - Example:

Name will appear here

Age will appear here

Student status will appear here

Examples in JS File:

Topic 3: Arithmetic Operators

Operators are symbols that perform operations on values. Arithmetic operators perform math

Operator Name Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333...
** Exponent (Power) 10 ** 3 1000
% Modulo (Remainder) 10 % 3 1

Shorthand & Increment Operators

Shorthand Same As Increment/Decrement Same As
x += 5 x = x + 5 x++ x = x + 1
x -= 5 x = x - 5 x-- x = x - 1
x *= 5 x = x * 5 - -
x /= 5 x = x / 5 - -
⚠️ Operator Precedence (Order of Operations):
JavaScript follows PEMDAS/BODMAS just like math:
  1. Parentheses ()
  2. Exponents **
  3. Multiplication *, Division /, Modulo %
  4. Addition +, Subtraction -
Example: 6 / 2 * (1 + 2) = 6 / 2 * 3 = 3 * 3 = 9 (not 1!)
What is Modulo %?
Modulo gives you the remainder after division.
10 % 3 = 1 because 3 goes into 10 three times (3×3=9), with 1 left over.
Common use: Check if a number is even - num % 2 === 0 means it's even!

Examples in JS File:

Topic 4: User Input

There are two ways to accept input from users in JavaScript

2 Ways to Get User Input:
Easy way: window.prompt() - shows a popup input box. Simple but looks ugly
Professional way: HTML <input> + .value - styled input field on the page. The real-world approach
// EASY WAY - prompt popup
let username = window.prompt("What's your name?");

// PROFESSIONAL WAY - HTML input + button click
document.getElementById("mySubmit").onclick = function() {
    let username = document.getElementById("myText").value;
    document.getElementById("greeting").textContent = `Hello ${username}!`;
}
Concept Syntax What It Does
Get input value element.value Reads the current text in an input field
Button click handler element.onclick = function(){} Runs code when button is clicked
Anonymous function function(){} A function with no name, used inline
Prompt popup window.prompt("message") Shows a dialog box asking for input

User Input - Example:


Greeting will appear here

Examples in JS File:

Topic 5: Type Conversion

Converting a value from one data type to another - essential when working with user input

⚠️ Why You Need Type Conversion:
window.prompt() and HTML inputs always return strings, even if the user types a number.
So "5" + 3 gives "53" (string concatenation), not 8 (math)!
You must convert to Number() first before doing math.
// Number() - converts to a number
let age = Number("23");      // "23" - 23 (number)
let fail = Number("pizza"); // "pizza" - NaN (Not a Number)

// String() - converts to a string (text)
let str = String(42);       // 42 - "42"

// Boolean() - converts to true or false
let b1 = Boolean("pizza"); // any non-empty string - true
let b2 = Boolean("");      // empty string - false
let b3 = Boolean(0);       // 0 - false
Function Converts To Falsy Values (become false)
Number(value) Number Can return NaN if not convertible
String(value) String (text) Always succeeds
Boolean(value) Boolean 0, "", null, undefined, NaN
typeof Operator:
Use typeof to check what data type a variable is:
typeof "hello" - "string"
typeof 42 - "number"
typeof true - "boolean"
typeof undefined - "undefined"
What is NaN?
NaN stands for Not a Number. It appears when you try to do math with something that can't be converted to a number (like Number("pizza")).
Interestingly, typeof NaN is "number" - it's a numeric error value!

Examples in JS File:

Topic 6: Constants

Constants are variables that cannot be changed after they are set

When to Use const:
Use const for values that should never change - like mathematical constants (PI), configuration values, or fixed references.
By convention, constant names are written in ALL_CAPS (e.g., PI, MAX_SIZE).
// const = cannot be reassigned after declaration
const PI = 3.14159;

// This would throw an ERROR:
// PI = 420; ❌ TypeError: Assignment to constant variable

// Use const for things that won't change
let radius = 7;
let circumference = 2 * PI * radius; // 43.98...
Keyword Can Be Reassigned? Best Used For
let ✅ Yes Values that change (scores, user input, counters)
const ❌ No Fixed values (PI, tax rates, app config)
var ✅ Yes Avoid - old way with confusing scoping rules

Constants - Example:


Circumference will appear here

Note: PI is a const - it cannot be changed. The formula is 2 × π × r

Examples in JS File:

Topic 7: Math Object

JavaScript's built-in Math object provides properties and methods for mathematical operations

What is the Math Object?
Math is a built-in JavaScript object that comes with useful math functions and constants. You don't need to create it - it's always available!
Use it like: Math.methodName(value)

Rounding Methods

Method What It Does Example Result
Math.round(x) Round to nearest integer Math.round(3.6) 4
Math.floor(x) Always round DOWN Math.floor(3.9) 3
Math.ceil(x) Always round UP Math.ceil(3.1) 4
Math.trunc(x) Remove decimal (truncate) Math.trunc(3.9) 3

Other Math Methods

Method What It Does Example Result
Math.pow(x, y) x to the power of y Math.pow(2, 8) 256
Math.sqrt(x) Square root Math.sqrt(25) 5
Math.abs(x) Absolute value (removes - sign) Math.abs(-7) 7
Math.max(a, b, ...) Returns the largest number Math.max(3, 9, 1) 9
Math.min(a, b, ...) Returns the smallest number Math.min(3, 9, 1) 1
Math.random() Random decimal from 0 to <1 Math.random() 0.572...
Generating Random Integers (Very Common!):
// Random decimal from 0 to 0.999...
Math.random()

// Random integer from 0 to 5
Math.floor(Math.random() * 6)

// Random integer from 1 to 6 (dice roll)
Math.floor(Math.random() * 6) + 1

// Random integer between min and max (inclusive)
Math.floor(Math.random() * (max - min + 1)) + min
Math Constants:
Math.PI - 3.14159265358979... (Pi)
Math.E - 2.71828182845904... (Euler's Number)

Examples in JS File:

📄 loading...
Loading...