At its core, JavaScript relies on statements to perform actions. A statement is a line of code that instructs the computer to do something. Variables, on the other hand, are used to store and manipulate data within a program.
// Declaration and initialization of a variable
let message = "Hello, JavaScript!";
// Output the value of a variable
console.log(message);
In this example, let
is used to declare a variable named message
and assign it the value “Hello, JavaScript!”. The console.log()
statement outputs the value of the variable to the browser’s console.
JavaScript supports various data types, including:
null
, and undefined
.let age = 25; // Number
let name = "John"; // String
let isStudent = true; // Boolean
let noValue = null; // Null
let notDefined; // Undefined
let person = { name: "Alice", age: 30 }; // Object
let colors = ["red", "green", "blue"]; // Array
function greet(name) {
return `Hello, ${name}!`;
} // Function
JavaScript provides a wide range of operators for performing operations on values and variables. These include arithmetic operators (+
, -
, *
, /
), comparison operators (==
, ===
, !=
, !==
, <
, >
, <=
, >=
), and logical operators (&&
, ||
, !
), among others.
let x = 10;
let y = 5;
let sum = x + y; // Addition
let isGreater = x > y; // Comparison
let isTrue = true;
let isFalse = !isTrue; // Logical NOT
Control flow structures allow you to make decisions and execute code conditionally. Common control flow statements include if
, else if
, else
, switch
, for
, while
, and do...while
.
let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}
In this example, an if
statement is used to determine the grade based on the score
variable.
Functions are blocks of code that can be defined and reused throughout a program. They can take parameters (inputs) and return values (outputs).
function add(x, y) {
return x + y;
}
let result = add(3, 5); // Call the function
console.log(result); // Output: 8
JavaScript is an object-oriented language, and objects are a fundamental concept. Objects are collections of key-value pairs and can represent real-world entities.
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log(`Hello, ${this.firstName} ${this.lastName}!`);
}
};
person.greet(); // Output: Hello, John Doe!
In this example, person
is an object with properties like firstName
, lastName
, and a method greet
.
Arrays are ordered lists of values. They are versatile and commonly used to store collections of data.
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Accessing elements by index
colors.push("yellow"); // Adding an element to the end
colors.pop(); // Removing the last element
JavaScript has function-level scope, which means that variables declared within a function are only accessible within that function. However, closures allow inner functions to access variables from their outer functions.
function outer() {
let x = 10;
function inner() {
console.log(x); // Accessing x from the outer function
}
return inner;
}
let closure = outer();
closure(); // Output: 10
JavaScript supports asynchronous programming through features like Promises and the async/await
syntax. These are crucial for handling tasks that may take time, such as network requests.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
async function processAsync() {
try {
const data = await fetchData();
console.log(data); // Output: Data received
} catch (error) {
console.error(error);
}
}
processAsync();
JavaScript is the backbone of modern web development, enabling developers to create dynamic, interactive, and feature-rich web applications. Its syntax, encompassing variables, data types, operators, control flow, functions, objects, and more, forms the foundation for crafting engaging user experiences on the web. Understanding and mastering JavaScript syntax is essential for anyone aspiring to become a proficient web developer, as it opens the door to creating web applications that respond to user input, interact with servers, and deliver content in real-time.