JavaScript Basics:
Variables, Functions, and
Events
🔹 Introduction to Core Concepts in JavaScript
🔹 With Practical Examples
What is JavaScript?
•JavaScript is a high-level, interpreted scripting language.
•It runs in the browser and makes web pages interactive.
•Key uses:
•Dynamic content (change HTML/CSS).
•Handle events (clicks, input, etc.).
•Communicate with servers (AJAX, APIs).
What is a Variable?
•variable stores data (like numbers, text, objects).
•Variables can be changed (mutable).
Declaring Variables (ES6+)
Example
javascript
let name = "John";
const age = 30;
var country = "USA";
Variables in JavaScript
Keyword Description
var Old way, function-scoped. Avoid using.
let Block-scoped (recommended).
Block-scoped, constant value (cannot be re-
const
assigned).
Data Types in JavaScript
• Primary Data Types
• String → "Hello"
• Number → 42, 3.14
• Boolean → true, false
• Undefined → Variable declared but no value
• Null → Intentional empty value
• Object → { key: value }
• Array → [1, 2, 3]
Functions in JavaScript
What is a Function?
Reusable block of code performing a specific task.
Helps organize code into smaller, manageable pieces.
Functions can accept parameters and return values.
Types of Functions
Type Example
Function Declaration function greet() {}
Function Expression const greet = function() {}
Arrow Function (ES6) const greet = () => {}
Function Example
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!
Arrow Function Example
const square = (x) => x * x;
console.log(square(5)); // 25
Events in JavaScript
What are Events?
Events are user actions, like:
Clicks
Key presses
Page loads
JavaScript listens for events and runs code in response.
Event Listeners
Adding an Event Listener
document.getElementById('btn').addEventListener('click',
function() {
alert('Button Clicked!');
});
Example HTML
<button id="btn">Click Me</button>
Common Events
Event Description
click User clicks on an element
mouseover Mouse enters an element
keydown Key is pressed
submit Form is submitted
Combined Example (Variables, Functions &
Events)
HTML
<button id="welcomeBtn">Greet</button>
JavaScript
let userName = "Student";
function greetUser() {
alert(`Welcome, ${userName}!`);
}
document.getElementById('welcomeBtn').addEventListener('click', greetUser);
Summary
✅ Variables store data (let, const, var).
✅ Functions organize reusable logic.
✅ Events trigger actions based on user interactions.