CSS Unit 1 (22519)
CSS Unit 1 (22519)
Introduction .......................................................................................................................... 3
Object .................................................................................................................................... 6
Method .................................................................................................................................. 8
Dot Syntax............................................................................................................................. 8
Datatypes ............................................................................................................................ 10
Operators ............................................................................................................................ 11
Expression........................................................................................................................... 14
4. ‘if-else-if’ : ............................................................................................................. 16
3. Using Object.defineProperty........................................................................................ 23
Deleting Properties............................................................................................................. 23
UNIT 1. BASICS OF JAVASCRIPT PROGRAMMING
Introduction
JavaScript is a limited featured client side programming language. It runs at the client
end through the user’s browser without sending messages back and forth to the server.
It is widely used by web developers to do things such as build dynamic web pages,
respond to events, create interactive forms, validate data that the visitor enters through a form,
control the browser, etc.
With JavaScript, users can build modern web applications to interact directly without
reloading the page every time.
Features of JavaScript
1. Lightweight: JavaScript is designed to be easy to use and has a small footprint, making
it efficient for web development.
2. Dynamic Typing: Variables in JavaScript do not need to declare a type. A variable can
hold different types of data at different times.
3. Interpreted Language: JavaScript code is executed directly by the web browser without
the need for prior compilation.
4. Event-Driven: JavaScript responds to events like user actions (clicks, key presses),
making it ideal for interactive web pages.
5. Versatile: JavaScript can be used for both front-end (client-side) and back-end (server-
side) development.
6. Object-Based: Although not purely object-oriented, JavaScript supports objects and can
create and manipulate them.
7. Prototype-Based: Instead of classes, JavaScript uses prototypes for inheritance,
allowing objects to inherit directly from other objects.
8. First-Class Functions: Functions in JavaScript are treated as first-class citizens,
meaning they can be assigned to variables, passed as arguments, and returned from
other functions.
9. Asynchronous Programming: JavaScript supports asynchronous operations using call-
backs, promises, and async/await, making it efficient for handling tasks like data
fetching.
10. Wide Browser Support: JavaScript is supported by all major web browsers, making it
a universal language for web development.
11. Rich Libraries and Frameworks: JavaScript has a vast ecosystem of libraries (like
jQuery) and frameworks (like React, Angular, and Vue) that simplify development and
enhance functionality.
12. Community Support: A large and active community provides abundant resources,
tutorials, and support for learning and troubleshooting JavaScript.
Limitations of JavaScript
1. Security Issues: JavaScript runs in your web browser, so if not properly secured, it can
be exploited by hackers to steal information or cause damage.
2. Browser Compatibility: Not all web browsers interpret JavaScript in the same way. This
can lead to inconsistencies where a script works fine in one browser but not in another.
3. Client-Side Dependency: JavaScript is mostly used on the client-side, which means it
relies on the user's device. If the user disables JavaScript in their browser, the
functionality can break.
4. Performance: JavaScript can be slower than some other programming languages,
especially for complex calculations or large-scale applications, because it runs in the
browser and shares resources with other tasks.
5. Limited File Access: For security reasons, JavaScript has restricted access to the user's
file system, making it difficult to read or write files directly.
6. No Multi-Threading: JavaScript traditionally runs on a single thread, meaning it can
only do one thing at a time, which can slow down performance if it's trying to handle
multiple heavy tasks simultaneously.
7. Loose Typing: The flexibility of not having to declare variable types can lead to
unexpected bugs and errors, as the data type of a variable can change during the
program execution.
8. Code Maintenance: JavaScript code can become difficult to maintain and debug,
especially in larger projects, because of its dynamic nature and the lack of strict rules
compared to other languages.
9. Dependency on External Libraries: While libraries and frameworks can make
development easier, over-reliance on them can lead to issues if those libraries become
outdated, have bugs, or introduce security vulnerabilities.
10. SEO Limitations: JavaScript-heavy websites can sometimes be difficult for search
engines to index properly, potentially affecting the site's search ranking.
11. Memory Management: JavaScript does not provide low-level memory control, which
can lead to inefficient memory usage and performance issues in complex applications.
12. Backward Compatibility: New features added to JavaScript might not be supported in
older browsers, requiring developers to use polyfills or avoid certain features to ensure
compatibility.
Object
A JS object is a collection of properties and methods. It is a way to group data together and
store it in a structured way. Objects can be created with ‘{}’ with an optional list of properties.
Object Creation
The simplest way to create an object in JS is using the object literal. It is a comma separated
key-value pair enclosed in ‘{}’, assigned to a variable.
Syntax: let obj_name = { key n: value n};
obj_name – Each object should be uniquely identified by a name or IDs in webpage to
distinguish between them.
property – The data in the object is stored in key-value pairs, called a property. The key is
a string while value can be any data-type, including another object.
Object Property
In JS, there are two kinds of object properties:
- Data Properties
They store a value that can be retrieved or set directly using dot (.) notation or bracket
([]) notation.
Data properties have four attributes:
- Value – Value associated with property. Defaults to ‘undefined’ if not specified.
- Writable – A Boolean indicating if the property’s value can be changed with an
assignment operator. Defaults to false.
- Enumerable – A Boolean indicating if the property should show up in ‘for..in’
or ‘object.keys()’ enumerations. Defaults to false.
- Configurable – A Boolean indicating if the property can be deleted or its
attributes can be changed. Defaults to ‘false’.
Example:
const obj = {};
Object.defineProperty(obj, ‘data’, {value : 10, writable : true, enumerable : true, configurable : true});
console.log(obj.data);
obj.data = 20;
console.log(obj.data);
- Accessor Properties
They do not store a value directly but instead define functions (getters and setters) to
retrieve (‘get’) or modify (‘set’) a value.
Characteristics of accessor properties:
- Get – A function that is called to get the property value.
Syntax – get property () {
//function body}
- Set – A function that is called to set the property value.
Syntax – set property (var_name) {
//function body}
- Enumerable
- Configurable
Example:
const obj = {
val : 10, //property
get property() //getter function [called when obj.property is accessed.]
{ return this.val; },
set property(newval) //setter function [called when a new value is assigned to val.]
{ this.val = newval; }
};
console.log(obj.property); //JS checks if there is a getter function associated with property. If yes, it is called.
obj.property = 20; //Triggers the setter method.
console.log(obj.property); //JS checks if there is a setter function associated with property. If yes, it is called.
console.log(obj.val); //Triggers the getter method.
Key differences:
Parameter Data Property Accessor Property
Value Storage Stores a value directly. Does not store a value directly.
Attributes value, writable, enumerable, configurable get, set, enumerable, configurable
Get value Directly reads the stored value. Calls the getter function to retrieve the value.
Set value Directly assigns a new value. Calls the setter function to set the value.
Use case Simple storage and retrieval of values. Adding logic when getting or setting values.
Note:
- If you want to make the properties of an object immutable, you can use ‘Object.freeze()’. This prevents
modification of the existing properties and adding/removing properties as well.
- Using ‘const’ keyword to declare an object means that the reference to the object is constant, i.e, you cannot
reassign the object to a different reference. However, the properties of the object itself can still be changed.
Method
JS Method is a function that is a property of an object. Methods are used to define actions that
an object can perform. Essentially, methods are functions that are associated with objects.
Example: const person = {
f_name: "John",
l_name: "Doe",
name: function()
{
return this.f_name + " " + this.l_name;
}};
document.write(person.name()); // Output: "John Doe"
Dot Syntax
A dot notation is used to access the object properties and methods in JS.
A dot separates the name of the object from the property and method.
The first part is the name of the object and the second part is either property or method of the
object.
With the dot and bracket notation, you can:
a) Access the value of a property by its key
b) Modify the value of an existing property by its key
c) Add a new property to an object
Example:
var person = {
fname : “John”,
lname ; “Doe”
};
document.write(“Firstname” +person.fname); //Accessing Property
person.lname = “XYZ”; //Modifying property
person.age = 45; //Adding Property
Main Event
The change in the state of an object is called an Event. In HTML, there are various events
which represent that some activity is performed by user or browser. When JS code is included
in HTML, JS reacts over these events and allow the execution. This process of reacting over
events is called event handling. Thus, JS handles HTML events via event handlers.
Key Differences:
Datatypes
Datatype Description Example
Number Represents both integers and floating point numbers. 42, 3.14
String Represents a sequence of characters. ‘Hello’, “World”
Boolean Represents true or false values. true, false
Object Represents a collection of properties in key-value pairs. {name ; ‘John’, age : 30};
Array A special type of object used for storing ordered collections. [1,2,3]
Function A block of code designed to perform a particular task. function greet(){}
Undefined Indicates that a variable has not been assigned a value. let x;
Null Represents the intentional absence of any object value. let y = null;
Date Represents date and time. new Date();
Note:
- Arrays are technically objects, they can be identified specifically using ‘Array.isArray(arr_name)’.
- The typeof for ‘null’ returns ‘object’ which is a historical bug in JS.
Operators
In JavaScript, operators are used to perform operations on variables and values. Here's a
comprehensive overview of different types of operators available in JavaScript:
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
Operator Description Example Result
+ Addition 5+2 7
- Subtraction 5-2 3
* Multiplication 5*2 10
/ Division 5/2 2.5
% Modulus 5%2 1
++ Increment let a = 5; a++; 6
-- Decrement a--; 4
2. Assignment Operators
Assignment operators are used to assign values to variables.
Operator Description Example Equivalent to
= Assignment x=5 x=5
+= Addition Assignment x += 5 x=x+5
-= Subtraction Assignment x -= 5 x=x-5
*= Multiplication Assignment x *= 5 x=x*5
/= Division Assignment x /= 5 x=x/5
%= Modulus Assignment x %= 5 x=x%5
3. Comparison Operators
Comparison operators are used to compare two values.
Operator Description Example Result
== Equal to 5 == 5 TRUE
=== Strict equal (value and type) 5 === "5" FALSE
!= Not equal 5 != 3 TRUE
!= = Strict not equal (value and type) 5 !== "5" TRUE
> Greater than 5>3 TRUE
< Less than 5<3 FALSE
>= Greater than or equal to 5 >= 5 TRUE
<= Less than or equal to 5 <= 3 FALSE
4. Logical Operators
Logical operators are used to combine multiple Boolean expressions.
Operator Description Example (x = 6, y = 3) Result
&& Logical AND (x < 10 && y > 1) True
|| Logical OR (x == 5 || y == 5) False
! Logical NOT !(x == y) True
5. Bitwise Operators
Bitwise operators are used to perform bitwise operations.
Operator Description Example Same as Result
& AND 5&1 0101 & 0001 1
|| OR 5 || 1 0101 || 0001 5
^ XOR 5^1 0101 ^ 0001 4
~ NOT ~5 ~ 0101 -6
<< Left Shift 5 << 1 0101 << 0001 10
>> Right Shift 5 >> 1 0101 >> 0001 2
>>> Unsigned Right Shift 5 >>> 1 0101 >>> 0001 2
6. String Operators
String operators are used to manipulate string values.
Operator Description Example Result
+ Concatenation “Hello” + “ World” “Hello World”
+= Concatenate Assignment str1 += “str2” str1 has “str2” appended to it
In JavaScript, an expression is any valid unit of code that resolves to a value. Expressions can
range from a simple value like a number or a string to more complex combinations involving
variables, operators, and function calls. Expressions are fundamental to JavaScript
programming as they form the building blocks for more complex operations.
The test condition is tested before entering the loop body. document.write(“Invalid day”);
{
//body of loop
}
- ‘for’ loop:
WAP to display prime numbers from 1 to 20 using for loop.
o A for loop is an entry controlled
var flag;
loop that allows the code to be executed
for (var i = 2; i <= 20; i++) repeatedly.
{ o It provides a concise way of
flag = true; writing the loop structure.
for (var j = 2; j <= i; j++) o Unlike a while loop, a ‘for’
{ statement includes the initialization,
}
b) Exit controlled loops:
The test condition is tested or evaluated at the end of loop body. Therefore, the loop body will execute
at least once, irrespective of whether the test condition is true or false. ‘do..while’ loop is an exit
controlled loop.
- ‘do..while’ loop:
WAP to print odd numbers from 1 to 20
o A do..while loop is an exit-controlled loop that allows the
using do..while loop.
code to be executed first and after that checks for the
let num = 1;
condition and depending upon that the body of the loop
do
is executed repeatedly.
o When the condition becomes false, the loop terminates {
Function Terminates the entire loop or switch statement. Skips the current iteration & moves to the next
iteration of the loop.
Use in loops Used to exit the loop immediately. Used to skip the rest of the code inside the loop
for the current iteration only.
Use in switch Terminates the switch case statement. Not applicable in switch statements.
Effect on loop Ends the loop immediately. Continues with the next iteration of the loop.
Use case When a condition is met & you want to exit the When you want to skip the current iteration based
loop early. on a condition but continue looping.
Flow control Transfers control to the statement following the Transfers control to the beginning of the next
loop or switch. iteration of the loop.
Querying Properties
To query or access the properties of an object, you can either use dot notation or bracket
notation.
The LHS should be an expression whole value is an object.
Dot (‘.’) Notation –
- It is used when the exact name of the property is known and it is a valid
identifier, i.e, it doesn’t contain white spaces or special characters.
- The RHS must be a simple identifier that names the property.
- Syntax – object.property
Example:
const person = {
name : “Alice”,
age : 25};
console.log(person.name);
Example:
const person = {
name : “Alice”,
age : 25
“favorite color” : blue};
console.log(person[“favorite color”]);
Setting Properties
Setting the property of an object in JavaScript can be done in several ways, depending on how
you're defining or modifying the object. Here are a few common methods:
1. Using dot or bracket notation
If you have an existing object and want to set its property directly:
Example:
let person = {}; // Define an empty object
person.age = 30; // Set the data property
let property_name = “name”;
person[peroperty_name] = “John”;
It allows more comples property definitions, including defining properties with specific
attributes.
Example:
let obj = {};
Object.defineProperty(obj, 'data', {
value: 'some value',
writable: true, // Can the value be changed?
enumerable: true, // Should the property show up in for...in loops?
configurable: true // Can the property be deleted or modified?
});
Deleting Properties
The ‘delete’ operator allows you to remove a property from an object if it exists. If the
property’s values is an object and there are no more references to the object, the object held by
that property is eventually released automatically.
Syntax – delete object.property;
OR
delete object[property];
Example:
let person = {
name : ‘John’,
age : 30,
city : ‘’New York
};
delete(person.age);
console.log(person);
Note-
- Deleting Non-configurable properties: If a property is defined with ‘configurable : false’ using
‘Object.defineProperty’, it cannot be deleted using ‘delete’.Attempting to delete a mpn-configurable property
will simply return false and the property will remain unchanged.
- Deleting undefined properties: It will simply return ‘true’ without any effect.
- Deleting properties in arrays: While JS objects are also arrays, using ‘delete’ on array elements doesn’t update
the ‘length’ property or remove array elements effectively. Use array.splice() instead.