JavaScript Objects, Methods and Functions
JavaScript Objects
In JavaScript, an object is data, with properties and methods.
When you declare a JavaScript variable like this:
const message="Hello World!";
You create a JavaScript String object.
The String object has a built-in property called length. For the string above, length has the value 12.
The String object also have several built-in methods.
Accessing Object Properties
Syntax
objectName.propertyName
Example
const message = "Hello world!";
let messageLength = message.length; //12
Accessing Object Methods
Syntax
objectName.methodName()
Example
const message = "Hello world!";
let newMessage = message.toUpperCase(); //HELLO WORLD!
JavaScript Arrays
An array is a special variable, which can hold more than one value at a time. There are various ways of creating an array:
- Regular
const questions = []; questions[ 0 ] = "1 + 1"; questions[ 1 ] = "2 x 3"; questions[ 2 ] = "6 - 4"; - Litteral
const questions = [ "1 + 1", "2 x 3", "6 - 4" ];
Array Properties
| Property | Description |
|---|---|
| constructor | Returns the function that created the Array object's prototype |
| length | Sets or returns the number of elements in an array |
| prototype | Allows you to add properties and methods to an Array object |
Array Methods
| Method | Description |
|---|---|
| concat() | Joins two or more arrays, and returns a copy of the joined arraysExample
|
| every() | Checks if every element in an array pass a test and returns a boolean valueExample |
| fill() | Fills the elements in an array with a static value from an optional start index (default 0) to an optional end index (default array length)Example |
| filter() | Creates a new array with every element in an array that pass a testExample |
| find() | Returns the value of the first element in an array that passes a testExample |
| findIndex() | Returns the index of the first element in an array that passes a test, otherwise returns -1Example |
| forEach() | Calls a function for each array elementExample |
| includes() | Searches the array for an element and returns true if the element exists in the array, and false if it doesn'tExample |
| indexOf() | Searches the array for an element and returns its positionExample |
| isArray() | Checks whether an object is an arrayExample |
| join() | Joins all elements of an array into a string, and takes a separator as optionExample |
| lastIndexOf() | Search the array for an element, starting at the end, and returns its positionExample |
| map() | Creates a new array with the result of calling a function for each array elementExample |
| pop() | Removes the last element of an array, and returns that elementExample |
| push() | Adds new elements to the end of an array, and returns the new lengthExample |
| reduce() | Reduce the values of an array to a single value (going left-to-right)Example |
| reduceRight() | Reduce the values of an array to a single value (going right-to-left)Example |
| reverse() | Reverses the order of the elements in an array. The original array is modified.Example |
| shift() | Removes the first element of an array, and returns that elementExample |
| slice() | Selects a part of an array, and returns the new array. The original array is not modified.Example |
| some() | Checks if any of the elements in an array pass a testExample |
| sort() | Sorts the elements of an array and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values, so should not be used for sorting number values.Example |
| splice() | Adds/Removes elements from an arrayExample |
| toString() | Converts an array to a string, and returns the resultExample |
| unshift() | Adds new elements to the beginning of an array, and returns the new lengthExample |
| valueOf() | Returns the primitive value of an arrayExample |
Functions
A function is a collection of JavaScript statements. These statements usually have a single purpose, such as performing a complex calculation or verifying the data entered into an HTML form. Functions can be passed copies of objects or variables to work with.This is done in the parameter list.
JavaScript functions can be placed inside script tags anywhere in the document. However, they should be placed in the head of the document to guarantee they are loaded before being called from script statements in the body of the document.
There are several ways to declare a function in JavaScript
-
Function Declaration: A function declaration is a named function that can be called from anywhere in your code. Here is an example for a function with no parameters and which does not return anything:
Here is an example for a function with 2 parametersfunction myFunction() { console.log("Hello World"); }(a and b)which returnsa + bfunction addNumbers(a, b) { return a + b; }
let myFunction = function() {
console.log("Hello World");
};
Here is an example for a function with 2 parameters (a and b) which returns a + b
let addNumbers = function(a, b) {
return a + b;
};
let myFunction = () => {
console.log("Hello World");
};
Here is an example for a function with 2 parameters (a and b) which returns a + b
let addNumbers = (a, b) => {
return a + b;
};
This example can also be written as follows:
let addNumbers = (a, b) => a + b;
Both forms are equivalent and it's a matter of preference. The first form is more concise and is recommended if the function only contains a single expression (such as a return statement). The second form with a block body is recommended if you need to write multiple statements in the function body.
It's important to note that the syntax of an arrow function is different from a traditional function expression, but the functionality is the same. In all three cases, the result is a function named myFunction that logs "Hello World" to the console when it is called.
Syntax
function functionName( parameter_1, parameter_2, .. parameter_n ) {
statement1;
statement2;
.
.
.
statementn;
}
Example
Here is a function that finds that maximum value of two numbers.
function getMax( n1, n2 ) {
if ( n1 < n2 ) {
return n2;
} else {
return n1;
}
Here is an example of how this function might be used.
<html>
<head>
<script>
function getMax( n1, n2 ) {
if ( n1 < n2 ) {
return n2;
} else {
return n1;
}
}
</script>
</head>
<body>
<script>
document.write( "<p>" );
document.write( "The largest number of 5 or 6 is: " + getMax( 5, 6 ) );
document.write( "</p>" );
</script>
</body>
</html>
A function to check the length of a student username
<html>
<head>
<script>
function checkUserName( form ) {
if ( form.reg.value.length != 8 ) {
alert( "You have not entered an eight character string" );
return false;
} else {
alert( "This is correct" );
return true;
}
}
</script>
</head>
<body>
<p> Please enter your student username: <input type="text" name="reg" />
<input type="button" onclick="checkUserName(form);" value="check validity"/>
</body>
</html>
Example Built in class
Global Functions
The JavaScript language comes with global properties and functions that can be used with all the built-in JavaScript objects:
| decodeURI() | Decodes a URI |
| decodeURIComponent() | Decodes a URI component |
| encodeURI() | Encodes a URI |
| encodeURIComponent() | Encodes a URI component |
| eval() | Evaluates a string and executes it as if it was script codeExample |
| isFinite() | Determines whether a value is a finite, legal number |
| isNaN() | Determines whether a value is not a number (NAN) |
| Number() | Converts an object's value to a number |
| parseFloat() | Parses a string and returns a floating point number |
| parseInt() | Parses a string and returns an integer |
| String() | Converts an object's value to a string |
Review Questions
- Question 1 -
- Question 2 -
- Question 3 -