Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6K views

JavaScript Impress

1) The document discusses 3 basic data types in JavaScript: numbers, strings, and booleans. Numbers represent numeric values, strings represent text, and booleans represent true/false values. 2) It provides examples of each data type, such as age represented as a number, name represented as a string, and whether someone wears glasses represented as a boolean. 3) The document explains that each data type can be manipulated in different ways, such as multiplying numbers, slicing strings to extract characters, and checking if two booleans are both true.

Uploaded by

Rebecca Er
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6K views

JavaScript Impress

1) The document discusses 3 basic data types in JavaScript: numbers, strings, and booleans. Numbers represent numeric values, strings represent text, and booleans represent true/false values. 2) It provides examples of each data type, such as age represented as a number, name represented as a string, and whether someone wears glasses represented as a boolean. 3) The document explains that each data type can be manipulated in different ways, such as multiplying numbers, slicing strings to extract characters, and checking if two booleans are both true.

Uploaded by

Rebecca Er
Copyright
© © All Rights Reserved
Available Formats
Download as ODP, PDF, TXT or read online on Scribd
You are on page 1/ 86

Data Types

What is Data?
Data is information that we store in our
computer programs.
For example:
Your name is a piece of data, and so is your age,
the color of your hair, how many siblings you have,
where you live, whether you’re male or female…
these things are all data.
In JavaScript, there are 3 basic types of data:

Numbers

Strings

Booleans
Numbers are used for representing, well, numbers!

For example, your age can be represented as a number,


and so can your height.

Numbers in JavaScript look like this:


4;
Strings are used to represent text.

Your name can be represented as a string in JavaScript, as


can your email address.

Strings look like this:


“Hello World!”;
Booleans are values that can be true or false.

For example, a Boolean value about you would be whether


you wear glasses. Another could be whether you like broccoli.

A Boolean looks like this:


true;
There are different ways to work with each data type

For example, you can multiply two numbers, but you can’t multiply
two strings.
With a String, you can ask for the first five characters.
With Boolean, you can check to see whether two values are both
true.
The following code example illustrates each of these possible
operations.
99 * 123;
12177
"This is a long string".slice(0, 4);
"This"
true && false;
false
Note
You may have noticed that all of these commands
end with a semicolon “;”.
Semicolons mark the end of a particular JavaScript
command or instruction (also called a statement),
sort of like the period at the end of a sentence.
Numbers And Operators
JavaScript lets you perform basic mathematical
operations like:
Addition, subtraction, multiplication, and division.
To make these calculations, we use the symbols
+, -, *, and /, which are called operators.
You can use the JavaScript console just like a
calculator.
We’ve already seen one example, adding
together 3 and 4.
Let’s try something harder...
What’s 12,345 + 56,789?
12345 + 56789;
69134

That’s not so easy to work out in your head, but JavaScript calculated it
in no time.

You can add multiple numbers with multiple plus signs:

22 + 33 + 44;
99
JavaScript can also do subtraction . . .
1000 - 17;
983
and multiplication, using an asterisk . . .
123 * 456;
56088
and division, using a forward slash . . .
12345 / 250;
49.38
You can also combine these simple operations
to make something more complex, like this:
1234 + 57 * 3 - 31 / 4;
1397.25
Here it gets a bit tricky, because the result of this
calculation (the answer) will depend on the order
that JavaScript does each operation. In math,
the rule is that multiplication and division always
take place before addition and subtraction.
And JavaScript follows this rule as well.
1234 + 57 * 3 - 31 / 4

1234 + 171 - 31 / 4

1234 + 171 - 7.75

1405 - 7.75

1397.25

The figure above shows the order JavaScript would follow. First, JavaScript
multiplies 57 * 3 and gets 171 (shown in red).
Then it divides 31 / 4 to get 7.75 (shown in blue).
Next it adds 1234 + 171 to get 1405 (shown in green).
Finally it subtracts 1405 - 7.75 to get 1397.25, which is the final result.
What if you wanted to do the addition and the subtraction
first, before doing the multiplication and division?
For example, say you have 1 brother and 3 sisters and
8 candies, and you want to split the candies equally among
your 4 siblings? (You’ve already taken your share!)
You would have to divide 8 by your number of siblings.
Here’s an attempt:
8 / 1 + 3;
11
That can’t be right! You can’t give each sibling 11 candies
when you’ve only got 8!
The problem is that JavaScript does division before addition, so it
divides 8 by 1 (which equals 8) and then adds 3 to that, giving you 11.
To fix this and make JavaScript do the addition first, we can use parentheses:

8 / (1 + 3);
2
That’s more like it! two candies to each of your
siblings.
The parentheses force JavaScript to add 1 and
3 before dividing 8 by 4.
Variables
JavaScript lets you give names to values using variables. You can think of
a variable as a box that you can fit one thing in. If you put something else
in it, the first thing goes away.
To create a new variable, use the keyword var, followed by the name of the
variable.
A keyword is a word that has special meaning in JavaScript. In this case,
when we type var, JavaScript knows that we are about to enter the name
of a new variable.
For example, here’s how you’d make a new variable called nick:
var nick;
undefined
We’ve created a new variable called nick. The
console spits out undefined in response. But
this isn’t an error! That’s just what JavaScript
does whenever a command doesn’t return a
value.
What’s a return value?
Well, for example, when you typed 12345 + 56789;
The console returned the value 69134.
Creating a variable in JavaScript doesn’t return
a value, so the interpreter prints undefined.
To give the variable a value, use the equal sign:
var age = 12;
undefined
Setting a value is called assignment (we are assigning the
value 12 to the variable age). Again, undefined is printed,
because we’re creating another new variable.
The variable age is now in our interpreter and set to the value
12.
That means that if you type age on its own, the interpreter will
show you its value:
age;
12
Cool! The value of the variable isn’t set in stone, though
(they’re called variables because they can vary), and if
you want to update it, just use = again:
age = 13;
13
This time the var keyword wasn’t used, because the variable age
already exists. You need to use var only when you want to create
a variable, not when you want to change the value of a variable.

Notice also, because we’re not creating a new variable, the value 13
is returned from the assignment and printed on the next line.
This slightly more complex example solves the candies problem
from earlier, without parentheses:
var numberOfSiblings = 1 + 3;
var numberOfCandies = 8;
numberOfCandies / numberOfSiblings;
2
First we create a variable called numberOfSiblings and assign it
the value of 1 + 3 (which JavaScript works out to be 4). Then we
create the variable numberOfCandies and assign 8 to it. Finally, we
write numberOfCandies / numberOfSiblings. Because numberOfCandies is 8
and numberOfSiblings is 4, JavaScript works out 8 / 4 and gives us 2.
Naming Variables:
Be careful with your variable names, because it’s easy to misspell them.
Even if you just get the capitalization wrong, the JavaScript interpreter
won’t know what you mean!
For example, if you accidentally used a lowercase c in numberOfCandies,
you’d get an error:

numberOfcandies / numberOfSiblings;
ReferenceError: numberOfcandies is not defined
Unfortunately, JavaScript will only do exactly what you ask
it to do. If you misspell a variable name, JavaScript has no
idea what you mean, and it will display an error message.
Another tricky thing about variable names in JavaScript is that
they can’t contain spaces, which means they can be difficult to
read. I could have named my variable numberofcandies with
no capital letters, which makes it even harder to read because
it’s not clear where the words end. Is this variable “numb erof can
dies” or “numberofcan dies”?
Without the capital letters, it’s hard to tell.
One common way to get around this is to start each word with a
capital letter as in NumberOfCandies.

This convention is called camel case because it supposedly


looks like the humps on a camel.
+= (Plus Equals) And
-= (Minus Equals)
To increase the value of a variable by a certain
amount, you could use this code:
var x = 10;
x = x + 5;
x;
15
Here, we start out with a variable called x, set to
10. Then, we assign x + 5 to x.
Because x was 10, x + 5 will be 15.
What we’re doing here is using the old value of
x to work out a new value for x.
Therefore, x = x + 5 really means “add 5 to x.”
JavaScript gives you an easier way of increasing or decreasing
a variable by a certain amount, with the += and -= operators.

For example,
if we have a variable x, then x += 5 is the same as saying
x = x + 5.
The -= operator works in the same way.
So x -= 9 would be the same as x = x - 9 (“subtract 9 from x”).
Here’s an example using both of these operators to keep
track of a score in a video game:
var score = 10;
score += 7;
17
score -= 3;
14
In this example,
we start with a score of 10 by assigning the value 10 to the
variable score.
Then we beat a monster, which increases score by 7 using the
+= operator. (score += 7 is the same as score = score + 7).
Before we beat the monster, score was 10, and 10 + 7 is 17,
so this operation sets score to 17.
After our victory over the monster, we crash into
a meteor and score is reduced by 3.
Again,
score -= 3 is the same as score = score – 3.
Because score is 17 at this point, score - 3 is
14, and that value gets reassigned to score.
Strings

So far, we’ve just been working with numbers.


Now let’s look at another type of data: strings.
Strings in JavaScript are just sequences of
characters, which can include letters, numbers,
punctuation, and spaces.
We put strings between quotes so JavaScript
knows where they start and end.
For example, here’s a classic:
"Hello world!";
"Hello world!"
To enter a string, just type a double quotation
mark (") followed by the text you want in the
string, and then close the string with another
double quote.
You can also use single quotes ('), but to keep
things simple, we’ll just be using double quotes
in this book.
You can save strings into variables, just like
numbers:
var myAwesomeString = "Something REALLY awesome!!!";
There’s also nothing stopping you from assigning a
string to a variable that previously contained a number:
var myThing = 5;
myThing = "this is a string";
"this is a string"
What if you put a number between quotes?
Is that a string or a number?
Well,
In JavaScript, a string is a string, even if it
happens to have some characters that are
numbers.
For example:
var numberNine = 9;
var stringNine = "9";

numberNine is a number, and stringNine is a string.


To see how these are different, let’s try adding them together:
numberNine + numberNine;
18
stringNine + stringNine;
"99"
When we add the number values 9 and 9, we
get 18.
But when we use the + operator on "9" and "9",
the strings are simply joined together to form
"99".
Joining Strings
When you use + to join two strings, you make a new string
with the second string attached to the end of the first
string, like this:
var greeting = "Hello";
var myName = "Nick";
greeting + myName;
"HelloNick"
Here,
we create two variables (greeting and myName) and assign each
a string value ("Hello" and "Nick", respectively).
When we add these two variables together, the strings are
combined to make a new string, "HelloNick".
That doesn’t look right, though there should be a space between
Hello and Nick.
But JavaScript won’t put a space there unless we specifically tell it to
by adding a space in one of the original strings:
var greeting = "Hello ";
var myName = "Nick";
greeting + myName;
"Hello Nick"
Finding The Length Of A String
You can do a lot more with strings other than just adding them
together. Here are some examples.
To get the length of a string, just add .length to the end of it:
"Supercalifragilisticexpialidocious".length;
34
You can also add .length to the end of a variable
that contains a string:
var java = "Java";
java.length;
4
var script = "Script";
script.length;
6
var javascript = java + script;
javascript.length;
10
Here, we assign the string "Java" to the variable java and the
string "Script" to the variable script. Then we add .length to the end
of each variable to determine the length of each string, as well as
the length of the combined strings.
Notice that you can add .length to the actual string or
to a variable that contains a string.
This illustrates something very important about
variables:
Anywhere you can use a number or a string, you can
also use a variable containing a number or a string.
Getting A Single Character
From A String
Sometimes you want to get a single character from a string.
For example,
you might have a secret code where the message is made
up of the second character of each word in a list of words.
You’d need to be able to get just the second characters
and join them all together to create a new word.
To get a character from a particular position in a string,
use square brackets, [ ].
Just take the string, or the variable containing the string,
and put the number of the character you want in a pair
of square brackets at the end.
For example,
to get the first character of myName, use myName[0],
like this:
var myName = "Nick";
myName[0];
"N"
myName[1];
"i"
myName[2];
"c"
myName[3];
“k”
Notice that to get the first character of the string, we use 0 rather than 1.
That’s because JavaScript starts counting at zero.
That means when you want the first character of a string, you use 0.
When you want the second one, you use 1; and so on.
Let’s try out our secret code, where we hide a
message in some words’ second characters.
Here’s how to find the secret message in a sequence of words:
var codeWord1 = "are";
var codeWord2 = "tubas";
var codeWord3 = "unsafe";
var codeWord4 = "?!";
codeWord1[1] + codeWord2[1] + codeWord3[1] + codeWord4[1];
"run!"
Again,
notice that to get the second character of each string,
we use 1.
Cutting Up Strings
To “cut off” a piece of a big string, you can use slice.
For example,
you might want to grab the first bit of a long movie
review to show as a teaser on your website.
To use slice, put a period after a string or a variable
containing a string, followed by the word slice and
opening and closing parentheses.
Inside the parentheses, enter the start and end
positions of the slice of the string you want,
separated by a comma.
"a string".slice(1, 5)
These two numbers set the start and end of the
slice.
var longString = "My long string is long";
longString.slice(3, 14);
"long string"
The first number in parentheses is the number
of the character that begins the slice,
and the second number is the number of the
character after the last character in the slice.
We basically tell JavaScript, “Pull a slice out of this longer string starting
at the character at place 3 and keep going until you hit place 14.”
If you include only one number in the parentheses after slice, the string
that it slices will start from that number and continue all the way to the
end of the string, like this:
var longString = "My long string is long";
longString.slice(3);
"long string is long"
Changing Strings To All Capitals
Or Lowercase Letters
If you have some text that you just want to shout, try using toUpperCase
to turn it all into capital letters.
"Hello there, how are you doing?".toUpperCase();
"HELLO THERE, HOW ARE YOU DOING?"
When you use .toUpperCase() on a string, it
makes a new string where all the letters are
turned into uppercase.
You can go the other way around, too:
"hELlo THERE, hOW ARE yOu doINg?".toLowerCase();
"hello there, how are you doing?"
As the name suggests, .toLowerCase() makes all
of the characters lowercase.
But shouldn’t sentences always start with a
capital letter?
How can we take a string and make the first letter
uppercase but turn the rest into lowercase?
Note
See if you can figure out how to turn "hELlo THERE, hOW ARE yOu
doINg?" into "Hello there, how are you doing?" using the tools you
just learned.
Here’s one approach:
1. var sillyString = "hELlo THERE, hOW ARE yOu doINg?";
2. var lowerString = sillyString.toLowerCase();
3. var firstCharacter = lowerString[0];
4. var firstCharacterUpper = firstCharacter.toUpperCase();
5. var restOfString = lowerString.slice(1);
6. firstCharacterUpper + restOfString;
"Hello there, how are you doing?"
Let’s go through this line by line.
At (1), we create a new variable called sillyString and save the string we want to
modify to that variable.
At (2), we get the lowercase version of sillyString ("hello there how are you
doing?") with .toLowerCase() and save that in a new variable called lowerString.
At (3), we use [0] to get the first character of lowerString ("h") and save it in
firstCharacter (0 is used to grab the first character).
Then, at (4), we create an uppercase version of firstCharacter ("H") and call that
firstCharacterUpper.
At (5), we use slice to get all the characters in lowerString, starting from the
second character ("ello there how are you doing?") and save that in restOfString.
Finally, at (6), we add firstCharacterUpper ("H") to restOfString to get "Hello there,
how are you doing?".
We could turn lines (2) through (6) into just one line, like this:
var sillyString = "hELlo THERE, hOW ARE yOu doINg?";
sillyString[0].toUpperCase() + sillyString.slice(1).toLowerCase();
"Hello there, how are you doing?"
It can be confusing to follow along with code
written this way, though, it’s a good idea to use
variables for each step of a complicated task
like this.
At least until you get more comfortable reading
this kind of complex code.
Booleans
A Boolean value is simply a value that’s either true or false.
For example,
here’s a simple Boolean expression:
var javascriptIsCool = true;
javascriptIsCool;
true
In this example,
we created a new variable called javascriptIsCool
and assigned the Boolean value true to it.
On the second line, we get the value of
javascriptIsCool, which, of course, is true!
Logical Operators
Just as you can combine numbers with mathematical
operators (+, -, *, /, and so on), you can combine
Boolean values with Boolean operators.
When you combine Boolean values with
Boolean operators, the result will always be
another Boolean value (either true or false).
The three main Boolean operators in JavaScript
are &&, ||, and !.
They may look a bit weird, but with a little practice,
they’re not hard to use. Let’s try them out!
&& (and)
&& means “and”. When reading aloud, people
call it “and,” “andand,” or “ampersand-
ampersand.” (Ampersand is the name of the
character &).
Use the && operator with two Boolean values to
see if they’re both true.
For example,
before you go to work, you want to make sure
that you’ve had a shower and you have your
suitcase. If both are true, you can go to work,
but if one or both are false, you can’t leave yet.
var hadShower = true;
var hasSuitcase = false;
hadShower && hasSuitcase;
false

Here we set the variable hadShower to true and the variable hasSuitcase to false.

When we enter hadShower && hasSuitcase, we are basically asking JavaScript,


“Are both of these values true?” Since they aren’t both true (you don’t have your
suitcase), JavaScript returns false (you’re not ready for work).
Let’s try this again, with both values set to true:
var hadShower = true;
var hasBackpack = true;
hadShower && hasBackpack;
true

You might also like