Chapter 9. JavaScript Expressions, Operators, Statements, and Arrays

JavaScript is the most commonly used web programming language and is very popular among developers around the world. This chapter will cover most of the expressions, operators, statements, and arrays used in this language.

Expressions

A valid unit of code required to resolve a value is known as an expression. It is a set of literals, operators, variables, and expressions required to evaluate a value. This value can be a string or any logical value. An expression results in a value that can be written wherever a value is expected. There are two types of expressions:

  • An expression that assigns a value to a variable
  • An expression that has a value

Consider the following example:

var A = 2;

In the preceding example, a value is assigned to variable A, and for assigning that value to the variable, we use an assignment operator. Now consider another example:

2+3;

In this example, no value is assigned to a variable; however, it evaluates the result of 2+3 as 5. The operator used in this expression is known as an addition operator.

Expressions in JavaScript can be broadly classified into three types:

  • Arithmetic: These evaluate numbers. This means that these expressions perform mathematical calculations between values.
  • Logical: These are used to evaluate and give the result in the form of true or false.
  • String: These are used to evaluate strings.

Note

There is another type of expression known as a conditional expression. These expressions are usually used in the if-else and loop conditions. These conditional expressions evaluate the result in the form of true or false and have only two values True and False. If the first condition is true, then it will evaluate first, otherwise it will evaluate second, for example:

int age = 20;
var flag;
if (age<18) {
  flag=true;
}
else {
  flag=false;
}

Primary expressions

In JavaScript, primary expressions are basic keywords and they are special objects, identifiers, and literals, which do not need any further evaluation to resolve their value. They may also be the result of another expression that is surrounded by brackets.

For example, this and function are keywords and these are primary expressions in JavaScript. The this keyword always returns a value whenever it enters an execution context. Identifiers are also primary expressions, and they refer to a function or an object.

There are four types of literals, as primary expressions:

  • Boolean literals: These contain 1/0 or true/false
  • Null literals: These contain a null value
  • Undefined literals: These contain any type of data type
  • String literals: These contain a string of characters

Object initializer

In JavaScript, an object initializer is used to initialize an object. It is an expression known as an object initializer. Every object in JavaScript is an entity that has a type. Every object has some property associated with it. There are functions associated with objects and these functions are called methods. Objects properties are basically JavaScript variables. A property associated with an object tells you about the object's characteristics.

Object properties can belong to primitive data types such as int or other data types such as char. An object can have an empty property as well. We can create an object with an empty property, as follows:

var xyz={};

In these curly brackets, you can easily and quickly create objects. These are comma-separated name-value pairs. The object initializer is basically used to create a new object. These object initializers are called object literals.

Tip

In JavaScript, the property name and object name are case sensitive, so when you create an object, this should be kept in mind.

An object initializer creates an object with a literal notation, for example:

var studentInfo =  {  age:24, Name:"Ali" };

This is covered in more detail in Chapter 8, JavaScript Object-Oriented Programming.

The function definition expression

Functions in JavaScript are defined with a function keyword. Expressions are defined on these functions. They are used to declare a function or function expression. You can define a function anywhere in your script. Functions use expressions to define their prototype.

There are many ways to define a function in JavaScript, for example, we have the following:

  • The function declaration
  • The function expression

The function declaration

When a browser thinks of executing a script, a function declaration is a pre-executed stage. A function can be declared anywhere in your code:

function greetings() {
  alert("Happy New Year");
}
greetings();

The function expression

When a function takes the form of an expression, it is called a function expression. This expression can be a large expression, meaning that the function declaration requires several expressions. The function that is assigned with a function expression can be named or can be without a name. This is commonly referred to as an anonymous function. It is a first-class value, which means that it allows passing values in the function as parameters.

Consider the following example:

var abc=function() {
  return 1;
};

 var xyz=function foo() {
  return 2;
};

A function value can also be assigned to another function parameter. In this way, a function value is passed to another function parameter as a pass-by-value.

var f = function f ( function foo() );

A function in JavaScript is also a regular value. If you do not want your variables to be set in the global scope, then put these variables into a function. We do this because it's not always a good choice to set a global variable, as it can be accessed by any function anywhere in the program, which may alter the value of the variable and overwrite the original value that was supposed to be used. Functions are generally written inside brackets because JavaScript allows expressions to be all in the same space.

The property access expression

In JavaScript, to access a value of an object or value of an array element, we use the property access operation. There are two ways of writing the property access expression to access values from these expressions:

  • Bracket notation
  • Dot notation

The bracket notation

A bracket notation is also known as an array notation. The syntax for writing a bracket notation is as follows:

get=abc[xyz];
abc[xyz]=set;
get = abc [1]; // get value at array abc index 1 

The dot notation

A dot notation is also known as an object notation. The syntax for writing a dot notation is as follows:

 document.write ("hello world");

The invocation expression

In JavaScript, an invocation expression is used to execute or invoke a function or an expression. When a function invocation starts, it first evaluates its expression and then its arguments. Here are the two targets on an invocation expression:

  • The invocation target
  • The optional argument list

Invocation target

An invocation target followed by an open bracket then a target list and then a closing bracket target list must be classified as a method or object. There are two types of argument lists:

  • Positional arguments
  • Named arguments

Positional arguments are expressions and named arguments are identifiers. Here is an example of an invocation expression:

Function.getvalue(5);
Math.max(2,3);

Named arguments are the arguments that are passed with its name.

The optional argument list

Variable is assigned a value that is passed as a parameter to the function. If the value is not passed, a default value is assigned to the variable:

function add(a, b) {
  b = typeof b !== 'undefined' ?  b : 0; // if b not defined set it to 0
  return a+b;
}

add(10); // returns 10

The object creation expression

In JavaScript, this expression is used to create an object using the constructor method. This method is used to initialize an object's properties. This method first creates new objects and then initializes the objects using object initializer methods in JavaScript. The constructors that are used to initialize the object do not return any value, and this value becomes the value of the object. Consider the following example:

New myObj();

Evaluation expression

The evaluation expression is used to evaluate a string. This is a property of the global object in JavaScript. When it evaluates a string, it gives a value as the output.

The Eval() function is used in JavaScript to get a value. In this function, we do the following:

  • As the input, we pass one argument
  • If it does not return a value, then it means that there is an error in the code, and it will send an exception
    var x = 10;
    console.log(eval("x * 5")); //50

There are two ways you can invoke an eval() function:

  • Direct: Calls a function directly named 'eval'. Direct eval() executes code in its local scope. For example:
    var abc = 'global scope';
        function directEval() {
            'use strict';
            var abc = 'local scope';
            console.log(eval('abc')); // local scope
        }
  • Indirect: By calling it through call() function, method of window or by storing it with a different name and calling from there, etc. Indirect eval() executes code in its global scope. For example:
    var abc = 'global scope';
        function indirectEval() {
            'use strict';
            var abc = 'local scope';
            // eval via call()
            console.log(eval.call(null, 'abc')); // global scope
            console.log(window.eval('abc')); // global scope
            console.log((1, eval)('abc')); // global scope
            // eval with a different name
            var abceval = eval;
            console.log(abceval('abc')); // global scope
            var obj = { eval: eval };
            console.log(obj.eval('abc')); // global scope
        }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.10