Strings in JavaScript
A "string" in JavaScript - and in most other programming languges - is a piece of text.
The name probably derives from it being stored as a string of characters. Our very first
Hello world
had 'Hello world' as a string.
A string in JavaScript is any number of characters (including zero) inside quotes. These
can be "double" or 'single' quotes. Both these lines of JavaScript code will work:
alert('Hello world')
alert("Hello world")
There is an advantage to using double quotes. If you use double quotes then you can use a
single quote inside the string. Try this to see what I mean:
alert("Your name is '" + userName + "'.");
Joining strings together
An earlier
program
asked for the user's name and then welcomed them. If you had entered your name as "fred"
then the alert would have displayed "Hello fred.". It did that with this line of code:
alert("Hello " + userName + ".")
There are two things to notice in this line, the different types of string and the need
to tell the program every detail of what you want.
Types of string
One is that the + sign is being used to join three items of thext together. These
three items are "Hello" , "fred" and the full stop ".". Each of these is a string but
they demonstrate two different types of string. The userName is a string variable and
will hold a different value every time that the program runs. The other two, the "Hello"
and the "." will be the same on every run of the program and are known as string literals.
The program does exactly as it's told
You'll see that there is a space after "Hello" in this line of code:
alert("Hello " + userName + ".")
Why is it there and what would happen if you remove it?
It's a good illustration of the fact that the computer has no common sense whatsoever and
will do exactly what your script tells it to do - no more and no less. Without that space
the program would display the two words with no space between them. "HelloFred." Try it.
Fancy quotes
Be careful when copying code from a word processor or a published source. Some of these
use "smart" quotes where the marks are angled in towards the text like “this” or ‘this’.
These look nicer in text but the browser will not recognise them. It can only work with
the plain straight quotes.
The preceding paragraph illustrates the problem nicely. It was supposed to show the words
"this" and 'this' with curly rather than with straight quotes but your browser might not
have been able to display those characters.
|