JavaScript Basics with Examples

JavaScript is a versatile programming language that powers web interactivity. Whether you’re a beginner or looking to refresh your skills, this guide will walk you through the fundamentals with practical examples.

Introduction to JavaScript

JavaScript is a scripting language used primarily in web development. It adds functionality to websites, enabling dynamic content and user interactions. Unlike HTML and CSS, which handle structure and styling, JavaScript handles behavior and interactivity.

Basic Syntax

Comments

Comments are used to explain code and are ignored by the browser. They help make the code more readable.

// Single-line comment
/* Multi-line comment
This is another line of the comment */

Variables

Variables are containers for storing data values. In JavaScript, you can declare variables using let, const, or var.

let x = 5; // Declare a variable and assign a value
const y = 10; // Declare a constant (value cannot be changed)
var z = 15; // Declare a variable (function-scoped)

Data Types

JavaScript has several data types, including primitive types and objects.

let number = 42; // Number
let string = "Hello, World!"; // String
let boolean = true; // Boolean
let und = undefined; // Undefined
let nul = null; // Null
let obj = {}; // Object
let arr = []; // Array
let sym = Symbol(); // Symbol
let bigInt = 123n; // BigInt

Operators

JavaScript has various operators for performing operations on variables and values.

let a = 10;
let b = 5;

// Arithmetic Operators
console.log(a + b); // Addition
console.log(a - b); // Subtraction
console.log(a * b); // Multiplication
console.log(a / b); // Division
console.log(a % b); // Modulus
console.log(a ** b); // Exponentiation

// Assignment Operators
a += b; // a = a + b
a -= b; // a = a - b
a *= b; // a = a * b
a /= b; // a = a / b
a %= b; // a = a % b
a **= b; // a = a ** b

// Comparison Operators
console.log(a == b); // Equality
console.log(a === b); // Strict Equality
console.log(a != b); // Inequality
console.log(a !== b); // Strict Inequality
console.log(a > b); // Greater Than
console.log(a < b); // Less Than
console.log(a >= b); // Greater Than or Equal To
console.log(a <= b); // Less Than or Equal To

Control Structures

If-Else Statement

Used to execute different blocks of code based on conditions.

let age = 18;

if (age >= 18) {
    console.log("You are eligible to vote!");
} else {
    console.log("You are not eligible to vote yet.");
}

Switch Statement

Used as an alternative to multiple if-else statements.

let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the week");
        break;
    case "Friday":
        console.log("End of the week");
        break;
    default:
        console.log("Another day");
}

Loops

Loops execute a block of code multiple times based on a condition.

For Loop

for (let i = 0; i < 5; i++) {
    console.log(i); // Outputs 0, 1, 2, 3, 4
}

While Loop

let j = 0;
while (j < 5) {
    console.log(j); // Outputs 0, 1, 2, 3, 4
    j++;
}

Do-While Loop

let k = 0;
do {
    console.log(k); // Outputs 0, 1, 2, 3, 4
    k++;
} while (k < 5);

Loop Control

Break

Exits the loop immediately.

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
    console.log(i); // Outputs 0, 1, 2, 3, 4
}

Continue

Skips the current iteration and continues with the next one.

for (let i = 0; i < 5; i++) {
    if (i === 2) {
        continue;
    }
    console.log(i); // Outputs 0, 1, 3, 4
}

Functions

Functions are reusable blocks of code that perform specific tasks.

Function Declaration

function greet(name) {
    console.log("Hello, " + name + "!");
}

greet("Alice"); // Outputs: Hello, Alice!

Function Invocation

Functions are called (invoked) using the function name followed by parentheses.

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

let result = add(5, 3);
console.log(result); // Outputs: 8

Parameters and Return Values

Parameters are values passed into a function, and return values are the results the function gives back.

function multiply(a, b) {
    return a * b;
}

let product = multiply(4, 5);
console.log(product); // Outputs: 20

Function Expressions

Functions can be assigned to variables using function expressions.

let square = function(n) {
    return n * n;
};

console.log(square(5)); // Outputs: 25

Arrays

Arrays are used to store multiple values in a single variable.

Creating Arrays

let fruits = ["apple", "banana", "cherry"];

Accessing Elements

console.log(fruits[0]); // Outputs: apple

Array Methods

push()

Adds elements to the end of an array.

fruits.push("date");
console.log(fruits); // Outputs: ["apple", "banana", "cherry", "date"]

pop()

Removes the last element of an array.

fruits.pop();
console.log(fruits); // Outputs: ["apple", "banana", "cherry"]

shift()

Removes the first element of an array.

fruits.shift();
console.log(fruits); // Outputs: ["banana", "cherry"]

unshift()

Adds elements to the beginning of an array.

fruits.unshift("apple");
console.log(fruits); // Outputs: ["apple", "banana", "cherry"]

Advanced Methods

forEach()

Executes a function once for each array element.

fruits.forEach(function(fruit) {
    console.log(fruit);
});
// Outputs: apple, banana, cherry

map()

Creates a new array with the results of a function applied to each element.

let numbers = [1, 2, 3, 4];
let squared = numbers.map(function(n) {
    return n * n;
});
console.log(squared); // Outputs: [1, 4, 9, 16]

filter()

Creates a new array with elements that pass a test.

let evenNumbers = numbers.filter(function(n) {
    return n % 2 === 0;
});
console.log(evenNumbers); // Outputs: [2, 4]

reduce()

Executes a function against each element and returns a single value.

let sum = numbers.reduce(function(accumulator, current) {
    return accumulator + current;
}, 0);
console.log(sum); // Outputs: 10

Error Handling

Try-Catch

Used to handle runtime errors gracefully.

try {
    console.log(x); // x is not defined
} catch (error) {
    console.log("An error occurred: " + error.message);
}

Throw

Used to throw a custom error.

function validateAge(age) {
    if (age < 0) {
        throw new Error("Age cannot be negative");
    }
}

try {
    validateAge(-5);
} catch (error) {
    console.log(error.message); // Outputs: Age cannot be negative
}

Frequently Asked Questions

Q1: What is JavaScript used for?

A: JavaScript is primarily used for creating dynamic web content, handling user interactions, and building web applications.

Q2: Is JavaScript the same as Java?

A: No, JavaScript and Java are different languages. JavaScript is lightweight and designed for web browsers, while Java is a general-purpose programming language.

Q3: How do I declare a variable in JavaScript?

A: You can declare a variable using let, const, or var. let is used for variables that may change, const for constants, and var is function-scoped.

Q4: What are data types in JavaScript?

A: JavaScript has several data types, including numbers, strings, booleans, null, undefined, objects, arrays, symbols, and BigInts.

Q5: How do I handle errors in JavaScript?

A: You can use try-catch blocks to catch and handle runtime errors, and throw statements to throw custom errors.

Conclusion

JavaScript is a powerful and flexible language that forms the backbone of web development. By mastering the basics covered in this guide, you’ll be well on your way to creating dynamic and interactive web applications. Keep practicing, and soon you’ll be comfortable with more advanced concepts and techniques.

Index
Scroll to Top