Alert!! Operators are Functions in Javascript ??
imsabir
Posted on December 2, 2022
An operator is actually a special function that are written in your code.
Generally, operators take two parameters and return one result.
Let's look at an example.
var a = 3 + 4;
console.log(a); //7
Quite easy to guess what you will see on screen
Seven i.e. 3+4 = 7
No rocket science in this.
But
** How did the JavaScript engine do that? **
How did it know that this was my intent to add three and four?
Well, code, saw the plus sign and added these two numbers.
This plus sign is an operator.
It's the addition operator and it's actually a function under the hood.
It would be as if I declared a function and instead of giving it the name add and instead, simply gave it the name plus.
Gave it two number and then returned.
Like
function +(3,4){
//
}
If this was a function name, I would then put parentheses and pass three and four to it, and that would have been a normal function call like +(3,4)
instead of 3+4
.
But this as other programming languages follow the process so does javascript. This notation is known as 'Infix Notation'.
Infix means that the function name, the operator, sits between the two parameters.
So, instead of +(3,4)
, calling the function this way.
Say, we remove the parentheses, and the comma so, it will become +3 4
.This is called prefix notation.
And if I put the plus sign at the end. This is called postfix notation.
There are other operators.
Like - minus
,* multiplication
,>
, <
.
console.log this value.
In 4>3
or 3<4
, this is a function, a special one, because the greater than function, it accepts two numbers and returns a Boolean.
That these parameters are being passed to those functions and
a value is being returned.
And inside those functions, there is pre-written code, essentially, for you that the JavaScript language, the engine provides to do, or run, or to invoke these functions.
So, we saw that operators are functions.
Keep Coding until I next Camp !!
Cheers
Posted on December 2, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024