Skip to main content

JavaScript (Vanilla JS) - The Basics

The Basics of JavaScript, often referred to as "Vanilla JavaScript" - introduction for beginners.

JavaScript, often referred to as Vanilla JavaScript when not combined with libraries or frameworks, is a versatile programming language that primarily runs in web browsers.

Here are some basics to get you started with Vanilla JavaScript:

Variables

In JavaScript, you can declare variables using var, let, or const. Use let or const for better variable scoping.

let age = 25;
const name = "John";

Data Types

JavaScript has several data types, including numbers, strings, booleans, arrays, objects, and more.

let number = 42;
let text = "Hello, World!";
let isTrue = true;
let fruits = ["apple", "banana", "cherry"];
let person = { name: "John", age: 30 };

Functions

Functions are blocks of reusable code.

function greet(name) {
return `Hello, ${name}!`;
}

const greeting = greet("Alice");

Conditionals

You can use if, else if, and else to make decisions in your code.

if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

Loops

You can use loops like for and while for repetitive tasks.

for (let i = 0; i < 5; i++) {
console.log(i);
}

let x = 0;
while (x < 5) {
console.log(x);
x++;
}

Arrays

Arrays are used to store collections of data.

const colors = ["red", "green", "blue"];
console.log(colors[0]); // Access the first element
colors.push("yellow"); // Add an element

Objects

Objects are used to store key-value pairs.

const person = { name: "Alice", age: 28 };
console.log(person.name); // Access a property
person.city = "New York"; // Add a property

DOM Manipulation

You can manipulate the Document Object Model (DOM) to change the content and structure of a web page.

// Get an element by its ID
const element = document.getElementById("my-element");
element.innerHTML = "New content";

Event Handling

You can use JavaScript to respond to user interactions.

document.getElementById("my-button").addEventListener("click", function () {
alert("Button clicked!");
});

Asynchronous JavaScript

JavaScript supports asynchronous programming with setTimeout, setInterval, and AJAX requests.

setTimeout(function () {
console.log("Delayed message");
}, 2000);

Error Handling

Use try...catch to handle errors gracefully.

try {
// Code that might throw an error
} catch (error) {
console.error(error);
}

✅ In Summary

These are some foundational concepts for getting started with Vanilla JavaScript. As you gain experience, you can explore more advanced topics like closures, promises, and modern JavaScript features introduced in ES6 and later.

✅ Resources