Monday, June 26, 2023

JavaScript For in Loop

 

The For In Loop

The JavaScript for in statement loops through the properties of an Object:

for (key in object) {
  // code block to be executed
}

Example

const person = {fname:"John", lname:"Doe", age:25};

let text = "";
for (let x in person) {
  text += person[x];
}

Example Explained

  • The for in loop iterates over a person object
  • Each iteration returns a key (x)
  • The key is used to access the value of the key
  • The value of the key is person[x]                 

    For In Over Arrays

    The JavaScript for in statement can also loop over the properties of an Array:
     for (variable in array) {
      code
    }

    Example


  • const numbers = [45491625];

    for (let x in numbers) {
      txt += numbers[x];
    }
  • let txt = "";

No comments:

Post a Comment

JavaScript Animated

  JavaScript Animated <!DOCTYPE html> <html> <style> #myContainer {   width: 400px;   height: 400px;   position: relative;...