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:

  1. Regular
    const questions = [];
    questions[ 0 ] = "1 + 1";      
    questions[ 1 ] = "2 x 3";
    questions[ 2 ] = "6 - 4";
    
  2. 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 arrays

Example

const fruits = ["Apple", "Banana", "Mango"];
const vegetables = ["Carrot", "Potato"];
const fruitsAndVeg = fruits.concat(vegetables);
//fruitsAndVeg is equal to ["Apple", "Banana", "Mango", "Carrot", "Potato"]
every() Checks if every element in an array pass a test and returns a boolean value

Example

function containsFiveLetters(currentValue) {
  return currentValue.length == 5;
}

const fruit1 = ["Apple", "Banana", "Mango"];
const fruit2 = ["Apple", "Mango"];

console.log(fruit1.every(containsFiveLetters));
//outputs: false
console.log(fruit2.every(containsFiveLetters));
//outputs: true
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

const fruits = ["Apple", "Banana", "Mango", "Orange"];

fruits.fill("Strawberry", 2, 4);
// fills with "Strawberry" from position 2 until position 4
console.log(fruits);
//outputs ["Apple", "Banana", "Strawberry", "Strawberry"]
filter() Creates a new array with every element in an array that pass a test

Example

function containsFiveLetters(currentValue) {
  return currentValue.length == 5;
}

const fruits = ["Apple", "Banana", "Mango", "Orange", "Strawberry"];
const result = fruits.filter(containsFiveLetters);
//result is equal to ["Apple", "Mango"]
find() Returns the value of the first element in an array that passes a test

Example

function containsSixLetters(currentValue) {
  return currentValue.length == 6;
}

const fruits = ["Apple", "Banana", "Mango", "Orange", "Strawberry"];
let result = fruits.find(containsSixLetters);
//result is equal to "Banana"
findIndex() Returns the index of the first element in an array that passes a test, otherwise returns -1

Example

function containsSixLetters(currentValue) {
  return currentValue.length == 6;
}

const fruits = ["Apple", "Banana", "Mango", "Orange", "Strawberry"];
let result = fruits.findIndex(containsSixLetters);
//result is equal to 1
forEach() Calls a function for each array element

Example

const fruits = ["Apple", "Banana", "Mango"];
fruits.forEach(function(element) {
console.log(element);
}); //outputs: "Apple" //outputs: "Banana" //outputs: "Mango"
includes() Searches the array for an element and returns true if the element exists in the array, and false if it doesn't

Example

const fruits = ["Apple", "Banana", "Mango"];
let isInTheArray = fruits.includes("Banana"); 
// isInTheArray is equal to true
indexOf() Searches the array for an element and returns its position

Example

const fruits = ["Apple", "Banana", "Mango"];
let pos = fruits.indexOf("Banana"); 
// pos is equal to 1
isArray() Checks whether an object is an array

Example

const fruits = ["Apple", "Banana", "Mango"];
console.log(Array.isArray(fruits));
// outputs true
join() Joins all elements of an array into a string, and takes a separator as option

Example

const fruits = ["Apple", "Banana", "Mango"];
let myString = fruits.join(" * ");
// myString is equal to: Apple * Banana * Mango 
lastIndexOf() Search the array for an element, starting at the end, and returns its position

Example

const fruits = ["Apple", "Banana", "Mango", "Banana", "Strawberry"];
let pos = fruits.lastIndexOf("Banana"); 
// pos is equal to 3
map() Creates a new array with the result of calling a function for each array element

Example

const array1 = [1, 4, 9, 16];

function doubleValues(myVal) {
  return( myVal * 2); 
}

const map1 = array1.map(doubleValues);

console.log(map1);
// outputs: Array [2, 8, 18, 32]
pop() Removes the last element of an array, and returns that element

Example

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.pop());
// outputs: "Mango"

console.log(fruits);
// outputs: Array ["Apple", "Banana"]

fruits.pop();

console.log(fruits);
// outputs: Array ["Apple"]
push() Adds new elements to the end of an array, and returns the new length

Example

const fruits = ["Apple", "Banana", "Mango"];
fruits.push("Orange"); //["Apple", "Banana", "Mango", "Orange"]
reduce() Reduce the values of an array to a single value (going left-to-right)

Example

const array1 = [1, 2, 3, 4];

function addUp(total, num) {
  return (total + num);
}

// 1 + 2 + 3 + 4
console.log(array1.reduce(addUp));
// outputs: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(addUp, 5));
// outputs: 15
reduceRight() Reduce the values of an array to a single value (going right-to-left)

Example

const array1 = [1, 2, 3, 4];

function takeAway(total, num) {
  return (total - num);
}

// 4 - 3 - 2 - 1
console.log(array1.reduceRight(takeAway));
// outputs: -2

// 5 - 4 - 3 - 2 - 1
console.log(array1.reduceRight(takeAway, 5));
// outputs: -5
reverse() Reverses the order of the elements in an array. The original array is modified.

Example

const fruits = ["Apple", "Banana", "Mango"];
fruits.reverse(); 
console.log( fruits );
//outputs: Array ["Mango", "Banana", "Apple"]
shift() Removes the first element of an array, and returns that element

Example

const fruits = ["Apple", "Banana", "Mango"];
let firstElement = fruits.shift();

console.log(fruits);
//outputs: Array ["Banana", "Mango"]

console.log(firstElement);
//outputs: "Apple"
slice() Selects a part of an array, and returns the new array. The original array is not modified.

Example

const fruits = ["Apple", "Banana", "Mango", "Banana", "Strawberry"];

console.log(fruits.slice(2));
//outputs: Array ["Mango", "Banana", "Strawberry"]

console.log(fruits.slice(2, 4));
//outputs: Array ["Mango", "Banana"]

console.log(fruits.slice(1, 5));
//outputs: Array ["Banana", "Mango", "Banana", "Strawberry"]
some() Checks if any of the elements in an array pass a test

Example

const myArray = [1, 2, 3, 4, 5];

let even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(myArray.some(even));
//outputs: true
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

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
//outputs: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
//outputs: Array [1, 100000, 21, 30, 4]
splice() Adds/Removes elements from an array

Example

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
//inserts at index 1
console.log(months);
//outputs: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
//replaces 1 element at index 4
console.log(months);
//outputs: Array ['Jan', 'Feb', 'March', 'April', 'May']
toString() Converts an array to a string, and returns the result

Example

const fruits = ["Apple", "Banana", "Mango"];
let myString = fruits.toString();
// myString is equal to: Apple, Banana, Mango 
unshift() Adds new elements to the beginning of an array, and returns the new length

Example

const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.unshift("Strawberry", "Orange"));
//outputs: 5

console.log(fruits);
//outputs: Array ["Strawberry", "Orange", "Apple", "Banana", "Mango"]
valueOf() Returns the primitive value of an array

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
let v = fruits.valueOf();

console.log(v);
//outputs: Array ["Banana", "Orange", "Apple", "Mango"]

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 Expression: A function expression is a function that is assigned to a variable. You can use function expressions to create anonymous functions or to assign a function to a variable. Here is an example for a function with no parameters and which does not return anything:
    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;
    };
  • Arrow Function: Arrow functions were introduced in ECMAScript 6 (ES6) and provide a shorthand syntax for defining functions. Here is an example for a function with no parameters and which does not return anything:
    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 code

    Example

    const match4 = 140;
    const match3 = 30;
    let match = 3;
    match = "match" + match;
    alert("You win: £" + eval(match)); // alert("You win £30");
    
    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