EXPRESSIONS IN JAVASCRIPT

Expressions:

  • An expression is any valid unit of code that resolves to a value.
  • An expression is any valid set of literals, variables, operators, and expressions that evaluates to a single value.
  • The value may be a number, a string, or a logical value.
  • Two types of expressions:

      1. those that assign a value to a variable
      2. those that simply have a value.
For example, the expression
x = 7 is an expression that assigns x the value 7. This expression itself evaluates to 7. Such expressions use assignment operators.
On the other hand, the expression
3 + 4 simply evaluates to 7; it does not perform an assignment. The operators used in such expressions are referred to simply as operators.
JavaScript has the following kinds of expressions:

  1. Arithmetic: evaluates to a number, for example 3.14159.-Generally uses arithmetic operators
  2. String: evaluates to a character string, for example "Fred" or "234"-generally uses string operators
  3. Logical: evaluates to true or false-Generally uses Logical operators.The special keyword null denotes a null value. In contrast, variables that have not been assigned a value are undefined, and cannot be used without a run-time error.
  4. Primary expressions: Basic keywords and general expressions in JavaScript.
  5. Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions
Basic keywords and general expressions in JavaScript.
this:
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method.
Use this either with the dot or the bracket notation.
Syntax:
this["propertyName"]
this.propertyName
Example:
Suppose a function called validate validates an object's value property, given the object and the high and low values:
function validate(obj, lowval, hival){
  if ((obj.value < lowval) || (obj.value > hival))
    console.log("Invalid Value!");
}
Left-hand-side expressions:
Left values are the destination of an assignment.
new:
use the new operator to create an instance of a user-defined object type or of one of the built-in object types.
 Use new as :
var objectName = new objectType([param1, param2, ..., paramN]);
super:
The super keyword is used to call functions on an object's parent.
 It is useful with classes to call the parent constructor.
 Syntax:
super([arguments]); // calls the parent constructor.
super.functionOnParent([arguments]);

Conditional Expressions
A conditional expression can have one of two values based on a condition.
syntax:
(condition) ? val1 : val2
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a conditional expression anywhere you would use a standard expression.
Example:
status = (age >= 18) ? "adult" : "minor"
This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to status.

No comments:

Post a Comment