Home / JavaScript / JavaScript Basics: A Complete Beginner's Guide

JavaScript Basics: A Complete Beginner's Guide

JavaScript Basics: A Complete Beginner's Guide

Welcome to JavaScript! This guide will teach you everything you need to know to get started with one of the most popular programming languages in the world.

What is JavaScript?

JavaScript is a programming language that makes websites interactive and dynamic. It runs directly in your web browser and can make buttons click, forms validate, animations happen, and much more.

Getting Started

1. Writing Your First JavaScript Code

JavaScript code goes inside <script> tags or in external .js files. Here's a simple example:

<!DOCTYPE html>
<html>
<head>
    <title>My First JavaScript</title>
</head>
<body>
    <h1>Hello World!</h1>
    
    <script>
        console.log("Hello, World!");
    </script>
</body>
</html>

2. The Console

The console.log() function is your best friend for learning JavaScript. It prints messages to the browser's developer console.

console.log("This will appear in the console");
console.log(42);
console.log(true);

Variables

Variables are containers that store information. Think of them as labeled boxes.

Creating Variables

// Using let (recommended for modern JavaScript)
let name = "John";
let age = 25;
let isStudent = true;

// Using const (for values that won't change)
const PI = 3.14159;
const companyName = "Tech Solutions";

Variable Names

  • Start with a letter, underscore, or dollar sign
  • Can contain letters, numbers, underscores, and dollar signs
  • Cannot contain spaces or special characters
  • Case-sensitive (name ≠ Name)

Data Types

JavaScript has several data types:

1. Strings

Text data enclosed in quotes:

let greeting = "Hello";
let message = 'Welcome to JavaScript';
let sentence = "I'm learning JavaScript";

2. Numbers

Whole numbers and decimal numbers:

let age = 25;
let price = 19.99;
let temperature = -5;

3. Booleans

True or false values:

let isRaining = true;
let isSunny = false;
let isLoggedIn = true;

4. Undefined and Null

Special values that represent "nothing":

let emptyValue; // undefined
let nothing = null;

Basic Operations

Mathematical Operations

let x = 10;
let y = 5;

console.log(x + y);  // Addition: 15
console.log(x - y);  // Subtraction: 5
console.log(x * y);  // Multiplication: 50
console.log(x / y);  // Division: 2
console.log(x % y);  // Modulo (remainder): 0
console.log(x ** 2); // Exponentiation: 100

String Operations

let firstName = "John";
let lastName = "Doe";

// Concatenation (joining strings)
let fullName = firstName + " " + lastName;
console.log(fullName); // John Doe

// String methods
console.log(firstName.length); // 4
console.log(firstName.toUpperCase()); // JOHN

User Interaction

Alert Boxes

alert("Hello, World!");

Prompt Dialogs

let userName = prompt("What is your name?");
console.log("Hello, " + userName);

Conditional Statements

Make decisions in your code with if statements:

let age = 18;

if (age >= 18) {
    console.log("You can vote!");
} else {
    console.log("You cannot vote yet.");
}

// Multiple conditions
let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else {
    console.log("Grade: C or lower");
}

Loops

Repeat actions with loops:

For Loop

// Count from 1 to 5
for (let i = 1; i <= 5; i++) {
    console.log(i);
}

// Loop through array
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

While Loop

let count = 1;
while (count <= 5) {
    console.log(count);
    count++;
}

Functions

Functions are reusable blocks of code:

// Function declaration
function greet() {
    console.log("Hello, World!");
}

// Call the function
greet(); // Output: Hello, World!

// Function with parameters
function greetPerson(name) {
    console.log("Hello, " + name + "!");
}

greetPerson("Alice"); // Output: Hello, Alice!

// Function that returns a value
function addNumbers(a, b) {
    return a + b;
}

let result = addNumbers(5, 3);
console.log(result); // Output: 8

Arrays

Arrays store multiple values in one variable:

// Creating arrays
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];

// Accessing array elements
console.log(colors[0]); // red (first element)
console.log(colors[2]); // blue (third element)

// Modifying array elements
colors[1] = "yellow";
console.log(colors); // ["red", "yellow", "blue"]

// Array methods
numbers.push(6);        // Add to end
numbers.pop();          // Remove from end
numbers.unshift(0);     // Add to beginning
numbers.shift();        // Remove from beginning

Objects

Objects store collections of related data:

let person = {
    name: "John",
    age: 30,
    isStudent: false,
    hobbies: ["reading", "swimming", "coding"]
};

// Accessing object properties
console.log(person.name);        // John
console.log(person["age"]);      // 30
console.log(person.hobbies[0]);  // reading

// Modifying object properties
person.age = 31;
person.job = "Developer"; // Add new property

DOM Manipulation (Basic)

The Document Object Model lets you change what users see:

// Change text content
document.getElementById("myHeading").textContent = "New Heading";

// Change HTML content
document.getElementById("myParagraph").innerHTML = "<strong>Bold Text</strong>";

// Change CSS styles
document.getElementById("myDiv").style.backgroundColor = "blue";

Common Mistakes to Avoid

  1. Missing semicolons: While not always required, they're good practice
  2. Using = instead of == or ===: = is assignment, == and === are comparisons
  3. Forgetting to close brackets: Always match your { } and ( )
  4. Case sensitivity: Namename

Practice Exercises

Try these simple exercises to practice:

  1. Create a variable that stores your name and print it to the console
  2. Create two variables with numbers, add them together, and display the result
  3. Write a function that takes two parameters and returns their sum
  4. Create an array of your favorite fruits and loop through it to print each one

Next Steps

Now that you've learned the basics, try:

  • Building simple interactive web pages
  • Creating calculator programs
  • Working with more complex objects and arrays
  • Learning about events (clicks, keypresses)
  • Exploring more advanced JavaScript concepts like closures and prototypes

Remember: Practice is key to learning programming! The more you code, the better you'll get. Happy coding!