This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

  • 9.2 JS 2009 (ES5)

    • ECMAScript 2009, also known as ES5, was the first major revision to JavaScript.
    • This chapter describes the most important features of ES5.

    ES5 Features

    ES5 Syntactical Changes

    • Property access [ ] on strings
    • Trailing commas in array and object literals
    • Multiline string literals
    • Reserved words as property names

    The "use strict" Directive

    • "use strict" defines that the JavaScript code should be executed in "strict mode".
    • With strict mode you can, for example, not use undeclared variables.
    • You can use strict mode in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.
    • "use strict" is just a string expression. Old browsers will not throw an error if they don't understand it.

    return to top of page

    String.trim()

    String.trim() removes whitespace from both sides of a string.

    Example 1: JS Strings - String.trim()
    var str = "       Hello World!        ";
    alert(str.trim()

    return to top of page

    Array.isArray()

    The isArray() method checks whether an object is an array.

    Example 2: JS Arrays - isArray()
    function myFunction() {
      var fruits = ["Banana", "Orange", "Apple", "Mango"];
      var x = document.getElementById("demo");
      x.innerHTML = Array.isArray(fruits);
    }

    return to top of page

    Array.forEach()

    The forEach() method calls a function once for each array element.

    Example 3: JS Array.forEach()
    var txt = "";
    var numbers = [45, 4, 9, 16, 25];
    numbers.forEach(myFunction);
    
    function myFunction(value) {
      txt = txt + value + "<br>";
    }

    return to top of page

    Array.map()

    This example multiplies each array value by 2:

    Example 4: JS Array.map()
    var numbers1 = [45, 4, 9, 16, 25];
    var numbers2 = numbers1.map(myFunction);
    
    function myFunction(value) {
      return value * 2;
    }

    return to top of page

    Array.filter()

    This example creates a new array from elements with a value larger than 18:

    Example 5: JS Array.filter()
    var numbers = [45, 4, 9, 16, 25];
    var over18 = numbers.filter(myFunction);
    
    function myFunction(value) {
      return value > 18;
    }

    return to top of page

    Array.reduce()

    This example finds the sum of all numbers in an array:

    Example 6: JS Array.reduce()
    var numbers1 = [45, 4, 9, 16, 25];
    var sum = numbers1.reduce(myFunction);
    
    function myFunction(total, value) {
      return total + value;
    }

    return to top of page

    Array.every()

    This example checks if all values are over 18:

    Example 8: JS Array.every()
    var numbers = [45, 4, 9, 16, 25];
    var allOver18 = numbers.every(myFunction);
    
    function myFunction(value) {
      return value > 18;
    }

    return to top of page

    Array.some()

    This example checks if some values are over 18:

    Example 9: JS Array.some()
    var numbers = [45, 4, 9, 16, 25];
    var allOver18 = numbers.some(myFunction);
    
    function myFunction(value) {
      return value > 18;
    }

    return to top of page

    Array.indexOf()

    Search an array for an element value and returns its position.

    Example 10: JS Array.indexOf()
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var a = fruits.indexOf("Apple");

    return to top of page

    Array.lastIndexOf()

    Array.lastIndexOf() is the same as Array.indexOf(), but searches from the end of the array.

    Example 11: JS Array.lastIndexOf()
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    var a = fruits.lastIndexOf("Apple");

    return to top of page

    JSON.parse()

    • A common use of JSON is to receive data from a web server.
    • Imagine you received this text string from a web server:
    '{"name":"John", "age":30, "city":"New York"}'

    The JavaScript function JSON.parse() is used to convert the text into a JavaScript object:

    var obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

    Try it yourself

    return to top of page

    JSON.stringify()

    • A common use of JSON is to send data to a web server.
    • When sending data to a web server, the data has to be a string.
    • Imagine we have this object in JavaScript:
    var obj = {name:"John", age:30, city:"New York"};

    Use the JavaScript function JSON.stringify() to convert it into a string.

    var myJSON = JSON.stringify(obj);
    • The result will be a string following the JSON notation.
    • myJSON is now a string, and ready to be sent to a server:
    Example 12: JS JSON.stringify()
    var obj = {name:"John", age:30, city:"New York"};
    var myJSON = JSON.stringify(obj);
    document.getElementById("demo").innerHTML = myJSON;

    return to top of page

    Date.now()

    Date.now() returns the number of milliseconds since zero date (January 1. 1970 00:00:00 UTC).

    Example 13: JS Date.now()
    var timInMSs = Date.now();

    Date.now() returns the same as getTime() performed on a Date object.

    return to top of page

    Property Getters and Setters

    • ES5 lets you define object methods with a syntax that looks like getting or setting a property.
    • This example creates a getter for a property called fullName:
    Example 14: JS Getters and Setters part 1
    // Create an object:
    var person = {
      firstName: "John",
      lastName : "Doe",
      get fullName() {
        return this.firstName + " " + this.lastName;
      }
    };
    
    // Display data from the object using a getter:
    document.getElementById("demo").innerHTML = person.fullName;

    This example creates a setter and a getter for the language property:

    Example 15: JS Getters and Setters part 2
    var person = {
      firstName: "John",
      lastName : "Doe",
      language : "NO",
      get lang() {
        return this.language;
      },
      set lang(value) {
        this.language = value;
      }
    };
    
    // Set an object property using a setter:
    person.lang = "en";
    
    // Display data from the object using a getter:
    document.getElementById("demo").innerHTML = person.lang;

    This example uses a setter to secure upper case updates of language:

    Example 16: JS Getters and Setters part 3
    var person = {
      firstName: "John",
      lastName : "Doe",
      language : "NO",
      set lang(value) {
        this.language = value.toUpperCase();
      }
    };
    
    // Set an object property using a setter:
    person.lang = "en";
    
    // Display data from the object:
    document.getElementById("demo").innerHTML = person.language;

    return to top of page

    New Object Property Methods

    • Object.defineProperty() is a new Object method in ES5.
    • It lets you define an object property and/or change a property's value and/or metadata.
    Example 17: JS New Object Property Methods part 1
    // Create an Object:
    var person = {
      firstName: "John",
      lastName : "Doe",
      language : "NO",
    };
    
    // Change a Property:
    Object.defineProperty(person, "language", {
      value: "EN",
      writable : true,
      enumerable : true,
      configurable : true
    });
    
    // Enumerate Properties
    var txt = "";
    for (var x in person) {
      txt += person[x] + "<br<";
    }
    document.getElementById("demo").innerHTML = txt;

    Next example is the same code, except it hides the language property from enumeration:

    Example 18: JS New Object Property Methods part 2
    // Create an Object:
    var person = {
      firstName: "John",
      lastName : "Doe",
      language : "NO",
    };
    
    // Change a Property:
    Object.defineProperty(person, "language", {
      value: "EN",
      writable : true,
      enumerable : false,
      configurable : true
    });
    
    // Enumerate Properties
    var txt = "";
    for (var x in person) {
      txt += person[x] + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;

    This example creates a setter and a getter to secure upper case updates of language:

    Example 19: JS New Object Property Methods part 3
    /// Create an Object:
    var person = {
      firstName: "John",
      lastName : "Doe",
      language : "NO"
    };
    
    // Change a Property:
    Object.defineProperty(person, "language", {
      get : function() { return language },
      set : function(value) { language = value.toUpperCase()}
    });
    
    // Change Language
    person.language = "en";
    
    // Display Language
    document.getElementById("demo").innerHTML = person.language;

    ES5 added a lot of new Object Methods to JavaScript:

    ES5 New Object Methods

    // Adding or changing an object property
    Object.defineProperty(object, property, descriptor)
    
    // Adding or changing many object properties
    Object.defineProperties(object, descriptors)
    
    // Accessing Properties
    Object.getOwnPropertyDescriptor(object, property)
    
    // Returns all properties as an array
    Object.getOwnPropertyNames(object)
    
    // Returns enumerable properties as an array
    Object.keys(object)
    
    // Accessing the prototype
    Object.getPrototypeOf(object)
    
    // Prevents adding properties to an object
    Object.preventExtensions(object)
    // Returns true if properties can be added to an object
    Object.isExtensible(object)
    
    // Prevents changes of object properties (not values)
    Object.seal(object)
    // Returns true if object is sealed
    Object.isSealed(object)
    
    // Prevents any changes to an object
    Object.freeze(object)
    // Returns true if object is frozen
    Object.isFrozen(object)

    return to top of page

    Property Access on Strings

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

    Example 20: JS Property Access on Strings part 1
    var str = "HELLO WORLD";
    str.charAt(0);            // returns H

    ES5 allows property access on strings:

    Example 21: JS Property Access on Strings part 2
    var str = "HELLO WORLD";
    str[0];                   // returns H

    Property access on string might be a little unpredictable.

    Trailing Commas

    ES5 allows trailing commas in object and array definitions:

    Object Example

    person = {
      firstName: "John",
      lastName: " Doe",
      age: 46, 
    }

    Array Example

    points = [
      1,
      5,
      10,
      25,
      40,
      100, 
    ];
    • WARNING !!!
    • Internet Explorer 8 will crash.
    • JSON does not allow trailing commas.

    JSON Objects:

    // Allowed:
    var person = '{"firstName":"John", "lastName":"Doe", "age":46}'
    JSON.parse(person)
    
    // Not allowed:
    var person = '{"firstName":"John", "lastName":"Doe", "age":46,}'
    JSON.parse(person)

    JSON Arrays:

    // Allowed:
    points = [40, 100, 1, 5, 25, 10]
    
    // Not allowed:
    points = [40, 100, 1, 5, 25, 10,]

    Strings Over Multiple Lines

    ES5 allows string literals over multiple lines if escaped with a backslash:

    Example 21: JS Strings Over Multiple Lines part 1
    "Hello \
    Dolly!";
    • The \ method might not have universal support.
    • Older browsers might treat the spaces around the backslash differently.
    • Some older browsers do not allow spaces behind the \ character.
    • A safer way to break up a string literal, is to use string addition (+):
    Example 22: JS Strings Over Multiple Lines part 2
    "Hello " +
    "Dolly!";

    Reserved Words as Property Names

    ES5 allows reserved words as property names:

    Object Example

    var obj = {name: "John", new: "yes"}

    Try it yourself

    Browser Support for ES5

    Chrome 23, IE 10, and Safari 6 were the first browsers to fully support ES5:

    Chrome browser Edge browser Firefox browser Safari browser Opera browser
    Chrome 23 IE10 / Edge Firefox 21 Safari 6 Opera 15
    Sep 2012 Sep 2012 Apr 2013 Jul 2012 Jul 2013
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon