Javascript Program Flow and Data Structures

Javascript Program Flow and Data Structures ( Loop, Array and Object ) part 4

Welcome to a new class on Javascript Program Flow and Data Structures ( Loop, Array, and Object ) part 4; we will be looking at the various topics under this, if you missed the previous class on Javascript you can check here, and if you will rather start from the beginning of this course, start from here. ; let us begin with:

Javascript Program Flow and Data StructuresJavascript Program Flow and Data Structures: Loops

Loops are another fundamental building block that allows us to run a procedure repeatedly. In this lesson, we will take a look at while and for loops

while loops

To run a segment of code while a particular condition remains true, use a while loop, Take a look at this code

                    

var num = 0;

while(num <= 10) {
  if(num !== 10) {
   console.log("The number is", num, "- less than 10");
  } else {
   console.log("The number is", num, "- the loop is now over");
  }
  num++;

OUTPUT

                    

The number is 0 - less than 10
The number is 1 - less than 10
The number is 2 - less than 10
The number is 3 - less than 10
The number is 4 - less than 10
The number is 5 - less than 10
The number is 6 - less than 10
The number is 7 - less than 10
The number is 8 - less than 10
The number is 9 - less than 10
The number is 10 - the loop is now over

If the condition specified in the while statement is met, the code block will be executed in the while statement.

The program will return to the beginning of the while statement and check to see if the condition is still true after it has been run. If this is the case, the code will be executed once again.

When the while statement’s condition is met, the execution of the code block loops will continue until the condition of the while statement is met.

A word of caution: loops have the potential to run endlessly if the loop is not terminated at some point. In order to ensure that the while loop’s condition does ultimately become false, we add an increment to num at the end of the code block in the beginning.

for loops

for loops are another procedure for running a code block repeatedly. They are constructed using the following syntax:

                    

for( initialization statement; loop condition; ending statement) {
/* code block to execute*/
}

  • The initialization statement is executed before the loop starts.
  • The middle condition determines whether or not the loop will run again.
  • The last statement is executed each time after the loop has been executed.

Let’s take a look at how this works in practice. The following example logs the numbers 0 through 100 to the console:

                    

for(var i = 0; i <= 100; i++){
  console.log(i);
}

OUTPUT

                    

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

The first statement,

sets a variable named i to a value of 0 before the first execution of the loop happens. Then the loop proceeds.

Once the program gets to the end of the code block, it proceeds to execute the last statement,

which increments i to a value of 1. The program then checks the loop condition,

Since i is less than 100, the loop proceeds again. This continues until i reaches a value of 101, where the loop condition becomes false and the loop terminates.

for loops are flexible and you can reach a false condition in many different ways, for example, printing the values of 0 to 100 in reverse:

                    

for(var i = 100; i >= 0; i--){
  console.log(i);
}

OUTPUT

                    

100
99
98
97
96
95
94
93
92
91
90
89
88
87
86
85
84
83
82
81
80
79
78
77
76
75
74
73
72
71
70
69
68
67
66
65
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
48
47
46
45
44
43
42
41
40
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0

Javascript Program Flow and Data Structures: Arrays

In many cases, you will have a collection of connected data that you will need to organize.

Consider the following scenario: we have a list of pupils in a classroom. One method of storing information about individual pupils would be to assign them to a different variable in the database.

                    

var student1 = "Mary";
var student2 = "Barbara";
var student3 = "David";
var student4 = "Alex";

There’s the question of what would happen if you had many students. Separating each pupil into their own variable rapidly becomes a painstaking process.

On the other hand, Javascript includes a number of specific variable types for dealing with large datasets. Let’s get started on one of them right now.

Javascript Program Flow and Data Structures: Arrays

It is possible to store several values in a Javascript array, which is a variable. The values are retrieved through the use of a numerical indexing system.

To create an empty array, place brackets ([]) after the variable definition like follows:

When creating the array, you can also assign values by including them in between the brackets, with commas separating the values. Going back to our example, we can create an array named students like so:

                    

var students = ["Mary", "Barbara", "David", "Alex"];

The values in an array can be accessed by writing the name of the array followed by an index position with the following syntax:

                    
//Logs "Barbara" to the console
console.log(students[1])

OUTPUT

Barbara

Arrays are zero-indexed, meaning the first item in an array will have an index of 0, the second item’s index will be 1And so forth.

In an array, you can store any valid Javascript data type, and you are not limited to storing data of a single type.

So, you could store both Strings and Numbers in an array to indicate a student’s name and age:

                    

var students = ["Mary", 10, "Barbara", 11, "David", 12, "Alex", 11];

Objects

A Javascript object is another variable that allows us to store numerous bits of data in a single location on the computer.

Aside from arrays, objects are capable of holding any acceptable Javascript data type, including arrays and other objects, in addition to other objects. In contrast to arrays, data in objects is kept in object attributes rather than in the object itself.

Once again, let us consider the situation of a classroom full of students: We will create an object out of a single student that has numerous properties:

                    

var student = {
  name: "Mary", 
  age: 10 
}

An object is declared using curly braces ({}). Properties and their values are stored within the curly braces, separated by a colon (:). Each property is separated by a comma (,), which comes after each property’s value.

The following object has two propertiesname and age. You can access the student the object’s property values by looking up a property using either the dot notation or bracket notation:

                    

An object is declared using curly braces ({}). Properties and their values are stored within the curly braces, separated by a colon (:). Each property is separated by a comma (,), which comes after each property’s value.

The following object has two properties: name and age. You can access the student object’s property values by looking up a property using either dot notation or bracket notation:

OUTPUT

Mary 10 Mary 10

As previously stated, an object’s property values can be any valid Javascript data type. Here’s a student object with a grades property with a value that is another object:

                    

var student = {
  name: "Mary", 
  age: 10, 
  grades: {
    quiz1: 90, 
    quiz2: 88, 
    quiz3: 95
  }
}

Once an object has been created, you can add additional properties by using dot or bracket notation:

                    

//set new property values using dot notation 
student.gender = "female";

//set new property values using bracket notation
student["height"] = "122cm";

console.log(student.gender, student.height);

OUTPUT

female 122cm

 

                    

//remove object properties using the delete keyword
delete student.gender;

console.log(student.gender);

Iterating through object properties

Like with arrays, we can use a loop to go through all an object’s properties to access its values.

Javascript provides a special for...in syntax for iterating through object properties. Let’s take a look at another student object and go through its properties:

                    

var student = {
  name: "Mary", 
  age: 10, 
  grades: [90, 88, 95]
}

for(property in student) {
  console.log(property);
}

OUTPUT

name age grades

Notice how this loop logs the object’s properties to the console. To access the value associated with each property, you must use bracket notation, like this:

LET’S REVISE

Since Javascript treats functions as just another variable, it is possible to use the operations array’s functions by accessing them using bracket notation ([]).

We can then use the () operator to invoke the function.

This same logic applies to Javascript objects:

                    

//functions can be stored in an object as property values
var operations = {
  sum: function(x, y){ return x + y; }, 
  subtract: function(x, y){ return x - y; }, 
  multiply: function(x, y){ return x * y; }, 
  divide: function(x, y){ return x / y; }
};

//functions can be called from an object by accessing a property (dot or bracket)
//and using then the () operator
console.log(operations.multiply(5, 10));
console.log(operations["multiply"](5, 10));

Output

50

50

Let’s go back to the student example we were using in earlier lessons.

                    

var createStudent = function(name, age) {
  var student = {
    name: name, 
    age: age
  }
  return student;
}

var student1 = createStudent("Mary", 10);
var student2 = createStudent("Michael", 12);

console.log("Students:", student1.name, student2.name);

Output

Students: Mary Michael

How do you add another students to this to make student3, you can use

                    

var student3 = createStudent("Akinade", 12);

Now, we’ve abstracted the creation of a student into a more general function. This pattern is part of a computer science concept referred to as object-oriented programming.

The idea behind object-oriented programming is to represent data in objects as properties. We can then also define functions (or methods) that allow us to modify those properties. For instance, we could create functionality to increment the student’s age on their birthday:

                    

var birthday = function(student) {
  student.age++;
}

birthday(student1);
console.log(student1.age);

Output

11

As with many other programming concepts, there is a better way to write the code above. Instead of defining a separate function that requires us to pass in the object as an argument, we could make the function another property of the object:

                    

var createStudent = function(name, age) {
  var student = {
    name: name, 
    age: age, 
    birthday: function(){
     this.age++;
    }
  }
  return student;
}

var student1 = createStudent("Mary", 10);
var student2 = createStudent("Michael", 12);

student1.birthday();
console.log(student1.age)

 

this

The code above introduces a new concept: the this keyword. What exactly does this do?

Every time we call the createStudent() function, a new instance of  student object is created. The this keyword allows us to create functions that modify the specific instance of the object to which the function is attached.

Javascript Program Flow and Data Structures

When we call the birthday() function, this takes a look at which object the function is residing in, and then accesses the age property from that object.

Object construction using this

Javascript has a specific syntax for constructing objects. Instead of returning an object, we can simply add properties to a function using this, like example:

                    

var Student = function(name, age) {
  this.name = name; 
  this.age = age;
}

When you use this to add properties to a function, Javascript treats the function as an object constructor because it will instantiate (or construct) a new object with the properties defined using this whenever it is called.

To create a new object using the Student function, we can explicitly instantiate an object using the new keyword, like so:

                    

var student1 = new Student("Mary", 11);

console.log("Student 1: " + student1.name);

OUTPUT

With object constructors, the intent of our code becomes much clearer. Every time we use the new keyword with the Student function, we are creating a new student object.

It should be noted that it is standard practice to start constructor names with a capital letter so that it is clear that the function is an object constructor.

We can also define methods using the constructor syntax:

Leave a Reply

Your email address will not be published. Required fields are marked *