JavaScript
Object orientation
What is a Class?
You can think of a class like a blueprint of a house. A class is not a real world object but we
can create objects from a class. It is like an template for an object.
We can create classes using the class keyword which is reserved keyword in JavaScript.
Classes can have their own properties and methods. We will study how to create a class in
detail shortly. This is just a high level overview of a class.
What is an Object?
An object is an instance of a class. Now with the help of the house class we can construct a
house. We can construct multiple houses with the help of same house class.
Consider a Student class. Student can have properties like name, age, standard and so on, and
functions like study, play, and do home work.
class Student{
// Data (Properties)
Name;
Age;
Standard;
//Method (Action)
study(){
}
Play(){
}
doHomeWork(){
}
}
There are 4 main principles in OOP, and they are:
Abstraction
Encapsulation
Inheritance
Polymorphism
What Does Abstraction Mean in OOP?
Abstraction means hiding certain details that don't matter to the user and only showing
essential features or functions.
For example, take a cell phone. We don't show details
like verifyTemperature(), verifyVolt(), frontCamOn(), frontCamOff() and so on. Instead we
provide essential features which matter to user like camera(), volumeBtn(), and others.
What Does Encapsulation Mean in OOP?
Encapsulation means keeping properties and methods private inside a class, so that they are
not accessible from outside that class.
This will keep code that's outside the class from accidentally manipulating internal methods
and properties.
What Does Inheritance Mean in OOP?
Inheritance makes all properties and methods available to a child class. This allows us to
reuse common logic and to model real-world relationships. We will discuss inheritance in
further section of this article with practical example.
What Does Polymorphism Mean in OOP?
Polymorphism means having different and many forms. We can overwrite a method inherited
from a parent class.
For ex:
class User{
email
password
login(providedPassword){
// Login User
}
checkMessage(){
// Check any new message
}
}
------------------------------------------Child class: Admin class--------------
// Not actual JavaScript syntax
class Admin inherit User{
// email is Inherited Property
// password is Inherited Property
permissions // Own Property
// Inherited Method
login(providedPassword){
// Different Login User
}
// Inherited Method
checkMessage(){
// Check any new message
}
// Own Method
chechStats(){
// Check Stats
}
}
The Login method in Admin is different from the inherited class User (Method overriding).
General syntactic characteristics :
all JavaScript scripts will be embedded in HTML documents
Either directly, as in
<script type = "text/javaScript">
-- JavaScript script -
</script>
For ex:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
Or
Indirectly, as a file specified in the src attribute of <script>, as in
<script type = "text/javaScript"
src = "myScript.js">
</script>
For ex:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src=" myScript.js ">
</script>
</body>
</html>
Language Basics:
Identifier form:
begin with a letter or underscore, followed by any number of letters, underscores, and digits
Case sensitive
25 reserved words, plus future reserved words
Comments: both // and /* ... */
Scripts are usually hidden from browsers that do not include JavaScript interpreters by
putting them in special comments
<!--
-- JavaScript script -
//-->
Also hides it from HTML validators
Semicolons can be a problem They are "somewhat" optional.
You can omit the semicolon between two statements if they are written on separate
lines.
You can omit a semicolon at the end of a program or if the next token in the program
is a closing curly brace }.
You should put each statement on its own line whenever possible and terminate each
statement with a semicolon.
Primitives:
JavaScript is a dynamically typed language. It means that a variable doesn’t associate with a
type. In other words, a variable can hold a value of different types.
For example:
let counter=120;// counter is a number
counter=false;//counter is now boolean
counter=”welcome”;//counter is now a string
The undefined type:
The undefined type is a primitive type that has only one value undefined. By default, when a
variable is declared but not initialized, it is assigned the value of undefined.
For ex:
let counter;
console.log(counter);//undefined
The null type:
The null type is the second primitive data type that also has only one value null.
For example:
let ob=null;
console.log(typeof ob);//object
The typeof null returns object is a known bug in JavaScript. A proposal to fix this was
proposed but rejected. The reason was the that fix would break a lot of existing sites.
JavaScript defines that null is equal to undefined as follows:
console.log(null==undefined);//true
The number type
JavaScript uses the number type to represent both integer and floating-point numbers.
The following statement declares a variable and initializes its value with an integer:
let num=100;
To represent a floating-point number, you include a decimal point followed by at least one
number.
For example:
let price=99.12;
let discount=0.5;
Note: JavaScript automatically converts a floating-point number into an integer number if the
number appears to be a whole number.
The reason is that Javascript always wants to use less memory since a floating-point value
uses twice as much memory as an integer value.
NaN
NaN stands for Not a Number. It is a special numeric value that indicates an invalid number.
For example, the division of a string by a number returns NaN.
For ex:
console.log(‘a’/2);
The NaN has two special characteristics:
Any operation with NaN returns NaN.
The NaN does not equal any value, including itself.
For ex:
console.log(NaN /2);// NaN
console.log(NaN == NaN);//false
The string type
In JavaScript, a string is a sequence of zero or more characters. A string literal begins and
ends with either a single quote(') or a double quote (").
A string that begins with a double quote must end with a double quote. Likewise, a string that
begins with a single quote must also end with a single quote:
let greeting=’Hi’;
let painting=”Excellent”;
The boolean type
The boolean type has two literal values: true and false in lowercase. The following example
declares two variables that hold the boolean values.
let inProgress=false;
let completed=true;
console.log(typeof completed);//Boolean
The symbol type
JavaScript added a primitive type in ES6: the symbol. Different from other primitive types,
the symbol type does not have a literal form.
To create a symbol, you call the Symbol function as follows:
let s1=Symbol();
The Symbol function creates a new unique value every time you call it.
Console.log(Symbol()==Symbol());//false
The bigint type
The bigint type represents the whole numbers that are larger than 253 – 1. To form
a bigint literal number, you append the letter n at the end of the number:
let pageView=98048405844850483;
Console.log(typeof(pageView));//bigint
The object type
In JavaScript, an object is a collection of properties, where each property is defined as a key-
value pair.
The following example defines an empty object using the object literal syntax:
let emptyoblect={};
The following example defines the person object with two
properties: firstName and lastName.
Let person={
firstName: ’Virat’,
lastName: ‘Kohli’
};
To access a object’s property, you can use:
1- The dot notation (.)
2- The array-like notation ([]).
The following example uses the dot notation (.) to access
the firstName and lastName properties of the person object.
console.log(person. firstName);
console.log(person. lastName)
Expressions:
JavaScript’s expression is a valid set of literals, variables, operators, and expressions that
evaluate a single value that is an expression. This single value can be a number, a string, or a
logical value depending on the expression.
For ex:
// Illustration of function* expression
// use of function* keyword
function* func() {
yield 1;
yield 2;
yield 3;
yield " - Geeks";
}
let obj = '';
// Function calling
for (const i of func()) {
obj = obj + i;
}
// Output
console.log(obj);
Output:
123 – Geeks
The yield* expression in JavaScript is used when one wants to delegate some other iterable
object. This function iterates over the particular operand and yields each value that is returned
by it.
Syntax:
yield* expression;
Return Value: It returns the iterable object.
For ex:
function* func1() {
yield "a";
yield "b";
yield* func3();
}
function* func3() {
yield "geeks";
}
function* func2() {
yield* func1();
yield 4/2;
yield 5/2;
}
const it = func2();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
Output:
{value: 'a', done: false}
{value: 'b', done: false}
{value: 'geeks', done: false}
{value: 2, done: false}
{value: 2.5, done: false}
{value: undefined, done: true}
Screen Output & Keyboard Input
The JavaScript model for the HTML document is the Document object
The model for the browser display window is the Window object
o The Window object has two properties, document and window, which refer to
the document and window objects, respectively
The Document object has a method, write, which dynamically creates content
o The parameter is a string, often concatenated from parts, some of which are
variables
e.g., document.write("Answer: " + result + "<br />");
The Window object has three methods for creating dialog boxes alert,
confirm, and prompt
The default object for JavaScript is the Window object currently being displayed, so
calls to these methods need not include an object reference.
1. alert("Hey! \n");
Parameter is plain text, not HTML
Opens a dialog box which displays the parameter string and
an OK button
A variable containing some value, can also be passed as a parameter.
Syntax: alert();
For ex:
<DOCTYPE html>
<html>
<head>
<title>
Confirm
</title>
</head>
<body>
<script type="text/javascript">
var operand1=200;
var operand2=100;
var resultadd = operand1+operand2 ;
alert(resultadd);
</script>
</body>
</html>
2. confirm("Do you want to continue?");
Opens a dialog box and displays the parameter and two
buttons, OK and Cancel
Syntax: confirm();
For ex:
<DOCTYPE html>
<html>
<head>
<title>
Confirm
</title>
</head>
<body>
<script type="text/javascript">
var c = "Hey";
confirm(c);
</script>
</body>
</html>
2. prompt("What is your name?", "");
Opens a dialog box and displays its string parameter, along with a text
box and two buttons, OK and Cancel
Syntax: prompt();
The second parameter is for a default response if the user
presses OK without typing a response in the text box (waits for OK)
For ex:
<DOCTYPE html>
<html>
<head>
<title>
Prompt
</title>
</head>
<body>
<script type="text/javascript">
var a = prompt("What is the value of 'a'? \n", "");
</script>
</body>
</html>
JS Control Flow Or Condition
JavaScript if Statement
We use the if keyword to execute code based on some specific condition.
The syntax of if statement is:
if (condition) {
// block of code
}
The if keyword checks the condition inside the parentheses ().
If the condition is evaluated to true, the code inside { } is executed.
If the condition is evaluated to false, the code inside { } is skipped.
Example:
// Program to check if the number is positive
const number = 6;
// check if number is greater than 0
if (number > 0) {
// the body of the if statement
console.log("positive number");
}
console.log("nice number");
JavaScript else Statement
We use the else keyword to execute code when the condition specified in the preceding if statement
evaluates to false.
The syntax of the else statement is:
if (condition) {
// block of code
// execute this if condition is true
}
else {
// block of code
// execute this if condition is false
}
The if...else statement checks the condition and executes code in two ways:
If condition is true, the code inside if is executed. And, the code inside else is
skipped.
If condition is false, the code inside if is skipped. Instead, the code inside else is
executed.
Example :
let age = 17;
// if age is 18 or above, you are an adult
// otherwise, you are a minor
if (age >= 18) {
console.log("You are an adult");
else {
console.log("You are a minor");
// Output: You are a minor
JavaScript else if Statement
We can use the else if keyword to check for multiple conditions.
The syntax of the else if statement is:
// check for first condition
if (condition1) {
// if body
}
// check for second condition
else if (condition2){
// else if body
}
// if no condition matches
else {
// else body
}
// rating of 2 or below is bad
// rating of 4 or above is good
// else, the rating is average
if (rating <= 2) {
console.log("Bad rating");
}
else if (rating >= 4) {
console.log("Good rating!");
}
else {
console.log("Average rating");
}
// Output: Good rating!
Nested if...else Statement:
When we use an if...else statement inside another if...else statement, we create a nested
if...else statement.
For example:
let marks = 60;
// outer if...else statement
// student passed if marks 40 or above
// otherwise, student failed
if (marks >= 40) {
// inner if...else statement
// Distinction if marks is 80 or above
if (marks >= 80) {
console.log("Distinction");
}
else {
console.log("Passed");
}
}
else {
console.log("Failed");
}
// Output: Passed
JavaScript for loop :
In JavaScript, the for loop is used for iterating over a block of code a certain number of
times.
for (initialsation; condition;increament) {
// for loop body
}
Example 1: Print Numbers From 1 to 5
for (let i = 1; i < 6; i++) {
console.log(i);
}
Output
1
2
3
4
5
Iteration Variable Condition: i < 6 Action
1 is printed.
st
1 i=1 true i is increased to
2.
2 is printed.
2nd i=2 true
i is increased to 3.
3 is printed.
3rd i=3 true
i is increased to 4.
4 is printed.
4th i=4 true
i is increased to 5.
5 is printed.
5th i=5 true
i is increased to 6.
6th i=6 false The loop is terminated.
JavaScript while and do...while Loop:
JavaScript while Loop
The while loop repeatedly executes a block of code as long as a specified condition is true.
The syntax of the while loop is:
while (condition) {
// body of loop
}
1. The while loop first evaluates the condition inside ( ).
2. If the condition evaluates to true, the code inside { } is executed.
3. Then, the condition is evaluated again.
4. This process continues as long as the condition evaluates to true.
5. If the condition evaluates to false, the loop stops.
Example 1: Display Numbers From 1 to 3
// initialize variable i
let i = 1;
// loop runs until i is less than 4
while (i < 4) {
console.log(i);
i += 1;
}
Run Code
Output
1
2
3
Here is how the above program works in each iteration of the loop:
Condition: i <
Variable Action
4
i=1 true 1 is printed. i is increased to 2.
i=2 true 2 is printed. i is increased to 3.
i=3 true 3 is printed. i is increased to 4.
i=4 false The loop is terminated.
JavaScript do...while Loop
The do...while loop executes a block of code once, then repeatedly executes it as long as the
specified condition is true.
The syntax of the do...while loop is:
do {
// body of loop
} while(condition);
Example 3: Display Numbers from 3 to 1
let i = 3;
// do...while loop
do {
console.log(i);
i--;
} while (i > 0);
Output
3
2
1
JavaScript break Statement
The break statement terminates the loop immediately when it's encountered
if (i == 3) {
break;
}
console.log(i);
}
Run Code
Output
1
2
JavaScript continue Statement:
The continue statement skips the current iteration of the loop and proceeds to the next
iteration.
/ display odd numbers
for (let i = 1; i <= 5; i++) {
// skip the iteration if i is even
if (i % 2 == 0) {
continue;
}
console.log(i);
}
// Output:
// 1
// 3
// 5
JavaScript switch...case Statement:
The JavaScript switch...case statement executes different blocks of code based on the value of
a given expression.
Syntax of the switch...case Statement
switch (expression)
{
case value1:
// code block to be executed if expression matches value1
break;
case value2:
// code block to be executed if expression matches value2
break;
...
default:
// code block to be executed if expression doesn't match any case
}
let day = 3;
let activity;
switch (day) {
case 1:
console.log("Sunday");
break;
case 2:
console.log("Monday");
break;
case 3:
console.log("Tuesday");
break;
case 4:
console.log("Wednesday");
break;
case 5:
console.log("Thursday");
break;
case 6:
console.log("Friday");
break;
case 7:
console.log("Saturday");
break;
default:
console.log("Invalid Day");
}
Output
Tuesday
Difference between While and Do-While Loop
Parameter While Do-While
Loop body is executed, and
Loop body is executed after the
Definition then the given condition is
given condition is evaluated.
checked.
Variables are initialized before the Variables may initialize after
Variables initialized
execution of the loop. the loop.
Loop Type Entry Control Loop Exit Control Loop.
Semicolon is not used as a part of Semicolon is used as a part of
Semicolon
the syntax. the syntax.
while(condition){ do{
Syntax // loop body // loop body
} } while (condition);
JavaScript Objects:
JavaScript object is a variable that can store multiple data in key-value pair.
Create JavaScript Objects
The syntax of JavaScript object is:
const objectName = {
key1: value1,
key2: value2,
...,
keyN: valueN
};
Here,
objectName - Name of the object.
key1: value1 - The first key-value pair.
key2: value2 - The second key-value pair.
keyN: valueN - The Nth key-value pair.
Each key-value pair has a colon : between them and is separated by a comma ,.
Access Object Properties
You can access the value of a property by using its key.
const dog = {
name: "Rocky",
};
// access property
console.log(dog.name);
JavaScript Array
An array is an object that can store multiple values at once.
const age = [17, 18, 15, 19, 14];
In the above example, we created an array to record the age of five students.
Why Use Arrays?
Arrays allow us to organize related data by grouping them within a single variable.
Suppose you want to store a list of fruits. Using only variables, this process might look like
this:
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Orange";
Here, we've only listed a few fruits. But what if we need to store 100 fruits?
For such a case, the easiest solution is to store them in an array.
let fruits = ["Apple", "Banana", "Orange", ...];
Create an Array
We can create an array by placing elements inside an array literal [], separated by commas.
For example,
const numbers = [10, 30, 40, 60, 80];
Here,
numbers - Name of the array.
[10, 30, 40, 60, 80] - Elements of the array.
JavaScript Date and Time
In JavaScript, date and time are represented by the Date object. The Date object provides the
date and time information and also provides various methods.
Creating Date Objects
There are four ways to create a date object.
new Date()
new Date(milliseconds)
new Date(Date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date()
You can create a date object using the new Date() constructor. For example,
const timeNow = new Date();
console.log(timeNow); // shows current date and time
Output
Mon Jul 06 2020
Here, new Date() creates a new date object with the current date and local time.
JavaScript Date Methods
There are various methods available in JavaScript Date object.
Method Description
Returns the numeric value corresponding to the current time (the
now() number of milliseconds elapsed since January 1, 1970 00:00:00
UTC)
getFullYear() Gets the year according to local time
getMonth() Gets the month, from 0 to 11 according to local time
getDate() Gets the day of the month (1–31) according to local time
getDay() Gets the day of the week (0-6) according to local time
getHours() Gets the hour from 0 to 23 according to local time
getMinutes Gets the minute from 0 to 59 according to local time
getUTCDate() Gets the day of the month (1–31) according to universal time
setFullYear() Sets the full year according to local time
setMonth() Sets the month according to local time