0% found this document useful (0 votes)
11 views

Comparing Strings

The document explains how to compare strings in JavaScript, highlighting that string comparisons are case-sensitive and based on ASCII values. It also introduces switch statements as an alternative to multiple if-else statements for executing code based on the value of a variable, detailing how to prevent falling through cases with break statements. Additionally, it emphasizes the importance of including a default case in switch statements to handle unmatched cases.

Uploaded by

senafkuma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Comparing Strings

The document explains how to compare strings in JavaScript, highlighting that string comparisons are case-sensitive and based on ASCII values. It also introduces switch statements as an alternative to multiple if-else statements for executing code based on the value of a variable, detailing how to prevent falling through cases with break statements. Additionally, it emphasizes the importance of including a default case in switch statements to handle unmatched cases.

Uploaded by

senafkuma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Comparing Strings

LessonDownloads

Comparing strings
Another way to work with strings is by comparing them. You've seen the
comparison operators == and != when you compared numbers for equality.
You can also use them with strings! For example, let’s compare the
string "Yes" to "yes".

"Yes" == "yes"
Returns: false
When you run this in the console, it returns false. Why is
that? "Yes" and "yes" are the same string, right? Well not quite.

A. Case-sensitive

When you compare strings, case matters. While both string use the same
letters (and those letters appear in the same order), the first letter in the first
string is a capital Y while the first letter in the second string is a lowercase y.

'Y' != 'y'
Returns: true

B. Internal Working

In Javascript, strings are compared character-by-character in alphabetical


order. Each character has a specific numeric value, coming from ASCII value
of Printable characters(opens in a new tab). For example, the character 'A'
has a value 65, and 'a' has a value 97. You can notice that a lowercase letter
has a higher ASCII value than the uppercase character. If you want to know
the ASCII value of a particular character, you can try running the code below:

// Pick a string. Your string can have any number of


characters.
const my_string = "a";

// Calculate the ASCII value of the first character, i.e.


the character at the position 0.
const ASCII_value = my_string.charCodeAt(0);
// Let us print
console.log(ASCII_value);
In the example above, if you wish to print ASCII values of all the characters in
your string, you would have to use Loops that we will study in later part of this
course. Just for reference, here is how you can use a loop to print the ASCII
value of all characters in a string.

const my_string = "Udacity";

// Iterate using a Loop


for (let i = 0; i < my_string.length; i++) {
console.log(my_string.charCodeAt(i));
}
The ASCII values of [A-Z] fall in the range [65-90], whereas, the ASCII values
of [a-z] fall in the range [97-122]. Therefore, when we compare strings, the
comparison happens character-by-character for the ASCII values.
Quiz Question

Which of these expressions evaluate to true? Make a guess and then enter
each expression into the console.

"green" == "blue"

"green" == "green"

"green" == "Green"
"Green" == "green"

"green" > "blue"

"green" > "green"

"green" > "Green"

"Green" > "green"


Submit

Quiz: Favorite Food


LessonDownloads

Directions:
Create a string with the name of your favorite food. The first letter of the string
should be capitalized.

Running Your Code

Enter the following in the terminal:


node favorite-food.js
Start Workspace

After starting your workspace, remember to keep the page open. Closing the
page will shut down the workspace and halt any associated processes.
Start Workspace
Try the quiz on your own first. If you get stuck you can check the solution by
clicking the button below.
Show Solution

Switch Statement
LessonDownloads

So Many Options!
Show Video Transcript
Video Transcript
0:00
As you continue to write more and more conditional statements,
0:03
sometimes you might run into code that looks like this.
0:06
Basically each one of these conditional statements is checking for
0:10
a specific value in one variable, and
0:12
if that's true then the code inside the if statement will be ran.
0:16
Just to show you how this works, let's run this code and
0:18
see what its output back to us.
0:20
All right, so because the variable option is set to 3 we get print it back you
0:24
selected option 3, so not terribly complicated.
0:27
Now what about told you there's another way to achieved the same result
without
0:32
using any conditional statement.
0:35
Well, in fact, there's just so happens to be another way and
0:38
that is by using a switch statement.
0:40
Now switch statement only works in situations like these where you have
0:44
a bunch of chained if statements based on the value of the same variable.
0:47
Let me rewrite this code using a switch statement and
0:50
then I'll explain how it works.
0:52
I'll keep the conditional statement version here on this side so
0:55
you can see the difference.
0:56
Okay, so
0:57
what I've done is I've wrapped all my code inside of a switch statement.
1:01
And just like it reads,
1:02
I want to switch which piece of code is ran based on the variable option.
1:07
The other thing I've done is I have replaced each if statement with a case
1:10
clause where the value of the case represents the value the variable
1:14
option needs to be in order to run the code that is contained underneath it.
1:18
Basically, if the value of option is say, 3 when our code reaches
1:23
the switch statement, it's going to look to see if a case like that exists.
1:27
If it does, and in this case it does, then it transfers control of that case,
1:32
and continues executing.
1:33
If it doesn't, then it bypasses the switch statement completely.
1:37
Just to show you how this works, let's run this code, and
1:40
see what is output back to us.
1:43
Look at that.
1:44
Instead of just printing you selected option 3 we also got option 4,
1:49
option 5 and option 6, so why is this happening?
1:53
Well, it's important to understand exactly what is going on when you use
1:57
a switch statement.
1:58
Remember, once our code reaches a switch statement,
2:01
it looks to see if in case for the bearable we are switching on exist.
2:06
If it does, then it transfers control to that case and continues executing.
2:10
But what it doesn't do is prevent any of the cases below it from not running.
2:15
This behavior is called falling through.
2:17
You see, you can think of a switch statement almost like jumping you to
2:21
a line of code, based on the value of a variable.
2:24
So in this case, option is set to 3 so we jump to the case 3, and
2:28
then we continue running our code.
2:30
That's why the other print statement get executed.
2:33
If you actually want to stop after a case is ran,
2:36
then you will need to use the keyword break.
2:39
A break statement can be used to exit our switch statement so
2:41
that no other cases are ran.
2:43
If I add break statements to each case and then ran this code again,
2:47
you see that we only get back you selected option 3.
2:51
Also, technically I don't need the break statement here on the last case
because
2:55
this is the last case in a switch statement.
2:57
So there's a couple of things to take away from this.
3:00
Switch statements only work in situations where you want to execute
3:03
statements of code based on the value of some variable.
3:06
It's just another alternative and you might see it come up from time to time.
3:10
Another thing worth mentioning is that you can use a switch statement on
3:13
any type of data, not just numbers.
3:16
Also, there are even some scenarios where you might want to
3:18
leverage the falling through behavior of a switch statement.
3:21
We'll look at that more closely in the next section.
If you find yourself repeating else if statements in your code, where each
condition is based on the same value, like this:

if (option === 1) {
console.log("You selected option 1.");
} else if (option === 2) {
console.log("You selected option 2.");
} else if (option === 3) {
console.log("You selected option 3.");
} else if (option === 4) {
console.log("You selected option 4.");
} else if (option === 5) {
console.log("You selected option 5.");
} else if (option === 6) {
console.log("You selected option 6.");
}
then it might be time to use a switch statement.

Switch Statement
A switch statement is an another way to chain multiple else if statements that
are based on the same value without using conditional statements.
Instead, you just switch which piece of code is executed based on a value.

switch (option) {
case 1:
console.log("You selected option 1.");
case 2:
console.log("You selected option 2.");
case 3:
console.log("You selected option 3.");
case 4:
console.log("You selected option 4.");
case 5:
console.log("You selected option 5.");
case 6:
console.log("You selected option 6.");
}
Here, each else if statement (option === [value]) has been replaced with
a case clause (case [value]:) and those clauses have been wrapped inside the
switch statement.

Switch Looks for Matching Values

When the switch statement evaluates, it starts at the top and looks for
a case clause whose expression evaluates to the same value as the result of
the expression passed to the switch statement.

When it finds a match, it transfers control to that case clause to executed the
code for that case.

So, if you set option equal to 3...


const option = 3;

switch (option) {
...
}
Prints:
You selected option 3.
You selected option 4.
You selected option 5.
You selected option 6.
...then the switch statement prints out options 3, 4, 5, and 6.

But that’s not exactly like the original if...else code at the top? So what’s
missing?

Use Break to Avoid Falling Through


After the code in the matching case is run, the switch statement continues to
run all of the code below that statement too! This is called falling through.

We can prevent the code from falling through by adding a break statement at
the end of each case.

The break statement will terminate the switch statement and transfer control to
the code following the switch statement which prevents the switch statement
from falling through and running the code in the other case clauses.

const option = 3;

switch (option) {
case 1:
console.log("You selected option 1.");
break;
case 2:
console.log("You selected option 2.");
break;
case 3:
console.log("You selected option 3.");
break;
case 4:
console.log("You selected option 4.");
break;
case 5:
console.log("You selected option 5.");
break;
case 6:
console.log("You selected option 6.");
break; // technically, not needed
}
Prints: You selected option 3.

Set a Default Case

What happens if none of the cases match? Nothing -- because there is no


code to run. That works in some situations, but it most cases you'll want to
add a default case to catch situations when none of the case statements match.

const option = 23;

switch (option) {
case 1:
console.log("You selected option 1.");
break;
case 2:
console.log("You selected option 2.");
break;
case 3:
console.log("You selected option 3.");
break;
case 4:
console.log("You selected option 4.");
break;
case 5:
console.log("You selected option 5.");
break;
case 6:
console.log("You selected option 6.");
break;
default:
console.log("You did not select a valid option.");
}
Prints: You did not select a valid option.
It is good practice to always set a default case.
Question 1 of 4

Does it matter where the default statement is placed?


What is the output from this code:

const favoriteFood = "soup";


let restaurant = undefined;

switch(favoriteFood) {
case "pizza":
restaurant ="pizzeria";
break;
default:
restaurant ="diner";
break;
case "tacos":
restaurant ="taqueria";
break;
case "sushi":
restaurant ="sushi bar";
break;
case "pancakes":
restaurant ="pancake house";
break;
}

console.log("Go to the " + restaurant);

Go to the undefined

Go to the diner
Submit
Question 2 of 4

What is the output from the following switch statement?

const month = 7;
let days;

switch(month) {
case 1:
case 2:
days = 28;
break;
case 3:
case 4:
days = 30;
break;
case 5:
case 6:
days = 30;
break;
case 7:
case 8:
case 9:
days = 30;
break;
case 10:
case 11:
days = 30;
break;
case 12:
default:
days = 31;
}

console.log("There are " + days + " days in this


month.");
There are 31 days in this month.

There are 30 days in this month.

There are 28 days in this month.


Submit
Question 3 of 4

What is the output from the following switch statement?

const month = 5;
let days;

switch (month) {
case 1:
days = 31;
break;
case 2:
days = 28;
break;
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
}

console.log('There are ' + days + ' days in this


month.');

There are 31 days in this month.

There are 30 days in this month.


There are 28 days in this month.
Submit
Question 4 of 4

What is the output from the following switch statement?

var month = 2;

switch(month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
days = 28;
}

console.log("There are " + days + " days in this


month.");

There are 31 days in this month.


There are 30 days in this month.

There are 28 days in this month.


Submit

Read More

Learn more about how switch statements work in the documentation: MDN
Web Docs: switch

You might also like