JS TutorialLesson #149

JavaScript 2009 (ES5)

The first major revision to JavaScript.

ECMAScript 2009

The first major revision to JavaScript.

ECMAScript 2009 is also known as ES5.

ES5 Features

FeatureDescription
"use strict"Allows code to be executed in "strict mode"
[String [] access](js_es5.asp?#mark_string_property_access)Returns the character at a specified index in a string
Multiline stringsAallows strings over multiple lines if escaped with \
String.trim()Removes whitespace from both sides of a string
Array.isArray()Returns true if a variable is an array
Array forEach()Calls a function for each array element
Array map()Creates a new array from a function on each element
Array filter()Creates an array from array elements that passes a test
Array reduce()Reduces an array to a single value (from left)
Array reduceRight()Reduces an array to a single value (from right)
Array every()Checks if all array values pass a test
Array some()Checks if some values pass a test
Array indexOf()Search for an element value and returns its position
Array lastIndexOf()Search for an element value and returns its position
JSON.parse()Convert JSON into a JavaScript object
JSON.stringify()Convert JSON into a string
Date.now()Returns the number of milliseconds since zero date
Date toISOString()Converts a date object into to an ISO string
Date toJSON()Converts a date object into to a JSON string
Property gettersAllows for defining how a property value is retrieved
Property settersAllows for defining how a property value is set
Reserved namesAllows reserved names as property names
Object.create()Creates an object from an existing object
Object.keys()Returns an array with the keys of an object
Object managementObject management methods
Object protectionObject protection methods
Object defineProperty()Allows for defining or changing object properties
Function bind()Let objects borrow methods from other objects
Trailing commasallows trailing commas in object and array definitions:

Browser Support

JavaScript 2009 is supported in all modern browsers since July 2013:

Chrome 23IE/Edge 10Firefox 21Safari 6Opera 15

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. > Learn More ...

Property Access on Strings

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

Example

Example Code

javascript
Try it Yourself
let str = "HELLO WORLD";

str.charAt(0);     // returns H

ES5 allows property access on strings:

Example

Example Code

javascript
Try it Yourself
let str = "HELLO WORLD";

str[0];           // returns H
Property access on string might be a little unpredictable. > Read more in JS String Methods.

Strings Over Multiple Lines

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

Example

Example Code

javascript
Try it Yourself
"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

Example Code

javascript
Try it Yourself
"Hello " +
"Dolly!";

Reserved Words as Property Names

ES5 allows reserved words as property names:

Object Example

Example Code

javascript
Try it Yourself
var obj = {name: "John", new: "yes"}

String trim()

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

Example

Example Code

javascript
Try it Yourself
var str = "       Hello World!        ";
alert(str.trim());

Learn more in JS String Methods.


Array.isArray()

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

Example

Example Code

javascript
Try it Yourself
const fruits = ["Banana", "Orange", "Apple", "Mango"];

result = Array.isArray(fruits);

Learn more in JS Array Methods.


Array forEach()

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

Example

Example Code

javascript
Try it Yourself
const numbers = [45, 4, 9, 16, 25];

numbers.forEach(myFunction);

Learn more in JS Array Iteration Methods.


Array map()

The map() method creates a new array by performing a function on each array element.

Example

Example Code

javascript
Try it Yourself
const numbers1 = [45, 4, 9, 16, 25];

const numbers2 = numbers1.map(myFunction);

function myFunction(value) {

  return value * 2;

}

Learn more in JS Array Iteration Methods.


Array filter()

The filter() method creates a new array from array elements that passes a test.

Example

Example Code

javascript
Try it Yourself
const numbers = [45, 4, 9, 16, 25];

const over18 = numbers.filter(myFunction);

function myFunction(value) {

  return value > 18;

}

Learn more in JS Array Iteration Methods.


Array reduce()

The reduce() method reduces an array to a single value.

Example

Example Code

javascript
Try it Yourself
const numbers = [45, 4, 9, 16, 25];

let sum = numbers.reduce(myFunction);

function myFunction(total, value) {

  return total + value;

}

Learn more in JS Array Iteration Methods.


Array reduceRight()

The reduceRight() method reduces an array to a single value (from right to left).

Example

Example Code

javascript
Try it Yourself
const numbers1 = [45, 4, 9, 16, 25];

let sum = numbers1.reduceRight(myFunction);

function myFunction(total, value) {

  return total + value;

}

Learn more in JS Array Iteration Methods.


Array every()

The every() method checks if all array values pass a test.

Example

Example Code

javascript
Try it Yourself
const numbers = [45, 4, 9, 16, 25];

let allOver18 = numbers.every(myFunction);

function myFunction(value) {

  return value > 18;

}

Learn more in JS Array Iteration Methods.


Array some()

The some() method checks if some array values pass a test.

Example

Example Code

javascript
Try it Yourself
const numbers = [45, 4, 9, 16, 25];

let allOver18 = numbers.some(myFunction);

function myFunction(value) {

  return value > 18;

}

Learn more in JS Array Iteration Methods.


Array indexOf()

The indexOf() method searches for an element value and returns its position.

Example

Example Code

javascript
Try it Yourself
const fruits = ["Apple", "Orange", "Apple", "Mango"];

let position = fruits.indexOf("Apple") + 1;

Learn more in JS Array Search Methods.


Array lastIndexOf()

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

Example

Example Code

javascript
Try it Yourself
const fruits = ["Apple", "Orange", "Apple", "Mango"];

let position = fruits.lastIndexOf("Apple") + 1;

Learn more in JS Array Search Methods.


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:

Example

Example Code

javascript
Try it Yourself
'{"name":"John", "age":30, "city":"New York"}'

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

Example

Example Code

javascript
Try it Yourself
const txt = '{"name":"John", "age":30, "city":"New York"}'

const myObj = JSON.parse(txt);

Read more in our JSON Tutorial.


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:

Example

Example Code

javascript
Try it Yourself
const myObj = {name:"John", age:30, city:"New York"};

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

Example

Example Code

javascript
Try it Yourself
const myJSON = JSON.stringify(myObj);
The result will be a string following the JSON notation.

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

Example

Example Code

javascript
Try it Yourself
const myObj = {name:"John", age:30, city:"New York"};

const myJSON = JSON.stringify(myObj);

Read more in our JSON Tutorial.


Date.now()

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

Example

Example Code

javascript
Try it Yourself
var timInMSs = Date.now();

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

Learn more in JS Date Methods.


Date toISOString()

The toISOString() method converts a Date object to a string, using the ISO standard format:

Example

Example Code

javascript
Try it Yourself
const d = new Date();

document.getElementById("demo").innerHTML = d.toISOString();

Learn more in JS Date Methods.


Date toJSON()

toJSON() converts a Date object into a string, formatted as a JSON date.

JSON dates have the same format as the ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ:

Example

Example Code

javascript
Try it Yourself
d = new Date();

document.getElementById("demo").innerHTML = d.toJSON();

Learn more in JS Date Methods.


Property Getters

A property getter is a method that allows you to define how a property value is retrieved when it is accessed.

This example creates a getter for a property called fullName:

Example

Example Code

javascript
Try it Yourself
// Create an object:
const 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;

Learn more about Gettes and Setters in JS Object Accessors


Property Setters

A property setter is a method that allows you to define how a property value is set.

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

Example

Example Code

javascript
Try it Yourself
const 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;

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

Example

Example Code

javascript
Try it Yourself
const 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;

Learn more about Getters and Setters in JS Object Accessors


Object.defineProperty()

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

Example Code

javascript
Try it Yourself
// Create an Object:
const person = {
  firstName:
  "John",
  lastName : "Doe",
  language : "NO",
};

  // Change a Property:
Object.defineProperty(person, "language", {

  value: "EN",
  writable : true,
  enumerable : true,
  configurable : true
});

//
  Enumerate Properties
let txt = "";
for (let x in person) {

  txt += person[x] + " ";
}

// Display Properties

document.getElementById("demo").innerHTML =
  txt;

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

Example

Example Code

javascript
Try it Yourself
// Create an Object:
const person = {
  firstName:
  "John",
  lastName : "Doe",
  language : "NO",
};

  // Change a Property:
Object.defineProperty(person, "language", {

  value: "EN",
  writable : true,
  enumerable : false,
  configurable : true
});

//
  Enumerate Properties
let txt = "";
for (let x in person) {

  txt += person[x] + " ";
}
document.getElementById("demo").innerHTML =
  txt;

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

Example

Example Code

javascript
Try it Yourself
// Create an Object:
const 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;
Learn More: > Object Management

Object.create()

The Object.create() method creates an object from an existing object.

Example

Example Code

javascript
Try it Yourself
// Create an Object:

const person = {

  firstName: "John",

  lastName: "Doe"

};

// Create new Object

const man = Object.create(person);

man.firstName = "Peter";

Learn more in JS Object Definition


Object.keys()

The Object.keys() method returns an array with the keys of an object.

Example

Example Code

javascript
Try it Yourself
// Create an Object

const person = {

  firstName: "John",

  lastName: "Doe",

  age: 50,

  eyeColor: "blue"

};

// Get the Keys

const keys = Object.keys(person);
Learn More: > JS Object Iterations

Object Management

ES5 added new Object management methods to JavaScript:

Managing Objects

Example Code

javascript
Try it Yourself
// Adding or changing an object property

Object.defineProperty(object, property, descriptor)

// Adding or changing object properties

Object.defineProperties(object, descriptors)

// Accessing a Property

Object.getOwnPropertyDescriptor(object, property)

// Accessing Properties

Object.getOwnPropertyDescriptors(object)

// Returns all properties as an array

Object.getOwnPropertyNames(object)

// Accessing the prototype

Object.getPrototypeOf(object)
Learn More: > Object Management

Object Protection

ES5 added Object protection methods to JavaScript:

Protecting Objects

Example Code

javascript
Try it Yourself
// 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)

Function Bind()

With the bind() method, an object can borrow a method from another object.

This example creates 2 objects (person and member).

The member object borrows the fullname method from the person object:

Example

Example Code

javascript
Try it Yourself
const person = {

  firstName:"John",

  lastName: "Doe",

    fullName: function () {

    return this.firstName + " " + this.lastName;

    }

}

const member = {

  firstName:"Hege",

  lastName: "Nilsen",

}

let fullName = person.fullName.bind(member);

Learn more in Function bind().


Trailing Commas

ES5 allows trailing commas in object and array definitions:

Object Example

Example Code

javascript
Try it Yourself
person = {

  firstName: "John",

  lastName: "
Doe",

age: 46,

}

Array Example

Example Code

javascript
Try it Yourself
points = [

  1,

  5,

  10,

  25,

  40,

  100,

];

WARNING

JSON does not allow trailing commas.

JSON Objects:

Example Code

javascript
Try it Yourself
//
  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)

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let str = "HELLO WORLD";

str.charAt(0);     // returns H

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let str = "HELLO WORLD";

str[0];           // returns H

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
"Hello \
Dolly!";

JS Example 4

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
"Hello " + 
"Dolly!";

Object Example

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
var obj = {name: "John", new: "yes"}

JS Example 6

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: