Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 15, 2020 04:15 pm GMT

Useful JavaScript Operators

What are operators? They can do all kinds of things and take many different forms. They turn up everywhere, so the goal of this article is to familiarize you with operators that you'll see and use frequently. There are a few different families of operators in JavaScript, but today we'll focus to those most useful for web dev.

Assignment operators

One type of operator you're probably familiar with is assignment operators. They assign the value on their right side to their left side, like we'd do declaring a variable: var variable = 0. Besides = there are a number of assignment operators that are useful shorthand.

// Assign a value to a new variablevar variable = 0;// Shorthand to increase variable's value by 1variable += 2;// Shorthand to decrease the variable's value by 1variable -= 1;// Our variable is at 1console.log(variable);// Shorthand to multiply a value into variablevariable *= 2;// Shorthand to divide variable by valuevariable /= 2;// Our variable is at 1console.log(variable);
Enter fullscreen mode Exit fullscreen mode

These shorthand assignment operators save us from having to write variable = variable + 1 out to add, write variable = variable - 1 to subtract, and so on.

Comparison Operators

Another family of operators called comparison operators are used to compare two values.

Greater & Less Than

These operators return true if the values on either side compare as written: greater than, less than, greater than or equal to, and less than or equal to.

// Assign a variable for comparisonvar target = 4;// Is variable greater than the target?console.log(variable > target);// Is variable less than the target?console.log(variable < target);// Assign the target to the variablevariable = target;// Is the variable greater than or equal to the target?console.log(variable >= target);// Is it less than or equal to the target?console.log(variable <= target);
Enter fullscreen mode Exit fullscreen mode

Because operators return values, we're able to log to the console and see what's happening.

Note!
Remember in an operator, the = will always come last. Don't confuse >= with =>, an arrow function declaration.

Different Equals

The comparison operators above are fairly familiar, but the comparison of equality takes a couple different forms.

If you've read other JavaScript projects, you might wonder: what is the difference between === and ==, between a triple equals and a double equals? Both perform similar comparisons, but the triple equals is used to ascertain strict equality, while the double equals is used to ascertain abstract equality. The main difference between these two is that == will compare both values after converting them to a common type, while === will compare the values without attempting to convert either one. Thus the term 'strict equality': it is not as loose in determining sameness.

// Let's start with a string a single number.var str = '3';// Abstract equals says an integer is equal to our stringconsole.log(str == 3);// Strict equals recognizes that a string and an integer are// are different typesconsole.log(str === 3);// To return true, we can compare with a literal stringconsole.log(str === '3');
Enter fullscreen mode Exit fullscreen mode

Arithmetic Operators

We can use arithmetic operators to manipulate values and return a number. One useful operators from this family is the remainder operator, %, which returns the remainder of dividing the numbers given on its left and right.

// Get the remainder of 5 divided by 2console.log(5 % 2);
Enter fullscreen mode Exit fullscreen mode

There are also several useful shorthands that allow us to perform number manipulations effectively in place: ++, --, and -.

// Shorthand to increase a number by 1variable++;console.log(variable);// Shorthand to decrease a number by 1variable--;// Variable is back where we startedconsole.log(variable);// Shorthand to negate a valueconsole.log(-variable);
Enter fullscreen mode Exit fullscreen mode

A single + is a unary operator to attempt a value's conversion into a number. We could use this to revisit our earlier example of strict and abstract equality.

We could replace this line:

console.log(str === 3);
Enter fullscreen mode Exit fullscreen mode

which returns false because str is equal to '3', with this line:

console.log(+str === 3);
Enter fullscreen mode Exit fullscreen mode

to return true.

This works because we use the + operator to convert str to a number value before the comparison.

Logical Operators

You'll frequently logical operators that represent or and and to test multiple conditions at once. Or is written using || and will return true if either the left or right sides of the operator are true. And is written using && and will return true only if both sides of the operator are true. We might use these with if to express the conditions under which we want to do something.

// a music track that can be in our libraryvar inLibrary = true;// count how many times the track was playedvar playCount = 0;// Do something if we played the track or added it to libraryif (inLibrary || playCount > 0) {  console.log('some interaction with this track');}// Do something else if we've both added to library & playedif (inLibrary && playCount > 0) {  console.log('track both played and in library');}else {  console.log('track either in library or played');}
Enter fullscreen mode Exit fullscreen mode

In the example above, we could have used comparison operators to write if (inLibrary === true ..., but since inLibrary is a boolean, we don't need to write === true. It's redundant because merely accessing a boolean will give you its value of true or false.

Conditional (ternary) operator

The conditional operator is the only JavaScript operator that receives three operands (the others receive one or two), so it's also known as ternary. This operator is very useful, however it reads like something of a shorthand. The conditional operator is at work when you see something like this: var v = condition === true ? 4 : 7; with ? and ;.

This syntax is a condensed form of something like this:

// declare a valuevar val;// set the value if a condition is metif (condition === true) {  val = 4;}// else set the value differentlyelse {  val = 7;}
Enter fullscreen mode Exit fullscreen mode

We're testing a condition and doing one thing if the result is true, or a different thing if it's false. Using the conditional operator we can rewrite the above idea into something more condensed:

// declare a value by first testing a conditionvar val = condition === true ? 4 : 7;
Enter fullscreen mode Exit fullscreen mode

The ternary operator allows us to specify a condition to test, and separate outcomes to return if the condition proves true or false.

Here's another example. We have a toolbar HTML element that has a toggling open and a closed state. We have another HTML element with the nav for our page. We want the nav to appear when the toolbar is open, and disappear when the toolbar is closed. First we'll grab that nav element in our JavaScript as navElement. Then we can use the ternary operator to check the toolbar's status.

// declare a variable in accordance with navOpen's valuevar showNav = navOpen ? true : false;// we can add class active to show the nav or remove it to hideif (showNav) {  navElement.classList.add('active');}else {  navElement.classList.remove('active');}
Enter fullscreen mode Exit fullscreen mode

Last Word

Operators allow us to express all kinds of relationships in JavaScript. They're trivial but crucial to familiarize yourself with as you learn how to read and write JavaScript. The conditional operator is an especially good addition to your tool belt. Of course, other operators exist outside of what's demonstrated in this article, but this is a collection of operators that are important to recognize and understand.


Original Link: https://dev.to/sprite421/useful-javascript-operators-3d8d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To