Professional Documents
Culture Documents
Web Unit3 (Nep)
Web Unit3 (Nep)
UNIT III
Introduction to javaScript
Features of JavaScript
According to a recent survey conducted by Stack Overflow, JavaScript is the most popular
language on earth.With advances in browser technology and JavaScript having moved into
the server with Node.js and other frameworks, JavaScript is capable of so much more. Here
are a few things that we can do with JavaScript:
JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
Functions in JS are objects. They may have properties and methods just like other
objects. They can be passed as arguments in other functions.
Can handle date and time.
Performs Form Validation although the forms are created using HTML.
No compiler is needed.
Applications of JavaScript
Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
Web Applications: With technology, browsers have improved to the extent that a
language was required to create robust web applications. When we explore a map in
Google Maps then we only need to click and drag the mouse. All detailed view is just a
click away, and this is possible only because of JavaScript. It uses Application
Programming Interfaces(APIs) that provide extra power to the code. The Electron and
React are helpful in this department.
Server Applications: With the help of Node.js, JavaScript made its way from client to
server and Node.js is the most powerful on the server side.
Games: Not only in websites, but JavaScript also helps in creating games for leisure.
The combination of JavaScript and HTML 5 makes JavaScript popular in game
development as well. It provides the EaseJS library which provides solutions for
working with rich graphics.
Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This framework
works for applications that require the Internet for their functioning.
Art: Artists and designers can create whatever they want using JavaScript to draw on
HTML 5 canvas, and make the sound more effective also can be used p5.js library.
Machine Learning: This JavaScript ml5.js library can be used in web development by
using machine learning.
Mobile Applications: JavaScript can also be used to build an application for non-web
contexts. The features and uses of JavaScript make it a powerful tool for creating
mobile applications. This is a Framework for building web and mobile apps using
JavaScript. Using React Native, we can build mobile applications for different operating
systems. We do not require to write code for different systems. Write once use it
anywhere!
Limitations of JavaScript
Security risks: JavaScript can be used to fetch data using AJAX or by manipulating
tags that load data such as <img>, <object>, <script>. These attacks are called cross-site
script attacks. They inject JS that is not part of the site into the visitor’s browser thus
fetching the details.
Performance: JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so
performance is not considered a big restriction in its use.
Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, and client and
server-side objects otherwise it would be difficult for them to write advanced scripts
using JavaScript.
Weak error handling and type checking facilities: It is a weakly typed language as there
is no need to specify the data type of the variable. So wrong type checking is not
performed by compile.
Variables
In JavaScript, variables are used to store and manage data. They are created using
the var, let, or const keyword.
var:
Declares a variable. It has a function-scoped or globally-scoped behavior.
var x = 10;
output:
Hello GFGC
10
12
22
Block-scoped variables
It’s commonly used for variables that may change their value.
let y = "Hello";
Output
Hello learners
joining
12
joining 12
const:
Declares variables that cannot be reassigned. It’s block-scoped as well.
const PI = 3.14;
Example: In this example, we will declare the variable using the const keyword.
const a = "Hello learners"
console.log(a);
const b = 400;
console.log(b);
const c = "12";
console.log(c);
Output
Hello learners
400
12
Global Variable
These are variables that are defined in global scope i.e. outside of functions. These
variables have a global scope, so they can be accessed by any function directly. In the case
of global scope variables, the keyword they are declared with does not matter they all act
the same. A variable declared without a keyword is also considered global even though it is
declared in the function.
Local Variable
When you use JavaScript, local variables are variables that are defined within functions.
They have local scope, which means that they can only be used within the functions that
define them. Accessing them outside the function will throw an error
Data Types
JavaScript is a dynamically typed (also called loosely typed) scripting language. In
JavaScript, variables can receive different data types over time.
The latest ECMAScript standard defines eight data types Out of which seven data types
are Primitive(predefined) and one complex or Non-Primitive.
String: JavaScript Strings are similar to sentences. They are made up of a list of
characters, which is essentially just an “array of characters, like “Hello GeeksforGeeks”
etc.
Boolean: Represent a logical entity and can have two values: true or false.
Null: This type has only one value that is null.
Undefined: A variable that has not been assigned a value is undefined.
Symbol: Symbols return unique identifiers that can be used to add unique property keys
to an object that won’t collide with keys of any other code that might add to the object.
BigInt: BigInt is a built-in object in JavaScript that provides a way to represent whole
numbers larger than 253-1.
“This course was packed with amazing and well-organized content! The project-based
approach of this course made it even better to understand concepts faster. Also the
instructor in the live classes is really good and knowledgeable.”- Tejas | Deutsche Bank
With our revamped Full Stack Development Program: master Node.js and React that
enables you to create dynamic web applications.
So get ready for salary hike only with our Full Stack Development Course.
JavaScript Operators
JavaScript operators operate the operands, these are symbols that are used to manipulate a
certain value or operand. Operators are used to performing specific mathematical and
logical computations on operands.
A % B means remainder
Modulus ‘%’ operator gives a
Modulus (%) (A/B) Y = 5 % 4 gives
remainder of an integer division.
Y=1
Y **= A is
Exponentiation This raises the value of a variable to
equivalent to Y=Y **
Assignment (** =) the power of the right operand.
A
the variable.
The bitwise operator in JavaScript is used to convert the number to a 32-bit binary number
and perform the bitwise operation. The number is converted back to the 64-bit number after
the result.
Name Description Syntax
Y = ? A : B If the condition is
Ternary It is like the short form of the if-
true then Y = A otherwise Y =
Operator(?): else condition.
B
delete object
This operator is more specifically // or
Delete used to delete JavaScript object delete object.property
properties. // or
delete object[‘property’]
objectName
The instanceof operator returns true if the
instanceof instanceof
specified object is of the specified object type.
objectType
JavaScript Conditional statements allow you to execute specific blocks of code based on
conditions. If the condition meets then a particular block of action will be executed
otherwise it will execute another block of action that satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
if statement: Executes a block of code if a specified condition is true.
else statement: Executes a block of code if the same condition of the preceding if
statement is false.
else if statement: Adds more conditions to the if statement, allowing for multiple
alternative conditions to be tested.
switch statement: Evaluates an expression, then executes the case statement that
matches the expression’s value.
ternary operator (conditional operator): Provides a concise way to write if-else
statements in a single line.
1. Using if Statement
The if statement is used to evaluate a particular condition. If the condition holds true, the
associated code block is executed.
Syntax:
if ( condition ) {
// If the condition is met,
//code will get executed.
}
Example: In this example, we are using the if statement to find given number is even or
odd.
let num = 20;
if (num % 2 === 0) {
console.log("Given number is even number.");
}
if (num % 2 !== 0) {
console.log("Given number is odd number.");
};
Output
Given number is even number.
Syntax:
if (condition1) {
// Executes when condition1 is true
}
else
{
// Executes when condition2 is true
}
Example: In this example, we are using if-else conditional statement to check the driving
licence eligibility date.
Output
You are eligible of driving licence
3. else if Statement
The else if statement in JavaScript allows handling multiple possible conditions and
outputs, evaluating more than two options based on whether the conditions are true or false.
Syntax:
if (1st condition) {
// Code for 1st condition
} else if (2nd condition) {
// ode for 2nd condition
} else if (3rd condition) {
// Code for 3rd condition
} else {
// ode that will execute if all
// above conditions are false
}
Output
Given number is zero.
As the number of conditions increases, you can use multiple else-if statements in
JavaScript. but when we dealing with many conditions, the switch statement may be a more
preferred option.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
...
case valueN:
statementN;
break;
default:
statementDefault;
};
Example: In this example, we find a branch name Based on the student’s marks, this
switch statement assigns a specific engineering branch to the variable Branch. The output
displays the student’s branch name,
const marks = 85; case marks >= 60:
let Branch; Branch = "Electronics and
switch (true) { communication";
case marks >= 90: break;
Branch = "Computer science case marks >= 50:
engineering"; Branch = "Civil engineering";
break; break;
case marks >= 80: default:
Branch = "Mechanical engineering"; Branch = "Bio technology";
break; break;
case marks >= 70: }
Branch = "Chemical engineering"; console.log(`Student Branch name is :
break; ${Branch}`);
Output
Student Branch name is : Mechanical engineering
Syntax:
condition ? value if true : value if false
Example: In this example, we use the ternary operator to check if the user’s age is 18 or
older. It prints eligibility for voting based on the condition.
Output
You are eligible to vote.
JavaScript Loops
JavaScript Loops are powerful tools for performing repetitive tasks efficiently. Loops in
JavaScript execute a block of code again and again while the condition is true.
For example, suppose we want to print “Hello World” 5 times. This can be done using JS
Loop easily. In Loop, the statement needs to be written only once and the loop will be
executed 5 times as shown below:
Syntax
for (initialization; testing condition; increment/decrement) {
statement(s)
}
Flowchart
Initialization condition: It initializes the variable and mark the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Test Condition: It is used for testing the exit condition of a for loop. It must return a
boolean value. It is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
Statement execution: Once the condition is evaluated to be true, the statements in the
loop body are executed.
Increment/ Decrement: It is used for updating the variable for the next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the
end of its life cycle.
Example
// JavaScript program to illustrate for loop
let x; Output
for (x = 2; x <= 4; x++) { Value of x: 2
console.log("Value of x: " + x); Value of x: 3
} Value of x: 4
Flowchart
While loop starts with checking the condition. If it is evaluated to be true, then the loop
body statements are executed otherwise first statement following the loop is executed.
For this reason, it is also called the Entry control loop
Once the condition is evaluated to be true, the statements in the loop body are executed.
Normally the statements contain an updated value for the variable being processed for
the next iteration.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
Example
// JavaScript code to use while loop
let val = 1; Output
while (val < 6) 1
{ 2
console.log(val); 3
val += 1; 4
} 5
Syntax
do {
Statements...
}
while (condition);
Flowchart
The do-while loop starts with the execution of the statement(s). There is no checking of
any condition for the first time.
After the execution of the statements and update of the variable value, the condition is
checked for a true or false value. If it is evaluated to be true, the next iteration of the
loop starts.
When the condition becomes false, the loop terminates which marks the end of its life
cycle.
It is important to note that the do-while loop will execute its statements at least once
before any condition is checked and therefore is an example of the exit control loop.
Example
let test = 1;
do { } while(test <= 5)
console.log(test);
test++; Output
NANDINI S D, GFGCW, H N PURA Page 18
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)
1 4
2 5
3
Syntax
for(let variable_name in object_name) {
// Statement
}
Syntax:
for(let variable_name of object_name) {
// Statement
}
only the parent loop/block. To terminate the outer loop from the inner loop using the break
keyword, users need to define the label.
Syntax
Label:
statement (loop or block of code)
Example
let sum = 0, a = 1; if (sum > 12) {
// Label for outer loop break outerloop;
outerloop: while (true) { }
a = 1; console.log("sum = " + sum);
// Label for inner loop a++;
innerloop: while (a < 3) { }
sum += a; }
sum = 6
Output sum = 7
sum = 1 sum = 9
sum = 3 sum = 10
sum = 4 sum = 12
Syntax
break;
Example
for (let i = 1; i < 6; i++) {
if (i == 4) Output
break; 1
console.log(i); 2
} 3
Syntax
continue;
NANDINI S D, GFGCW, H N PURA Page 20
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)
Example
for (let i = 0; i < 11; i++) { Output
if (i % 2 == 0) 1
continue; 3
5
console.log(i); 7
} 9
Functions in JavaScript
JavaScript function is a set of statements that take inputs, do some specific computation,
and produce output.
A JavaScript function is executed when “something” invokes it (calls it).
Example: A basic javascript function, here we create a function that divides the 1st element
by the second element.
function myFunction(g1, g2) {
return g1 / g2;
}
const value = myFunction(8, 2); // Calling the function
console.log(value);
output:
4
You must already have seen some commonly used functions in JavaScript like alert(),
which is a built-in function in JavaScript. But JavaScript allows us to create user-defined
functions also. We can create functions in JavaScript using the keyword `function`.
Function Invocation:
Triggered by an event (e.g., a button click by a user).
When explicitly called from JavaScript code.
Function Definition:
Before, using a user-defined function in JavaScript we have to create one. We can use the
above syntax to create a function in JavaScript. A function definition is sometimes also
termed a function declaration or function statement. Below are the rules for creating a
function in JavaScript:
Every function should begin with the keyword function followed by,
A user-defined function name that should be unique,
A list of parameters enclosed within parentheses and separated by commas,
A list of statements composing the body of the function enclosed within curly braces {}.
Output
15
Function Expression:
It is similar to a function declaration without the function name. Function expressions can
be stored in a variable assignment.
Syntax:
let gfgcw= function(paramA, paramB) {
// Set of statements
}
Output
16
Example:
// Function to convert Fahrenheit to Celsius
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
Arrow Function:
It is one of the most used and efficient methods to create a function in JavaScript because
of its comparatively easy implementation. It is a simplified as well as a more compact
version of a regular or normal function expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Function Parameters
Till now, we have heard a lot about function parameters but haven’t discussed them in
detail. Parameters are additional information passed to a function. For example, in the
above example, the task of the function calcAddition is to calculate the addition of two
numbers. These two numbers on which we want to perform the addition operation are
passed to this function as parameters. The parameters are passed to the function within
parentheses after the function name and separated by commas. A function in JavaScript can
have any number of parameters and also at the same time, a function in JavaScript can not
have a single parameter.
Output
69
Calling Functions:
After defining a function, the next step is to call them to make use of the function. We can
call a function by using the function name separated by the value of parameters enclosed
between the parenthesis and a semicolon at the end. The below syntax shows how to call
functions in JavaScript:
Syntax:
functionName( Value1, Value2, ..);
Output:
Hello Admin welcome to Gfgc
Return Statement
There are some situations when we want to return some values from a function after
performing some operations. In such cases, we can make use of the return statement in
JavaScript. This is an optional statement and most of the time the last statement in a
JavaScript function. Look at our first example with the function named as calcAddition.
This function is calculating two numbers and then returns the result.
Syntax: The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value which we want
to return from it. We can use an expression also instead of directly returning the value.
Function Definition
A function definition or function statement starts with the function keyword and continues
with the following.
Function’s name.
A list of function arguments contained in parenthesis and separated by commas.
Statements are enclosed in curly brackets.
Syntax:
function name(arguments)
{
javascript statements
}
Function Calling
To call a function at a later point in the script, simply type the function’s name. By default,
all JavaScript functions can utilize argument objects. Each parameter’s value is stored in an
argument object. The argument object is similar to an array. Its values may be accessed
using an index, much like an array. It does not, however, provide array methods.
function welcome() {
console.log("welcome to GfGC");
}
welcome();
Output
welcome to GfGC
Function Arguments
A function can contain one or more arguments that are sent by the calling code and can be
utilized within the function. Because JavaScript is a dynamically typed programming
language, a function argument can have any data type as a value.
function welcome(name) {
console.log("Hey " + "" + name + " " + "welcome to GfG");
}
// Passing arguments
welcome("Rohan");
Output
Hey Rohan welcome to GfGC
Return Value
A return statement is an optional part of a JavaScript function. If you wish to return a value
from a function, you must do this. This should be the final statement of a function.
function welcome() {
// Return statement
return "Welcome to GfGG";
}
console.log(welcome());
Output
Welcome to GfGC
Function Expression
We may assign a function to a variable and then utilize that variable as a function in
JavaScript. It is known as a function expression.
Output
Welcome to GfGC
1. Named function:
A named function is one that we write in code and then use whenever we need it by
referencing its name and providing it with some parameters. Named functions come in
handy when we need to call a function several times to give various values to it or run it
multiple times.
function add(a, b) {
return a + b;
}
console.log(add(5, 4));
Output
9
2. Anonymous function:
We can define a function in JavaScript without giving it a name. This nameless function is
referred to as the anonymous function. A variable must be assigned to an anonymous
function.
Output
9
3. Nested Functions:
A function in JavaScript can contain one or more inner functions. These nested functions
fall within the purview of the outer function. The inner function has access to the variables
and arguments of the outer function. However, variables declared within inner functions
cannot be accessed by outer functions.
function msg(firstName) {
function hey() {
console.log("Hey " + firstName);
}
return hey();
}
msg("Ravi");
Output
Hey Ravi
Output
Welcome to GfgC
Syntax:
call()
Return Value: It calls and returns a method with the owner object being the argument.
Output
100
JavaScript Numbers
JavaScript Numbers are primitive data types. Unlike other programming languages, you
don’t need int, float, etc. to declare different numeric values. JavaScript numbers are
always stored in double-precision 64-bit binary format IEEE 754.
This format stores numbers in 64 bits,
0-51 bit stores value(fraction)
52-62 bit stores exponent
2. Scientific Notation
JavaScript allows writing extra-large or extra-small numbers using scientific (exponent)
notation.
Example:
let a = 156e5;
let b = 156e-5; Output
console.log(a); 15600000
console.log(b); 0.00156
3. Integer Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
Example:
let a = 999999999999999;
let b = 9999999999999999; Output
console.log(a); 999999999999999
console.log(b); 10000000000000000
Example:
let x = 0.22 + 0.12; //x will be let x = 0.22 + 0.12;
0.33999999999999997 let y = (0.22 * 10 + 0.12 * 10) / 10;
To solve this problem, multiply and console.log(x);
divide: console.log(y);
let x = (0.22 * 10 + 0.12 * 10) / 10; // x
will be 0.34 Output
NANDINI S D, GFGCW, H N PURA Page 29
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)
0.33999999999999997 0.34
6. Numeric Strings
JavaScript automatically converts the numeric strings to numbers in most operations like.
Example:
let x = "100" / "10";
let y = "100" * "10"; Output
let z = "100" - "10"; 10
console.log(x); 1000
console.log(y); 90
console.log(z);
Number Literals:
The types of number literals You can use decimal, binary, octal, and hexadecimal.
1. Decimal Numbers:
JavaScript Numbers does not have different types of numbers(ex: int, float, long, short)
which other programming languages do. It has only one type of number and it can hold
both with or without decimal values.
let a=33;
let b=3.3; Output
console.log(a); 33
console.log(b); 3.3
2. Octal Number:
If the number starts with 0 and the following number is smaller than 8. It will be parsed as
an Octal Number.
let x = 0562; Output
console.log(x); 370
3. Binary Numbers:
They start with 0b or 0B followed by 0’s and 1’s.
let x = 0b11;
let y = 0B0111; Output
console.log(x); 3
console.log(y); 7
4. Hexadecimal Numbers:
They start with 0x or 0X followed by any digit belonging (0123456789ABCDEF)
JavaScript Strings
You can create JavaScript Strings by enclosing text in single or double quotes. String
literals and the String constructor provide options. Strings allow dynamic manipulation,
making it easy to modify or extract elements as needed.
Declaration of a String
Example:
let str = 'Create String with Single Quote'; Output
console.log(str); Create String with Single Quote
Syntax:
let str = “String with double quote”;
Example:
let str = "Create String with Double
Quote"; Output
console.log(str); Create String with Double Quote
3. String Constructor
You can create a string using the String Constructor. The String Constructor is less
common for direct string creation, it provides additional methods for manipulating strings.
Generally, using string literals is preferred for simplicity.
Syntax:
let str = 'Template Litral String';
let newStr = `String created using ${str}`;
Example:
let str = 'Template Litral String';
let newStr = `String created using ${str}`; Output
console.log(newStr); String created using Template Litral String
5. Empty String
You can create an empty string by assigning either single or double quotes with no
characters in between.
Syntax:
NANDINI S D, GFGCW, H N PURA Page 32
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)
Example:
let str1 = '';
let str2 = ""; Output
console.log("Empty String with Single Empty String with Single Quotes:
Quotes: " + str1); Empty String with Double Quotes:
console.log("Empty String with Double
Quotes: " + str2);
Syntax:
let str = `
This is a
multiline
string`;
Example:
let str = `
This is a Output
multiline This is a
string`; multiline
console.log(str); string
2. String Concatenation
You can combine two or more strings using + Operator.
Example:
let str1 = 'Java';
let str2 = 'Script'; Output
let result = str1 + str2; Concatenated String: JavaScript
console.log("Concatenated String: " +
result);
3. Escape Characters
We can use escape characters in string to add single quotes, dual quotes, and backslash.
Syntax:
\' - Inserts a single quote
\" - Inserts a double quote
\\ - Inserts a backslash
Example: The better way to break a string is by using the string addition.
const str = "'GFGCW' is a"
+ " learning portal"; Output
console.log(str); 'GFGCW' ' is a learning portal
You can create JavaScript Arrays using the Array constructor or using the shorthand array
literal syntax, which employs square brackets. Arrays can dynamically grow or shrink in
size as elements are added or removed.
Declaration of an Array
There are basically two ways to declare an array i.e. Array Literal and Array Constructor.
1. Creating an Array using Array Literal
Creating an array using array literal involves using square brackets [] to define and
initialize the array. This method is concise and widely preferred for its simplicity.
Syntax:
let arrayName = [value1, value2, ...];
Example:
let names = [];
console.log(names); Output
let courses = ["HTML", "CSS", []
"Javascript", "React"]; [ 'HTML', 'CSS', 'Javascript', 'React' ]
console.log(courses);
Syntax:
let arrayName = new Array();
Example:
// Declaration of an empty array arr[1] = 20;
// using Array constructor arr[2] = 30;
let names = new Array(); console.log(arr);
console.log(names);
let courses = new Array("HTML", "CSS", Output
"Javascript", "React"); []
console.log(courses); [ 'HTML', 'CSS', 'Javascript', 'React' ]
let arr = new Array(3); [ 10, 20, 30 ]
arr[0] = 10;
CSS
Output Javascript
HTML React
Output
Original Array: HTML,CSS,Javascript,React,Node.js
After Removed the last elements: HTML,CSS,Javascript,React
After Removed the First elements: CSS,Javascript,React
After Removed 2 elements starting from index 1: CSS
7. Array Length
Get the length of an array using the length property.
Output
Array Length: 5
Output
Array After Increase the Length: [ 'HTML', 'CSS', 'Javascript', 'React', 'Node.js', <2 empty
items> ]
Array After Decrease the Length: [ 'HTML', 'CSS' ]
Output
HTML
CSS
JavaScript
React
Output
Concatenated Array: [ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'Expess.js' ]
11. Conversion of an Array to String
We have a builtin method toString() to converts an array to a string.
Output
HTML,CSS,JavaScript,React
Output
Object
Objects in Javascript
Objects, in JavaScript, are the most important data type and form the building blocks for
modern JavaScript. These objects are quite different from JavaScript’s primitive data types
(Number, String, Boolean, null, undefined, and symbol) in the sense that these primitive
data types all store a single value each (depending on their types).
Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,
...
}
Note:- Object() can be called with or without new. Both create a new object.
let school = {
name: 'Vivekananda School',
location: 'Delhi',
established: '1971',
20: 1000,
displayInfo: function () {
console.log(`The value of the key 20 is ${school['20']}`);
}
}
school.displayInfo();
Output
The value of the key 20 is 1000
But more on the bracket notation later. Property names can also be strings with more than
one space separated words. In which case, these property names must be enclosed in quotes
:
let school = {
"school name" : "Vivekananda School",
}
Inherited Properties
Inherited properties of an object are those properties that have been inherited from the
object’s prototype, as opposed to being defined for the object itself, which is known as the
object’s Own property. To verify if a property is an object’s Own property, we can use
the hasOwnProperty method. Property Attributes Data properties in JavaScript have
four attributes.
value: The property’s value.
writable: When true, the property’s value can be changed
enumerable: When true, the property can be iterated over by “for-in” enumeration.
Otherwise, the property is said to be non-enumerable.
configurable: If false, attempts to delete the property, change the property to be an
access-or property, or change its attributes (other than [[Value]], or changing
[[Writable]] to false) will fail.
Output
True
Output
Vivekanada
1971
Bracket Notation
Syntax:
objectName["memberName"]
Output
Vivekanada School
1000
Unlike dot notation, the bracket keyword works with any string combination, including, but
not limited to multi-word strings.
NANDINI S D, GFGCW, H N PURA Page 43
WEB TECHNOLOGIES (6TH SEM BSc)(NEP)
Output
name
age
nationality
gender
Deleting Properties
To Delete a property of an object we can make use of the delete operator. An example of
its usage has been listed below.
Output
Name
Undefined
window.pageYOffset The number of pixels that the current document has been
scrolled vertically.
Frame objects:
The HTML DOM Window frames property in HTML DOM is used to return the frame
element in the form of an array object. This property represents all <iframe> elements in
the current window. DOM Windowframe is a read-only property.
Syntax:
window.frames
Properties:
length property: It returns the number of iframe elements in the current window.
location property: It changes the location of the iframe.
Return Value: It returns a reference to the Window object, representing all the frames in
the current window.
JavaScript Events
Javascript has events to provide a dynamic interface to a webpage. These events are
hooked to elements in the Document Object Model(DOM).
These events by default use bubbling propagation i.e, upwards in the DOM from children
to parent. We can bind events either as inline or in an external script.
Syntax:
<HTML-element Event-Type = "Action to be performed">
JavaScript onkeyup event: This event is a keyboard event and executes instructions
whenever a key is released after pressing.
onmouseover event: This event corresponds to hovering the mouse pointer over the
element and its children, to which it is bound to.
JavaScript onmouseout event: Whenever the mouse cursor leaves the element which
handles a mouseout event, a function associated with it is executed.
JavaScript onchange event: This event detects the change in value of any element listing
to this event.
JavaScript onload event: When an element is loaded completely, this event is evoked.
JavaScript onfocus event: An element listing to this event executes instructions whenever
it receives focus.
JavaScript onblur event: This event is evoked when an element loses focus.
Example:
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}
Output: In the above code, we make use of ‘dadalert’ which is not a reserved keyword and
is neither defined hence we get the error.
Example: In this example, we will see the usage of try-catch block in javascript.
try {
dadalert("Welcome Fellow Geek!");
}
catch (err) {
console.log(err);
}
Output:
Example: In this example, we will see how a throw statement is used to throw an error in
javascript.
try {
throw new Error('Yeah... Sorry');
}
catch (e) {
console.log(e);
}
Output:
Example: In this example, we will learn about the final statement of Javascript.
try {
console.log('try');
} catch (e) {
console.log('catch');
} finally {
console.log('finally');
}
Output: The Finally Block can also override the message of the catch block so be careful
while using it.
Syntax:
document.getElementById("Form_ID");
JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is
used by different web applications to communicate with each other. It is the replacement of the
XML data exchange format. It is easy to struct the data compare to XML. It supports data
structures like arrays and objects and the JSON documents that are rapidly executed on the
server.
Why JSON?
It is a Language-Independent format that is derived from JavaScript. It is Human-readable and
writable. It is a lightweight text-based data interchange format which means, it is simpler to
read and write when compared to XML. Though it is derived from a subset of JavaScript, yet
it is Language independent. Thus, the code for generating and parsing JSON data can be
written in any other programming language.
Syntax Rules: Data is in name/value pairs and they are separated by commas. It uses curly
brackets to hold the objects and square brackets to hold the arrays.
Example:
{
"Data Structures": [
{
"Name" : "Trees",
"Course" : "Intoduction of Trees",
"Content" : [ "Binary Tree", "BST",
"Generic Tree"]
},
{
"Name" : "Graphs",
"Topics" : [ "BFS", "DFS", "Topological Sort" ]
}
]
}
Properties:
screen.width
screen.height
screen.availWidth
screen.availHeight
screen.colorDepth
screen.pixelDepth
HTML screen.width Property: The screen.width property returns the user’s screen width
in pixels.
HTML screen.height Property: The screen.height property returns the users screen height
in pixels.