JavaScript Coding Challenge Flashcards

1
Q

CODE: In JavaScript how can you check for all variables defined in the global scope (e.g. window)?

A

Code:

for (let variableName in window) {
if (window.hasOwnProperty(variableName)) {
console.log(variableName);
}
}

In this code:
1) The for…in loop iterates through all properties of the window object.

2) The hasOwnProperty() method is used to check if the property is directly defined on the window object and not inherited from its prototype chain. This helps filter out built-in properties and methods.

3) The console.log() statement logs the variable names to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

CODE: In JavaScript if you have a code like this:

const turtle1 = ‘Leonardo’;
const turtle2 = ‘Raphael’;
const turtle3 = ‘Donatello’;
const turtle4 = ‘Michelangelo’;

let allTurtles = ‘’;

How would you loop this into the allTurtles variable?

A

Easiest way here is to create an array and then use the array method .join to get all together.

e.g.

let turtleArray = [turtle1, turtle2, turtle3, turtle4]
allTurtles = turtleArray.join(, )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

CODE: Imagine you want to create a loop with which you want to access each character of a string.

How would you do it with a while loop?
How would you do it with a for loop?

A

const phrase = “Knock knock”;

WHILE LOOP:
let count = 0;

while (count < phrase.length) {
console.log(The ${count}. character of phrase is: ${phrase[count]});
count += 1;
}

FOR LOOP:
for (i = 0; i < phrase.length; i++) {
console.log (The ${i}. character of phrase is: ${phrase[i]})
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly