JavaScript is a versatile programming idioma used primarily for creating interactive and dynamic elements on web pages. Below are some fundamental concepts and examples to get started:
1. Variables and Data Types:
- Variables are used to store data values. Use
let
oconst
to declare variables.
let message = 'Hello, World!';
const PI = 3.14;
- JavaScript has several data types:
- Primitive Types: String, Number, Boolean, Undefined, Null
- Complex Types: Object, Array, Function
2. Operators:
- Arithmetic Operators:
+
,-
,*
,/
,%
- Comparison Operators:
==
,===
,!=
,!==
,>
,<
,>=
,<=
- Logical Operators:
&&
(AND),||
(OR),!
(NOT)
3. Control Structures:
- If Statement:
let num = 10;
if (num > 0) {
console.log('Positive number');
} else {
console.log('Negative number');
}
- For Loop:
for (let i = 0; i < 5; i++) {
console.log(i);
}
- While Loop:
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
4. Functions:
- Functions are reusable blocks of code that perform a specific task.
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet('John');
- Arrow Functions:
const square = (x) => {
return x * x;
};
console.log(square(5)); // Output: 25
5. Arrays and Objects:
- Arrays:
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Output: apple
fruits.push('grape');
- Objects:
let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(person.fullName()); // Output: John Doe
6. DOM Manipulation:
- The Document Object Model (DOM) represents the structure of HTML documents.
- JavaScript can be used to interact with and manipulate the DOM.
// Get element by ID
let heading = document.getElementById('main-heading');
heading.style.color = 'red';
// Create new element
let paragraph = document.createElement('p');
paragraph.textContent = 'This is a new paragraph.';
document.body.appendChild(paragraph);
7. Events:
- Events are actions or occurrences that happen in the browser.
- JavaScript can listen for and respond to events.
let button = document.getElementById('myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
8. Asynchronous JavaScript:
- JavaScript is single-threaded, but asynchronous operations can be performed using callbacks, promises, and async/await.
// Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully');
}, 2000);
});
}
fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
9. Error Handling:
- Utilice
try...catch
blocks to handle errors gracefully.
try {
// Code that may throw an error
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
}
10. Local Storage:
- JavaScript can store data locally in the browser’s storage.
// Store data
localStorage.setItem('username', 'John');
// Retrieve data
let username = localStorage.getItem('username');
console.log('Username:', username); // Output: Username: John
// Remove data
localStorage.removeItem('username');
Conclusión:
These are some fundamental concepts and examples of JavaScript. As you continue learning, you’ll encounter more advanced topics such as AJAX, ES6 features (like classes and modules), APIs, and frameworks/libraries like React, Vue.js, and Node.js. Practicing coding exercises and building projects will solidify your understanding of JavaScript and its capabilities for creating dynamic and interactive web applications.
Recomienda a tus amigos. Ganemos criptomonedas juntos.
Gana hasta 40% de comisión en cada operación a través de Binance Spot, Futuros y Pool.
Si este contenido le ha resultado útil, considere la posibilidad de hacer una donación
Crear contenidos valiosos requiere tiempo y esfuerzo. Si esta guía le ha resultado útil e informativa, considere la posibilidad de hacer una donación para apoyar nuestro trabajo y ayudarnos a seguir ofreciendo recursos valiosos a nuestra comunidad.
Su contribución nos permite crear más contenidos, mejorar nuestros servicios y ampliar nuestro alcance para beneficiar a más personas.
Formas de donar:
- Criptodonaciones:
- Puedes enviar donaciones en criptodivisas.
- PayPal:
- Haga una donación a través de PayPal.
Ningún donativo es demasiado pequeño, y toda contribución es muy apreciada. Gracias por su apoyo.