NIT-4
U
JAVASCRIPT
Topic-1:Introduction
● J avaScript is a versatile, dynamically typed programming language that
brings life to web pages by making them interactive.
● It is used for building interactive web applications.
● It supports both client-side and server-side development.
● It integrates seamlessly with HTML, CSS, and a rich standard library.
● JavaScript is a single-threaded language that executes one task at a time.
● It is an interpreted language which means it executes the code line by line.
Key Features of JavaScript:
HerearesomekeyfeaturesofJavaScriptthatmakeitapowerfullanguageforweb
development:
● Client-SideScripting:JavaScriptrunsontheuser'sbrowser,sohasafaster
response time without needing to communicate with the server.
● Versatile:Canbeusedforawiderangeoftasks,fromsimplecalculationsto
complex server-side applications.
● Event-Driven:Responds to user actions (clicks, keystrokes)in real-time.
● Asynchronous: It can handle tasks like fetching data fromserverswithout
freezing the user interface.
● Rich Ecosystem: There are numerous libraries and frameworks built on
JavaScript, such as React, Angular, and [Link], which make development
faster and more efficient.
Some fundamental concepts:
● Variables:Store data.
● Data Types:Numbers, strings, booleans, objects, arrays.
● Functions:Reusable blocks of code.
● Loops:Repeat tasks.
Limitations of JavaScript:
● Security Risks: Can be used for attacks like Cross-Site Scripting (XSS),
wheremaliciousscriptsareinjectedintoawebsitetostealdatabyexploiting
elements like <img>, <object>, or <script> tags.
● Performance: Slower than traditional languages forcomplextasks,butfor
simple tasks in a browser, performance is usually not a major issue.
● C omplexity: To write advanced JavaScript, programmers need to
understand core programming concepts, objects, and both client- and
server-side scripting, which can be challenging.
● Weak Error Handling and Type Checking: Weakly typed, meaning
variables don’t require explicit types. This can lead to issues as type
checking is not strictly enforced.
Topic-2:Language Elements
🔑 1. Literals (fixed values)
● Numbers → 10, 3.14, -5
● Strings → "hello", 'world', `template`
● Boolean → true, false
● Null → null
● Undefined → undefined
● Objects → { name: "Alex", age: 20 }
● Arrays → [1, 2, 3, 4]
🔑 2. Identifiers
● Names you give to variables, functions, classes, etc.
🔑 3. Variables & Constants
● Declared with var, let, const
🔑 4. Operators
● Arithmetic → +, -, *, /, %, **
● Assignment → =, +=, -=, *=
● Comparison → ==, ===, !=, !==, <, >, <=, >=
● Logical → &&, ||, !
● Ternary → condition ? expr1 : expr2
🔑 5. Expressions & Statements
● Expression → produces a value → 5 + 3, x > 10
● Statement → performs an action → if (x > 10) { [Link]("big"); }
🔑 6. Control Flow
● Conditional → if, else if, else, switch
● Loops → for, while, do...while, for...in, for...of
● Jump → break, continue
🔑 7. Functions
● Reusable blocks of code.
🔑 8. Objects & Classes
● Object:An object is an instance of a class.
● Class: A class is a template to create objectshavingsimilarpropertiesand
behavior.
🔑 9. Events & Error Handling
● Events: JavaScript events are actions or occurrences that happen in the
browser, such as user interactions (clicks, key presses), page loading, or
changes in the DOM. Events allow for dynamic and interactive web pages.
● Error Handling: JavaScript provides mechanisms to manage unexpected
issues that occur during code execution, preventing program crashes and
improving user experience. The primary tools for error handling are:
“try”,”catch”,”finally”blocks.
a) try block:Encloses code that might potentiallythrow an error.
b) catch block: Catches and handles errors thrown within the try block. It
receives an Error object containing details about the error.
c)finallyblock:Executescoderegardlessofwhetheranerroroccurredornot,
typically used for cleanup tasks.
🔑 10. Modules
● Used for structuring code across files.
Topic-3:Objects of Javascript
● A n object in JavaScript is a data structure used to store related data
collections.
● Itstoresdataaskey-valuepairs,whereeachkeyisauniqueidentifierforthe
associated value.
● O bjectsaredynamic,whichmeansthepropertiescanbeadded,modified,or
deleted at runtime.
There are two primary ways to create an object in JavaScript:
● Object Literal
● Object Constructor.
1 . Creation Using Object Literal: The objectliteralsyntaxallowsyoutodefine
and initialize an object with curly braces {}, setting properties as key-value pairs.
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
[Link](obj);
Output:
{ name: 'Sourav', age: 23, job: 'Developer' }
2. Creation Using new Object() Constructor:
let obj = new Object();
[Link]= "Sourav",
[Link]= 23,
[Link]= "Developer"
[Link](obj);
utput:
O
{ name: 'Sourav', age: 23, job: 'Developer' }
asic Operations on JavaScript Objects:
B
1.AccessingObjectProperties:Youcanaccessanobject’spropertiesusingeither
dot notation or bracket notation.
Input:
let obj = { name: "Sourav", age: 23 };
// Using Dot Notation
[Link]([Link]);
// Using Bracket Notation
[Link](obj["age"]);
utput:
O
Sourav
23
2 . Modifying Object Properties: Properties in an object can be modified by
reassigning their values.
I nput:
let obj = { name: "Sourav", age: 22 };
[Link](obj);
o [Link] = 23;
[Link](obj);
utput:
O
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
3 . Adding Properties to an Object: You can dynamically addnewpropertiesto
an object using dot or bracket notation.
I nput:
let obj = { model: "Tesla" };
[Link] = "Red";
c [Link](obj);
Output:
{ model: 'Tesla', color: 'Red' }
4 .RemovingPropertiesfromanObject:Thedeleteoperatorremovesproperties
from an object.
I nput:
let obj = { model: "Tesla", color: "Red" };
delete [Link];
[Link](obj);
utput:
O
{ model: 'Tesla' }
5 .CheckingifaPropertyExists:Youcancheckifanobjecthasapropertyusing
the in operator or "hasOwnProperty()" method.
I nput:
let obj = { model: "Tesla" };
[Link]("color" in obj);
[Link]([Link]("model"));
utput:
O
false
true
6 .MergingObjects:Objectscanbemergedusing"[Link]()"orthespread
syntax { ...obj1, ...obj2 }.
I nput:
let obj1 = { name: "Sourav" };
let obj2 = { age: 23};
let obj3 = { ...obj1, ...obj2 };
[Link](obj3);
utput:
O
{ name: 'Sourav', age: 23 }
7 . Object Length: You can find the number of properties in an object using
[Link]().
I nput:
let obj = { name: "Sourav", age: 23 };
[Link]([Link](obj).length);
utput:
O
2
opic-4:Otherobjects(likedata,math,string,regularexpressions,
T
arrays)
I nJavaScript,objectslikeDate,Math,String,RegExp(RegularExpressions),and
Array are built-in global objects that provide specific functionalities and properties.
1. Date Object:
● The Date object is used to work with dates and times.
● It allows for creating new date instances, getting and setting various date
components (year, month, day, hour, minute, second, millisecond), and
performing date calculations.
[Link] Object:
● The Math object is astaticobjectthatprovidesmathematicalconstantsand
functions.
● It does not have a constructor; all its properties and methods are accessed
directly through the Math object itself.
● Examples include [Link] (for pi), [Link]() (for arandomnumber),
[Link](), [Link](), [Link](), [Link](), etc.
[Link] Object:
● The String object represents sequences of characters.
● Whilestringscanbecreatedasprimitivevalues(e.g.,letstr="hello";),they
can also be created as String objects (e.g., let strObj = new String("hello");).
● T heStringobjectprovidesnumerousmethodsformanipulatingstrings,such
as length, toUpperCase(), toLowerCase(), indexOf(), substring(), replace(),
etc.
[Link] (Regular Expressions) Object:
● The RegExp object is used to work with regular expressions, which are
patterns used for matching character combinations in strings.
● Regular expressions can be created using the RegExp constructor or as
literal values enclosed in forward slashes (e.g., /pattern/flags).
● Methods like test() and exec() are available on RegExp objects, and string
methods like match(), replace(), and split() can utilize regular expressions.
[Link] Object:
● The Array object is used to store ordered collections of values.
● Arrays can be created using literal notation ([]) or the Array constructor.
● Arrays are resizable and can contain a mix of different data types.
● The Array object provides a rich set of methods for manipulating arrays,
such as push(), pop(), shift(), unshift(), splice(), map(), filter(), reduce(), etc.