DEV Community

loading...
Cover image for Operators

Operators

winstonpuckett profile image Winston Puckett ・2 min read

2 + 2 = 4

Whenever you've done math, you've used operators. +, -, /, * are all operators that tell you what to do with a set of operands. In fact, the definition is quite similar:

"A symbol which communicates how to change an input or set of inputs."

In math, we think of operating on numbers, but we can also operate on booleans, strings, and other data types.

Unary, Binary, Ternary operators

The prefix is the important part here. "Un-", meaning one, is an operator that operates on one input. Likewise, "bin-" and "ter-" mean two and three respectively.

Here are some examples.

  • !x (Not): A unary operator that flips a boolean value. For instance "true == !false" is true. To read this operator, just substitute the word "not" for the symbol "!".
  • x > y (Greater than): A binary operator that takes in two values and returns true if the left side is greater than the right side.
  • x ? y : z (Conditional operator): A ternary operator that takes in a boolean for the first value, and then if it's true, returns the second. If it's not true, returns the third. This funny little operator can save some mental overhead when used correctly. Just don't chain conditional operators together please.

Assignment vs Comparison Operators

You may have realized that "=" is an operator. In programming, you could assign something like, "x is equal to y," or you can compare something like, "is x equal to y?"

In both cases you would write that our more or less like "x = y". So programming languages often specify the assignment with one equals sign and the comparison operator with two. A valid example looks like this:

// assignment "="
var x = true;
var y = false;

// comparison "=="
if (x == y)
    Console.WriteLine("x and y are equal");
else if (x == true)
    Console.WriteLine("x is true");
Enter fullscreen mode Exit fullscreen mode

Operators vs Functions

One thing that interests me is that an operator is almost like a special type of predefined function. If you think about it, functions take in 0-n parameters and return 0-1 values. We could replace the add operator with an add function relatively easily. If I was going to design a language today, I might try that out.

Next steps

I've told you what an operator is, but I haven't talked about many specific operators. Go look up boolean operators (as these are the basis for a lot of programs), and then make sure you understand the modulus operator. Learning these will give you practice replacing operator symbols with meaningful words, and then reading operations as a sentence in your head.

Discussion (0)

pic
Editor guide