1626972960
Hello Friends,
In this lecture we are going to learn switch case statement in javascript in hindi step by step, If you like the lecture please don’t forget to share and subscribe for more lectures.
#switchcase #javascriptswitchstatement #webdevelopment #webdesign #softwaredevelopment
#javascript
1680093309
The JavaScript switch statement is a way to make decisions in your code based on different conditions. It is a more organized and concise alternative to using multiple if-else statements. The switch statement evaluates a given expression, which can be a variable or a value, and compares it to several possible cases. If the value of the expression matches one of the cases, the associated code block (a set of instructions) is executed. If no match is found, an optional default case can be executed as a fallback, meaning it runs when none of the other cases apply.
For example, here’s a simple switch statement that checks the value of a variable called day
:
switch (day) {
case "Monday":
console.log("Start of the work week! 😴");
break;
case "Friday":
console.log("End of the work week! 🥳");
break;
default:
console.log("A regular day");
}
By mastering switch statements, you can write cleaner, more efficient, and better-organized JavaScript code, ultimately improving your overall programming skills.
switch
Statement Basics: Anatomy and structureswitch statements begins with the keyword switch
, followed by an expression in parentheses. This expression is compared to a series of case labels enclosed in a switch block. Each case label represents a distinct value, and the code block that follows the case is executed when the expression matches the case label’s value. A break
statement is typically used to exit the switch block after a matching case is executed, ensuring that only the intended code block runs, and preventing fall-through to the next cases. Optionally, a default case can be included to provide a fallback action when none of the case labels match the expression, ensuring a response for unknown values.
switch(expression) {
case {value1}:
// <-- Your Code to execute -->
break // optional
case {value2}:
// <-- Your Code to execute -->
break // optional
default: // optional
// <-- Code that executes when no values match-->
}
const superhero = 'Spider-Man';
switch (superhero) {
case 'Batman':
console.log('🦇 The Dark Knight!');
break;
case 'Wonder Woman':
console.log('👸 The Amazon Princess!');
break;
default:
console.log('💥 There are so many amazing superheroes!');
}
The switch statement is an alternative to using if-else statements when you have multiple conditions to handle. While if-else statements are suitable for checking a series of conditions that can be expressed as true or false, switch statements are more efficient when dealing with a single expression that can take on multiple distinct values. In essence, switch statements can make your code cleaner, more organized, and easier to read when you have several related conditions to manage.
For example, consider the following if-else structure:
if (color === "red") {
console.log("The color is red 🟥");
} else if (color === "blue") {
console.log("The color is blue 🟦");
} else if (color === "green") {
console.log("The color is green 🟩");
} else {
console.log("Unknown color 🌈");
}
The equivalent switch statement would look like this:
switch (color) {
case "red":
console.log("The color is red 🟥");
break;
case "blue":
console.log("The color is blue 🟦");
break;
case "green":
console.log("The color is green 🟩");
break;
default:
console.log("Unknown color 🌈");
}
The switch statement offers a more organized and readable way to handle multiple conditions, particularly when dealing with a large number of cases. In a switch statement, the expression being evaluated is the variable or value inside the parentheses (in this example, the variable color
).
switch
over if-else
if-else
over switch
Both switch
and if-else
solve similar problems and have advantages and disadvantages based on your use cases. To help you make your decision, I’ve created a simple switch statement:
switch (yourUseCase) {
case 'large_number_of_conditions':
case 'single_variable_evaluation':
case 'multiple_discrete_values':
console.log('Consider using a switch statement.');
break;
case 'complex_conditions':
case 'range_based_conditions':
case 'non_constant_cases':
console.log('Consider using an if-else pattern.');
break;
default:
console.log('Choose the most appropriate control structure based on your specific use case.');
}
switch
Statement Functionality and Techniques:The switch statement provides additional functionality and concepts that can be used to improve the performance, readability, and conciseness of your code.
default
caseThe default case in a switch statement is executed when none of the other cases match the provided expression. It serves as a fallback to handle unexpected or unknown values, ensuring a response is provided even if there’s no matching case.
const beverage = 'lemonade';
switch (beverage) {
case 'coffee':
console.log('☕️ Enjoy your coffee!');
break;
case 'tea':
console.log('🍵 Have a relaxing cup of tea!');
break;
default:
console.log('🥤 Your choice of drink is not listed, but cheers anyway!');
}
break
keywordThe break
keyword is used in a switch statement to exit the switch block once a matching case is found and executed. It prevents the code from continuing to execute the remaining cases, ensuring only the correct output is generated.
const transport = 'bike';
switch (transport) {
case 'car':
console.log('🚗 Drive safely!');
break;
case 'bike':
console.log('🚲 Enjoy your bike ride!');
break;
case 'bus':
console.log('🚌 Have a pleasant bus journey!');
break;
}
A case cannot have more than one condition in a switch statement. To incorporate multiple conditions in one case, consider using the fall-through technique. Not only does it save you time, it ensure you don’t repeat yourself.
Fall-through in a switch statement occurs when you intentionally omit the break
keyword in a case, allowing the code execution to continue to the next case(s) until a break
is encountered or the end of the switch block is reached. This can be useful when multiple cases share the same output or action.
const clothing = 'jacket';
switch (clothing) {
case 't-shirt':
case 'shorts':
console.log('😎 Looks like it\'s warm outside!');
break;
case 'jacket':
case 'sweater':
console.log('❄️ Bundle up, it\'s cold!');
// No break, fall-through to the next case
case 'scarf':
console.log('🧣 Don\'t forget your scarf!');
break;
}
break
statement)A frequent mistake when using switch statements is not including the break
statement after each case. This error results in unintentional fall-through, executing multiple cases instead of just the desired one.
How to fix it: Add a break
statement after each case to prevent fall-through.
const mood = 'happy';
switch (mood) {
case 'happy':
console.log('😀 Keep smiling!');
// <--- Missing break statement
case 'sad':
console.log('☹️ Cheer up!');
break;
case 'angry':
console.log('😠 Take a deep breath!');
break;
}
// --Output--
//😀 Keep smiling!
//☹️ Cheer up!
Switch statements use strict comparison, which can lead to unexpected results when comparing different data types. In the example below, the string "2"
is not equal to the number 2
. This pitfall might cause your cases not to execute as intended.
How to fix: Consider the type of your variables and remember it will be evaluated strictly. TypeScript may help if you’re working on larger projects.
const numOfPets = '2';
switch (numOfPets) {
case 2: // Because '2' !== 2
console.log('🐾 Double the fun!');
break;
default:
console.log('🐾 Share the love!');
}
// -- Output --
// 🐾 Share the love!
A common pitfall in switch statements is declaring variables without block scope or incorrect scopes, causing them to be accessible in other cases, or creating syntax errors. You may experience an Uncaught SyntaxError: ...
if you try to redeclare the same variable in multiple clauses.
The fixes:
let
before your switch statement, or;{ ... }
)Block scope your clauses:
// The problem:
switch (weather) {
case 'rain':
const notification = '🌦️ ️Rainy days can be cozy!';
console.log(notification);
break;
case 'thunder':
// 'notification' is still accessible here
console.log(notification + ' ⚡ Be careful!');
break;
}
// Fix 1: Use Block Scope when declaring
switch (weather) {
case 'rain': { // <-- look here.
const notification = '🌦️ ️Rainy days can be cozy!';
console.log(notification);
break;
}
case 'thunder': {
const notification = '⚡ Be careful!';
console.log(notification);
break;
}
}
// Fix 2: Declare it with let before your statement
let notification = '' // <-- look here.
switch (weather)
case 'rain':
notification = '🌦️ ️Rainy days can be cozy!';
console.log(notification);
break;
case 'thunder':
notification = '⚡ Be careful!';
console.log(notification);
break;
}
Now that you know what a switch
statement is, how it works, and when to use it, it’s time to start implementing it! I hope you’ve enjoyed this article. Join us over on the SitePoint Community if you have any questions about this piece or JavaScript in general.
Original article source at: https://www.sitepoint.com/
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1626660120
Learn how to create flexible components in React for your design system using Styled Components–a CSS in JS library.
Styled Components help make components more readable and keep the headache of styling and element architecture separated.
The pros and cons are often debated, but we’re big fans at Skillthrive. If you want to learn more about the pros and cons so you can make the decision for yourself, check out this article: https://webdesign.tutsplus.com/articles/an-introduction-to-css-in-js-examples-pros-and-cons--cms-33574
👀 LIVE DEMO 👀
https://zealous-morse-4e0f08.netlify.com/
🗂 DOWNLOADS 🗂
⏰ TIMESTAMPS ⏰
Setup a Gatsby Site with Styled Components: 1:37
Create the Styled Components: 4:51
Install Google Fonts on Gatsby: 7:28
How to Use a JavaScript Switch Statement with Styled Components: 7:57
How to Use Your New Styled Component: 14:22
#WebDev #WebDesign #WebDevelopment
#javascript #webdev #react #javascript switch statements #styled components
1600078740
Javascript switch statement is used to perform different actions based on various conditions. You can use multiple if…else…if statements, but it is a little bit cumbersome instead you can use the switch statement to execute the code based on conditions. In one function, you can handle multiple conditions using a switch statement.
The switch statement which handles this situation precisely, and it does so more efficiently than repeated if…else if statements.
See the following syntax.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how a switch statement works:
#javascript #switch #js