JavaScript Coding Challenge Flashcards
CODE: In JavaScript how can you check for all variables defined in the global scope (e.g. window)?
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.
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?
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(,
)
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?
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]}
)
}