Other Operators


Other Operators

🙋 Need help? Ask an expert now!

There are many other operators that exist in JavaScript, and you will not recognize most of them just yet. Don't worry, we will cover them later in the course. The first operator is +, which represent string concatenation. If the second operand is not a string when the operator is used, the second operand is converted to a string automatically.

The member access operator . is used to access object members. For example, you can access the pi field inside the Math object using a member access operator. Square brackets [] are used as indexers, to access a member with a certain variable, such as strings and arrays. Parentheses ( ) are used to override the default operator precedence or to invoke functions.

Conditional operators are a little more confusing. The conditional operator ?: has the form b ? x : y. If the expression b is true, then the result is x else the result is y. The sample code below has an example of the conditional operator and how it functions.

Finally, the new operator is used to create new objects, as shown before. Another operator you should be familiar with is the typeof operator, which returns the data type of the value.

Let's go through the different operators shown in the sample code above one by one. The string concatenation prints "FirstSecond15" instead of "FirstSecond6" because the "1" and the "5" are automatically converted to a string, which is why the addition did not work. The member access operator shows how the pi field in the Math object can be accessed using the dot notation. The square brackets are used with a data type called the array, which you will learn in the future. The statement names[0] will always print the first element of the array names. The parenthesis show how operator precedence is overruled using the parenthesis, just like how it would be in a regular mathematical expression. The conditional operator will print one of the statements based on whether or not "a > b" is true. Try changing the values of a and b and see if you can print the other statement. The new operator creates a new Number object with the value 4. Finally, the typeof operator prints the data type of the given value. In this case, it will print "number".

Edit Me on GitHub!

Application Question

Consider the following code segment:

var fibonacci = [1, 1, 2, 3, 5, 8];

What does the console.log() statement above print?