Welcome to the JavaScript tutorial! In this tutorial, we will cover the basics of the JavaScript programming language. JavaScript is a high-level, interpreted programming language that is commonly used to create dynamic web content.
Here are some of the topics we will cover:
- Variables and data types
- Operators
- Control structures (if statements, loops, etc.)
- Functions
- Objects
- Arrays
- DOM manipulation
- Events
Let's get started!
- Variables and Data Types In JavaScript, you can declare variables using the "var", "let", or "const" keywords. Variables are used to store values of different data types such as numbers, strings, booleans, etc. Here are some examples:
csharpvar x = 5; // x is a number
let name = "John"; // name is a string
const PI = 3.14; // PI is a constant with the value of 3.14
- Operators JavaScript has a variety of operators, including arithmetic operators (+, -, *, /), comparison operators (>, <, ==, !=), and logical operators (&&, ||). Here are some examples:
lessvar x = 5;
var y = 10;
var z = x + y; // z is now 15
var a = (x > y); // a is false
var b = (x == 5 && y == 10); // b is true
- Control Structures JavaScript supports if statements, for loops, while loops, and switch statements. Here are some examples:
javascriptif (x > y) {
console.log("x is greater than y");
} else {
console.log("y is greater than x");
}
for (var i = 0; i < 10; i++) {
console.log(i);
}
var i = 0;
while (i < 10) {
console.log(i);
i++;
}
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
// more cases...
default:
console.log("Invalid day");
}
- Functions Functions are used to encapsulate code and reuse it. You can define a function using the "function" keyword. Here's an example:
javascriptfunction greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // prints "Hello, John!"
- Objects Objects are used to group related data and functions together. They are defined using curly braces {}. Here's an example:
javascriptvar person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
console.log(person.name); // prints "John"
person.greet(); // prints "Hello, my name is John"
- Arrays Arrays are used to store collections of data. They are defined using square brackets []. Here's an example:
javascriptvar fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // prints "apple"
fruits.push("grape"); // adds "grape" to the end of the array
console.log(fruits.length); // prints 4
- DOM Manipulation The Document Object Model (DOM) is a programming interface for web documents. You can manipulate the DOM using JavaScript to create dynamic web content. Here's an example:
javascript// HTML code:
// <div id="myDiv"></div>
var myDiv = document.getElementById