JavaScript Objects


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";
Try it Yourself »

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"};
Try it Yourself »

The values are written as name:value pairs (name and value separated by a colon).

Note 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;}

Note JavaScript objects are containers for named values (called properties) and 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"};
Try it Yourself »

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"
};
Try it Yourself »

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]

Example1

person.lastName;
Try it Yourself »

Example2

person["lastName"];
Try it Yourself »

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example

name = person.fullName();
Try it Yourself »

If you access the fullName property, without (), it will return the function definition:

Example

name = person.fullName;
Try it Yourself »

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.

Note You will learn more about objects later in this tutorial.

 







JavaScript Scope


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

}
Try it Yourself »

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

}
Try it Yourself »

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 carName as a global variable, even if it is executed inside a function.

Example

// code here can use carName

function myFunction() {
    carName = "Volvo";

    // code here can use carName

}
Try it Yourself »

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.

Global variables are deleted when you close the page.


Function Arguments

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


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

// code here can use window.carName

function myFunction() {
    carName = "Volvo";
}
Try it Yourself »

Did You Know?

Note Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.

 







JavaScript Events


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:

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:

<some-HTML-elementsome-event=' some JavaScript'>

With double quotes:

<some-HTML-elementsome-event=" some JavaScript">

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

Example

< button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button>
Try it Yourself »

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

< button onclick="this.innerHTML=Date()">The time is?</button>
Try it Yourself »
Note JavaScript code is often several lines long. It is more common to see event attributes calling functions:

Example

< button onclick="displayDate()">The time is?</button>
Try it Yourself »

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

What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser actions:

Many different methods can be used to let JavaScript work with events:

Note You will learn a lot more about events and event handlers in the HTML DOM chapters.

 







JavaScript Strings


JavaScript strings are used for storing and manipulating text.


JavaScript Strings

A JavaScript string simply stores a series of characters like "John Doe"

A string can be any text inside quotes. You can use single or double quotes:

Example

var carname = "Volvo XC60";
var carname = 'Volvo XC60';
Try it Yourself »

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";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
Try it Yourself »

String Length

The length of a string is found in the built in property length:

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Try it Yourself »

Special Characters

Because strings must be written within quotes, JavaScript will misunderstand this string:

var y = "We are the so-called "Vikings" from the north."

The string will be chopped to "We are the so-called ".

The solution to avoid this problem, is to use the \ escape character.

The backslash escape character turns special characters into string characters:

Example

var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
Try it Yourself »

The escape character (\) can also be used to insert other special characters in a string.

This is the list of special characters that can be added to a text string with the backslash sign:

Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed

Breaking Long Code Lines

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly.";
Try it Yourself »

You can also break up a code line within a text string with a single backslash:

Example

document.getElementById("demo").innerHTML = "Hello \
Dolly!";
Try it Yourself »
Note The \ method is not a ECMAScript (JavaScript) standard.
Some browsers do not allow spaces behind the \ character.

The safest (but a little slower) way to break a long string is to use string addition:

Example

document.getElementById("demo").innerHTML = "Hello" +
"Dolly!";
Try it Yourself »

You cannot break up a code line with a backslash:

Example

document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Try it Yourself »

Strings Can be Objects

Normally, JavaScript strings are primitive values, created from literals: var firstName = "John"

But strings can also be defined as objects with the keyword new: var firstName = new String("John")

Example

var x = "John";
var y = new String("John");

// typeof x will return string
// typeof y will return object
Try it Yourself »

Note Don't create strings as objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:

When using the == equality operator, equal strings looks equal:

Example

var x = "John";              
var y = new String("John");

// (x == y) is true because x and y have equal values
Try it Yourself »

When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value.

Example

var x = "John";              
var y = new String("John");

// (x === y) is false because x and y have different types (string and object)
Try it Yourself »

Or even worse. Objects cannot be compared:

Example

var x = new String("John");              
var y = new String("John");

// (x == y) is false because x and y are different objects
// (x == x) is true because both are the same object
Try it Yourself »
Note JavaScript objects cannot be compared.

String Properties and Methods

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

String methods are covered in next chapter.


String Properties

Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object

String Methods

Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and returns the matches
replace() Searches a string for a value and returns a new string with the value replaced
search() Searches a string for a value and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
substr() Extracts a part of a string from a start position through a number of characters
substring() Extracts a part of a string between two specified positions
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object

 







JavaScript String Methods


String methods help you to work with strings.


Finding a String in a String

The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
Try it Yourself »

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Try it Yourself »

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.

Note JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...

Both methods accept a second parameter as the starting position for the search.


Searching for a String in a String

The search() method searches a string for a specified value and returns the position of the match:

Example

var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
Try it Yourself »
Note

Did You Notice?

The two methods, indexOf() and search(), are equal.

They accept the same arguments (parameters), and they return the same value.

The two methods are equal, but the search() method can take much more powerful search values.

You will learn more about powerful search values in the chapter about regular expressions.


Extracting String Parts

There are 3 methods for extracting a part of a string:


The slice() Method

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the starting index (position), and the ending index (position).

This example slices out a portion of a string from position 7 to position 13:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);

The result of res will be:

Banana
Try it Yourself »

If a parameter is negative, the position is counted from the end of the string.

This example slices out a portion of a string from position -12 to position -6:

Example

var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);

The result of res will be:

Banana
Try it Yourself »

If you omit the second parameter, the method will slice out the rest of the string:

Example

var res = str.slice(7);
Try it Yourself »

or, counting from the end:

Example

var res = str.slice(-12);
Try it Yourself »

Note Negative positions does not work in Internet Explorer 8 and earlier.

The substring() Method

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);

The result of res will be:

Banana
Try it Yourself »

If you omit the second parameter, substring() will slice out the rest of the string.


The substr() Method

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

Example

var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);

The result of res will be:

Banana
Try it Yourself »

If the first parameter is negative, the position counts from the end of the string.

The second parameter can not be negative, because it defines the length.

If you omit the second parameter, substr() will slice out the rest of the string.


Replacing String Content

The replace() method replaces a specified value with another value in a string:

Example

str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
Try it Yourself »

The replace() method can also take a regular expression as the search value.

By default, the replace() function replaces only the first match. To replace all matches, use a regular expression with a g flag (for global match):

Example

str = "Please visit Microsoft!";
var n = str.replace(/Microsoft/g,"W3Schools");
Try it Yourself »
Note The replace() method does not change the string it is called on. It returns a new string.

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toUpperCase();  // text2 is text1 converted to upper
Try it Yourself »

A string is converted to lower case with toLowerCase():

Example

var text1 = "Hello World!";       // String
var text2 = text1.toLowerCase();  // text2 is text1 converted to lower
Try it Yourself »

The concat() Method

concat() joins two or more strings:

Example

var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
Try it Yourself »

The concat() method can be used instead of the plus operator. These two lines do the same:

Example

var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");

Note All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.

Extracting String Characters

There are 2 safe methods for extracting string characters:


The charAt() Method

The charAt() method returns the character at a specified index (position) in a string:

Example

var str = "HELLO WORLD";
str.charAt(0);            // returns H
Try it Yourself »

The charCodeAt() Method

The charCodeAt() method returns the unicode of the character at a specified index in a string:

Example

var str = "HELLO WORLD";

str.charCodeAt(0);        //returns 72
Try it Yourself »

Accessing a String as an Array is Unsafe

You might have seen code like this, accessing a string as an array:

var str = "HELLO WORLD";

str[0];                    // returns H

This is unsafe and unpredictable:

If you want to read a string as an array, convert it to an array first.


Converting a String to an Array

A string can be converted to an array with the split() method:

Example

var txt = "a,b,c,d,e";   // String
txt.split(",");          // Split on commas
txt.split(" ");          // Split on spaces
txt.split("|");          // Split on pipe
Try it Yourself »

If the separator is omitted, the returned array will contain the whole string in index [0].

If the separator is "", the returned array will be an array of single characters:

Example

var txt = "Hello";       // String
txt.split("");           // Split in characters
Try it Yourself »