JavaScript Events

Toggle navigation
TUTORIAL HOME
JavaScript Events
❮ Previous Next ❯
HTML events are “things” that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can “react” on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

With double quotes:

In the following example, an onclick attribute (with code), is added to a button element:

Example
<button onclick="document.getElementById(‘demo’).innerHTML = Date()”>The time is?
»
In the example above, the JavaScript code changes the content of the element with id=”demo”.

In the next example, the code changes the content of its own element (using this.innerHTML):

Example
The time is?
»
JavaScript code is often several lines long. It is more common to see event attributes calling functions:

Example
The time is?
»
Common HTML Events
Here is a list of some common HTML events:

Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
The list is much longer: Omegas JavaScript Reference HTML DOM Events.

What can JavaScript Do?
Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

Things that should be done every time a page loads
Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data
And more …
Many different methods can be used to let JavaScript work with events:

HTML event attributes can execute JavaScript code directly
HTML event attributes can call JavaScript functions
You can assign your own event handler functions to HTML elements
You can prevent events from being sent or being handled
And more …
You will learn a lot more about events and event handlers in the HTML DOM chapters.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »

❮ Previous Next ❯

JavaScript Objects

Toggle navigation
TUTORIAL HOME
JavaScript Objects
❮ Previous Next ❯
Real Life Objects, Properties, and Methods
In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

car.name = Fiat

car.model = 500

car.weight = 850kg

car.color = white
car.start()

car.drive()

car.brake()

car.stop()
All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

JavaScript Objects
You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

var car = “Fiat”;
»
Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

var car = {type:”Fiat”, model:”500″, color:”white”};
»
The values are written as name:value  pairs (name and value separated by a colon).

JavaScript objects are containers for named values.

Object Properties
The name:values pairs (in JavaScript objects) are called properties.

var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

Property Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + ” ” + this.lastName;}
JavaScript objects are containers for named values called properties or methods.

Object Definition
You define (and create) a JavaScript object with an object literal:

Example
var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
»
Spaces and line breaks are not important. An object definition can span multiple lines:

Example
var person = {
    firstName:”John”,
    lastName:”Doe”,
    age:50,
    eyeColor:”blue”
};
»
Accessing Object Properties
You can access object properties in two ways:

objectName.propertyName
or

objectName[“propertyName”]
Example1
person.lastName;
»
Example2
person[“lastName”];
»
Accessing Object Methods
You access an object method with the following syntax:

objectName.methodName()
Example
name = person.fullName();
»
If you access the fullName method, without (), it will return the function definition:

Example
name = person.fullName;
»
A method is actually a function definition stored as a property value.

Do Not Declare Strings, Numbers, and Booleans as Objects!
When a JavaScript variable is declared with the keyword “new”, the variable is created as an object:

var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object
Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

You will learn more about objects later in this tutorial.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »

❮ Previous Next ❯

JavaScript Scope

Toggle navigation
TUTORIAL HOME
JavaScript Scope
❮ Previous Next ❯
Scope is the set of variables you have access to.

JavaScript Scope
In JavaScript, objects and functions are also variables.

In JavaScript, scope is the set of variables, objects, and functions you have access to.

JavaScript has function scope: The scope changes inside functions.

Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.

Local variables have local scope: They can only be accessed within the function.

Example
// code here can not use carName

function myFunction() {
    var carName = “Volvo”;

    // code here can use carName

}
»
Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.

A global variable has global scope: All scripts and functions on a web page can access it.

Example
var carName = ” Volvo”;

// code here can use carName

function myFunction() {

    // code here can use carName

}
»
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare a global variable carName, even if the value is assigned inside a function.

Example
myFunction();

// code here can use carName

function myFunction() {
    carName = “Volvo”;
}
»
Do NOT create global variables unless you intend to.

In “Strict Mode” automatically global variables will fail.

Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.

In HTML, the global scope is the window object. All global variables belong to the window object.

Example
var carName = “Volvo”;

// code here can use window.carName

»
Did You Know?
Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.

The Lifetime of JavaScript Variables
The lifetime of a JavaScript variable starts when it is declared.

Local variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab), but remains available to new pages loaded into the same window.

Function Arguments
Function arguments (parameters) work as local variables inside functions.

❮ Previous Next ❯

JavaScript Functions

JavaScript Functions
❮ Previous Next ❯
A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when “something” invokes it (calls it).

Example
function myFunction(p1, p2) {
    return p1 * p2;              // The function returns the product of p1 and p2
}
»
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:
(parameter1, parameter2, …)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {
    code to be executed
}
Function parameters are the names listed in the function definition.

Function arguments are the real values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other programming languages.

Function Invocation
The code inside the function will execute when “something” invokes (calls) the function:

When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
You will learn a lot more about function invocation later in this tutorial.

Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will “return” to execute the code after the invoking statement.

Functions often compute a return value. The return value is “returned” back to the “caller”:

Example
Calculate the product of two numbers, and return the result:

var x = myFunction(4, 3);        // Function is called, return value will end up in x

function myFunction(a, b) {
    return a * b;                // Function returns the product of a and b
}
The result in x will be:

12
»
Why Functions?
You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce different results.

Example
Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius(77);
»
The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Accessing a function without () will return the function definition instead of the function result:

Example
function toCelsius(fahrenheit) {
    return (5/9) * (fahrenheit-32);
}
document.getElementById(“demo”).innerHTML = toCelsius;
»
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Example
Instead of using a variable to store the return value of a function:

var x = toCelsius(77);
var text = “The temperature is ” + x + ” Celsius”;
You can use the function directly, as a variable value:

var text = “The temperature is ” + toCelsius(77) + ” Celsius”;
»
You will learn a lot more about functions later in this tutorial.

Test Yourself with Exercises!
Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

❮ Previous Next ❯

JavaScript Data Types

TUTORIAL HOME
JavaScript Data Types
❮ Previous Next ❯
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16;                               // Number
var lastName = “Johnson”;                      // String
var x = {firstName:”John”, lastName:”Doe”};    // Object
The Concept of Data Types
In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

var x = 16 + “Volvo”;
Does it make any sense to add “Volvo” to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

var x = “16” + “Volvo”;
When adding a number and a string, JavaScript will treat the number as a string.

Example
var x = 16 + “Volvo”;
»
Example
var x = “Volvo” + 16;
»
JavaScript evaluates expressions from left to right. Different sequences can produce different results:

JavaScript:
var x = 16 + 4 + “Volvo”;
Result:
20Volvo
»
JavaScript:
var x = “Volvo” + 16 + 4;
Result:
Volvo164
»
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches “Volvo”.

In the second example, since the first operand is a string, all operands are treated as strings.

JavaScript Types are Dynamic.
JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

Example
var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = “John”;      // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like “John Doe”.

Strings are written with quotes. You can use single or double quotes:
Example
var carName = “Volvo XC60”;   // Using double quotes
var carName = ‘Volvo XC60’;   // Using single quotes
You can use quotes inside a string, as long as they don’t match the quotes surrounding the string:

Example
var answer = “It’s alright”;             // Single quote inside double quotes
var answer = “He is called ‘Johnny'”;    // Single quotes inside double quotes
var answer = ‘He is called “Johnny”‘;    // Double quotes inside single quotes
Try it yourself »
You will learn more about strings later in this tutorial.

JavaScript Numbers
JavaScript has only one type of numbers.

Numbers can be written with, or without decimals:
Example
var x1 = 34.00;     // Written with decimals
var x2 = 34;        // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:

Example
var y = 123e5;      // 12300000
var z = 123e-5;     // 0.00123
Try it yourself »
You will learn more about numbers later in this tutorial.

JavaScript Booleans
Booleans can only have two values: true or false.

Example
var x = true;
var y = false;
Booleans are often used in conditional testing.

You will learn more about conditional testing later in this tutorial.

JavaScript Arrays
JavaScript arrays are written with square brackets.

Array items are separated by commas.

The following code declares (creates) an array called cars, containing three items (car names):

Example
var cars = [“Saab”, “Volvo”, “BMW”];
»
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

You will learn more about arrays later in this tutorial.

JavaScript Objects
JavaScript objects are written with curly braces.

Object properties are written as name:value pairs, separated by commas.

Example
var person = {firstName:”John”, lastName:”Doe”, age:50, eyeColor:”blue”};
»
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

You will learn more about objects later in this tutorial.

The typeof Operator
You can use the JavaScript typeof  operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

Example
typeof “”                  // Returns “string”
typeof “John”              // Returns “string”
typeof “John Doe”          // Returns “string”
»
Example
typeof 0                   // Returns “number”
typeof 314                 // Returns “number”
typeof 3.14                // Returns “number”
typeof (3)                 // Returns “number”
typeof (3 + 4)             // Returns “number”
»
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.

The typeof operator can return one of these primitive types:

string
number
boolean
null
undefined
Example
typeof “John”              // Returns “string”
typeof 3.14                // Returns “number”
typeof true                // Returns “boolean”
typeof false               // Returns “boolean”
»
Complex Data
The typeof operator can return one of two complex types:

function
object
Example
typeof [1,2,3,4]             // Returns “object” (not “array”, see note below)
typeof {name:’John’, age:34} // Returns “object”
typeof function myFunc(){}   // Returns “function”
»
The typeof operator returns “object” for arrays because in JavaScript arrays are objects.

Undefined
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.

Example
var person;                // Value is undefined, type is undefined
»
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.

Example
person = undefined;        // Value is undefined, type is undefined
»
Empty Values
An empty value has nothing to do with undefined.

An empty string variable has both a value and a type.

Example
var car = “”;              // The value is “”, the typeof is “string”
»
Null
In JavaScript null is “nothing”. It is supposed to be something that doesn’t exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can consider it a bug in JavaScript that typeof null is an object. It should be null.

You can empty an object by setting it to null:

Example
var person = null;         // Value is null, but type is still an object
»
You can also empty an object by setting it to undefined:

Example
var person = undefined;   // Value is undefined, type is undefined
»
Difference Between Undefined and Null
typeof undefined           // undefined
typeof null                // object
null === undefined         // false
null == undefined          // true
»

❮ Previous Next ❯

JavaScript Arithmetic

Toggle navigation
TUTORIAL HOME
JavaScript Arithmetic
❮ Previous Next ❯
A typical thing to do with numbers is arithmetic.

JavaScript Arithmetic Operators
Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
— Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

Example
var x = 100 + 50;
»
or variables:

Example
var x = a + b;
»
or expressions:

Example
var x = (100 + 50) * a;
»
Operators and Operands
The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

Operand Operator Operand
100 + 50
The addition operator (+) adds numbers:

Adding
var x = 5;
var y = 2;
var z = x + y;
»
The subtraction operator (-) subtracts numbers.

Subtracting
var x = 5;
var y = 2;
var z = x – y;
»
The multiplication operator (*) multiplies numbers.

Multiplying
var x = 5;
var y = 2;
var z = x * y;
»
The division operator (/) divides numbers.

Dividing
var x = 5;
var y = 2;
var z = x / y;
»
The modular operator (%) returns the division remainder.

Modulus
var x = 5;
var y = 2;
var z = x % y;
»
The increment operator (++) increments numbers.

Incrementing
var x = 5;
x++;
var z = x;
»
The decrement operator (–) decrements numbers.

Decrementing
var x = 5;
x–;
var z = x;
»
Operator Precedence
Operator precedence describes the order in which operations are performed in an arithmetic expression.

Example
var x = 100 + 50 * 3;
»
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).

And (as in school mathematics) the precedence can be changed by using parentheses:

Example
var x = (100 + 50) * 3;
»
When using parentheses, the operations inside the parentheses are computed first.

When many operations have the same precedence (like addition and subtraction), they are computed from left to right:

Example
var x = 100 + 50 – 3;
»
JavaScript Operator Precedence Values
Value Operator Description Example
19 ( ) Expression grouping (3 + 4)

18 . Member person.name
18 [] Member person[“name”]

17 () Function call myFunction()
17 new Create new Date()

16 ++ Postfix Increment i++
16 — Postfix Decrement i–

15 ++ Prefix Increment ++i
15 — Prefix Decrement –i
15 ! Logical not !(x==y)
15 typeof Type typeof x

14 * Multiplication 10 * 5
14 / Division 10 / 5
14 % Modulo division 10 % 5
14 ** Exponentiation 10 ** 2

13 + Addition 10 + 5
13 – Subtraction 10 – 5

12 << Shift left x << 2
12 >> Shift right x >> 2
12 >>> Shift right (unsigned) x >>> 2

11 < Less than x < y
11 <= Less than or equal x <= y
11 > Greater than x > y
11 >= Greater than or equal x >= y

10 == Equal x == y
10 === Strict equal x === y
10 != Unequal x != y
10 !== Strict unequal x !== y

6 && Logical and x && y
5 || Logical or x || y

3 = Assignment x = y
3 += Assignment x += y
3 -= Assignment x -= y
3 *= Assignment x *= y
3 %= Assignment x %= y
3 <<= Assignment x <<= y
3 >>= Assignment x >>= y
3 >>>= Assignment x >>>= y
3 &= Assignment x &= y
3 ^= Assignment x ^= y
3 |= Assignment x |= y
Pale red entries indicates experimental or proposed technology (ECMASScript 2016 or ES7)

Expressions in parentheses are fully computed before the value is used in the rest of the expression.

Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »

❮ Previous Next ❯

JavaScript Operators

TUTORIAL HOME
JavaScript Operators
❮ Previous Next ❯
Example
Assign values to variables and add them together:

var x = 5;         // assign the value 5 to x
var y = 2;         // assign the value 2 to y
var z = x + y;     // assign the value 7 to z (x + y)
»
The assignment operator (=) assigns a value to a variable.

Assignment
var x = 10;
»
The addition operator (+) adds numbers:

Adding
var x = 5;
var y = 2;
var z = x + y;
»
The multiplication operator (*) multiplies numbers.

Multiplying
var x = 5;
var y = 2;
var z = x * y;
»
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic on numbers:

Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
— Decrement
Arithmetic operators are fully described in the JS Arithmetic chapter.

JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
The addition assignment operator (+=) adds a value to a variable.

Assignment
var x = 10;
x += 5;
»
Assignment operators are fully described in the JS Assignment chapter.

JavaScript String Operators
The + operator can also be used to add (concatenate) strings.

Example
txt1 = “John”;
txt2 = “Doe”;
txt3 = txt1 + ” ” + txt2;
The result of txt3 will be:

John Doe
»
The += assignment operator can also be used to add (concatenate) strings:

Example
txt1 = “What a very “;
txt1 += “nice day”;
The result of txt1 will be:

What a very nice day
»
When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will return a string:

Example
x = 5 + 5;
y = “5” + 5;
z = “Hello” + 5;
The result of x, y, and z will be:

10
55
Hello5
»
If you add a number and a string, the result will be a string!

JavaScript Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
Comparison operators are fully described in the JS Comparisons chapter.

JavaScript Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type
Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators
Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001 1
| OR 5 | 1 0101 | 0001 0101 5
~ NOT ~ 5 ~0101 1010 10
^ XOR 5 ^ 1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010   2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010   2
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

❮ Previous Next ❯

JavaScript Variables

Toggle navigation
TUTORIAL HOME
JavaScript Variables
❮ Previous Next ❯
JavaScript Variables
JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables:

Example
var x = 5;
var y = 6;
var z = x + y;
»
From the example above, you can expect:

x stores the value 5
y stores the value 6
z stores the value 11
Much Like Algebra
In this example, price1, price2, and total, are variables:

Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
»
In programming, just like in algebra, we use variables (like price1) to hold values.

In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

From the example above, you can calculate the total to be 11.

JavaScript variables are containers for storing data values.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
JavaScript identifiers are case-sensitive.

The Assignment Operator
In JavaScript, the equal sign (=) is an “assignment” operator, not an “equal to” operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

The “equal to” operator is written like == in JavaScript.

JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like “John Doe”.

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example
var pi = 3.14;
var person = “John Doe”;
var answer = ‘Yes I am!’;
»
Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is called “declaring” a variable.

You declare a JavaScript variable with the var keyword:

var carName;
After the declaration, the variable has no value. (Technically it has the value of undefined)

To assign a value to the variable, use the equal sign:

carName = “Volvo”;
You can also assign a value to the variable when you declare it:

var carName = “Volvo”;
In the example below, we create a variable called carName and assign the value “Volvo” to it.

Then we “output” the value inside an HTML paragraph with id=”demo”:

Example

var carName = “Volvo”;
document.getElementById(“demo”).innerHTML = carName;

»
It’s a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables
You can declare many variables in one statement.

Start the statement with var and separate the variables by comma:

var person = “John Doe”, carName = “Volvo”, price = 200;
»
A declaration can span multiple lines:

var person = “John Doe”,
carName = “Volvo”,
price = 200;
»
Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined.

The variable carName will have the value undefined after the execution of this statement:

Example
var carName;
»
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value.

The variable carName will still have the value “Volvo” after the execution of these statements:

Example
var carName = “Volvo”;
var carName;
»
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:

Example
var x = 5 + 2 + 3;
»
You can also add strings, but strings will be concatenated:

Example
var x = “John” + ” ” + “Doe”;
»
Also try this:

Example
var x = “5” + 2 + 3;
»
If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Now try this:

Example
var x = 2 + 3 + “5”;
»
Test Yourself with Exercises!
Exercise 1 »  Exercise 2 »  Exercise 3 »  Exercise 4 »  Exercise 5 »  Exercise 6 »

❮ Previous Next ❯

JavaScript Comments

JavaScript Comments
❮ Previous Next ❯
JavaScript comments can be used to explain JavaScript code, and to make it more readable.

JavaScript comments can also be used to prevent execution, when testing alternative code.

Single Line Comments
Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

This example uses a single-line comment before each code line:

Example
// Change heading:
document.getElementById(“myH”).innerHTML = “My First Page”;
// Change paragraph:
document.getElementById(“myP”).innerHTML = “My first paragraph.”;
»
This example uses a single line comment at the end of each line to explain the code:

Example
var x = 5;      // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2
»
Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the code:

Example
/*
The code below will change
the heading with id = “myH”
and the paragraph with id = “myP”
in my web page:
*/
document.getElementById(“myH”).innerHTML = “My First Page”;
document.getElementById(“myP”).innerHTML = “My first paragraph.”;
»
It is most common to use single line comments.
Block comments are often used for formal documentation.

Using Comments to Prevent Execution
Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a comment.

This example uses // to prevent execution of one of the code lines:

Example
//document.getElementById(“myH”).innerHTML = “My First Page”;
document.getElementById(“myP”).innerHTML = “My first paragraph.”;
»
This example uses a comment block to prevent execution of multiple lines:

Example
/*
document.getElementById(“myH”).innerHTML = “My First Page”;
document.getElementById(“myP”).innerHTML = “My first paragraph.”;
*/
»

❮ Previous Next ❯

JavaScript Syntax

JavaScript Syntax
❮ Previous Next ❯
JavaScript syntax is the set of rules, how JavaScript programs are constructed.

JavaScript Programs
A computer program is a list of “instructions” to be “executed” by the computer.

In a programming language, these program instructions are called statements.

JavaScript is a programming language.

JavaScript statements are separated by semicolons:

Example
var x, y, z;
x = 5;
y = 6;
z = x + y;
»
In HTML, JavaScript programs are executed by the web browser.

JavaScript Statements
JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.

Fixed values are called literals. Variable values are called variables.

JavaScript Literals
The most important rules for writing fixed values are:

Numbers are written with or without decimals:

10.50

1001
»
Strings are text, written within double or single quotes:

“John Doe”

‘John Doe’
»
JavaScript Variables
In a programming language, variables are used to store data values.

JavaScript uses the var keyword to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

var x;

x = 6;
»
JavaScript Operators
JavaScript uses arithmetic operators ( + – *  / ) to compute values:

(5 + 6) * 10
»
JavaScript uses an assignment operator  ( = ) to assign values to variables:

var x, y;
x = 5;
y = 6;
»
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

5 * 10
»
Expressions can also contain variable values:

x * 10
»
The values can be of various types, such as numbers and strings.

For example, “John” + ” ” + “Doe”, evaluates to “John Doe”:

“John” + ” ” + “Doe”
»
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.

The var keyword tells the browser to create variables:

var x, y;
x = 5 + 6;
y = x * 10;
»
JavaScript Comments
Not all JavaScript statements are “executed”.

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

var x = 5;   // I will be executed

// var x = 6;   I will NOT be executed
»
You will learn more about comments in a later chapter.

JavaScript Identifiers
Identifiers are names.

In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).

The rules for legal names are much the same in most programming languages.

In JavaScript, the first character must be a letter, an underscore (_), or a dollar sign ($).

Subsequent characters may be letters, digits, underscores, or dollar signs.

Numbers are not allowed as the first character.
This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.

The variables lastName and lastname, are two different variables.

var lastname, lastName;
lastName = “Doe”;
lastname = “Peterson”;
»
JavaScript does not interpret VAR or Var  as the keyword var.

JavaScript and Camel Case
Historically, programmers have used different ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. It is reserved for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.

JavaScript Character Set
JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the world.

For a closer look, please study our Complete Unicode Reference.

❮ Previous Next ❯