JavaScript Basics: Variables, Loops, and Functions
1. What is JavaScript?
JavaScript is the programming language of the web. It allows you to make your web pages interactive and
dynamic.
<button onclick="alert('Hello!')">Click me</button>
2. Variables
Variables store data values. You can use 'let', 'const', or 'var' to declare variables.
let name = "Souad";
const age = 25;
var city = "Montreal";
3. Loops
Loops are used to repeat code. Two common loops are 'for' and 'while'.
for (let i = 0; i < 5; i++) {
console.log("Number: " + i);
}
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Practice:
Print all even numbers from 0 to 10 using a loop.
4. Functions
Functions are reusable blocks of code. Here's how to define a function:
function greet(name) {
return "Hello, " + name;
}
Arrow Function:
const greet = (name) => "Hello, " + name;
JavaScript Basics: Variables, Loops, and Functions
Challenge:
Write a function that checks if a number is even.
function isEven(num) {
return num % 2 === 0;
}
5. Interacting with HTML
You can use JavaScript to interact with HTML elements like this:
<input id="nameInput" />
<button onclick="sayHello()">Say Hello</button>
<script>
function sayHello() {
const name = document.getElementById("nameInput").value;
alert("Hello " + name + "!");
}
</script>
Homework:
1. Ask for the user's name.
2. Display a greeting.
3. Ask how many times to repeat it.
4. Use a loop to repeat.