- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - ES5
JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and 'use strict' directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain.
New Added Features in JavaScript ES5
Here are the new methods, features, etc., added to the ES5 version of JavaScript.
- Array every()
- Array filter()
- Array forEach()
- Array isArray()
- Array indexOf()
- Array lastIndexOf()
- Array map()
- Array reduce()
- Array reduceRight()
- Array some()
- Date now()
- Date toJSON()
- Date toISOString()
- Function bind()
- JSON parse()
- JSON stringify()
- Multiline strings
- Object methods
- Object defineProperty()
- Property getters and setters
- Reserved words as property names
- "use strict"
- String[number] access
- String trim()
- Trailing commas
Here, we have explained each feature in detail.
JavaScript Array every()
The array.every() method checks whether each element of the array follows a particular condition.
Example
In the below code, we use the array.every() method to check whether each element of the array is even.
<html> <body> <div id = "output"> All elements of the array are even? </div> <script> const arr = [10, 20, 30, 40, 2, 6]; function even(element) { return element % 2 == 0; } document.getElementById("output").innerHTML += arr.every(even); </script> </body> </html>
Output
All elements of the array are even? true
JavaScript Array filter()
The array.filter() filters array elements and gets filtered elements in the new array.
Example
In the below code, we filter the array elements which are divisible by 10.
<html> <body> <div id = "output"> Elements divisible by 10 are </div> <script> const arr = [10, 20, 8, 30, 40, 2, 6]; function divide(element) { return element % 10 == 0; } document.getElementById("output").innerHTML += arr.filter(divide); </script> </body> </html>
Output
Elements divisible by 10 are 10,20,30,40
JavaScript Array forEach()
The array.forEach() traverses the array elements. It is similar to loops in JavaScript.
Example
The below code uses the array.forEach() method to traverse the array and print each array element in the new line.
<html> <body> <div id="output"> </div> <script> const arr = ["TATA", "Honda", "Toyota", "Maruti"]; arr.forEach(traverse); // Using the array.forEach() method function traverse(element) { document.getElementById("output").innerHTML += element + "<br>"; } </script> </body> </html>
Output
TATA Honda Toyota Maruti
JavaScript Array isArray()
The Array.isArray() method checks whether the object passed as an argument is an array.
Example
The below code checks whether the arr is an array using the Array.isArray() method.
<html> <body> <div id = "output"> </div> <script> const arr = ["TATA", "Honda", "Toyota", "Maruti"]; let bool = Array.isArray(arr); document.getElementById("output").innerHTML += "Is arr array? " + bool; </script> </body> </html>
Output
Is arr array? true
JavaScript Array indexOf()
The array.indexOf() method returns the first index of the particular element in the array.
Example
The below code finds the first index of 23 in the array, which is 0.
<html> <body> <div id = "output"> The first index of 23 in the array is </div> <script> const arr = [23, 45, 32, 12, 23, 56]; document.getElementById("output").innerHTML += arr.indexOf(23); </script> </body> </html>
Output
The first index of 23 in the array is 0
JavaScript Array lastIndexOf()
The array.lastIndexOf() method returns the last index of the particular element in the array.
Example
The code below finds the last index of the 45 in the array, which is 4.
<html> <body> <div id = "output"> The last index of 45 in the array is </div> <script> const arr = [23, 45, 32, 45, 45, 56]; document.getElementById("output").innerHTML += arr.lastIndexOf(45); </script> </body> </html>
Output
The last index of 45 in the array is 4
JavaScript Array map()
The array.map() method returns a new array after mapping current array elements with new ones.
Example
The below code uses the map() method to create a new array by doubling the array elements.
<html> <body> <div id = "output"> The new array is </div> <script> const arr = [1, 2, 3, 4, 5]; function doubleEle(element) { return element * 2; } document.getElementById("output").innerHTML += arr.map(doubleEle); </script> </body> </html>
Output
The new array is 2,4,6,8,10
JavaScript Array reduce()
The array.reduce() method reduces the array to a single value.
Example
The below code multiples all elements of the array using the array.reduce() method.
<html> <body> <div id = "output">The multiplication result of the array elements is </div> <script> const arr = [1, 2, 3, 4, 5]; function multiplier(multiplication, element) { return multiplication * 2; } document.getElementById("output").innerHTML += arr.reduce(multiplier); </script> </body> </html>
Output
The multiplication result of the array elements is 16
JavaScript Array reduceRight()
The array.reduceRight() method reduces the array from right to left instead of left to right.
Example
<html> <body> <div id = "output">The merged array elements in the reverse order is: </div> <script> const arr = ["How", "are", "you", "doing?"]; function merge(res, element) { return res += element + " "; } document.getElementById("output").innerHTML += arr.reduceRight(merge); </script> </body> </html>
Output
The merged array elements in the reverse order is: doing?you are How
JavaScript Array some()
The array.some() method is used to check whether some elements of the array follow the particular condition.
Example
The code below checks whether the array contains 1 or more strings with lengths greater than 3.
<html> <body> <div id = "output">Array contains one or more strings with lengths greater than 3? </div> <script> const arr = ["How", "are", "you", "doing?"]; function func_len(element) { return element.length > 3; } document.getElementById("output").innerHTML += arr.some(func_len); </script> </body> </html>
Output
Array contains one or more strings with lengths greater than 3? true
JavaScript Date now()
The Date.now() method is used to get the total number of milliseconds since 1st January 1970.
Example
The below code finds the total milliseconds from 1st January 1970.
<html> <body> <div id = "output">Total milliseconds since 1st January, 1970 is: </div> <script> document.getElementById("output").innerHTML += Date.now(); </script> </body> </html>
Output
Total milliseconds since 1st January, 1970 is: 1702540225136
JavaScript Date toJSON()
The date.toJSON() method converts the date into the JSON date format. The JSON date format is the same as the ISO format. The ISO format is YYYY-MM-DDTHH:mm:ss.sssZ.
Example
The below code prints the current date in JSON format.
<html> <body> <div id = "output">The current date in JSON format is: </div> <script> const date = new Date(); document.getElementById("output").innerHTML += date.toJSON(); </script> </body> </html>
Output
The current date in JSON format is: 2023-12-18T06:12:52.366Z
JavaScript Date toISOString()
The date.toISOString() method is used to convert the date into the ISO standard format.
Example
The below code prints the current date in the standard ISO string format.
<html> <body> <div id = "output">The current date in ISO string format is: </div> <script> const date = new Date(); document.getElementById("output").innerHTML += date.toISOString(); </script> </body> </html>
Output
The current date in ISO string format is: 2023-12-18T06:13:50.159Z
JavaScript Function bind()
The bind() method is used to borrow the method from another object.
Example
In the below code, the bird object contains the properties and printInfo() method. The animal object contains only name and category properties.
We used the bind() method to borrow the printInfo() method from the bird object for the animal object. In the output, the printInfo() method prints the information of the animal object.
<html> <body> <div id = "result"> </div> <script> const output = document.getElementById("result"); const bird = { name: "Parrot", category: "Bird", printInfo() { return "The name of the " + this.category + " is - " + this.name; } } const animal = { name: "Lion", category: "Animal", } const animalInfo = bird.printInfo.bind(animal); output.innerHTML += animalInfo(); </script> </body> </html>
Output
The name of the Animal is - Lion
JavaScript JSON parse()
The JSON.parse() method is used to convert the string into the JSON object.
Example
The code given below converts the string into an object. Also, we have printed the values of object properties in the output.
<html> <body> <div id = "demo"> </div> <script> const output = document.getElementById("demo"); const objStr = '{"name":"Sam", "age":40, "city":"Delhi"}'; const obj = JSON.parse(objStr); output.innerHTML += "The parsed JSON object values are - <br>"; output.innerHTML += "name : " + obj.name + "<br>"; output.innerHTML += "age : " + obj.age + "<br>"; output.innerHTML += "city: " + obj.city + "<br>"; </script> </body> </html>
Output
The parsed JSON object values are - name : Sam age : 40 city: Delhi
JavaScript JSON stringify()
The JSON.stringify() method converts the object into a string.
Example
The code below converts the obj object into the string using JSON.strringify() method.
<html> <body> <div id = "output">The object in the string format is - </div> <script> const obj = { message: "Hello World!", messageType: "Welcome!", } document.getElementById("output").innerHTML += JSON.stringify(obj); </script> </body> </html>
Output
The object in the string format is - {"message":"Hello World!","messageType":"Welcome!"}
JavaScript Multiline Strings
You can use the backslash (‘\’) to break the line of the string and define the string in multiline.
Example
In the below example, we have defined the ‘str’ string in multiple lines and used the backslash to break the line.
<html> <body> <div id = "output"> </div> <script> let str = "Hi \ user"; document.getElementById("output").innerHTML += "The string is - " + str; </script> </body> </html>
Output
The string is - Hi user
JavaScript Object Methods
In ES5, object-related methods are added to manipulate and protect the objects.
Methods to Manipulate the Object
Sr.No. | Method | Description |
---|---|---|
1 | create() | To creat a new object, using an existing object as the prototype. |
2 | defineProperty() | To make a clone of the object and add new properties to its prototype. |
3 | defineProperties() | To define a property into a particular object and get the updated object. |
4 | getOwnPropertyDescriptor() | To get the property descriptor for the properties of the object. |
5 | getOwnPropertyNames() | To get object properties. |
6 | getPrototypeOf() | To get the prototype of the object. |
7 | keys() | To get all keys of the object in the array format. |
Methods to Protect the Object
Sr.No. | Method | Description |
---|---|---|
1 | freeze() | To prevent adding or updating object properties by freezing the object. |
2 | seal() | To seal the object. |
3 | isFrozen() | To check if the object is frozen. |
4 | isSealed() | To check if the object is sealed. |
5 | isExtensible() | To check if an object is extensible. |
6 | keys() | To get all keys of the object in the array format. |
7 | preventExtensions() | To prevent the prototype updation of the object. |
JavaScript Object defineProperty()
You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata.
Example
The code below contains the car object's brand, model, and price properties. We used the defineProperty() method to define the ‘gears’ property in the object.
<html> <body> <div id = "output">The obj object is - </div> <script> const car = { brand: "Tata", model: "Nexon", price: 1000000, } Object.defineProperty(car, "gears", { value: 6, writable: true, enumerable: true, configurable: true }) document.getElementById("output").innerHTML += JSON.stringify(car); </script> </body> </html>
Output
The obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}
JavaScript Property getters and setters
The getters and setters are used to access and update the object properties securely.
Example
In the below code, the watch object contains the brand and dial properties. We have defined the getter using the get keyword to access the brand property value.
Also, we have defined the setter using the set keyword to set the dial property value in the upper case.
In this way, you can secure the updating object property value.
<html> <body> <div id = "demo"> </div> <script> const output = document.getElementById("demo"); const watch = { brand: "Titan", dial: "ROUND", // Getter to get brand property get watchBrand() { return this.brand; }, // Setter to set Watch dial set watchDial(dial) { this.dial = dial.toUpperCase(); } } output.innerHTML = "The Watch brand is - " + watch.watchBrand + "<br>"; watch.watchDial = "square"; output.innerHTML += "The Watch dial is - " + watch.dial; </script> </body> </html>
Output
The Watch brand is - Titan The Watch dial is - SQUARE
JavaScript Reserved words as property names
After ES5, you can use the reversed words as a property name in the object.
Example
In the below code, ‘delete’ is used as an object property name.
<html> <body> <div id = "output">The obj object is - </div> <script> const obj = { name: "Babo", delete: "Yes", } document.getElementById("output").innerHTML += JSON.stringify(obj); </script> </body> </html>
Output
The obj object is - {"name":"Babo","delete":"Yes"}
JavaScript "use strict"
The strict mode was also introduced in the ES5.
The strict mode allows you to overcome errors and write clear code. You can use the ‘use strict’ directive to declare the strict mode.
Example
In the below code, you can uncomment the ‘num = 43’ line and observe the error. The strict mode doesn’t allow developers to define the variables without using var, let, or const keywords.
<html> <body> <div id = "output">The value of num is: </div> <script> "use strict"; let num = 43; // This is valid // num = 43; // This is invalid document.getElementById("output").innerHTML += num + "<br>"; </script> </body> </html>
Output
The value of num is: 43
JavaScript String[number] access
Before ES5, the charAt() method was used to access the string character from a particular index.
After ES5, you can consider the string as an array of characters and access string characters from the specific index as you access array elements.
Example
<html> <body> <div id = "output1">The first character in the string is: </div> <div id = "output2">The third character in the string is: </div> <script> let str = "Apple"; document.getElementById("output1").innerHTML += str[0]; document.getElementById("output2").innerHTML += str[2]; </script> </body> </html>
Output
The first character in the string is: A The third character in the string is: p
JavaScript String trim()
The string.trim() method removes the whitespaces from both ends.
Example
In the below code, we used the string.trim() method to remove the whitespaces from the start and end of the str string.
<html> <body> <div id = "output"> </div> <script> let str = " Hi, I am a string. "; document.getElementById("output").innerHTML = str.trim(); </script> </body> </html>
Output
Hi, I am a string.
JavaScript Trailing commas
You can add a trailing comma (A comma after the last element) in the array and object.
Example
In the below code, we have added the trailing comma after the last object property and array element. The code runs without error and prints the output.
<html> <body> <div id = "demo1"> </div> <div id = "demo2"> </div> <script> const obj = { name: "Pinku", profession: "Student", } document.getElementById("demo1").innerHTML =JSON.stringify(obj); let strs = ["Hello", "world!",]; document.getElementById("demo2").innerHTML = strs; </script> </body> </html>
Output
{"name":"John","profession":"Student"} Hello,world!
Note – The JSON string doesn’t allow the trailing comma.
For example,
let numbers = '{"num1": 10,"num2": 20,}'; JSON.parse(numbers); // Invalid numbers ='{"num1": 10,"num2": 20}'; JSON.parse(numbers); // Valid
In ES5, mostly array and object-related methods are introduced.