0% found this document useful (0 votes)
22 views23 pages

CSS Unit 1 (22519)

This document provides a comprehensive overview of JavaScript programming, covering its basics, features, limitations, and how to write a JavaScript program. It discusses key concepts such as objects, methods, variables, data types, and control structures like decision-making and looping statements. Additionally, it highlights the different ways to integrate JavaScript into HTML and the importance of event handling in web development.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views23 pages

CSS Unit 1 (22519)

This document provides a comprehensive overview of JavaScript programming, covering its basics, features, limitations, and how to write a JavaScript program. It discusses key concepts such as objects, methods, variables, data types, and control structures like decision-making and looping statements. Additionally, it highlights the different ways to integrate JavaScript into HTML and the importance of event handling in web development.

Uploaded by

Pallavi Deokar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Contents

UNIT 1. BASICS OF JAVASCRIPT PROGRAMMING ......................................................... 3

Introduction .......................................................................................................................... 3

Features of JavaScript ......................................................................................................... 3

Limitations of JavaScript .................................................................................................... 4

How to Write a JS Program ................................................................................................ 5

Different ways to add JS to the HTML file ................................................................... 5

Object .................................................................................................................................... 6

Object Creation ................................................................................................................ 6

Object Property ................................................................................................................ 6

Method .................................................................................................................................. 8

Dot Syntax............................................................................................................................. 8

Main Event ........................................................................................................................... 9

Values and Variables ........................................................................................................... 9

Datatypes ............................................................................................................................ 10

Operators ............................................................................................................................ 11

Expression........................................................................................................................... 14

Types of Expressions in JavaScript .............................................................................. 14

Decision Making Statements ............................................................................................. 15

1. The ‘if’ statement: ............................................................................................... 15

2. The ‘if-else’ statement: ........................................................................................ 15

3. Nested ‘if-else’ statement: ................................................................................... 15

4. ‘if-else-if’ : ............................................................................................................. 16

5. Switch Case Statement ........................................................................................ 16

Looping Statements ........................................................................................................... 17

a) Entry controlled loops: .................................................................................................. 17

b) Exit controlled loops: ................................................................................................ 19


The ‘continue’ statement: .............................................................................................. 20

The ‘break’ statement.................................................................................................... 21

Querying Properties ............................................................................................................. 21

Setting Properties ................................................................................................................. 22

1. Using dot or bracket notation ....................................................................................... 22

2. Using Object Literal ..................................................................................................... 22

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.

How to Write a JS Program


Web browsers are built to understand HTML and CSS and control those languages into
a visual display on the screen. The part of the web browser that understands HTML and CSS
is called the layout or rendering engine.
But most browsers also have something called JS interpreter. This is the part of the
browser that understands JS and can execute the steps of a JS program.
The web browser is usually expecting HTML, so you must specifically tell the browser
when JS is coming by using the <script> tag.
The <script> tag is regular HTML. It acts like a switch that in-effect says to the web
browser, “Here comes some JS code, you don’t know what to do with it, so hand it off to the
JS interpreter.”
When the web browser encounters the </script>, it knows that it reached the end of the
JS program & can get back to its normal duties.
Different ways to add JS to the HTML file
1. Add the <script> tag in the <head> section:
<html>
<head>
<title>My Web Page</title>
<script type = “text/javascript”> filename.html
</script>
</head>
2. Add the <script> tag in the <body> section:
<html>
<body>
<script type = “text/javascript”> filename.html
</script>
<body>
3. Using external JS file:
It is a text file containing JS code and ending with the file extension ‘.js’. The file is linked
to a web page using the <script> tag.
<html>
<head>
<title>My Web Page</title>
<script src = “jsfilename.js”> filename.html
</script>
</head>
document.write(“This is my first program with external js file”); //jsfilename.js

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.

Values and Variables


In JS, variables can be used to store reusable values.
The values of the variables are allocated using the assignment ‘=’ operator. JS variables must
have unique names.
These names are called identifiers.
There are some basic rules to declare a variable in JS:
 A variable name cannot be a keyword.
 These are case-sensitive.
 Can only begin with a letter, ‘_’ or ‘$’ symbol.
 Can contain letters, numbers, ‘_’ or ‘$’ symbol.
JS variables can be declared in 3 ways:
 Using var
 Using let
 Using const
Syntax: let/var/const variable_name = value;
Example:
var a = 10;
var a = 15; //No error for re-declaration and re-assignment of value
a = 5;
document.write(“a with var: ” +a);
let b = 60;
let b = “ABC”; //Uncaught SyntaxError: Identifier ‘b’ has already been declared
b = “XYZ”; //Re-assignment is possible
document.write(“b with let: ” +b);
const c = 100;
c = 105; // Uncaught TypeError: Assignment to constant variable
document.write(“c with const: ” +c);

Key Differences:

Key var let const


Function Scoped(Accessible
Block Scoped(Accessible
within the function they are Block Scoped(Accessible within
Scope within the function they are
declared in or globally if the function they are declared in)
declared in)
declared outside any function)
Allowed(initialized with
Hoisting Not allowed Not allowed
‘undefined’)
Can be declared without Can be declared without Must be initialized at the time
Reassigning
initialization and can be initialization and can be of declaration and cannot be re-
Value
reassigned. reassigned. assigned.
Redeclaration
Allowed within the same scope. Not allowed. Not allowed.
of Variable

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();

WAP to declare different variables and check their datatype.


let num = 42;
let str = ‘hello’;
let bool = true;
let obj = {name : “ABC”};
let fun = function() {};
let y;
let n = null;
document.write(“num: ” +typeOf(num));
document.write(“str: ” +typeOf(str));
document.write(“bool: ” +typeOf(bool));
document.write(“obj: ” +typeOf(obj));
document.write(“fun: ” +typeOf(fun));
document.write(“y: ” +typeOf(y));
document.write(“n: ” +typeOf(n));

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

7. Conditional (Ternary) Operator


The ternary operator is used to assign a value based on a condition.
Operator Description Example Result
?: Ternary (conditional) operator True? “Yes” : “No” “Yes”
8. Type Operators
Type operators are used to determine the type of a variable or object.
Operator Description Example Result
typeof Returns the type of a variable typeof(42); “number”

Returns true if an object is an let arr = [1,2,3];


instanceof TRUE
instance of a specified object arr instanceof Array;
Expression

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.

Types of Expressions in JavaScript

Expression Description Example


let sum = 5 + 10; // sum is an expression
These involve arithmetic operations that evaluates to 15
Arithmetic
such as addition, subtraction,
Expressions let product = 4 * 3; // product is an
multiplication, division, etc.
expression that evaluates to 12
let greeting = "Hello" + " World!"; // greeting
These involve operations on strings,
String Expressions is an expression that evaluates to "Hello
such as concatenation.
World!"
These involve logical operations like
Logical Expressions let isAdult = age >= 18 && hasID; // isAdult
AND (&&), OR (||), and NOT (!), and
is an expression that evaluates to true or false
they evaluate to boolean values (true or
based on the conditions
false).
These involve assigning a value to a let x = 10; // x = 10 is an assignment
Assignment variable using the assignment operator expression that evaluates to 10
Expressions (=). The entire assignment itself is also let y = (x = 20); // y is 20, and the expression x
an expression. = 20 also evaluates to 20
let greet = function(name) {
These involve defining functions as return "Hello, " + name;
Function Expressions expressions, which can then be assigned
to variables, passed as arguments, or }; // The entire function is an expression that
returned from other functions. can be invoked later
console.log(greet("Alice")); // "Hello, Alice"
let person = { name: "John", age: 30 }; //
Object and Array These involve creating objects or Object expression
Expressions arrays.
let numbers= [1, 2, 3, 4, 5]; //Array expression
These involve the ternary operator (? :), let canVote = (age >= 18) ? "Yes" : "No"; //
Conditional (Ternary) which evaluates a condition and returns canVote is an expression that evaluates to
Expressions one of two values based on whether the "Yes" or "No"
condition is true or false.
Invocation These involve calling functions or let result = myFunction(5, 10); //
Expressions methods. myFunction(5, 10) is an invocation expression
let x = 5;
Increment/Decrement These involve the increment (++) and
let y = ++x; // y is 6, x is also 6
Expressions decrement (--) operators.
let z = x--; // z is 6, x becomes 5
Decision Making Statements
In JS, decision-making statements are used to perform different actions based on different
conditions.
1. The ‘if’ statement:
It is used to execute a block of code if the specified condition is true.
Syntax: if (condition)
{
//block of code
}
2. The ‘if-else’ statement:
It is used to execute one block of code if the specified condition is true and another if the
condition is false.
Syntax: if (condition)
{
//executed if the condition is true
}else
{
// executed if the condition is false
}
3. Nested ‘if-else’ statement:
It is an ‘if’ statement inside another ‘if’ statement. This allows to check for multiple conditions
and execute different blocks of code.
Syntax: if(condition1)
{
//executed if condition1 is true
if(condition2)
{
//executed if condition2 is true
}else
{
// executed if condition2 is false
}
}
else
{
//executed if condition1 is false
}
4. ‘if-else-if’ :
It is an advanced form of ‘if-else’ that allows JS to make a correct decision out of several
conditions. All the ‘if’ conditions will be checked one by one. If any condition is false out
of the given, then that block will be skipped and others are executed.
Syntax: if(condition1)
{
//executed if condition1 is true
} else if (condition2)
{
//executed if condition2 is true
} else
{
//executed if no condition is true
}
5. Switch Case Statement
In JavaScript, a switch statement is a control structure that allows you to execute different
blocks of code based on the value of an expression. It is an alternative to using multiple if...else
statements, particularly when you need to compare the same expression to different values.
Syntax: switch (expression) WAP to print the day of the week based
{ on the given integer input.
case value1: let day = parseInt(prompt(“Enter a
// Code to execute if expression === value1 Number between 1-7”));
break; switch (day) {
case value2: case 1:
// Code to execute if expression === value2 document.write(“Monday”);
break; break;
// More cases... case 2:
default: document.write(“Tuesday”);
// Code to execute if expression doesn't match any cases break;
} case 3:
- expression: This is evaluated once. The value is compared with document.write(“Wednesday”);
the values for each case clause. break;
- case value1: This defines a specific value to match against the case 4:
expression. If the expression matches value1, the document.write(“Thursday”);
corresponding block of code is executed.
break;
- break: This statement is used to exit the switch block. If
case 5:
omitted, execution will continue into the next case, which is
document.write(“Friday”);
known as ‘fall-through.’
break;
- default: This optional block executes if none of the case values
match the expression. It is like an ‘else’ in an ‘if...else’ chain. case 6:
document.write(“Saturday”);
Looping Statements
break;
Looping in programming languages facilitates the execution
of a set of instructions/ functions repeatedly while some case 7:

condition evaluates to true. document.write(“Sunday”);

Loops are generally of 2 kinds: break;

a) Entry controlled loops: default:

The test condition is tested before entering the loop body. document.write(“Invalid day”);

‘for’ loop and ‘while’ loops are entry controlled loops. }


- ‘while’ loop: WAP to print even numbers from 1 to 20 using while loop.
o A while loop is an entry controlled loop that let i = 1;
allows the code to be executed repeatedly if the while (i <= 20)
condition is true.
{
o When the condition becomes false, the loop
if (i % 2 === 0)
terminates which marks the end of its lifecycle.
console.log(i);
o The while loop executes ZERO or MORE
i++;
times.
o Syntax – while (condition) }

{
//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,

if (i % j === 0 && j != i) condition and increment/decrement in


one line thereby providing a shorter,
flag = false;
easy to debug structure of looping.
}
o The for loop executes ZERO or
if (flag == true)
MORE times.
document.write(i + “<br>”);
o Syntax – for (initialization ;
} condition ; increment/decrement)
{
//body of loop
}
- ‘for..in’ loop: WAP to display properties of an object using
o The for..in loop in JS iterates over non-array objects. for..in loop.
Even though we can use for..in loop for an array, it is let person = {
generally not recommended. name: “ABC”,
o In each iteration, one of the properties of object, is
age: 40,
assigned to the loop variable and this loop continues
city: “Thane”
until all the properties of the object are processed.
};
o Syntax – for (var_name in object_name)
for(let key in person)
{
//body of loop console.log(key + “:” + person[key]);

}
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 {

which marks the end of its lifecycle. if (num % 2 !== 0)


o The do..while loop execured ONE or MORE times. console.log (num);
o Syntax – do num++;
{ }while(num <= 20);
//body of loop
} while (condition);
The ‘continue’ statement:
It is used to skip the rest of the code inside a loop for the current iteration and move on to the
next iteration of the loop. This is particularly useful when certain iterations are meant to be
skipped based on a condition without terminating the entire loop.
Syntax – continue;
OR
continue label;
Example1: Using continue in for:
for (let i = 0; i < 10; i++)
{ if (i % 2 == 0)
continue; //Skips all the even numbers
console.log (i);
}
Example2: Using continue in while:
let i = 0;
while (i < 10)
{ i++;
if (i % 2 == 0)
continue; //Skips all the even numbers
console.log (i);
}
Example3: Using continue with a labelled loop:
outerloop: for (let i = 0; i < 3; i++ )
{
for (let j = 0; j < 3; j++)
{
if (j === 1)
continue outerloop;
console.log(`i = ${i}, j = ${j}`);
}
}
The ‘break’ statement
It is used to exit a loop or a switch statement prematurely. When the break statement is
encountered, it immediately terminates the loop or switch and transfers control to the statement
that follows the terminated statement.
- Use of break in loops:
It is often used to stop the loop based on a condition that is met before the loop would naturally
terminate.
- Use of break in switch statements:
It is used to terminate a case and prevent the execution from falling through to subsequent
cases.
Key differences:

Parameter ‘Break’ Statement ‘Continue’ Statement

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);

 Bracket (‘[]’) Notation –


- It is used when the property name is dynamic, contains special characters or
isn’t a valid identifier.
- The value within the brackets must be an expression that evaluates to a string
that contains the desired property name.
- Syntax – object[“property”]

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”;

2. Using Object Literal


Example:
let obj = { When you create an object using an object literal, you can set the data property directly:
data: 'some value'
};
3. Using Object.defineProperty

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.

You might also like