JavaScript is a versatile programming language commonly used for web development. Below are some fundamental JavaScript commands, concepts, and examples that you might use when building a website:
1. Variables:
- Variables are used to store data values. They can be declared using var, let, or const.
var x = 10; // Declaring a variable named x with a value of 10
2. Data Types:
- JavaScript has various data types, including strings, numbers, booleans, objects, and arrays.
var name = "John";
var age = 30;
var isStudent = true;
3. Functions:
- Functions are reusable blocks of code. They can be defined and called.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // Output: Hello, John!
4. Conditional Statements:
- Use if, else if, and else for conditional logic.
var hour = 15;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
5. Loops:
- Loops, like for and while, help execute code repeatedly.
for (var i = 0; i < 5; i++) {
console.log("Count: " + i);
}
6. Arrays:
- Arrays store multiple values and can be accessed by index.
var colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: red
7. Objects:
- Objects store data as key-value pairs.
var person = {
firstName: "John",
lastName: "Doe"
};
console.log(person.firstName); // Output: John
8. DOM Manipulation:
- JavaScript can interact with the Document Object Model (DOM) to change HTML content or styles.
var element = document.getElementById("myElement");
element.innerHTML = "New content";
9. Event Handling:
- You can attach JavaScript functions to HTML events.
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
10. AJAX and Fetch:
- Use AJAX or the Fetch API to make asynchronous requests to a server.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
These are some fundamental JavaScript concepts and commands used when building websites. JavaScript offers a wide range of capabilities for web development, from simple interactivity to complex web applications.