-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Beginner Guide
- Introduction to JavaScript
- Setting Up Your Environment
- Your First JavaScript Program
- Understanding Variables
- Data Types in JavaScript
- Operators
- Type Conversion and Coercion
- Comments and Code Organization
- Practice Exercises
JavaScript is a programming language that brings life to websites. Think of a webpage like a house:
- HTML is the structure (walls, roof, doors)
- CSS is the decoration (paint, furniture, style)
- JavaScript is the electricity and plumbing (makes things work, react, and change)
JavaScript was created in 1995 by Brendan Eich in just 10 days. Originally designed for web browsers, it now runs everywhere:
- Websites (frontend)
- Servers (backend with Node.js)
- Mobile apps (React Native, Ionic)
- Desktop applications (Electron)
- Games (Phaser, Three.js)
- IoT devices (Johnny-Five)
- It's everywhere - Every website uses it
- Beginner-friendly - Easy to start, hard to master
- Instant feedback - See results immediately in browser
- Huge community - Millions of developers, countless resources
- Career opportunities - High demand, good salaries
Despite the similar name, JavaScript and Java are completely different languages:
| Feature | JavaScript | Java |
|---|---|---|
| Type System | Dynamic | Static |
| Compilation | Interpreted | Compiled |
| Primary Use | Web, Scripts | Enterprise, Android |
| Syntax | C-like | C-like |
| Created By | Netscape (Brendan Eich) | Sun Microsystems |
The name "JavaScript" was a marketing decision to ride on Java's popularity in 1995.
Every modern browser has a built-in JavaScript console:
- Open any browser (Chrome, Firefox, Edge, Safari)
- Press
F12orCtrl+Shift+I(Mac:Cmd+Option+I) - Click the "Console" tab
- Type JavaScript and press Enter
// Try this in your console:
console.log("Hello, World!");- Download Visual Studio Code
- Install the "Live Server" extension
- Create a new folder for your projects
- Create an HTML file and a JavaScript file
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Learning</title>
</head>
<body>
<h1>JavaScript Learning Environment</h1>
<script src="script.js"></script>
</body>
</html>script.js:
// Your JavaScript code goes here
console.log("JavaScript is running!");- Download Node.js
- Open terminal/command prompt
- Run JavaScript files directly:
node script.jsNo installation required:
// This is a comment - the computer ignores it
// Comments help humans understand the code
console.log("Hello, World!");Output:
Hello, World!
| Part | Explanation |
|---|---|
console |
An object that represents the browser console |
. |
Dot notation - accessing something inside console |
log() |
A function (action) that prints output |
"Hello, World!" |
A string (text) - the message to print |
; |
Semicolon - ends the statement (optional but recommended) |
console.log("Hello, World!");
console.log("My name is JavaScript.");
console.log("I am learning to code!");Output:
Hello, World!
My name is JavaScript.
I am learning to code!
alert("This is a popup message!");This creates a popup dialog in the browser.
// Ask the user for input
let userName = prompt("What is your name?");
console.log("Hello, " + userName + "!");A variable is like a labeled box that stores data. You can put things in, take them out, and change what's inside.
┌─────────────┐
│ myAge │ ← Variable name (label)
│ 25 │ ← Value (what's stored)
└─────────────┘
JavaScript has three ways to declare variables:
// Declare a variable
let myAge;
// Assign a value
myAge = 25;
// Or do both in one line
let myName = "Alice";
// You can change let variables
myAge = 26; // This works!
console.log(myAge); // Output: 26const PI = 3.14159;
const DAYS_IN_WEEK = 7;
// This will cause an error:
// PI = 3.15; // TypeError: Assignment to constant variable
// const must be initialized when declared
// const x; // SyntaxError: Missing initializervar oldStyleVariable = "I'm old school";
// var has some confusing behaviors
// Stick with let and constUse let when... |
Use const when... |
|---|---|
| Value will change | Value should never change |
| Loop counters | Configuration values |
| Accumulating values | Function references |
| User input | Imported modules |
// Good examples
const MAX_SIZE = 100; // Won't change
let currentSize = 0; // Will change
const API_KEY = "abc123"; // Won't change
let userScore = 0; // Will changeMust follow these rules:
// ✓ Valid names
let userName = "Alice";
let user_name = "Bob";
let userName2 = "Charlie";
let $price = 9.99;
let _private = "secret";
// ✗ Invalid names
// let 2userName = "Error"; // Can't start with number
// let user-name = "Error"; // Can't use hyphens
// let let = "Error"; // Can't use reserved words
// let my variable = "Error"; // Can't have spacesNaming Conventions (Best Practices):
// camelCase - preferred in JavaScript
let firstName = "John";
let lastName = "Doe";
let totalAmount = 100;
// UPPER_SNAKE_CASE - for constants
const MAX_CONNECTIONS = 10;
const API_BASE_URL = "https://api.example.com";
// Descriptive names
let userAge = 25; // Good
let x = 25; // Bad - what is x?
let isLoggedIn = true; // Good - boolean prefix
let hasPermission = false; // Good - boolean prefix// Declare multiple variables on one line
let a = 1, b = 2, c = 3;
// Or on multiple lines (more readable)
let firstName = "Alice",
lastName = "Smith",
age = 25,
isStudent = true;
// Or separately (often clearest)
let firstName = "Alice";
let lastName = "Smith";
let age = 25;
let isStudent = true;Data types tell JavaScript what kind of data is stored in a variable. JavaScript is dynamically typed, meaning variables can hold any type and types can change.
Primitives are the basic building blocks. There are 7 primitive types:
// Strings are text wrapped in quotes
let singleQuotes = 'Hello';
let doubleQuotes = "World";
let backticks = `Hello World`; // Template literals (ES6)
// Strings can be combined (concatenation)
let greeting = "Hello, " + "World!";
console.log(greeting); // "Hello, World!"
// Template literals allow embedded expressions
let name = "Alice";
let age = 25;
let message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // "My name is Alice and I am 25 years old."
// Strings have special characters
let newLine = "Line 1\nLine 2"; // New line
let tab = "Column 1\tColumn 2"; // Tab
let backslash = "Path: C:\\Users\\"; // Backslash
let quote = 'She said "Hello"'; // Nested quotes
// String length
let text = "JavaScript";
console.log(text.length); // 10
// Access individual characters (0-indexed)
console.log(text[0]); // "J"
console.log(text[4]); // "S"// Integers (whole numbers)
let integer = 42;
let negative = -17;
let zero = 0;
// Floating point (decimals)
let decimal = 3.14159;
let negativeDecimal = -2.5;
// Scientific notation
let scientific = 2.5e6; // 2,500,000
let tiny = 1e-6; // 0.000001
// Special numeric values
let infinity = Infinity; // Result of 1/0
let negInfinity = -Infinity; // Result of -1/0
let notANumber = NaN; // Result of 0/0 or "text"/2
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof Infinity); // "number"
console.log(typeof NaN); // "number" (yes, really!)
// Number operations
console.log(10 + 5); // 15 (addition)
console.log(10 - 5); // 5 (subtraction)
console.log(10 * 5); // 50 (multiplication)
console.log(10 / 5); // 2 (division)
console.log(10 % 3); // 1 (modulo - remainder)
console.log(2 ** 3); // 8 (exponentiation)
// Precision issues (floating point)
console.log(0.1 + 0.2); // 0.30000000000000004
// This is normal in most programming languages!// Booleans represent yes/no, on/off, true/false
let isTrue = true;
let isFalse = false;
// Booleans from comparisons
let isGreater = 5 > 3; // true
let isEqual = 5 === 5; // true
let isNotEqual = 5 !== 3; // true
// Booleans in conditions
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
}
// Truthy and Falsy values
// These are "falsy" (treated as false):
console.log(Boolean(false)); // false
console.log(Boolean(0)); // false
console.log(Boolean(-0)); // false
console.log(Boolean(0n)); // false (BigInt zero)
console.log(Boolean("")); // false (empty string)
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
// Everything else is "truthy"
console.log(Boolean(true)); // true
console.log(Boolean(1)); // true
console.log(Boolean(-1)); // true
console.log(Boolean("text")); // true
console.log(Boolean([])); // true (empty array)
console.log(Boolean({})); // true (empty object)// undefined means "value not assigned"
let notAssigned;
console.log(notAssigned); // undefined
console.log(typeof notAssigned); // "undefined"
// Functions return undefined by default
function doNothing() {}
let result = doNothing();
console.log(result); // undefined
// Accessing non-existent object properties
let person = { name: "Alice" };
console.log(person.age); // undefined// null means "intentionally empty"
let emptyValue = null;
console.log(emptyValue); // null
console.log(typeof emptyValue); // "object" (this is a bug in JS!)
// Use null when you want to explicitly say "no value"
let currentUser = null; // No user logged in yet
currentUser = "Alice"; // Now a user is logged in// Symbols are unique identifiers
let sym1 = Symbol("description");
let sym2 = Symbol("description");
// Each Symbol is unique, even with same description
console.log(sym1 === sym2); // false
// Used for object property keys (advanced use)
let id = Symbol("id");
let user = {
name: "Alice",
[id]: 12345 // Symbol as key
};// BigInt handles integers larger than Number can safely handle
let bigNumber = 9007199254740991n; // Note the 'n' suffix
let alsoBig = BigInt("9007199254740991");
// Regular numbers have a safe integer limit
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
// BigInt can go much larger
let huge = 1234567890123456789012345678901234567890n;
// BigInt operations
console.log(bigNumber + 1n); // 9007199254740992n
// Can't mix BigInt and regular numbers
// console.log(bigNumber + 1); // TypeError!
console.log(bigNumber + BigInt(1)); // Works!// Objects store collections of data
let person = {
name: "Alice",
age: 25,
isStudent: true,
greet: function() {
return "Hello!";
}
};
// Access properties with dot notation
console.log(person.name); // "Alice"
console.log(person.age); // 25
// Or with bracket notation
console.log(person["name"]); // "Alice"
console.log(person["isStudent"]); // true
// Modify properties
person.age = 26;
person.email = "alice@example.com"; // Add new property
// Arrays are also objects
let colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors.length); // 3console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (bug!)
console.log(typeof Symbol()); // "symbol"
console.log(typeof 10n); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects)
console.log(typeof function(){}); // "function"// Basic arithmetic
let a = 10;
let 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 (remainder/modulo)
console.log(a ** b); // 1000 (exponentiation: 10³)
// String concatenation
let firstName = "John";
let lastName = "Doe";
console.log(firstName + " " + lastName); // "John Doe"
// Number + String = String
console.log("Age: " + 25); // "Age: 25"
console.log(5 + "5"); // "55" (string!)
console.log(5 + 5 + "5"); // "105" (left to right: 10 + "5")let x = 10; // Basic assignment
// Compound assignment operators
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
// Increment and decrement
let counter = 0;
counter++; // counter is now 1 (postfix)
++counter; // counter is now 2 (prefix)
counter--; // counter is now 1
--counter; // counter is now 0
// Difference between prefix and postfix
let num = 5;
console.log(num++); // 5 (returns THEN increments)
console.log(num); // 6
let num2 = 5;
console.log(++num2); // 6 (increments THEN returns)// Equality comparison
console.log(5 == 5); // true (loose equality)
console.log(5 == "5"); // true (type coercion!)
console.log(5 === 5); // true (strict equality)
console.log(5 === "5"); // false (different types)
// Inequality
console.log(5 != 3); // true (loose inequality)
console.log(5 != "5"); // false (type coercion!)
console.log(5 !== 3); // true (strict inequality)
console.log(5 !== "5"); // true (different types)
// Relational operators
console.log(5 > 3); // true (greater than)
console.log(5 < 3); // false (less than)
console.log(5 >= 5); // true (greater than or equal)
console.log(5 <= 4); // false (less than or equal)
// String comparison (lexicographic/alphabetical)
console.log("apple" < "banana"); // true
console.log("a" < "A"); // false (lowercase > uppercase)
console.log("10" < "9"); // true (string comparison!)
// Always use strict equality (===) unless you have a specific reason!// AND (&&) - both must be true
console.log(true && true); // true
console.log(true && false); // false
console.log(false && false); // false
// OR (||) - at least one must be true
console.log(true || true); // true
console.log(true || false); // true
console.log(false || false); // false
// NOT (!) - reverses the value
console.log(!true); // false
console.log(!false); // true
console.log(!0); // true (0 is falsy)
console.log(!1); // false (1 is truthy)
// Short-circuit evaluation
let x = 0;
false && (x = 1); // x stays 0 (short-circuits)
console.log(x); // 0
true || (x = 2); // x stays 0 (short-circuits)
console.log(x); // 0
// Practical example
let userAge = 25;
let hasPermission = true;
if (userAge >= 18 && hasPermission) {
console.log("Access granted");
}
// Default values with ||
let userName = "";
let displayName = userName || "Guest"; // "Guest"
console.log(displayName);
// Nullish coalescing (??) - only null/undefined
let count = 0;
let displayCount = count ?? "None"; // 0 (not null/undefined)
console.log(displayCount);
let missing = null;
let displayMissing = missing ?? "None"; // "None"
console.log(displayMissing);Operators have an order of operations, just like in math:
// Precedence (highest to lowest):
// 1. Grouping: ()
// 2. Not: !
// 3. Multiplication, Division, Modulo: *, /, %
// 4. Addition, Subtraction: +, -
// 5. Comparison: <, <=, >, >=
// 6. Equality: ==, ===, !=, !==
// 7. And: &&
// 8. Or: ||
// 9. Assignment: =, +=, -=, etc.
console.log(2 + 3 * 4); // 14 (not 20)
console.log((2 + 3) * 4); // 20 (parentheses first)
console.log(true || false && false); // true (&& before ||)
console.log((true || false) && false); // false
// When in doubt, use parentheses!// To String
let num = 42;
console.log(String(num)); // "42"
console.log(num.toString()); // "42"
console.log(num + ""); // "42" (trick)
let bool = true;
console.log(String(bool)); // "true"
// To Number
let str = "42";
console.log(Number(str)); // 42
console.log(parseInt(str)); // 42 (integer)
console.log(parseFloat("3.14")); // 3.14 (float)
console.log(+str); // 42 (unary plus)
console.log(Number("hello")); // NaN (not a number)
console.log(parseInt("42px")); // 42 (parses until non-digit)
console.log(parseInt("px42")); // NaN (starts with non-digit)
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
// To Boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean([])); // true (empty array is truthy!)
console.log(Boolean({})); // true (empty object is truthy!)JavaScript automatically converts types in certain operations:
// String coercion with +
console.log("5" + 3); // "53" (number becomes string)
console.log(1 + "2" + 3); // "123"
console.log(1 + 2 + "3"); // "33" (1+2=3, then "33")
// Number coercion with other operators
console.log("5" - 3); // 2 (string becomes number)
console.log("5" * "2"); // 10
console.log("10" / "2"); // 5
console.log("10" % "3"); // 1
// Comparison coercion
console.log(5 == "5"); // true (string becomes number)
console.log(0 == false); // true (false becomes 0)
console.log("" == false); // true (both become 0)
console.log(null == undefined); // true (special case)
// Strict comparison (no coercion)
console.log(5 === "5"); // false
console.log(0 === false); // false
console.log("" === false); // false
// The weird ones
console.log([] == false); // true ([] becomes "")
console.log([] == ![]); // true (weird but true!)
console.log([] + []); // "" (empty string)
console.log({} + {}); // "[object Object][object Object]"// 1. Use strict equality (===)
if (value === 5) { /* ... */ }
// 2. Convert explicitly when needed
let input = "42";
let number = Number(input);
if (!isNaN(number)) {
console.log("Valid number:", number);
}
// 3. Check types with typeof
function processValue(value) {
if (typeof value === "string") {
return value.toUpperCase();
} else if (typeof value === "number") {
return value * 2;
}
}
// 4. Use default values
function greet(name) {
name = name || "Guest"; // Old way
// or
name = name ?? "Guest"; // New way (nullish coalescing)
console.log("Hello, " + name);
}
// 5. Validate input
function addNumbers(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new Error("Both arguments must be numbers");
}
return a + b;
}// This is a single-line comment
let x = 5; // This is an inline comment
// Comments explain WHY, not WHAT
// Bad: Set x to 5
// Good: Default retry count is 5 attempts
let retryCount = 5;/* This is a multi-line comment
It can span multiple lines
Useful for longer explanations */
/*
* Another style of multi-line comment
* Each line starts with an asterisk
* This is common in professional code
*/
/**
* JSDoc style comment for documentation
* @param {string} name - The user's name
* @returns {string} A greeting message
*/
function greet(name) {
return "Hello, " + name;
}// ============================================
// SECTION: Configuration Constants
// ============================================
const MAX_RETRIES = 3;
const TIMEOUT_MS = 5000;
const API_BASE_URL = "https://api.example.com";
// ============================================
// SECTION: State Variables
// ============================================
let currentUser = null;
let isLoggedIn = false;
let cartItems = [];
// ============================================
// SECTION: Helper Functions
// ============================================
function formatPrice(amount) {
return "$" + amount.toFixed(2);
}
function validateEmail(email) {
return email.includes("@");
}
// ============================================
// SECTION: Main Application Logic
// ============================================
function initializeApp() {
console.log("Application starting...");
loadUserPreferences();
setupEventListeners();
}
// ============================================
// SECTION: Event Handlers
// ============================================
function handleLogin(event) {
event.preventDefault();
// Login logic here
}
// Start the application
initializeApp();Create variables to store information about yourself:
- Name (string)
- Age (number)
- Is a student (boolean)
- Favorite color (string)
// Your solution here
let myName = "Your Name";
let myAge = 25;
let amIStudent = false;
let favoriteColor = "blue";
console.log("Name:", myName);
console.log("Age:", myAge);
console.log("Student:", amIStudent);
console.log("Favorite Color:", favoriteColor);Convert the following and log the results:
- The string "123" to a number
- The number 456 to a string
- The string "true" to a boolean
// Your solution here
let strNum = "123";
let convertedNum = Number(strNum);
console.log(convertedNum, typeof convertedNum); // 123 "number"
let num = 456;
let convertedStr = String(num);
console.log(convertedStr, typeof convertedStr); // "456" "string"
let boolStr = "true";
let convertedBool = Boolean(boolStr);
console.log(convertedBool, typeof convertedBool); // true "boolean"Calculate and log:
- The area of a rectangle (width: 10, height: 5)
- The perimeter of the same rectangle
- The area of a circle with radius 7 (use Math.PI)
// Your solution here
let width = 10;
let height = 5;
let area = width * height;
let perimeter = 2 * (width + height);
console.log("Area:", area); // 50
console.log("Perimeter:", perimeter); // 30
let radius = 7;
let circleArea = Math.PI * radius * radius;
console.log("Circle Area:", circleArea.toFixed(2)); // 153.94Given the string "JavaScript is awesome!", log:
- Its length
- The first character
- The last character
- The word "awesome" (using substring)
// Your solution here
let text = "JavaScript is awesome!";
console.log("Length:", text.length); // 21
console.log("First char:", text[0]); // "J"
console.log("Last char:", text[text.length - 1]); // "!"
console.log("Word:", text.substring(14, 21)); // "awesome!"Write expressions to check if a number is:
- Between 10 and 20 (inclusive)
- Either less than 0 or greater than 100
- A positive even number
// Your solution here
let num = 15;
let isBetween10And20 = num >= 10 && num <= 20;
console.log("Between 10 and 20:", isBetween10And20); // true
let isOutsideRange = num < 0 || num > 100;
console.log("Outside 0-100:", isOutsideRange); // false
let isPositiveEven = num > 0 && num % 2 === 0;
console.log("Positive even:", isPositiveEven); // false (15 is odd)Create a program that converts Celsius to Fahrenheit:
- Formula: F = (C × 9/5) + 32
- Convert 25°C, 0°C, and -10°C
// Your solution here
function celsiusToFahrenheit(celsius) {
return (celsius * 9/5) + 32;
}
console.log("25°C =", celsiusToFahrenheit(25) + "°F"); // 77°F
console.log("0°C =", celsiusToFahrenheit(0) + "°F"); // 32°F
console.log("-10°C =", celsiusToFahrenheit(-10) + "°F"); // 14°FIn this first part, you learned:
| Topic | Key Points |
|---|---|
| Variables | Use let for changing values, const for constants |
| Data Types | 7 primitives: string, number, boolean, undefined, null, symbol, bigint |
| Operators | Arithmetic, assignment, comparison, logical |
| Type Conversion | Explicit with Number(), String(), Boolean()
|
| Comments | Use // for single line, /* */ for multi-line |
In Part 2, we'll cover:
- Control Flow (if/else, switch)
- Loops (for, while, do-while)
- Functions (declarations, expressions, arrow functions)
- Scope and hoisting
let variable = value; // Can be changed
const CONSTANT = value; // Cannot be changedlet str = "text"; // String
let num = 42; // Number
let bool = true; // Boolean
let undef; // Undefined
let empty = null; // Null
let sym = Symbol(); // Symbol
let big = 9007199254740991n; // BigInt
let obj = {}; // Object
let arr = []; // Array+ Addition/Concatenation
- Subtraction
* Multiplication
/ Division
% Modulo (remainder)
** Exponentiation
= Assignment
== Loose equality (avoid)
=== Strict equality (use this)
!= Loose inequality
!== Strict inequality
&& Logical AND
|| Logical OR
! Logical NOTtypeof value // Returns the type as a string