JavaScript Statements - code -with tanveer
JavaScript is a high-level, interpreted programming language that is widely used for building dynamic web pages and web applications. In JavaScript, statements are the individual units of code that the interpreter can execute. Here are some common types of JavaScript statements:
1. Declaration Statements:
Declares a variable and optionally initializes it.
var x;
var y = 10;
let: Declares a block-scoped variable.
let a;
let b = 20;
const: Declares a block-scoped constant (unchangeable) variable.
const PI = 3.14;
2. Expression Statements:
Assignment: Assigns a value to a variable.
x = 5;
Increment/Decrement: Increases or decreases the value of a variable.
y++;
3. Control Flow Statements:
if statement: Executes a block of code if a specified condition is true.
if (condition) {
// code to be executed if the condition is true
}
- else statement: Executes a block of code if the condition in the if statement is false.
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
switch statement: Evaluates an expression and executes code depending on the matching case.
switch (value) {
case 1:
// code for case 1
break;
case 2:
// code for case 2
break;
default:
// code to be executed if no cases match
}
- for statement: Loops through a block of code a specified number of times.
for (let i = 0; i < 5; i++) {
// code to be executed in each iteration
}
while statement: Executes a block of code while a specified condition is true.
while (condition) {
// code to be executed while the condition is true
}
```
do-while statement:** Similar to the while statement, but the code is executed at least once
before the condition is checked.
do {
// code to be executed at least once
} while (condition);
break statement: Exits a loop or a switch statement.
while (true) {
// code
if (condition) {
break;
}
}
continue statement: Skips the rest of the loop's code for the current iteration and goes
to the next iteration.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
// code to be executed for each iteration, except when i is 2
}
4. Function Statements:
function declaration: Declares a function.
function add(a, b) {
return a + b;
}
function expression: Defines a function as part of an expression.
const multiply = function(a, b) {
return a * b;
};
arrow function expression: A concise way to write function expressions.
const square = (x) => x * x;
These are some of the fundamental types of statements in JavaScript. They can be combined and used to create more complex programs.
0 Comments