JavaScript ES5

What is ECMAScript 5?

ECMAScript 5 is also known as ES5 and ECMAScript 2009.

This chapter introduces some of the most important features of ES5.

ECMAScript 5 Features

These are the new features released in 2009:

  • "use strict" directive
  • String.trim()
  • Array.isArray()
  • Array.forEach()
  • Array.map()
  • Array.filter()
  • Array.reduce()
  • Array.reduceRight()
  • Array.every()
  • Array.some()
  • Array.indexOf()
  • Array.lastIndexOf()
  • JSON.parse()
  • JSON.stringify()
  • Date.now()
  • Property getters and setters
  • New object properties and methods

ECMAScript 5 Syntax Changes

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

"use strict" directive

"use strict"Define JavaScript code to be executed in "strict mode".

For example, with strict mode, you cannot use undeclared variables.

You can use strict mode in all programs. It can help you write clearer code, such as preventing you from using undeclared variables.

"use strict"It is just a string expression. If old browsers do not understand them, they will not throw an error."

Please read JS Strict Mode Read more content here.

String.trim()

String.trim() Remove whitespace characters from both ends of the string.

Example

var str = "       Hello World!        ";
alert(str.trim());

Try It Yourself

Please visit JS string methods Read more content here.

Array.isArray()

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

Example

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

Try It Yourself

Please visit JS Arrays Read more content here.

Array.forEach()

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

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.map()

This example multiplies each array value by 2:

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.filter()

This example creates a new array with elements greater than 18:

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.reduce()

This example determines the sum of all numbers in the array:

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.reduceRight()

This example is also to determine the sum of all numbers in the array:

Example

var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
  return total + value;
}

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.every()

This example checks if all values are greater than 18:

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.some()

This example checks if some values are greater than 18:

Example

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

Try It Yourself

Please visit JS array iteration methods Learn more content here.

Array.indexOf()

Retrieve the value of an element in the array and return its position:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");

Try It Yourself

Please visit JS array iteration methodsLearn more content here.

Array.lastIndexOf()

Array.lastIndexOf() versus Array.indexOf() Similarly, but starts searching from the end of the array.

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");

Try It Yourself

Please visit JS array iteration methods Learn more content here.

JSON.parse()

A common use of JSON is to receive data from a web server.

Imagine that you receive this text string from a web server:

'{"name":"Bill", "age":62, "city":"Seatle"}'

JavaScript Functions JSON.parse() Used to convert text to a JavaScript object:

var obj = JSON.parse('{"name":"Bill", "age":62, "city":"Seatle"}');

Try It Yourself

Please visit our JSON tutorial Learn more content here.

JSON.stringify()

A common use of JSON is to send data to a web server.

When sending data to a web server, the data must be a string.

Imagine that we have this object in JavaScript:

var obj = {"name":"Bill", "age":62, "city":"Seatle"};

Please use the JavaScript function JSON.stringify() to convert it to a string.

var myJSON = JSON.stringify(obj);

The result will be a string following the JSON notation.

myJSON is now a string, ready to be sent to the server:

Example

var obj = {"name":"Bill", "age":62, "city":"Seatle"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Try It Yourself

Please visit our JSON tutorial Learn more content here.

Date.now()

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

Example

var timInMSs = Date.now();

Try It Yourself

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

Please visit JS date to learn more.

Property getters and setters

ES5 allows you to define object methods using syntax similar to getting or setting properties.

This example creates a property named fullName: getter:

Example

// Create an object:
var person = {
  firstName: "Bill",
  lastName : "Gates"
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
});
// Use a getter to display data from the object:
document.getElementById("demo").innerHTML = person.fullName;

Try It Yourself

This example creates a setter and a getter:

Example

var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "NO",
  get lang() {
    return this.language;
  ,
  set lang(value) {
    this.language = value;
  }
});
// Use a setter to set an object property:
person.lang = "en";
// Use a getter to display data from the object:
document.getElementById("demo").innerHTML = person.lang;

Try It Yourself

This example uses a setter to ensure that the uppercase update of the language is maintained:

Example

var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "NO",
  set lang(value) {
    this.language = value.toUpperCase();
  }
});
// Use a setter to set an object property:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;

Try It Yourself

Please visit JS object accessors to learn more about getters and setters.

New object properties and methods

Object.defineProperty() is a new object method in ES5.

It allows you to define object properties and/or change the values and/or metadata of properties.

Example

// Create an object:
var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "NO", 
});
// Change 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;

Try It Yourself

The next example is the same code, but it hides the language property in enumeration:

Example

// Create an object:
var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "NO", 
});
// Change 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;

Try It Yourself

This example creates a setter and getter to ensure the uppercase update of the language:

Example

// Create an object:
var person = {
  firstName: "Bill",
  lastName : "Gates"
  language : "NO"
});
// Change property:
Object.defineProperty(person, "language", {
  get : function() { return language },
  set : function(value) { language = value.toUpperCase()}
});
// Change the language
person.language = "en";
// Display the language
document.getElementById("demo").innerHTML = person.language;

Try It Yourself

New object methods in ES5

ECMAScript 5 adds many new object methods to JavaScript:

// Add or change object property
Object.defineProperty(object, property, descriptor)
// Add or change multiple object properties
Object.defineProperties(object, descriptors)
// Access the property
Object.getOwnPropertyDescriptor(object, property)
// Returns an array of all properties
Object.getOwnPropertyNames(object)
// Returns an array of enumerable properties
Object.keys(object)
// Access the prototype
Object.getPrototypeOf(object)
// 防止向对象添加属性
Object.preventExtensions(object)
// 如果可以将属性添加到对象,则返回 true
Object.isExtensible(object)
// 防止更改对象属性(而不是值)
// Prevents adding properties to the object
// If properties can be added to the object, returns true
// Prevents changes to object properties (not values)
// If the object is sealed, returns true
// Prevents any changes to the object
// Returns true if the object is frozen
Object.isFrozen(object)

Please visit Object ECMAScript5 Learn more content here.

Property access of strings

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

Example

var str = "HELLO WORLD";
str.charAt(0);            // Returns H

Try It Yourself

ECMAScript 5 allows property access for strings:

Example

var str = "HELLO WORLD";
str[0];                   // Returns H

Try It Yourself

Property access of strings may be a bit unpredictable.

Please visit JS string methods Learn more content here.

Trailing Commas

ECMAScript 5 allows trailing commas in object and array definitions:

Object instance

person = {
  firstName: "Bill",
  lastName: "Gates",
  age: 62,
}

Array instance

points = [
  1,
  5,
  10,
  25,
  40,
  100,
];

Warning!!!

Internet Explorer 8 will crash.

JSON does not allow trailing commas.

JSON Object:

// Allowed:
var person = '{"firstName":"Bill", "lastName":"Gates", "age":62}'
JSON.parse(person)
// Not allowed:
var person = '{"firstName":"Bill", "lastName":"Gates", "age":62,}'
JSON.parse(person)

JSON Array:

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

Multi-line Strings

If backslashes are used for escaping, ECMAScript 5 allows multi-line string literals (literals):

Example

"Hello \
Kitty!";

Try It Yourself

The backslash method may not be universally supported.

Older browsers may handle spaces around backslashes differently.

Some older browsers do not allow spaces after the backslash character.

A safer way to split string literals is to use string concatenation:

Example

"Hello " + 
"Kitty!";

Try It Yourself

Reserved Words as Property Names

ECMAScript 5 allows reserved words to be used as property names:

Object Example

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

Try It Yourself

ES5 (ECMAScript 5) Browser Support

Chrome 23, IE 10, and Safari 6 are the first browsers to fully support ECMAScript 5:

Chrome 23 IE10 / Edge Firefox 21 Safari 6 Opera 15
September 2012 September 2012 April 2013 July 2012 July 2013