Skip to main content

JavaScript Statements

JavaScript Statements

JavaScript statements are instructions that the browser executes to perform actions. They can be as simple as assigning a value to a variable or as complex as creating a function. Understanding how statements work is crucial for writing effective JavaScript code.


What is a JavaScript Statement?

A JavaScript statement represents a single action or command. Statements are the building blocks of JavaScript programs. They can include declarations, assignments, expressions, and control structures. Each statement typically ends with a semicolon (;), although it's optional in some cases due to automatic semicolon insertion.


Variable Declarations

Variables are used to store data values. You can declare variables using let, const, or var.


// Variable declaration and initialization
let name = 'Alice';
const age = 30;
var city = 'New York';

console.log(name); // Output: Alice
console.log(age);  // Output: 30
console.log(city); // Output: New York

Assignment Statements

Assignment statements are used to assign values to variables. The = operator is used for assignment.


// Assigning values to variables
let x = 10;
x = 20; // Reassigning a new value

console.log(x); // Output: 20

Expression Statements

Expressions are pieces of code that produce a value. When used as statements, they perform an action or calculation.


// Expression statements
let result = 5 + 3; // The expression 5 + 3 produces the value 8
console.log(result); // Output: 8

Conditional Statements

Conditional statements execute different code blocks based on certain conditions.


// If-Else Statement
let score = 85;

if (score >= 90) {
  console.log('Grade: A');
} else if (score >= 80) {
  console.log('Grade: B');
} else {
  console.log('Grade: C');
}

Looping Statements

Looping statements allow you to execute a block of code multiple times.


// For Loop
for (let i = 0; i < 5; i++) {
  console.log(i); // Output: 0, 1, 2, 3, 4
}

// While Loop
let count = 0;
while (count < 5) {
  console.log(count); // Output: 0, 1, 2, 3, 4
  count++;
}

Function Statements

Functions are reusable blocks of code that perform a specific task. You can define functions using function declarations.


// Function Declaration
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet('Alice')); // Output: Hello, Alice!

Return Statements

Return statements are used to return a value from a function.


// Function with a return statement
function add(a, b) {
  return a + b;
}

let sum = add(5, 7);
console.log(sum); // Output: 12

Conclusion

JavaScript statements are fundamental to creating dynamic and interactive web applications. By understanding and using various types of statements, including variable declarations, assignments, expressions, conditionals, loops, and functions, you'll be able to write effective and efficient JavaScript code.

Comments