Skip to content

Latest commit

 

History

History
171 lines (161 loc) · 2.39 KB

23. for...in and for...of Loop.md

File metadata and controls

171 lines (161 loc) · 2.39 KB

for...in and for...of Loop

JavaScript for...of loop

Example 1

const numbers = [1, 3, 5, 9];

for (const element of numbers) {
  console.log(element);
}

Output

1
3
5
9

Example 2

const members = ['John', 'Sara', 'Jack'];
 
for (const name of members) {
  let fullname = name + ' ' + 'Smith';
  console.log(fullname);
}

Output

John Smith
Sara Smith
Jack Smith

for...of with strings

const name = 'Programiz';

for (let i of name) {
    console.log(i);
}

Output

P
r
o
g
r
a
m
i
z

JavaScript for...in loop

Example 1

const student = {
    name: 'Monica',
    class: 7,
    age: 12
};

console.log(student);

Output

{ name: 'Monica', class: 7, age: 12 }

Example 2

const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

for (let key in student) {
  console.log(key);
}

Output

name
class
age

Example 3

const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

for (let key in student) {
  let value = student[key];
  console.log(`${key} => ${value}`);
}

Output

name => Monica
class => 7
age => 12

Change Object values using for...in

const employee = {
    Jack: 24000,
    Paul: 34000,
    Monica: 32000
}

for (let i in employee) {
  let salary = employee[i] + 5000;
  console.log(`${i} : ${salary}`);
}

Output

Jack : 29000
Paul : 39000
Monica : 37000

Programming Task

Create an array named names with values: "jack", "rosie", "mira". Now, use a for...of loop to print each name of the array. However, while printing the name, change the first character to uppercase.

Solution:

const names = ['jack', 'rosie', 'mira'];
for (let element of names) {
    const result = element.charAt(0).toUpperCase() + element.slice(1);
    console.log(result);
}

Output

"Jack"
"Rosie"
"Mira"

Programiz Quiz

Q. What is the output of the program?

const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

for ( let key of student ) {
    console.log(`${key} => ${student[key]}`);
}
  1. Error
  2. name => Monica class => 7 age => 12
  3. name => name class => class age => age
  4. Monica => Monica 7 => 7 12 => 12

Answer: 3