Variables

Variables

Variables are common in programming languages. They are a way of storing a value in memory for later use. In JavaScript, we start by declaring a variable. This is done using the keyword var:
var a; // declare a variable called a
<< undefined


var message;
<< undefined
  

Notice that the console outputs undefined. This is a special JavaScript primitive value that is covered later in the chapter, but it’s basically saying that the variable has been created but is yet to be assigned a value.

You don’t actually have to declare variables before using them, but as we’ll see later, bad things can happen if you choose not to. So remember, a ninja will always declare variables.

You can even declare multiple variables at once:
var a,b,c; // 3 variables declared at once
<< undefined
 

Rules for Naming Variables

When naming variables, you should try to give them sensible names that describe what the variable represents; hence, answer is a better variable name than x.
A variable name can start with any upper or lower case letter, an underscore (_), or dollar symbol ($). It can also contain numbers but cannot start with them. Here are some examples:


$name
_answer
firstName
last_name
address_line1
  

Variable names are case sensitive, so ANSWER is different to Answer and answer.
When using multiple words for variable names there are two conventions that can be used. Camel case starts with a lowercase letter and then each new word capitalized:
firstNameAndLastName 

Underscore separates each new word with an underscore:
first_name_and_last_name 

JavaScript’s built-in functions use the camel-case notation, but you can choose to use one or the other or a combination of the two when naming variables. What’s important for a ninja is to be consistent.


Reserved Words

The following words are reserved for use by the language and cannot be used to name variables (or the function parameters and object properties that appear in later chapters):

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in instanceof, int, inteface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with 

These words are reserved because many of them are used by the language itself, and you will come across them later in this book.


Many are not used by the language, however; one can only assume they were planned to be used at some point, but never were. There are also a few words not reserved that should have been as they are an important part of the language:
undefined, NaN, Infinity 

These are covered later in this chapter. You should also avoid using these words for variable names.


Assigenment

To assign a value to a variable, we use the operator. This example shows how we would set the variable name to point to the string literal "Walter":
var name; // declare the variable first
<< undefined


name = "Walter"; // assign the variable to a string
<< "Walter
 

Once the variable has been assigned a value, it is displayed in the console output.
To see the value of a variable, simply enter it in the console. The variable name now refers to the string "Walter", so it will behave exactly the same as that string:
name;
<< "Walter"


typeof name;
<< "string"
 

This is a useful way of dealing with long strings as it saves us from typing them over and over again. It’s also useful if the value stored in the variable is likely to change (hence the name, variable).

You can declare and initialize a variable at the same time:

var name = "Jesse";
<< "Jesse"
 

You can also declare and assign values to multiple variables in a single statement:
var x = 2, y, z = "Hi!"; // y has only been declared, it's undefined
<< undefined
 


String Properties and Methods


Primitive values and objects have properties and methods. Properties are information about the object or value, while methods perform an action on the object or valueeither to change it or to tell us something about it.

Object Wrappers

Technically, only objects have properties and methods. JavaScript overcomes this by creating wrapper objects for primitive values. This all happens in the background, so for all intents and purposes it appears that primitive values also have properties and methods. 

We can access the properties of a string using dot notation. This involves writing a dot followed by the property we are interested in. For example, every string has a length property that tells us how many characters are in the string:
name = "Heisenberg"; // declare and assign a variable
<< "Heisenberg"

name.length; // call the length method on name
<< 10
  

As you can see, this tells us that there are ten characters in the string stored in the name variable.

Bracket Notations

Another notation you can use to access a primitive value’s properties are square brackets:
name['length']; // note the property name is in quote marks
<< 10
 



All properties of primitive values are immutable, which means that they’re unable to be changed. You can try, but your efforts will be futile:
name.length;
<< 10

name.length = 7; // try to change the length
<< 7


name.length; // check to see if it's changed
<< 10
  

A method is an action that a primitive value or object can perform. To call a method, we use the dot operator [.] followed by the name of the method, followed by parentheses (this is a useful way to distinguish between a property and a methodmethods end with parentheses). For example, we can write a string in all capital letters using the toUpperCase() method:
name.toUpperCase();
<< "HEISENBERG"
 

Or the toLowerCase() method, which will write my name in all lower-case letters:
name.toLowerCase();
<< "heisenberg"
 

If you want to know which character is at a certain position, you can use the charAt() method:
name.charAt(1);
<< "e"
 

This tells us that the character "e" is at position 1. If you were thinking that it should be "H", this is because the first letter is classed as being at position 0 (you’ll find that counting usually starts at zero in programming!).
If you want to find where a certain character or substring appears in a string, we can use the indexOf() method:
name.indexOf("H");
<< 0
  

If a character doesn’t appear in the string, -1 will be returned:
name.indexOf("a");
<< -1
 

If we want the last occurrence of a character or substring, we can use the lastIndexOf() method:
name.lastIndexOf("e");
<< 7
 

The concat() method can be used to concatenate two or more strings together:
"JavaScript".concat("Ninja");
<< "JavaScriptNinja"

"Hello".concat(" ","World","!");
<< "Hello World!"
 

A shortcut for string concatenation is to use the + symbol to add the two strings together:
"Java" + "Script" + " " + "Ninja";
<< "JavaScript Ninja"
 

The trim() method will remove any whitespace from the beginning and end of a string:
"    Hello World     ".trim();// the space in the middle will be preserved
<< "Hello World"

" \t\t JavaScript Ninja! \r".trim();// escaped tabs and carriage returns are also removed
<< "JavaScript Ninja!"
  


Support for trim ()
The trim() method was a relatively recent addition to the collection of string methods so is not supported in older browsers.  

0 Response to "Variables"

Post a Comment