JavaScript Examples

Practical JavaScript code examples for beginners

💡 What is JavaScript?

JavaScript is a programming language that makes web pages interactive. It can change content, respond to user actions, and create dynamic effects.


// Your first JavaScript code
console.log("Hello, JavaScript!");
alert("Welcome to JavaScript!");
                                    

Basic JavaScript Examples

📝

Variables

Store and use data

let name = "John";
let age = 25;
console.log(name + " is " + age);
🔢

Math Operations

Calculate numbers

let x = 10;
let y = 5;
let sum = x + y;
console.log("Sum: " + sum);
🔄

Functions

Reusable code blocks

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

Arrays

Store multiple values

let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3

🔹 Interactive Examples

JavaScript can respond to user actions:

🔸 Button Click Example

<button onclick="showMessage()">Click Me!</button>

<script>
function showMessage() {
    alert("Button was clicked!");
}
</script>

Try it:

🔹 Text Manipulation

Change text content dynamically:

<p id="demo">Original text</p>
<button onclick="changeText()">Change Text</button>

<script>
function changeText() {
    document.getElementById("demo").innerHTML = "Text changed!";
}
</script>

Try it:

Original text

🔹 Date and Time

Work with dates and times:

// Get current date
let now = new Date();
console.log(now);

// Format date
let today = new Date();
let dateString = today.toDateString();
console.log(dateString); // Mon Oct 23 2023

Current Date:

🔹 Conditional Statements

Make decisions in your code:

let age = 18;

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

// Ternary operator (short form)
let status = age >= 18 ? "adult" : "minor";
console.log("You are an " + status);

🔹 Loops

Repeat code multiple times:

// For loop
for (let i = 1; i <= 5; i++) {
    console.log("Count: " + i);
}

// While loop
let count = 1;
while (count <= 3) {
    console.log("While count: " + count);
    count++;
}

🧠 Test Your Knowledge

Which symbol is used to declare a variable in JavaScript?