Lecture-3 Loops, Arrays, Function and Object-3267
Lecture-3 Loops, Arrays, Function and Object-3267
Loops
● Loops are used to continually run a piece of code until a certain condition is
fulfilled. There are three types of loops in JavaScript: for, while, and do-while.
● Loops are powerful tools for performing repetitive tasks in programming. They
allow you to write more concise and efficient code by automating repetitive
tasks.
For loop:
A for loop is used to iterate over a specific range of values or over a collection of
elements. It is advisable to utilize this loop when you are aware of the anticipated
number of iterations.
The general syntax of a for loop is:
While loop:
This loop is best used when you don't know the number of iterations in advance but
have a condition that must be checked before each iteration. A while loop is used
to execute a block of code as long as a condition is true.
The general syntax of a while loop is:
Here, the condition is a boolean expression that is evaluated before each iteration
of the loop. The code inside the block will be executed repeatedly as long as the
condition is true.
Do-while loop:
This loop is similar to the while loop, but the condition is checked at the end of
each iteration instead of the beginning. This means the loop will always execute at
least once, even if the condition is initially false.
The general syntax of a do-while loop is as follows:
Functions
A function in JavaScript is a block of code that performs a specific task. It takes
inputs (parameters) and returns a value or performs an action.
Creating a function
Creating a function in JS involves the following steps:
1) Use the function keyword followed by the function name.
2) Inside the parentheses, specify any parameters the function will accept (if
any).
3) Define the code to be executed by the function inside curly braces.
4) Use the return keyword to specify the value to be returned by the function (if
any).
In this example, addNumbers is the function name and num1 and num2 are
the parameters. The function adds the two parameters and prints the result.
Parameters vs arguments
Parameters are the variables declared in a function's definition. Arguments are the
values passed to the function when it is called.
Return statements
● Functions in JavaScript can optionally return a value using the return
keyword. The value returned by a function can be used in other parts of the
code.
● The return statement is used to stop the execution of a function and return a
value to the calling code.
● A function can only have a single return statement. This means that once the
return statement is executed, the function will immediately terminate and
return the value specified by the statement.
● Any statements that appear after the return statement will be considered
"unreachable code," meaning they will not be executed. It's important to keep
this in mind when designing functions, as any code written after the return
statement will not have any effect on the function's output.
Invoking a function
To call a function in JavaScript, we simply need to use the function name followed by
parentheses and any arguments (if required) inside the parentheses. Here's an
example:
In this example, 5 and 10 act as arguments, and the value of the variable result is
equal to the function's return value.
Arrays
In JavaScript, an array is a collection of data values of any data type. Arrays are a
fundamental data structure and are used to store and manipulate data in many
JavaScript programs.
2. pop(): removes the last element from an array and returns it.
● Note that the `pop()` method in JavaScript returns the value of the
element that was removed from the end of the array.
Here,
○ array: The array to be modified
○ start: The index at which to start changing the array. If
negative, it will begin that many elements from the end of the
array.
○ deleteCount: An integer indicating the number of old array
elements to remove. If set to 0, no elements are removed.
○ item1, item2, ... item N: The elements to add to the array,
beginning from the start index. If you don't specify any elements,
splice() will only remove elements from the array.
● Using for loop: The general for loop works iterates over an array as
shown:
In this example, the loop iterates over each element of the myArray array and
logs it to the console.
● Using for…of loop: A more concise way to iterate over an array is by using
this loop shown as below:
In this example, the for...of loop iterates over each element of the
myArray array and logs it to the console.
○ You can also use other loop types, like while and do...while, to
iterate over arrays, but for and for...of are the most commonly
used.
○ When iterating over arrays using loops, it's essential to remember the
array index and length to avoid errors like going out of bounds or
skipping elements.
● Using for…in loop: In JavaScript, the for...in loop is used to iterate
over the properties of an object (to be covered later), but it can also be used
to iterate over the elements of an array. Here's a short example of how to use
the for...in loop to iterate over an array:
Note that while it's possible to use the for...in loop to iterate over an array, it's
generally recommended to use the for...of loop instead, as it's specifically
designed for iterating over iterable objects like arrays and avoids potential issues
with inherited properties and unexpected behavior.
Loop
Type Syntax Iterates Over Returns
Values of an iterable
object (e.g. array,
for...of for (variable of iterable) { ... } string, etc.) Value
Break and Continue
In JavaScript, break and continue are keywords used inside loops to control the
flow of the iteration.
● break is used to exit out of a loop entirely when a certain condition is met.
Once the break statement is executed, the loop will stop and control will
move to the next line of code after the loop.
For example:
● continue is used to skip the current iteration of a loop and move on to the
next iteration. Once the continue statement is executed, any code that
comes after it within the current iteration will be skipped.
For example:
● In this example, we have two arrays arr1 and arr2. We want to create a new
array that contains all the elements from both arrays. We can use the spread
operator to do this.
● By using ...arr1 and ...arr2, we are spreading out the elements of the
arrays and adding them to the new array arr3.
● Finally, we log the new array arr3 to the console, which contains all the
elements from arr1 and arr2.
○ A shallow copy creates a new object or array, but only the top-level
values are copied by reference. This means that if any copied values
are themselves objects or arrays, they will still be referenced to the
original objects or arrays.
● In the example above, we have an object person with three properties: name,
age, and hobbies. The hobbies property is an array of strings.
● To access the properties of the object, we can use dot notation (e.g.
person.name) or square bracket notation (e.g., person['name']).
● To access elements of the hobbies array, we use the square bracket notation
with the index of the element we want to access (e.g., person.hobbies[0]
to access the first element of the hobbies array).
Summarizing it
Let’s summarize what we have learned in this Lecture:
● Different types of Loops (for, while, and do while)
● Function in JS
● Arrays in JS
● Break and Continue
● Spread and Rest operator
● Objects in JS
References
● In-built Array methods: Link