Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views14 pages

JavaScript Control Structures Overview

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)
14 views14 pages

JavaScript Control Structures Overview

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

Lec.

07 JavaScript Control Structures



Objects in JavaScript​ 1
Object References and Copying​ 2
Garbage Collection​ 2
Object Methods and this​ 2
Constructor, Operator new​ 3
Optional Chaining ?.​ 4
Symbol Type​ 4
Object to Primitive Conversion​ 4
Data Types​ 6
Methods of Primitives​ 6
Array Methods​ 7
Object Methods​ 7
Key Notes​ 8
Conditional Statements​ 9
if Statement​ 9
switch Statement​ 10
Loops in JavaScript​ 11
for Loop​ 11
while Loop​ 11
forEach (used with arrays)​ 12
Summary​ 12

1
Objects in JavaScript
●​ Definition: Objects store key-value pairs (properties). Keys are strings
(or Symbols), values can be any type.
●​ Creation:
let user = {
name: "John",
age: 30,
"likes birds": true // Multi-word keys need quotes
};

2
Object References and Copying

●​ Reference Behavior: Objects are copied by reference (not


duplicated).

let user = { name: "John" };

let admin = user; // Both reference the same object

[Link] = "Alice";

●​ [Link]([Link]); // "Alice"
●​ Copying Methods:
○​ Shallow Copy: [Link]({}, obj) or { ...obj }.
○​ Deep Copy: Use libraries like [Link]().

Garbage Collection

●​ Automatic Memory Management: JavaScript automatically removes


unreachable objects from memory.
●​ Key Rule: An object is garbage-collected if no references point to it.

Object Methods and this

●​ Methods: Functions stored as object properties.

let user = {

name: "John",

greet() {

3
[Link](`Hello, ${[Link]}!`); // "this" refers to the object

};

●​ [Link](); // "Hello, John!"


●​ this Behavior: Depends on execution context (e.g., loses this in
standalone functions).

Constructor, Operator new

●​ Constructor Function: Creates objects with shared


properties/methods.

function User(name) {

[Link] = name;

[Link] = false;

●​ let user = new User("John"); // Creates a new object


●​ Steps of new:
1.​ Creates an empty object.
2.​ Assigns this to the new object.
3.​ Executes the function body.
4.​ Returns this (unless another object is returned).

4
Optional Chaining ?.

●​ Safe Property Access: Prevents errors when accessing nested


properties.

let user = {};

●​ [Link](user?.address?.street); // undefined (no error)


●​ Works with: Properties (obj?.prop), methods ([Link]?.()), and
arrays (arr?.[0]).

Symbol Type

●​ Unique Identifiers: Created via Symbol("description").


●​ Use Cases:
○​ Hidden object properties (not accessible without direct Symbol
reference).

let id = Symbol("id");

let user = { [id]: 123 };

●​ [Link](user[id]); // 123

Object to Primitive Conversion

●​ Implicit Conversion: Happens in operations like alert(obj) or


mathematical contexts.
●​ Conversion Methods:
○​ toString(): For string conversion ("expected String").
○​ valueOf(): For number conversion ("expected Number").

5
●​ Priority: JavaScript selects methods based on context (e.g., +obj
uses valueOf, String(obj) uses toString).

6
Data Types
JavaScript has 8 basic data types:

Primitive Types (Immutable)

●​ number: Integers, floats, Infinity, -Infinity, NaN (e.g., 3, 3.14).


●​ bigint: Large integers (e.g., 12345678901234567890n).
●​ string: Text (e.g., "Hello", `Template`).
●​ boolean: true or false.
●​ null: Intentional empty value.
●​ undefined: Uninitialized variable.
●​ symbol: Unique identifiers (e.g., Symbol('id')).

Non-Primitive Type (Mutable)

●​ object: Collections of key-value pairs (e.g., { name: "John" }, arrays,


functions).

Methods of Primitives
Primitives (except null/undefined) temporarily become objects to use
methods:
●​ Auto-Wrapping: JavaScript creates wrapper objects (e.g., String,
Number).
let str = "Hello";
●​ [Link](); // "HELLO" (uses temporary String object)
●​ Common Methods:
○​ Strings: slice(), indexOf(), toUpperCase().

7
○​ Numbers: toFixed(), parseInt().

Array Methods
Arrays ([]) are objects with built-in methods:

Modification

●​ push()/pop(): Add/remove elements from the end.


●​ shift()/unshift(): Remove/add elements from the start.

Iteration

●​ forEach(): Execute a function for each element.


●​ map(): Create a new array by transforming elements.

Searching

●​ find()/filter(): Find elements based on conditions.


●​ includes(): Check if an element exists.

Object Methods
Convert objects to arrays for iteration:
●​ [Link](obj): Returns array of keys.
[Link]({ name: "John", age: 30 }); // ["name", "age"]
●​ [Link](obj): Returns array of values.
[Link]({ name: "John", age: 30 }); // ["John", 30]
●​ [Link](obj): Returns [key, value] pairs.
[Link]({ name: "John", age: 30 }); // [["name", "John"], ["age", 30]]

8
Key Notes
●​ Dynamic Typing: Variables can change types (e.g., let x = 5; x =
"text").
●​ typeof Operator: Identifies types (quirky for null, which returns
"object").
●​ Type Conversion: Implicit coercion (e.g., "3" + 2 = "32").

9
Conditional Statements
Conditional statements let you run different code depending on conditions.
They help the program make decisions.

if Statement
Used to check a condition and run code if it's true.

Example:
let age = 18;
if (age >= 18) {
[Link]("You can vote!");
}

If the condition inside `if` is true, the code inside the curly braces runs.

else Statement
Used when we want to run one block of code if the condition is true, and
another if it's false.

Example:
let age = 16;
if (age >= 18) {
[Link]("You can vote!");
} else {
[Link]("You are too young to vote.");

10
}
else if Statement
Used to check multiple conditions one after another.

Example:
let score = 85;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else {
[Link]("Keep trying!");
}

switch Statement
Used to compare a value with many possible cases.

Example:
let day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of the week");
break;
case "Friday":
[Link]("Weekend is near!");
break;

11
default:
[Link]("Just another day");
}

Loops in JavaScript
Loops let you run the same code many times.
They are helpful when working with many items or repeating tasks.

for Loop
Best when you know how many times to repeat.

Example:
for (let i = 0; i < 5; i++) {
[Link]("Number: " + i);
}

while Loop
Runs as long as the condition is true.

Example:
let i = 0;
while (i < 3) {
[Link]("i is " + i);

12
i++;
}

forEach (used with arrays)


Used to run a function for each item in an array.

Example:
let fruits = ["apple", "banana", "cherry"];
[Link](function(fruit) {
[Link](fruit);
});

Summary
- Use `if`, `else`, and `else if` to make decisions.
- Use `switch` when checking one value against many options.
- Use `for` and `while` loops to repeat code.
- Use `forEach` with arrays to do something for each item.

13

You might also like