JavaScript Syntax: Basic and Advanced
Basic Syntax:
JavaScript uses a straightforward syntax for basic operations and control structures:
// Single-line comment
/*
Multi-line
comment
*/
// Variables
var variableName = 'Hello, World!';
let anotherVariable = 42;
const constantValue = 3.14;
// Data types
let number = 42;
let text = 'This is a string';
let booleanValue = true;
// Arrays
let myArray = [1, 2, 3, 4, 5];
// Objects
let myObject = {
key: 'value',
anotherKey: 123
};
// Functions
function myFunction(parameter) {
return 'Hello, ' + parameter + '!';
}
// Conditional statements
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
// Loops
for (let i = 0; i < 5; i++) {
// Code to repeat
}
// DOM Manipulation
document.getElementById('myElement').innerHTML = 'New content';
Advanced Syntax:
Advanced JavaScript involves more complex features and concepts:
// Closures
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
// Promises
function myAsyncFunction() {
return new Promise((resolve, reject) => {
// Asynchronous operation
if (success) {
resolve('Operation successful');
} else {
reject('Operation failed');
}
});
}
// Async/Await
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
// Arrow Functions
const add = (a, b) => a + b;
// Template Literals
let name = 'John';
let greeting = `Hello, ${name}!`;
// Destructuring Assignment
let person = { firstName: 'John', lastName: 'Doe' };
let { firstName, lastName } = person;
// Modules
// Exporting module:
// export function myFunction() { /* ... */ }
// Importing module:
// import { myFunction } from './myModule';
// ES6+ Features
// - Classes
// - Default Parameters
// - Rest and Spread Operators
// - Map, Set, WeakMap, WeakSet
// - Symbol, Proxy, Reflect
These examples provide a glimpse into JavaScript's syntax, covering both the basics and some advanced features. Continuously practice and explore real-world projects to deepen your understanding and proficiency in JavaScript.
0 Comment:
Post a Comment