# Introducing Operators, Loops and Functions

Objectives
After completing this lesson, you will be able to:

After completing this lesson, you will be able to:

• Explain operators
• Discover loops
• Describe functions
• Objects in JavaScript

## Assignment Operator

JavaScript operators allow us to perform tests, do math, join strings together, and other such things.

### Assignment operator

An assignment operator assigns a value to its left operand. This value is based on the result of the right operand. The simplest assignment operator is the "equal" (=), which assigns the value of the right operand to the left operand.

## Comparison Operator

A comparison operator compares its operands and returns a logical value based on whether the comparison is true or not.

The operands can be numeric, string, logical, or object values. Strings are compared to Unicode values based on the standard lexicographic order. If the two operands are not of the same type, JavaScript will in most cases attempt to convert them to a suitable type for comparison. This behavior generally results in the operands being compared numerically. The only exceptions to type conversion within comparisons are the operators === and !==, which perform strict comparisons. These operators do not attempt to convert the operands to compatible types before checking equality.

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

## Arithmetic Operators

An arithmetic operator takes numeric values (literals or variables) as operands and returns a single numeric value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*) and division (/). These operators work as in most other programming languages when used with floating point numbers (note in particular that division by zero gives infinity).

In addition to the standard arithmetic operators (+, -, * /), JavaScript provides other arithmetic operators.

## String Operator

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

## Bitwise Operators

A bitwise operator treats its operands as a set of 32 bits (zeros and ones) rather than decimal, hexadecimal, or octal numbers - for example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations with such binary representations, but they return standard numeric JavaScript values.

## Arrays

Arrays are generally described as "list-like objects". They are basically single objects that contain multiple values stored in a list. Array objects can be stored in variables and dealt with in much the same way as any other type of value, the difference being that we can access each value inside the list individually, and do extremely useful and efficient things with the list, like loop through it and do the same thing to every value. Maybe we have got a series of product items and their prices stored in an array, and we want to loop through them all and print them out on an invoice while totaling all the prices together and printing out the total price at the bottom.

Arrays consist of square brackets and items that are separated by commas.

You can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property.

Items in an array are numbered, starting from zero. This number is called the item's index. Therefore, the first item has index 0, the second has index 1, and so on. You can access individual items in the array using bracket notation and supplying the item's index in the same way that you accessed the letters in a string.

This is fine if you know the index of an item, but what if you do not? You can find the index of a particular item using the `indexOf()` method. This takes an item as an argument and returns the index, or -1 if the item was not found in the array.

To add one or more items to the end of an array, you can use `push()`. Note that you need to include one or more items that you want to add to the end of your array.

To remove the last item from the array, use `pop()`.

If you know the index of an item, you can remove it from the array using `splice()`.

Frequently, you will want to access every item in the array. You can do this using the `for` statement:

Occasionally, you will want to do the same thing to each item in an array, leaving you with an array that contains the changed items. You can do this using `map()`.

## Loops

Programming languages are very useful for swiftly completing repetitive tasks, from multiple basic calculations to just about any other situation where you've got a lot of similar items of work to complete. In this lesson, we examine the loop structures available in JavaScript that handle such needs.

Loops are all about doing the same thing repeatedly. Frequently, the code will be slightly different each time round the loop, or the same code will run but with different variables.

### For Loop

The `for` statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

1. The initializing expression `initialExpression`, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.

2. The `conditionExpression` expression is evaluated. If the value of `conditionExpression` is true, the loop statements execute. If the value of condition is false, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.)

3. The statement executes. To execute multiple statements, use a block statement `({ ... })` to group those statements.

4. If present, the update expression `incrementExpression` is executed.

5. Control returns to Step 2.

### Type of Loop - while and do ... while

`for` is not the only type of loop available in JavaScript. There are actually many others and, while you do not need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.

### Type of Loop - condition

The loop condition is evaluated at the beginning of a loop pass. If the evaluation is true, then the loop body is run through (and the statement is executed). If the condition is false, the program continues with the first statement after the while loop.

### Type of Loop - statement

An optional statement is executed as long as the condition is true. Multiple statements must be grouped into a block statement: `({ ... })`.

Note

A break statement can be used to end the loop prematurely before the condition changes to false.

The `do...while` statement creates a loop that executes a specific expression until the statement to be checked becomes false. The statement is checked after the expression has been executed, so that the expression is executed at least once.

### Type of Loop - for...of Loop

The `for...of` statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects, Typed Array, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

## Functions

### Overview

Functions are a way to package together functionalities that are to be reused. Whenever the functionality is needed, the function is called under its name instead of having to rewrite the same code repeatedly. A function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function can return a value.

Every function in JavaScript is a Function object.

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object, which you will learn later in this course.

The parameters of a function call are the arguments of the function. Arguments are passed as values of the function. If the function changes the value of an argument, the change does not take effect globally or in the calling function. To return a value other than the default, a function must have a return statement that specifies the value to return. Object references are also values, which are special: If the function changes the properties of a referenced object, the change is visible outside the function.

### Scope Functions

Variables defined in a function cannot be reached outside the function because the variables are only defined in the scope of the function. In contrast, a function can reach all variables and functions that were defined in the scope in which the function was also defined. In other words, a function defined in the global scope can reach all variables and functions of the global scope. When a function is defined in a function, the inner function can access all definitions of its parent function and all definitions to which the parent function has access.

### Function Declarations

The simplest way to define a function is the so-called function declaration.

A function declaration statement starts with the keyword function and the function name, followed by a pair of round brackets and a function body with a statement block. Parameters for the function can be specified in the parentheses, separated by commas. A semi-colon after the curly brackets is not required.

The parameter list between the two round brackets is a comma-separated list of names. Within the function, you can access the passed parameters by using the assigned names.

There is often confusion between two terms: parameters and arguments. The values that you pass to a function when you call it are the arguments. The variables in which the arguments are then available within the function are the parameters.

Between the two curly braces, the function body is noted: this houses the instructions that are to be executed when the function is called.

As in the case of variable declarations, the function declaration statement is also subject to automatic hoisting to the beginning of the scope in which it is located. This has the advantage that you can also call a function from places before the function declaration statement.

### Calling Functions

Defining a function does not execute it yet. The definition only gives the function a name and describes what should happen when the function is called. Only the call makes it possible to perform the actions with the specified parameters.

Functions must be in scope when they are called. The arguments of a function are not limited to strings and numbers, because whole objects can also be passed.

### Function Expression

A function expression is very similar to a function statement and has almost the same syntax. The biggest difference between a function expression and a function statement is the function name, which can be omitted in the function expression to create an anonymous function.

Function expressions in JavaScript are not hoisted, unlike function declarations. You cannot use function expressions before you create them.

A function expression can be used as an Immediately Invoked Function Expression (IIFE), which is executed immediately after definition.

Immediately Invoked Function Expressions (IIFEs) are very useful because they do not pollute the global object, and they are a simple way to isolate variables declarations.

Function declarations want a name, while function expressions do not require it.

This function is executed immediately as soon as the source code is executed. We immediately get the alert message "Hello".

### Return Statement

Functions can contain one or more return statements.

When a return statement is called in a function, the execution of the function is stopped. If a return value is specified, it is returned to the calling function. If no return value is specified, undefined is returned instead.

Functions can yield these returns:

• Primitive values (string, number, boolean, and so on)
• Object types (arrays, objects, functions, and so on)

To refer to the current function within the function body, you must create a named function expression. This name is then local only to the function body.

### Variables in Functions

All variables that are declared within a function with `var` or `let` are only known and valid within the function.

If a variable with the same name is defined in another function, the variables do not interfere with each other and cannot overwrite each other.

In the example below, we define the `calculateSquare` function with one parameter. In the function body, we create a local variable named result. This variable is only available in the function. We assign to the variable the method sqrt from the math object, which belongs to the global objects in JavaScript. We will talk about objects and their methods later. This method calculates the square root for us. We give this method our argument number and then return the value.

### Parameters and Arguments of Functions

Different arguments can be passed each time a function is called. Parameters are placeholders for current values - which are called arguments.

Missing parameters are considered undefined and do not cause an error.

A function call can pass more arguments than the function expects.

### Built-in Browser Functions

The JavaScript language has many built-in functions to allow you to do useful things without having to write all that code yourself.

As an example, there is the built-in function, `parseInt()`.

The `parseInt()` function parses a string argument and returns an integer of the specified radix.

The function contains the base of the number system for the conversion as a second optional parameter, which should always be specified.

### Closure

One can nest one function inside another. The nested (inner) function is private within its container function (outer function). It also forms a closure. A closure is an expression that can contain free variables (typically a function) together with an environment that encloses those variables (and thus closes the expression, hence the name closure).

Because a nested function is a closure, this means that it inherits the arguments and variables of its container function. In other words, the scope of the inner function contains the scope of the outer function.

Functions can be nested several times, for example, a function (A) contains a function (B) which contains a function (C). Both functions, B and C are closures, B can reach A and C can reach B. In addition, C can also reach A, because C can reach B and B can reach A. Therefore, a closure can contain several scopes; it recursively contains the scopes of the function that is the container. This is called scope chaining.

Closures are one of the most powerful functions of JavaScript. JavaScript supports the nesting of functions and allows the inner function full access to all defined variables and functions of the outer function (and all other variables and functions that the outer function can reach). However, the outer function does not have access to the variables and functions defined in the inner function. This supports more or less security for the variables of the inner function. If the inner function has access to the scope of the outer function, the variables and functions of the outer function must live longer than the executions of the inner function, because the inner function manages the survival of the outer function. A closure is created when the inner function is somehow made accessible in an outer scope of the outer function.

The closure is a special object with two extraordinary characteristics - it includes both the function and the environment in which it was created. This environment consists of all local variables that were in scope at the time the closure was created. In the example (in the figure above), myFunc is a closure that includes both the function myFunc and the string "JavaScript" that existed when the closure was created.

To summarize: the inner function can only be reached by statements of the outer function.

The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

If two arguments or variables exist in the scope of a closure with the same name, there is a name conflict. The innermost scope then has priority, which means that the innermost scope has the highest priority while the outermost scope has the lowest priority. This is because of scope chaining. The first link in the chain is the innermost scope and the last link is the outermost scope.

## Objects

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.

A property can store another object. This nesting of objects creates an arbitrarily long chain of objects that refer to each other.

JavaScript distinguishes between simple values and objects.

An object works as an assignment list that stores specific values under specific names. This name-value pair is called a property.

A property of an object can be explained as a variable that is attached to the object. Object properties are essentially the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object.

## Object literals

The simplest way to create an object in JavaScript is to use an object literal. This starts with an opening curly bracket { and ends with a closing bracket }. In between, the properties are listed with name and value. There is a colon between name and value, and a comma between the properties.

You can access the properties of an object with a simple dot-notation.

The properties of JavaScript objects can also be accessed or set using a bracket notation.

Another way of creating objects is using the `Object()` constructor function using the new keyword. Properties and methods can be declared using the dot notation `.property-name` or using the square brackets `["property-name"]`:

For now, we will just look at the two options. There are other ways to create objects.

## Methods

We can also define a function in an object in the properties. These properties are then called methods. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.

You can then call the method in the context of the object, as shown the figure, Example of Methods (II).

## Standard Objects

JavaScript provides its own objects. They can be seen as a kind of library containing useful properties and methods and can be used at any time without being created first. The standard objects include:

• Array
• String
• Date
• Math

Math is a built-in object that has properties and methods for mathematical constants and functions. It is not a function object.

Math works with the Number type. It does not work with BigInt.

The `Math.random()` method returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range, which you can then scale to your desired range.

## Window Object

The window object represents a window in browser.

HTML body automatically creates a Window object in Javascript. In browsers with tabs, each tab is an independent window, that is, a Window object.

The properties of the Window object provide information about the width and height of the browser window, its methods control animations, window events like onload check whether the document and all resources are loaded.

You can use the window object to get information about the history of the browser window (where was the user before?), operating system, browser type, and so on.

However, there are strict limits to the manipulation of these objects.

## The Document Object

The Document Object Model (DOM) is a standardized programming interface for structuring HTML and XML documents. It was developed and published by the World Wide Web Consortium.

The purpose of the Document Object Model is to make it as easy as possible for programmers to access the components of a web project and thus add, delete, or edit content, attributes, and styles. DOM serves as a platform-independent and language-neutral link between scripting languages such as JavaScript and the underlying web document by representing the structure of the document in a tree structure in which each node is an independent, controllable object. As a result of this form of structuring, the variant of a web project represented in this way is also referred to as a DOM tree.

According to the DOM, the elements of an HTML document are sub-objects of the document object. The individual HTML elements can have their own properties and methods.

Here are two methods of the document object as an example:

`querySelector()` - This method returns the first element within a document that matches the specified selector or selectors. To search for an ID, you must first set a hash sign. For a class, a dot must be set as this:

• `alert()` - Displays the alert box containing message with the OK button.
• `prompt()` - Displays a dialog box to get input from the user.
• `createElement()` - In an HTML document, this method creates a specified HTML
• `elementappendChild()` - This method appends a node (element) as the last child of an element

Save progress to your learning plan by logging in or creating an account