Breadcrumbs

Too Easy JavaScript - Working with Data [2]

In Part 1 you learned what JavaScript is and its basic syntax. Here in Part 2 we will look into working with data using JavaScript's variables and operators. You'll also learn some areas that extend on proper JavaScript syntax, to help you keep your code error free.

What are variables?

As in most programming languages, JavaScript has a way of storing data, typically referred to as a variable. This is a typical concept used in most programming languages.

A variable is an imaginary "container" in which you can store data. It is referred to by an assigned name, which you can later use throughout your program. Each "container", or variable, can only hold one piece of data at a time (excluding arrays, which we'll discuss in a later lesson).

JavaScript is a loosely typed language so its variables have the ability to hold strings, numbers, and boolean values. We'll discuss more on the different data types later in this lesson.

Declaring Variables

You declare a variable using the var keyword:

Code: JavaScript

// Declare a variable
var myVariable;

Variable names can contain underscores, alphabetic characters, and numbers. Although you can include underscores and digits, you must begin your variable name with an alphabetic character. There are many practices for naming variables, but it is best to use something that fits you.

You can also declare multiple variables using one var declaration:

Code: JavaScript

// Declare multiple variable
var myVariable, myVariable2, myVariable3;

Now that you've assigned your variable a name, you can store data in it using the assignment operator (=):

Code: JavaScript

// Declare a variable
var myVariable;
myVariable = "This is my variable!";

If your variable contains characters, meaning non-keywords and digits, then you must enclose the value in quotes (" "). This is typically referred to as a string. Strings can contain any characters, as long as they're surrounded by quotes.

Code: JavaScript

// Demonstrate Strings
var myString, notString;
myString = "This is a string"; // String
notString = 1; // Not a String

You can also define the variable's value when it is declared:

Code: JavaScript

// Declare a variable
var myVariable = "This is my variable!";

JavaScript Keywords

In JavaScript there are certain keywords that are part of the JavaScript language syntax. Therefore you cannot use these keywords as identifiers for variables or functions. JavaScript also reserves a few other words for possible inclusion in JavaScript's future syntax.

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

Data Types

As mentioned earlier, JavaScript is a loosely typed language so its variables have the ability to hold strings, numbers, and boolean values. The only difference in JavaScript is that you don't have to declare the data type, as in C++ or Java. Instead, the data type of a variable is determined by the value it holds.

We can use JavaScript's typeof keyword to determine a variable's data type:

Code: JavaScript

// Test typeof
var test = true; // boolean
alert(typeof test);

Escape Sequences

JavaScript offers escape sequences to allow characters to escape recognition as part of the JavaScript syntax. These are typically a character preceded by the backslash (\) character.

Sequence Description
b backspace
f form feed
n new line
r carriage return
' single quote
" double quote

[/cell]
[cell]single backslash character

We can now incorporate some of these escape sequences into our code:

Code: JavaScript

// Demonstrate Escape Sequences
alert("This is one line n This is "another".");

The most important escape sequence is the double quote. This is useful to incorporate quotation marks within a string without terminating it. This becomes vice-versa if you enclose a string in single quotes:

Code: JavaScript

document.write("These are "quotes"!"); // Double Quotes
document.write('These are 'quotes'!'); // Single Quotes

What are operators?

Operators allow you to manipulate and compare data. There are five kinds of operators - arithmetic, assignment, comparison, logical, and conditional. In this lesson we'll only cover arithmetic and assignment operators, as they directly affect variables.

Arithmetic Operators

Arithmetic operators perform mathematical operations, and most are for the number data type.

Operator Description
+ addition
- subtraction
* multiplication
/ division
% modulus
++ increment
-- decrement

Most of these are quite self explanatory. The modulus operator returns the remainder of a division problem. Incrementing a variable increases the value by one. Decrementing a variable decreases the value by one.

Code: JavaScript

// Arithmetic Operators
var add = 20 + 20; // Addition - Returns 40
var sub = 50 - 20; // Subtraction - Returns 30
var mul = 3 * 3; // Multiplication - Returns 9
var div = 9 / 3; // Division - Returns 3
var mod = 9 % 4 // Modulus - Returns 1
var inc = 5; inc = ++inc; // Increment Returns 6
var dec = 5; dec = --dec; // Decrement Returns 4

You can also use the addition (+) operator to connect two strings together:

Code: JavaScript

// Connect Two Strings
var one = "Hello ";
var two = "World!";

var together = one + two;
alert(together);

In order to better group longer expressions you can use parentheses. JavaScript follows the order of operations, Please Excuse My Dear Aunt Sally (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction).

Code: JavaScript

// Grouping Equations
var solution = 1 - 3 * 2; // returns -5 although unclear
var betterSolution = 1 - (3 * 2); // returns -5 and clear
var solution2 = (1-3) * 2; // different grouping, returns - 4

Assignment Operators

Excluding one operator, all assignment operators are shorthand versions of arithmetic operators. Assignment operators are used to assign values to variables:

Operator Example Equivalent
= a = b a = b
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a * b
/= a /= b a = a / b
%= a %= b a = a % b

Remember that the assignment operator (=) is not the same thing as 'equals'. The equality operator (==) is used for comparison only, which we'll discuss in the next lesson.

Summary

You've learned the basics of manipulating and storing data in JavaScript. You've learned two types of operators and how to use them. In Part 3 we'll continue by learning control structures and the remaining operators.