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).
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)
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":
The () Operator Invokes the Function
Using the example above, toCelsius refers to the function object, and toCelsius() refers to the function result.
Functions Used as Variable Values
Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.
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:
Properties
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
Methods()
====
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:
Object Properties
The name:values pairs (in JavaScript objects) are called properties.
var person = {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.
Accessing Object Properties
objectName.propertyName or objectName["propertyName"]
Accessing Object Methods
objectName.methodName()
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
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.
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.
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.
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:
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:
<some-HTML-element some-event='some JavaScript'>
With double quotes:
<some-HTML-element some-event="some JavaScript">
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:
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
String Methods and Properties
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.
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:
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.
Searching for a String in a String
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.
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
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:
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:
If you omit the second parameter, the method will slice out the rest of the string:
The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes
The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
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:
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.
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
The concat() Method
concat() joins two or more strings:
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:
charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
Accessing a String as an Array is Unsafe
You might have seen code like this, accessing a string as an array:
This is unsafe and unpredictable:
It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = "H" does not give an error (but does not work)
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:
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:
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:
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
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:
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:
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:
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")
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 look equal:
When using the === equality operator, equal strings are not equal, because the === operator expects equality in both type and value.
JavaScript String 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.
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:
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.
Searching for a String in a String
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.
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
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:
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:
If you omit the second parameter, the method will slice out the rest of the string:
The substring() Method
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes
The substr() Method
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
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:
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.
Converting to Upper and Lower Case
A string is converted to upper case with toUpperCase():
The concat() Method
concat() joins two or more strings:
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:
charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
Accessing a String as an Array is Unsafe
You might have seen code like this, accessing a string as an array:
This is unsafe and unpredictable:
It does not work in all browsers (not in IE5, IE6, IE7)
It makes strings look like arrays (but they are not)
str[0] = "H" does not give an error (but does not work)
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:
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:
JavaScript Numbers
JavaScript Numbers
JavaScript numbers can be written with, or without decimals:
Extra large or extra small numbers can be written with scientific (exponent) notation:
JavaScript Numbers are Always 64-bit Floating Point
Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
Value (aka Fraction/Mantissa) Exponent Sign
52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63)
Precision
Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
To solve the problem above, it helps to multiply and divide:
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
Never write a number with a leading zero (like 07).
Some JavaScript versions interpret numbers as octal if they are written with a leading zero.
By default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.
Division by 0 (zero) also generates Infinity:
Infinity is a number: typeOf Infinity returns number.
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
However, if the string contains a numeric value , the result will be a number:
You can use the global JavaScript function isNaN() to find out if a value is a number.
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:
NaN is a number, and typeof NaN returns number:
Numbers Can be Objects
Normally JavaScript numbers are primitive values created from literals: var x = 123
But numbers can also be defined as objects with the keyword new: var y = new Number(123)
Do not create Number objects. It slows down execution speed.
The new keyword complicates the code. This can produce some unexpected results:
When using the == equality operator, equal numbers looks equal:
When using the === equality operator, equal numbers 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.
JavaScript Math Object
JavaScript Math Object
The Math object allows you to perform mathematical tasks on numbers.
The Math Object
The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical methods.
One common use of the Math object is to create a random number:
Math has no constructor. No methods have to create a Math object first.
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
Math.round()
Math.round() rounds a number to the nearest integer:
Math.ceil()
Math.ceil() rounds a number up to the nearest integer:
Math.floor()
Math.floor() rounds a number down to the nearest integer:
Math Constants
JavaScript provides 8 mathematical constants that can be accessed with the Math object:
Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Object Methods
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle
JavaScript Dates
The Date object lets you work with dates (years, months, days, hours, minutes, seconds, and milliseconds)
JavaScript Date Formats
A JavaScript date can be written as a string:
Mon Sep 05 2016 03:38:46 GMT-0400 (Eastern Daylight Time)
or as a number:
1473061126870
Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.
Displaying Dates
In this tutorial we use a script to display dates inside a <p> element with id="demo":
The script above says: assign the value of Date() to the content (innerHTML) of the element with id="demo".
You will learn how to display a date, in a more readable format, at the bottom of this page.
Creating Date Objects
The Date object lets us work with dates.
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Using new Date(), creates a new date object with the current date and time:
Valid date strings (date formats) are described in the next chapter.
Using new Date(number), creates a new date object as zero time plus the number.
Zero time is 01 January 1970 00:00:00 UTC. The number is specified in milliseconds:
JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond.
Using new Date(7 numbers), creates a new date object with the specified date and time:
The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order:
JavaScript counts months from 0 to 11. January is 0. December is 11.
Date Methods
When a Date object is created, a number of methods allow you to operate on it.
Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time.
Date methods are covered in a later chapter.
Displaying Dates
When you display a date object in HTML, it is automatically converted to a string, with the toString() method.
The toUTCString() method converts a date to a UTC string (a date display standard).
The toDateString() method converts a date to a more readable format:
Date objects are static. The computer time is ticking, but date objects, once created, are not.
Time Zones
When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.
When getting a date, without specifying the time zone, the result is converted to the browser's time zone.
In other words: If a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.
JavaScript Date Formats
JavaScript Date Input
There are generally 4 types of JavaScript date input formats:
Type Example
ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015" or "2015/03/25"
Long Date "Mar 25 2015" or "25 Mar 2015"
Full Date "Wednesday March 25 2015"
JavaScript Date Output
Independent of input format, JavaScript will (by default) output dates in full text string format:
JavaScript ISO Dates
ISO 8601 is the international standard for the representation of dates and times.
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
The computed date will be relative to your time zone.
Depending on your time zone, the result above will vary between March 24 and March 25.
It can be written without specifying the day (YYYY-MM):
The T in the date string, between the date and time, indicates UTC time.
JavaScript Long Dates.
Long dates are most often written with a "MMM DD YYYY" syntax like this:
Month and day can be in any order:
And, month can be written in full (January), or abbreviated (Jan):
JavaScript Date Methods
Date methods let you get and set date values (years, months, days, hours, minutes, seconds, milliseconds)
Date Get Methods
Get methods are used for getting a part of a date. Here are the most common (alphabetically):
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
The getTime() Method
getTime() returns the number of milliseconds since January 1, 1970:
In JavaScript, the first day of the week (0) means "Sunday", even if some countries in the world consider the first day of the week to be "Monday"
You can use an array of names, and getDay() to return the weekday as a name:
Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabetically):
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
The setFullYear() Method
setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:
Date Input - Parsing Dates
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
You can then use the number of milliseconds to convert it to a date object:
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
UTC Date Methods
UTC date methods are used for working UTC dates (Univeral Time Zone dates):
Method Description
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds
Date Get Methods
Get methods are used for getting a part of a date. Here are the most common (alphabetically):
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
The getTime() Method
getTime() returns the number of milliseconds since January 1, 1970:
In JavaScript, the first day of the week (0) means "Sunday", even if some countries in the world consider the first day of the week to be "Monday"
You can use an array of names, and getDay() to return the weekday as a name:
Date Set Methods
Set methods are used for setting a part of a date. Here are the most common (alphabetically):
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
The setFullYear() Method
setFullYear() sets a date object to a specific date. In this example, to January 14, 2020:
Date Input - Parsing Dates
If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
You can then use the number of milliseconds to convert it to a date object:
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
UTC Date Methods
UTC date methods are used for working UTC dates (Univeral Time Zone dates):
Method Description
getUTCDate() Same as getDate(), but returns the UTC date
getUTCDay() Same as getDay(), but returns the UTC day
getUTCFullYear() Same as getFullYear(), but returns the UTC year
getUTCHours() Same as getHours(), but returns the UTC hour
getUTCMilliseconds() Same as getMilliseconds(), but returns the UTC milliseconds
getUTCMinutes() Same as getMinutes(), but returns the UTC minutes
getUTCMonth() Same as getMonth(), but returns the UTC month
getUTCSeconds() Same as getSeconds(), but returns the UTC seconds
JavaScript Arrays
JavaScript arrays are used to store multiple values in a single variable.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Never put a comma after the last element (like "BMW",).
The effect is inconsistent across browsers.
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
[0] is the first element in an array. [1] is the second. Array indexes start with 0.
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Examples
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
Array methods are covered in the next chapters.
The length Property
The length property of an array returns the length of an array (the number of array elements).
Adding Array Elements
The easiest way to add a new element to an array is using the push method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined "holes" in an array:
Looping Array Elements
The best way to loop through an array, is using a "for" loop:
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
When to Use Arrays. When to use Objects.
JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected results:
How to Recognize an Array
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
The problem with this solution is that ECMAScript 5 is not supported in older browsers.
Solution 2:
To solve this problem you can create your own isArray() function:
The function above always returns true if the argument is an array.
Or more precisely: it returns true if the object prototype contains the word "Array".
Solution 3:
The instanceof operator returns true if an object is created by a given constructor:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // returns true
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Never put a comma after the last element (like "BMW",).
The effect is inconsistent across browsers.
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new Array().
For simplicity, readability and execution speed, use the first one (the array literal method).
Access the Elements of an Array
You refer to an array element by referring to the index number.
This statement accesses the value of the first element in cars:
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
[0] is the first element in an array. [1] is the second. Array indexes start with 0.
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Array Elements Can Be Objects
JavaScript variables can be objects. Arrays are special kinds of objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array properties and methods:
Examples
var x = cars.length; // The length property returns the number of elements
var y = cars.sort(); // The sort() method sorts arrays
Array methods are covered in the next chapters.
The length Property
The length property of an array returns the length of an array (the number of array elements).
Adding Array Elements
The easiest way to add a new element to an array is using the push method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Adding elements with high indexes can create undefined "holes" in an array:
Looping Array Elements
The best way to loop through an array, is using a "for" loop:
Associative Arrays
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
WARNING !!
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
When to Use Arrays. When to use Objects.
JavaScript does not support associative arrays.
You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.
Avoid new Array()
There is no need to use the JavaScript's built-in array constructor new Array().
Use [] instead.
These two different statements both create a new empty array named points:
var points = new Array(); // Bad
var points = []; // Good
These two different statements both create a new array containing 6 numbers:
var points = new Array(40, 100, 1, 5, 25, 10); // Bad
var points = [40, 100, 1, 5, 25, 10]; // Good
The new keyword only complicates the code. It can also produce some unexpected results:
How to Recognize an Array
A common question is: How do I know if a variable is an array?
The problem is that the JavaScript operator typeof returns "object":
The typeof operator returns object because a JavaScript array is an object.
Solution 1:
To solve this problem ECMAScript 5 defines a new method Array.isArray():
The problem with this solution is that ECMAScript 5 is not supported in older browsers.
Solution 2:
To solve this problem you can create your own isArray() function:
The function above always returns true if the argument is an array.
Or more precisely: it returns true if the object prototype contains the word "Array".
Solution 3:
The instanceof operator returns true if an object is created by a given constructor:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits instanceof Array // returns true
No comments:
Post a Comment