Object prototypes in JavaScript

The blog provides the details on the usage of Object ProtoTypes in JavaScript. The Object Prototype allows the objects to acquire the properties and features from each other.  Each Object created in JavaScript is automatically assigned with prototype object. 

The Object Prototype was introduced through ECMAScript 2015 and before that it was not possible to access any object’s prototype. 

Why object prototype is required ?

The object prototype in JavaScript provides the inheritance by calling the object’s prototype which acts as a template to inherit the object’s methods and properties.

Using the prototype based approach, all objects which iterates with each other shares the same function and thus avoids the creation of copying the same function again.

The JavaScript Object is one of the JavaScript Data Types to store various keyed collections and complex entities. Whenever an object is created in JavaScript, it inherits the Default JavaScript Object properties and methods (defined in the Object.prototype)

Thus , Object.prototype.valueOf() , Object.prototype.toString() are available to each object that inherits from Object.prototype.

Object Prototype example

The below given is the object prototype example in JavaScript

<script>  
function Student(firstName, lastName, age, course) {
  this.firstName= firstName;
  this.lastName = lastName;
  this.age = age;
  this.course = course;
}
Student.prototype.fullName=function()  
  {  
    return this.firstName+" "+this.lastName;  
  } 
var student1=new Student("Mohit","Sharma", 28, "JavaScript");  
document.writeln(student1.fullName()+"<br>");  
document.writeln(student1.firstName()+"<br>"); 
document.writeln(student1.course()+"<br>"); 

</script>  

Here the Student1 inherits the object prototype properties from Student and Student inherits the object prototype properties from Object

Which means

Student1 -> Student -> Object

create() in object prototype

The below given is the example for create() used in object prototype

let student2 = Object.create(student1);

The create() allows to create a new object from the specified prototype object which means the student2 object is created using student1 as prototype object.

constructor property in object prototype

Every constructor function has a porotype property which points to the original object’s constructor property.

Let’s see the below example

let student3 = new student1.constructor('Rohit', 'Mehra', 26, 'JavaScript');
<script>  
function Student(firstName, lastName, age, course) {
  this.firstName= firstName;
  this.lastName = lastName;
  this.age = age;
  this.course = course;
}

Student.prototype.fullName=function()  
  {  
    return this.firstName+" "+this.lastName;  
  } 
var student1=new Student("Mohit","Sharma", 28, "JavaScript");  
document.writeln(student1.fullName()+"<br>");  
document.writeln(student1.firstName()+"<br>"); 
document.writeln(student1.course()+"<br>"); 

let student3 = new student1.constructor('Rohit', 'Mehra', 26, 'JavaScript');
document.writeln(student3.fullName()+"<br>");  
document.writeln(student3.firstName()+"<br>"); 
document.writeln(student3.course()+"<br>");

</script>  

The student3 object will print the values of the student1 object as it has inherited from student1

The constructor property allows you to return the name of the constructor it is an instance of

 student1.constructor.name

Browser Object Model (BOM) in JavaScript

The blog provides the details about the Browser Object Model in JavaScript . The Browser Object Model is supported by the browsers and not part of the JavaScript objects but it is used in the JavaScript programs to notify messages / alerts to the user.

window.alert("calling windows Object Model");  

Browser Object Model Types

The below given are the Browser Object Model Types which can be used in JavaScript

  • Windows Object Model
  • Screen Object Model
  • History Object Model
  • Navigator Object Model

Windows Object Model

The Windows Object Model provides the browser windows object to display user message similar to JavaScript alert messages.

Methods of Windows Object Model

The below given are the supported methods of Windows Object Model

Windows Object MethodMethod Description
alert()Windows method displays the alert box message with ok button.
confirm()Windows method displays the confirm dialog box message with
ok and cancel button.
prompt()Windows method displays a dialog box for user input
open()Windows method opens the new window.
close()Windows method closes the current window.
setTimeout()Windows method performs action like calling function, evaluating expressions etc. after specified time
Windows Object alert() Method examples
<script type="text/javascript">  
function welcomeUser(){  
 alert("Welcome to the oracleappshelp.com JavaScript Tutorial");  
}  
</script>  
<input type="button" value="click" onclick="welcomeUser()"/> 
Windows Object confirm() Method examples
<script type="text/javascript">  
function userfeedback(){  
var userInput= confirm("Do you like oracleappshelp.com Tutorials ?");  
if(userInput==true){  
alert("JavaScript Tutorial is awesome");  
}  
else{  
alert("Please add more examples");  
}  
  
}  
</script>  
  
<input type="button" value="User Feedback" onclick="userfeedback()"/>
Windows Object prompt() Method examples
<script type="text/javascript">  
function getUserName(){  
var userInput= prompt("Enter your Name ?");  
alert("Hello - "+userInput );  
  
}  
</script>  
  
<input type="button" value="click" onclick="getUserName()"/>
Windows Object setTimeout() Method examples
<script type="text/javascript">  
function display(){  
setTimeout(  
function(){  
alert("Message is displayed with after speciifed timeout")  
},1200);  
  
}  
</script>  
  
<input type="button" value="click" onclick="display()"/>  

History Object Model

The History Object Model provides the array of URLs which are visited by the user from the browser history.

History Object Model Methods

The below given are the methods for history object model

History Object MethodDescription
 forward()  Method loads the next page
 back() Method loads the previous page
 go() Method loads the page with given page number
History Object Model Method Examples

The below given methods can be invoked to get the browser history

history.forward();//loads next page  
history.go(2);// loads page with page number 2 
history.back(); //loads previous page  

Navigator Object Model

The Navigator Object Model allows to retrieve the browser information such as Application Name, Application Version , cookie details , user language , user agent details etc

Navigator Object Model Properties

The below given are the properties of Navigator Object Model

Navigator Object PropertyDescription
appNamemethod returns the application name
appVersionmethod returns the application version
appCodeNamemethod returns the code name
cookieEnabledmethod returns if cookie is enabled or not
userAgentmethod returns the user agent details
languagereturns language supported in Netscape and Firefox browsers
userLanguagereturns user language supported in IE browser
pluginsreturns the plugins supported in Netscape and Firefox browsers
systemLanguagereturns system language supported in IE browser
mimeTypes[]returns array of mime type supported in Netscape and Firefox browsers
platformreturns windows platform
onlinereturns if browser is online or not
Navigator Object Model Methods

The below given are the methods of Navigator Object Model

Navigator Object MethodDescription
javaEnabled()method checks if java is enabled.
taintEnabled()Deprecated. Method checks if taint is enabled
Navigator Object Model Method Examples
<script>  
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);  
document.writeln("<br/>navigator.appName: "+navigator.appName);  
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);  
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);  
document.writeln("<br/>navigator.language: "+navigator.language);  
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);  
document.writeln("<br/>navigator.platform: "+navigator.platform);  
document.writeln("<br/>navigator.onLine: "+navigator.onLine);  
</script>  

The output for Navigator Object Model

navigator.appCodeName: Mozilla
navigator.appName: Netscape
navigator.appVersion: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48
navigator.cookieEnabled: true
navigator.language: en-US
navigator.userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36 Edg/91.0.864.48
navigator.platform: Win32
navigator.onLine: true

Screen Object Model

The Screen Object Model allows to retrieve the browser information such as screen width, height, color depth , pixel depth, etc.

Screen Object Model Properties

The below given are the properties of Screen Object Model

Screen Object Property Description
widthmethod returns the screen width
heightmethod returns the screen height
availWidthmethod returns the available width
availHeightmethod returns the available height
colorDepthmethod returns the color depth
pixelDepthmethod returns the pixel depth.

Math Objects in JavaScript

The blog provides the details on the usage of JavaScript Math Object. The Math object in JavaScript helps in evaluating math operations.

Math Methods in JavaScript

The below given are the supported Math methods in JavaScript to perform math operations

Math MethodsMethod Description
abs()The method returns the absolute value of the given number.
abs() is a static method of Math Object.
acos()The method returns the arccosine of the given number in radians.
asin()The method returns the arcsine of the given number in radians.
atan()The method returns the arc-tangent of the given number in radians.
cbrt()The method returns the cube root of the given number.
ceil()The method returns a smallest integer value, greater than or equal to the given number.
cos()The method returns the cosine of the given number.
cosh()The method returns the hyperbolic cosine of the given number.
exp()The method returns the exponential form of the given number.
floor()The method returns largest integer value, lower than or equal to the given number.
hypot()The method returns square root of sum of the squares of given numbers.
log()The method returns natural logarithm of a number.
max()The method returns maximum value of the given numbers.
min()The method returns minimum value of the given numbers.
pow()The method returns value of base to the power of exponent.
random()The method returns random number between 0 (inclusive) and 1 (exclusive).
round()The method returns closest integer value of the given number.
sign()The method returns the sign of the given number
sin()The method returns the sine of the given number.
sinh()The method returns the hyperbolic sine of the given number.
aqrt()The method returns the square root of the given number
tan()The method returns the tangent of the given number.
tanh()The method returns the hyperbolic tangent of the given number.
trunc()The method returns an integer part of the given number.

Number Data Type in JavaScript

The blog provides the details on the usage of the JavaScript Number Data Type. The Number Data Type in JavaScript allows to a numeric value which can be further classified as : 

  • Regular Numbers
  • BigInt Numbers

Regular Numbers in JavaScript

The regular numbers follow the IEEE-754 Standard and allows to store the values in 64-bit format. As regular numbers supports both integer or floating numbers and thus also known as “double precision floating point numbers”.

Let’s understand the possible ways for representing the Number Value

Syntax for JavaScript Number

var numValue=new Number(value);  

The below given are few more examples of assinging the number values the variables

// assign integer value
var intNumber1=5;
//assign floating point value
var floatNumber2=42.24;
// assign exponent value, returns 100
var exponentNumber3=1e2;
// assign integer value by number object
var intAssignNumber4=new Number(123);

Syntactic Sugar in JavaScript Number

The JavaScript Number can be represented in many ways and “syntactic sugar” is one among them. It means the Number value can be represented with underscore (_) but when the value is evaluated it is ignored by the JavaScript Engine and reads the value without underscore.

let numValue = 1_23_456_7890;
// The JavaScript Engine reds the value as "1234567890"

The JavaScript allows the below constant values for Number Data Type

ConstantDescription
MIN_VALUEThe constant returns largest minimum value.
MAX_VALUEThe constant returns largest maximum value.
POSITIVE_INFINITYThe constant returns positive infinity, overflow value.
NEGATIVE_INFINITYThe constant returns negative infinity, overflow value.
NaNThe constant returns “Not a Number” value.

Number MethodsDescription
isFinite()The method returns if the given value is a finite number.
isInteger()The method returns if the given value is an integer.
parseFloat()The method returns converted string into a floating point number.
parseInt()The method returns converted string into an integer number.
toExponential()The method returns if the string that represents exponential notation of the given number.
toFixed()The method returns if the string that represents a number with exact digits after a decimal point.
toPrecision()The method returns if the string representing a number of specified precision.
toString()The method returns if the given number in the form of string.

JavaScript Number isFinite() example

<script>  
var numValue=11;  
// This returns TRUE as value is finite number
document.writeln(Number.isFinite(numValue));   //returnss True
</script>

JavaScript Number isInteger() example

<script>  
var numValue1=-25;  
var numValue2=25;  
 
document.writeln(Number.isInteger(numValue1));  //returnss True
document.writeln(Number.isInteger(numValue2));  //returnss True
</script>

JavaScript Number parseFloat() example

<script>  
var numValue1=-25;  
var numValue2=25.25;  
document.writeln(Number.parseFloat(numValue1)+"<br>");  //returns -25
document.writeln(Number.parseFloat(numValue2)+"<br>");  // returns 25.25
</script>

JavaScript Number parseInt() example

<script>  
var numValue1=-25;  
var numValue2=25.25;  
document.writeln(Number.parseInt(numValue1)+"<br>");  //returns -25
document.writeln(Number.parseInt(numValue2)+"<br>");  // returns 25
</script>

JavaScript Number toExponential () example

<script>  
var numValue1=-25;  
document.writeln(numValue1.toExponential());   // returns -2.5e+1
</script> 

JavaScript Number isInteger() example

<script>  
var numValue1=25.2552; 
document.writeln(a.toPrecision());   //returns 25
</script>

JavaScript Number toString() example

<script>  
var numValue1=-25;  
var numValue2=25.25;  
document.writeln(numValue1.toString() +"<br>");  //returns -25
document.writeln(numValue2.toString() +"<br>");  //returns 2.25
</script>

BigInt Numbers in JavaScript

The below given are the features of the JavaScript bigInt Numbers

  • A bigInt is a special numeric type supporting integers of arbitrary length.
  • A bigInt variable can be created by appending n to the end of an integer literal
  • A bigInt variable can be created by calling function BigInt that creates bigInt from strings, numbers etc
  • A bigInt does not allow to combine the bigInt variables with other data type variables
  • The bigInt Numbers performs the Math Operations similar to the regular Numbers
<script> 
alert(3n +4n );  // returns 7
alert(16n / 2n); // returns 8
</script>

JavaScript BigInt Number Example

<script> 
const bigIntNumValue = 1234512345123451234554321n;    
const bigIntNumAssigValue = BigInt("5432154321543215432154321");  

document.writeln(bigIntNumValue +"<br>");     //returns 1234512345123451234554321
document.writeln(bigIntNumAssigValue +"<br>"); //returns 5432154321543215432154321

</script> 

Boolean Data Type in JavaScript

The blog provides the details on the usage of JavaScript Boolean Data Type. The Boolean Data Type returns “true” or “false” based on the validation of the given condition

Boolean properties in JavaScript

PropertyDescription
constructorWhen used in constructor, it returns the reference of
Boolean function that created Boolean object.
prototypeallows the developer enables you to add properties and
methods in Boolean prototype.

Boolean Methods in JavaScript

MethodDescription
toSource()The method returns the source of Boolean object as a string.
toString()The method converts Boolean value into String.
valueOf()The method converts other data type into Boolean.

Boolean Syntax in JavaScript

Boolean flag =new Boolean(value);  

JavaScript Boolean Data Type Example

 <script>  
 var a =999;
 var b =998;
document.write(a<b);//returns false boolean value    
document.write(a> b);//returns true boolean value  
</script>

Set Object in JavaScript

The blog provides the details about the JavaScript Set object. The JavaScript Set object is used to store the elements with unique values supporting the primitive values or object references. 

  • The JavaScript Set object uses the Key-Value pair internally to store the elements. 
  • The JavaScript Set object does not support duplicate values
  • The JavaScript Set object allows the iteration of the stored elements in the insertion order.

Syntax for Java Script Set object

new Set([iterable])

Methods for JavaScript Set Object

Set MethodsDescription
add()Method allows to add the specified values to the Set object.
clear()Method allows to remove all the elements from the Set object.
delete()Method allows to delete the specified element from the Set object.
entries()Method allows to return an object of Set iterator with an array of [value, value] for each element.
forEach()Method allows to execute the specified function once for each value.
has()Method allows to indicate if the given Set object contains specified element.
values()Method allows to return an object of Set iterator with the values for each element.

JavaScript Set Object add() , clear() Example

<script>  
var subjects = new Set();  
subjects.add("English");  
subjects.add("Maths");  
subjects.add("Science");  
for (let elements of subjects) {  
 document.writeln(elements+"<br>");  
}
 
document.writeln("Size for Subject Set Object before clear() : "+ set.size+"<br>");  
set.clear();  
document.writeln("Size for Subject Set Object after clear(): "+set.size);   
</script> 

JavaScript Set Object add() , entries() , delete() example

<script>
var programming = new Set();  
programming.add("C").add("C++").add("Java");   
var itr=programming.entries();  
for(i=0;i<programming.size;i++)  
  {  
	document.writeln(itr.next().value+"<br>");  
  }  
 
document.writeln("Size for Programming Set Object before delete(): "+ set.size+"<br>");  
set.delete("C++");  
document.writeln("Size for Programming Set Object before delete(): "+set.size); 
</script>

JavaScript Set Object has() , value() example

<script>
var names = new Set();  
names.add("Robert").add("Matthew").add("John");
set.forEach(function display(value1,value2,set)   
{  
	document.writeln('key[' + value1 + '] = ' + value2+"<br>");  
})  
 document.writeln(names.has("Matthew"));    // returns true or false
}  
for(i=0;i<names.size;i++)  
  {  
	document.writeln(itr.next().value+"<br>");  
  }  
</script> 

Arrays in JavaScript

The blog describes the Array creation in JavaScript. An array is a group of element values. The JavaScript supports array creation in 3 ways

  • By using Array Literals
  • By creating Array Instance
  • By creating Array Constructor

JavaScript Array creation using Literals

The JavaScript allows to create array using literals. The array is defined with [ ] with the list of values. The below given is the example of array using literals

let student = ["Mohit", "Rohit", "Nitin"];
alert( student[0] ); // returns Mohit
alert( student[1] ); // returns Rohit
alert( student[2] ); // returns Nitin

Array allow to replace the element value at nth position

student[2] = 'John';

Array allows to add new element to an existing array object

student[3] = 'Robert';

Array length can be determined

alert( student.length ); // 3

An array can support mix of values

// mix of values
let student = [ '30', { name: 'Mohit Sharma' }, true, function() { alert('stuent is enrolled for the course'); } ];

// get object at index 1 
alert( student[1].name ); // Mohit Sharma

// get the function at index 3 
student[3](); // prints stuent is enrolled for the course

Empty array creation in JavaScript

JavaScript allows supports empty array as given below

let student = new Array();  // empty array using new Array()
let student = [];           // empty array using literals

Array creation using new keyword

The JavaScript allows to create object using new keyword

var student =new Array();  
<script>  
var count;  
var student = new Array();  
student[0] = "Mohit";  
student[1] = "Rohit";  
student[2] = "Vivek";  
  
for (count=0;count<student.length;count++){  
document.write(student[count] + "<br>");  
}  
</script> 

Array creation using constructor

The JavaScript allows to create object using constructor 

<script>  
var count;  
var student = new Array("Mohit", "Rohit", "Vivek");  
for (count=0;count<student.length;count++){  
document.write(student[count] + "<br>");  
}  
</script> 
MethodsDescription
 concat() method allows to concatenate two or more arrays
Syntax: array.concat(array1,array2,….,arrayn)  
Return: Combined values of all arrays
 copywithin()method copies the part of the array elements and returns the modified array
Syntax: array.copyWithin(target, start, end)  
Return: the modified array elements
 entriesmethod allows to iterate over each key/value pair in an array
Syntax: array.entries()  
Return: the newly created array iterator object
 every()method validates if all the array elements are satisfying the provided function conditions.
Syntax: array.every(callback(currentvalue,index,arr),thisArg) 
Return: Boolean value
 flat()The method concatenates all the elements of the given multidimensional array and flattens it into 1 dimensional array recursively till the specified depth.
Syntax: arr.flat(<depth>);
Return: new array containing all the sub-array elements of the multi dimensional array
 flatMap()method maps array elements via mapping function and results into a new array.
Syntax: arr.flatMap(function callback(currentValue[ , index[ , array]]) 
Return: new array where each element is the result of the callback function
 fill()method fills array elements with static values
Syntax: arr.fill(value[, start[, end]])  
Return: the modified array
 from()method creates a new array with copied element of another array
Syntax: Array.from(object,map_fun,thisArg);
Return: return new array object
 filter()method returns the new array containing the elements that pass the provided function conditions.
Syntax: array.filter(callback(currentvalue,index,arr),thisArg)
Return: New array with filtered array elements
 find()method returns the value of the first array element that satisfies the specified condition
 findIndex()method returns the index value of the first element that satisfies the specified condition
 forEach()method invokes the provided function once for each element of an array
 includes()method validates if given array contains the specified element
 indexOf()method searches the specified array element returns the index of the first match
 isArray()method validates if the passed value is an array
 join()method joins the array elements as a string
 keys()method creates an iterator object that contains loops through the given array keys
 lastIndexOf()method searches the specified element in the given array and returns the index of the last match
 map()method calls the specified function for every array element and returns the new array
 of()method creates a new array from a variable number of arguments, holding any type of argument
 pop()method removes and returns the last array element
 push()method adds one or more elements to the end of an array
 reverse()method reverses the array elements
reduce(function,initial)array executes a provided function for each value from left to right and reduces the array to a single value
 reduceRight()array executes a provided function for each value from right to left and reduces the array to a single value
 some()method validates if any array element passes the test of the implemented function
 shift()method removes and returns the first element of an array
 slice()method returns a new array containing the copy of the part of the given array
 sort()method returns the element of the given array in a sorted order
 splice()method add/remove elements to/from the given array
 toLocaleString()method returns a string containing all the elements of a specified array
 toString()method converts the elements of a specified array into string form, without affecting the original array
 unShift()method adds one or more elements in the beginning of an array
 values()method creates a new iterator object carrying values for each index in the array

JavaScript Array flat() example

// Array flat() example	
<script>
var teachers=['Angela','Cameron',['Stephnie','Brida']];
var newTeachersArr=teachers.flat(); //using array flat() method  
//create a new array with one dimesnioanl array
document.write("usgae of array flat() :  "+newTeachersArr);
</script>

JavaScript Array entries() example

  <script>  
	var subjects =['English','Math','Science','French'];  
    var itr=subjects.entries();  
    for(var i of itr) 
    {  
        document.write(i+"</br>");  
    }  
  </script> 

JavaScript Array fill() example

<script>  
var subjects =['English','Math','Science','French'];  
var result=subjects.fill("Computer Science");  
document.writeln(arr);  
</script> 

JavaScript Array from() example

<script>  
var strText=Array.from("Converts String to Array of Alphabet"); //The string will get converted to an array.  
document.write("Array contains: <br>" +strText);  
 </script>  

JavaScript Array concat(), entries() example

<script>  
// Array example for concat() 
var student1 = ["Mohit", "Rohit", "Vivek"];  
var student2 = ["John", "Smith", "Robert"]; 
var totalStudents=student1.concat(student2);  
document.writeln(totalStudents); 

var itr=totalStudents.entries();  
    document.write("usgae of array entries() :"+"<br>");  
      for(var e of itr) //for loop using var.  
    {  
        document.write(e+"</br>");  
    }  }  
</script> 

Data Types in JavaScript

The blog describes the usage of JavaScript Data Types. Data Types are provided to store the different types of values to be used in the program.

JavaScript Data Types

The Data Types in JavaScript can be classified into 2 types:

  • Primitive JavaScript Data Type
  • Non-Primitive JavaScript Data Type (also called as Reference Data Types)

Primitive JavaScript Data Types

The Primitive JavaScript Data Type can be further classified as given below

Data TypeDescription
Stringstores string values
Numberstores numeric values
Booleanstores boolean values (true /false)
Undefinedstores undefined value
Nullstores NULL value

Non-Primitive JavaScript Data Types

The Non-Primitive JavaScript Data Type can be further classified as given below

Data TypeDescription
Objectstores an object
Arraystores group of similar values as an Array
RegExpstores regular expression value
var num1;   // represents an undefined variable 
num1 = 10;  // represents a variable with numeric value   
num1 = 20;  // reassignment of variable value 

(num1 == num2)  //returns false 

num1 ="Some Text";  // variable num1 now represents a String Value "Some Text"

num2 = "Added With" // variable represents a String Value "Added With" 

num3 = num1 + 40   // Variable represents a string value "Some Text40"

num4 = num2 + num3  // Variable represents a string value "Added With Some Text40"

Object creation in JavaScript

The blog describes how to create objects in JavaScript. The JavaScript object is an entity  with state and behavior i.e. defines properties and methods. The objects in JavaScript can be created as given below

  • By using Literals and Properties
  • By creating an instance of an object
  • By creating an Object Constructor

JavaScript Object creation using Literals and Properties

An object can store the keyed collection of data. An object is created using Literals and properties . An object is surrounded with { } with the list of properties where a property is a key: value pair . A key is also called as property name.

Lets understand it with further examples

JavaScript supports creation of empty object as given below using literals and new Object ()

let student = new Object(); // "object constructor" syntax
let student = {};           // "object literal" syntax

Now lets consider another example where a student object is created and property name (key) and value is provided

let student = {     		// where student is an object
    studentId: 101			//where key "StudentId" store value as 101
    name: "Mohit Sharma",  	// where key "name" store value "Mohit Sharma"
    age: 30        			// where key "age" stores values as 30
	
	alert( student.studentId );     // returns 101
	alert( student.name ); 			// returns "Mohit Sharma"
	alert( student.age ); 			// returns 30
};

In the student object, we have define 3 properties

  1. studentId : where property name / key “StudentId” store value as 101
  2. name : where property name / key “name” store value “Mohit Sharma”
  3. age: where property name / key “age” stores values as 30

Remove Property from JavaScript Object

The created object properties can also be removed using the delete command

// Delete age property from the student object
delete student.age;

JavaScript Object creation through object instance

The object instance can be crated using the below given syntax

// new is used to create a new object
var objectname=new Object();  
<script>  
var student =new Object();  
student.studentId=101;  
student.name="Mohit Sharma";  
student.age= 30;  
document.write(student.studentId+" "+student.name+" "+student.age);  
</script>

JavaScript Object creation using constructor

The JavaScript objects can be created using the constructor as per the below given example.

<script>  
function student(studentId,name,age){  
this.studentId=studentId;  
this.name=name;  
this.age=age;  
}  
s=new student(101,"Mohit Sharma",30);  
  
document.write(s.studentId+" "+s.name+" "+s.age);  
</script>  

Control Statements in JavaScript

The blog describe the usage of Control Statement ( if ..else, Switch , loop) in JavaScript code. The control statements are useful when the code is required to be executed when a particular condition is met or justified or to be executed in loop for a particular interval or execution of code from available expressions. 

JavaScript Control Statement Types

The control statements in JavaScript can be broadly classified into 3 types

  • If -else statements
  • Switch statements
  • Loop

If Statement usage in JavaScript

The if-else statements in JavaScript is required when the code is requried to be executed when a conditon is either true or false. The if statements can be divided into 3 types

  • If statement : executes if the given expression is True
  • If-else statement : executes the first statement if the given expression is True, else the second statement
  • If-else-if statement : executes the statement where the expression is True from the given multiple condition

Syntax for If statement

if(expression1){  
//code executes when if expression1 is true  
}  
else if(expression2){  
//content to be evaluated if expression2 is true  
}  
else if(expression3){  
//content to be evaluated if expression3 is true  
}  
else{  
//content to be evaluated if no expression is true  
}  
<script>  
var x=100;  
if(x==98){  
		document.write("The value of x is 98");  
}  
else if(x==105){  
		document.write("The value of x is 105");
}  
else if(x==100){  
	document.write("The value of x is 100");
}  
else{  
	document.write("The value of x is other than 98,100 or 105");
}  
</script> 

Switch Statement usage in JavaScript

The switch statement is to be used when only one condition is true among the given multiple expressions.

Syntax for Switch statement

switch(expression){  
case value1:  
 //code executes when value1 is matched with expression  
 break;  
case value2:  
 //code executes when value2 is matched with expression    
 break;  
......  
  
default:   
 //code executes when No Value is matched with expression    
}  
<script>  
var color ="Red";
var setColorValue;  
switch(color){  
case 'Blue':  
setColorValue =" The selected color is Blue";
break;  
case 'Orange':  
setColorValue =" The selected color is Orange";  
break;  
case 'Red':  
 setColorValue =" The selected color is Red";
break;  
default:  
setColorValue =" The given color is other than Red, Blue or Orange"; 
}  
document.write(setColorValue);  
</script>  

Loop Statement usage in JavaScript

The Loop statements are useful when required when the program is to be iterated using for, while, do while or for-in loops. The Loop statements are classified into 4 types:

  • for loop : used when the element in the program is to be iterated for fixed number of times
  • while loop : used when the element in the program is to be iterated for infinite number of times till the expression or given condition is met.
  • do-while loop : similar to while loop for infinite number of times till the expression or given condition is met or not. The do while loop executes at least for 1 iteration
  • for-in loop: used to iterate the properties of an object
// example for   For Loop
<script>  
for (x=10; x<=20; x++)  
{  
document.write(x + "<br/>")  
}  
</script> 
//example for While loop
<script>  
var x=10 ;
while (x<=20)  
{  
document.write(x + "<br/>");  
x = x +5;  
}  
</script>  
//example for   do..while loop
<script>  
var x=10;  
do{  
document.write(x + "<br/>");  
x++;  
}while (x<=20);  
</script>

Operator Types in JavaScript

The below describes the usage of operators in JavaScript. The JavaScript provides the below given operators which allows to perform the operations on the operands to evaluate the variable value at run-time. 

  • Arithmetic Operators
  • Comparison /Relational Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Special Operators

Arithmetic Operators in JavaScript

The below given are the Airthmetic operators in the JavaScript

OperatorDescription
+Addition
Subtraction
*Multiplication
**Exponentiation
/Division
%Modulus
++Increment
Decrement

Relational Operators in JavaScript

The below given are the Comparison / Relational Operators in JavaScript

OperatorDescription
==equal to
===equal value and equal type
!=not equal
!==not equal value or not equal type
>greater than
<less than
>=greater than or equal to
<=less than or equal to
?ternary operator

Bitwise Operators in JavaScript

The below given are the Bitwise Operators in JavaScript

OperatorDescription
&AND
|OR
~NOT
^XOR
<<Zero fill left shift
>>Signed right shift
>>>Zero fill right shift

Logical Operators in JavaScript

The below given are the Logical Operators in JavaScript

OperatorDescription
&& Logical AND
||Logical OR
! Logical NOT

Assignment Operators in JavaScript

The below given are the assignment operators in JavaScript

OperatorExample
=x = y
+=x += y
-=x -= y
*=x *= y
/=x /= y
%=x %= y
**=x **= y

create variables in JavaScript

The blog describes the creation of JavaScript variables . The variables in JavaScript are like containers which helps in sorting the data values. 

How to define a JavaScript Variable ?

The below points need to be considered when creating JavaScript variables

  • A variable name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign
  • Digits can be used after the first letter of the variable name
  • A variable name is case sensitive

JavaScript Variable Types

The JavaScript variables can be broadly classified into 2 types

  • Local Variables : The local variables are defined within a specific block or function and their scope also remains within the block or function defined.
  • Global Variables: The global variables are those variables which are defined outside the block or function so that they can be accessible in any block or function to execute the value at run-time
<script>  
var length=10;       // global variable for length                     
var height=20;       // global variable for height
function area(){ 
var area= length * height  // local variable to calculate area
document.writeln(area);  
}  
</script> 

ES2015 Keyword let in JavaScript

The JavaScript provides the Function Scope and Global Scope but in 2015 ES2015 introduced 2 new JavaScript keywords – let and const.

The keyword let and keyword const allows to create the Block Scope variables and constants in JavaScript. The below given example clarifies how Block Scope is different from Function Scope and Global Scope.

Global Scope: The variables which are defined outside the function provides global scope due to its accessibility

Function Scope: The local variables which are defined within a function provides Function scope within the function only .

Variable Re-declaration: If the variables defined in the Function Scope are redeclared outside the function with different value, then it allows to update/ override the value for that variable. In the below given example , the local variable and global variables are defined currently and are within their scope but redeclaration of carColor changes the color to “grey”

<script>  
var carModel ="Toyota" ;  // Global Variable declaration 
var carColor = "Grey";    // local variable value ovrrides
function carFeatures(){ 
var carCylinder = "4";    // local variable / function scope
var carAirBags =  "2";    // local variable / function scope
var carColor = "Red";     // local variable / function scope
 }  
// Redeclaring same variable outside function scope, changes carColor values to "Red"


</script> 

Block Scope provides the solution to the variable redeclaration problem as this might lead to issues if not properly handled. ES2015 provides the keyword let which helps in creating local variables who access remains within the scope of the function.  

<script>  
var carModel ="Toyota" ;  // Global Variable declaration 
var carColor = "Grey";    // consider 

function carFeatures(){ 
var carCylinder = "4";    // local variable / function scope
var carAirBags =  "2";    // local variable / function scope
let carColor = "Red";     // local variable / function scope
 }  
// carColor remains as  "grey" //access global variable

</script> 

Thus when used var, the variable declared in the Function Scope redeclares the variable value outside the function.

When used keyword let, the variable declared in the Function Scope does not redeclare the variable outside the function

ES2015 Keyword Const in JavaScript

ES2015 Keyword Const does not provide the constant value rather it provides the constant reference to the value which means we cannot change the constant primitive values but it allows to change the constant properties for it. 

The below given example is NOT ALLOED as it changes the constant TV Array elements

const tv = {brand:"Samsung", model:"Plasma", color:"Black"};
 / Redefinifn the Car elements for the Const Car Object is not allowed
tv = {brand:"Samsung", model:"QLED", color:"Grey"};

The below example IS ALLOWED as it adds New element without changing the constant TV array elements

 const tv = {"Samsung", "Sony", "TCL"};
 car[2] = "Panasonic" // allowed, as it adds the New element wihtout changing the exisitng TV Array elements

The keyword Const can be used to declare the variable or redeclare the variables. The below points need to be considered when using const for declaring variables

Variable DeclarationScope
 Redeclaration or reassignment for var or
let variable to const within the same scope
( local or global)
NOT ALLOWED 
 Redeclaration or reassignment for const
variable within the same scope ( local or
global)
 NOT ALLOWED
Redeclaration or reassignment for const
variable in another scope
 ALLOWED