Switch statement Flashcards

1
Q

A switch statement is a type of control flow statement that provides multiple branches of code execution based on the value of an expression. It is a cleaner and more efficient alternative to multiple if-else statements.

A

let day = “Sunday”;

switch (day) {
case “Monday”:
console.log(“Today is Monday”);
break;
case “Tuesday”:
console.log(“Today is Tuesday”);
break;
case “Wednesday”:
console.log(“Today is Wednesday”);
break;
case “Thursday”:
console.log(“Today is Thursday”);
break;
case “Friday”:
console.log(“Today is Friday”);
break;
case “Saturday”:
console.log(“Today is Saturday”);
break;
case “Sunday”:
console.log(“Today is Sunday”);
break;
default:
console.log(“Invalid day”);
}

// Output: Today is Sunday

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Triple layer filtering using SQL in a .GET operation

A

app.get(‘/api/products’, function(req, res) {
var category = req.query.category;
var location = req.query.location;
var price = req.query.price;
var size = req.query.size;
var query = ‘SELECT * FROM products WHERE ‘;

switch(true) {
case (location && !price && !size):
query += ‘location = ‘ + location;
break;
case (!location && price && !size):
query += ‘price = ‘ + price;
break;
case (!location && !price && size):
query += ‘size = ‘ + size;
break;
case (location && price && !size):
query += ‘location = ‘ + location + ‘ AND price = ‘ + price;
break;
case (location && !price && size):
query += ‘location = ‘ + location + ‘ AND size = ‘ + size;
break;
case (!location && price && size):
query += ‘price = ‘ + price + ‘ AND size = ‘ + size;
break;
case (location && price && size):
query += ‘location = ‘ + location + ‘ AND price = ‘ + price + ‘ AND size = ‘ + size;
break;
default:
query += ‘1’;
}

connection.query(query, function (error, results, fields) {
if (error) throw error;
res.send(JSON.stringify(results));
});
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Triple layer filtering using full queries

A

switch (true) {
case req.query.location && req.query.price:
var sql = SELECT * FROM products WHERE location = '${req.query.location}' AND price = '${req.query.price}';
break;
case req.query.location && req.query.size:
var sql = SELECT * FROM products WHERE location = '${req.query.location}' AND size = '${req.query.size}';
break;
case req.query.size && req.query.price:
var sql = SELECT * FROM products WHERE size = '${req.query.size}' AND price = '${req.query.price}';
break;
case req.query.location:
var sql = SELECT * FROM products WHERE location = '${req.query.location}';
break;
case req.query.price:
var sql = SELECT * FROM products WHERE price = '${req.query.price}';
break;
case req.query.size:
var sql = SELECT * FROM products WHERE size = '${req.query.size}';
break;
default:
var sql = SELECT * FROM products;
}

conn.query(sql, function(err, result) {
if (err) throw err;
res.send(result);
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly