Javascript Expressions

In Javascript, the expression refers to a logical or mathematical equation for calculating a specific thing.

Example:

var x, y, z; // statement-1
x = 8; // statement-2
y = 10;  // statement-3
z = y - x; // expression-1, statement-4
document.getElementById("result").innerHTML = z; // statement-5

We can see from the above example, variable declaration, variable assignment, printing out the result, etc are statements as we already learned in the previous tutorial.

z = y - x can be considered as an expression because this line involves calculation although it assigns the value of z variable. But the value will be the result of y - x which is an arithmetic operation.

Expressions also can be considered as a statement. Means, every expression is a statement. But not all the statements are expressions.

Expressions Important Facts

Expressions are an important concept in programming, not only in Javascript, expressions are very important in every programming language. One of the repeated program error made by programmers is logical errors.

In general, the logical error happens for implementing incomplete or corrupted expressions. That’s why a program may output unwanted result and unexpected behavior because of wrong expressions. So we have to be concern about expression. And that’s why expression is important.

We will learn more about Javascript error in the later chapters.

Example:

var x, y, z, a;
x = 8; // statement
y = 10;  // statement
a = x * y;  // expression, statement
z = y - x; // expression, statement
a = a + z * x; //logical error, should be maintain calculation order
console.log(z); // statement

In the above example, a = a + z * x the expression may output unexpected result. Because you have to refer the calculation order by using the first bracket. Something like this, a = (a + z) * x if you want to add a and z first.

In this case, if you avoid bracket then conventionally z and x will multiply first and then the result will be added with a. This will probably output the wrong result.

Focusing on the expressions, while writing source code we can avoid this kind of errors. And the concept of expressions can help us to avoid program error, especially logical errors.

« Previous Next »