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.
You have already learned that JavaScript variables are containers for data values.
This code assigns a simple value (Fiat) to a variable named car:
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
![]() |
JavaScript objects are containers for named values. |
---|
The name:values pairs (in JavaScript objects) are called properties.
Property | Property Value |
---|---|
firstName | John |
lastName | Doe |
age | 50 |
eyeColor | blue |
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) and methods. |
---|
You define (and create) a JavaScript object with an object literal:
Spaces and line breaks are not important. An object definition can span multiple lines:
You can access object properties in two ways:
or
You access an object method with the following syntax:
If you access the fullName property, without (), it will return the function definition:
When a JavaScript variable is declared with the keyword "new", the variable is created as an 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. |
---|
Scope is the set of variables you have access to.
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.
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
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.
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.
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.
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 (parameters) work as local variables inside functions.
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.
![]() |
Your global variables (or functions) can overwrite window variables
(or functions). Any function, including the window object, can overwrite your global variables and functions. |
---|
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these 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:
With double quotes:
In the following example, an onclick attribute (with code), is added to a button element:
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):
![]() |
JavaScript code is often several lines long. It is more common to see event attributes calling functions: |
---|
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 |
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:
![]() |
You will learn a lot more about events and event handlers in the HTML
DOM chapters. |
---|
JavaScript strings are used for storing and manipulating text.
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:
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
The length of a string is found in the built in property length:
Because strings must be written within quotes, JavaScript will misunderstand this string:
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:
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 |
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:
You can also break up a code line within a text string with a single backslash:
![]() |
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:
You cannot break up a code line with a backslash:
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")
![]() |
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:
When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value.
Or even worse. Objects cannot be compared:
![]() |
JavaScript objects cannot be compared. |
---|
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.
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 |
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 |
String methods help you to work with strings.
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
![]() |
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.
The search() method searches a string for a specified value and returns the position of the match:
![]() |
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.
There are 3 methods for extracting a part of a string:
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:
The result of res will be:
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:
The result of res will be:
If you omit the second parameter, the method will slice out the rest of the string:
or, counting from the end:
![]() |
Negative positions does not work in Internet Explorer 8 and earlier. |
---|
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
The result of res will be:
If you omit the second parameter, substring() will slice out the rest of the string.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
The result of res will be:
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.
The replace() method replaces a specified value with another value in a string:
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):
![]() |
The replace() method does not change the string it is called on. It returns a new string. |
---|
A string is converted to upper case with toUpperCase():
A string is converted to lower case with toLowerCase():
concat() joins two or more strings:
The concat() method can be used instead of the plus operator. These two lines do the same:
![]() |
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. |
---|
There are 2 safe methods for extracting string characters:
The charAt() method returns the character at a specified index (position) in a string:
The charCodeAt() method returns the unicode of the character at a specified index in a string:
You might have seen code like this, accessing a string as an array:
This is unsafe and unpredictable:
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method:
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: