4. Flow Control Statement / Decision Making Statement
Decision Making Statement
Flow control statements in JavaScript are those statements that change the flow of execution in a program according to requirements and needs of the user.
Types of Control Statements in JavaScript
1. Conditional statement
2. Unconditional statement
1. Conditional Statements in JavaScript : A conditional statement in JavaScript is that statement that breaks the sequential flow of a program and jumps to another part of the code based on a specific condition.
1) If statement
2) If-else statement
3) Nested If-else statement
4) Switch statement
2. Unconditional Statements : An unconditional statement in JavaScript is that statement in which the flow of execution jumps to another part of code without carrying out any conditional test. It is also called unconditional execution in JavaScript.
JavaScript supports three types of unconditional statements. They are as follows:
1) Break statement
2) Continue statement
3) Return statement
for...in loop and for...of loop in Javascript
In JavaScript, the for...in loop and for...of loop are used for iterating over different kinds of data structures. Here are examples of both loops:
for...in loop:
The for...in loop is used to iterate over the enumerable properties of an object. It is typically used with objects, as it iterates over the keys (property names) of an object.
// Example with an object
const car = {
make: 'Toyota',
model: 'Camry',
year: 2022
};
for (let key in car) {
console.log(key + ': ' + car[key]);
}
// Output
make: Toyota
model: Camry
year: 2022
for...of loop:
The for...of loop is used to iterate over iterable objects, such as arrays, strings, maps, sets, etc. It provides a more concise syntax compared to the for...in loop.
// Example with an array
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
// Output
red
green
blue
Difference between for…of and for…in loops in JavaScript
1. for…of loop was introduced in ES6, whereas for…in loop introduced in ES5.
2. The for…in loop iterate through the keys of an object. In other words, for…in loop returns a list of keys. For example:
let list = [10, 20, 30];
// for...in loop returns a list of keys.
for(let x in list) {
console.log(x); // output: o, 1, 2.
}
The for…of loop iterates through the values of an iterable. For example:
let list = [10, 20, 30];
// for...of loop returns the values.
for(let x of list) {
console.log(x); // output: 10, 20, 30.
}
3. The for…of loop cannot be used to iterate over an object. Whereas, we can use for…in to loop over an iterable such as arrays and strings, but we should avoid using for…in for iterable objects.
Note: Some browser may not support for…of loop introduced in ES6. To know more, visit JavaScript for…of support.
Comments
Post a Comment