The Magic Behind JavaScript Syntax Shortcuts

栏目: IT技术 · 发布时间: 4年前

内容简介:At first glance, JavaScript might seem like a pretty easy and straightforward language to code in. But, the deeper you go, the more you'll realize that that's not true. Apart from the general complexity of its prototype-based model, the language also conta

At first glance, JavaScript might seem like a pretty easy and straightforward language to code in. But, the deeper you go, the more you'll realize that that's not true. Apart from the general complexity of its prototype-based model, the language also contains numerous syntactic shortcuts and unpredictable tricks that you have to constantly look out for. Let me show you 4 of them!

1. Conditional (ternary) operator

Although in JS if is a statement and cannot be assigned directly to a variable, there's an alternative that lets you do so. It's called the ternary operator and is often used to create simple, one-line assignments, based on a certain condition.

const condition = 1 > 0;
const result = condition ? "1 is greater than 0" : "1 is smaller than 0";
result; // "1 is greater than 0"

The syntax here is very straightforward. You start with a condition followed by a question mark ( ? ). After that come 2 expressions separated by a colon ( : ), that are used respectively when the condition is truthy or falsy (e.g. 0 , false , "" ).

Again the syntax and rules here are simple and incredibly easy to apply when dealing with short conditional assignments. With that said, fresh coders might have some problems understanding it at first.

2. Logical AND operator

The dynamic nature of JavaScript type system can often be quite problematic but it also allows for some cool shortcuts to be used. Take the logical AND operator ( && ) for example:

const allow = true;
const value = allow && "value";

The snippet above present a nice shortcut for what could look like this:

const allow = true;
let value;
if (allow) {
  value = "value";
}

Because the AND operator only evaluates the second expression when the first is truthy, it can be utilized to quickly assign a value to a variable when a certain condition is met.

However, you have to keep in mind that when the condition is falsy, it's this conditional expression (the first operand) that will end up being assigned to a variable. This might not be the desired effect and might break your code when e.g. strictly comparing it against undefined .

const allow = false;
const firstValue = allow && "value";
let secondValue;
if (allow) {
  secondValue = "value";
}

if (secondValue === undefined) {
  // This will be executed.
}
if (!firstValue) {
  // This will also be executed.
}
if (firstValue === undefined) {
  // But this won't.
}

Thus, the use of such shortcut isn't considered a good practice, although is still quite common.

3. Increment / decrement operator

The increment operator ( ++ ) is a common look within usual for loops, isn't it?

for (let i = 0; i < 10; i++) {
  // ...
}

Both it and its "negative" counterpart - the decrement operator ( -- ) do one simple job - they either increase or decrease the numeric value they're used on by 1 . And while that doesn't sound complicated, there are some lesser-known quirks connected with it. Take a look:

let baseValue = 10;
let secondValue = baseValue++;
let thirdValue = --baseValue;

baseValue; // 10
secondValue; // 10
thirdValue; // 10

So, what exactly is going on here? Those are the ++ and -- operators together with the usual value assignment in action. Did you know that they can be placed either before or after the operand?

Well, they obviously can, but their behavior, or should I say the order of operation , differs depending on the position:

  • If the operator comes after the operand (e.g. baseValue++ ), the original value is first assigned to the variable and then the operand gets increased/decreased.
  • If the operator comes before the operand (e.g. --baseValue ), the original value is first increased/decreased and then assigned to the variable.

So, in our snippet, the secondValue is assigned the value of baseValue ( 10 ), which then gets increased to 11 . After that, the baseValue is first decreased to 10 and then the result of that operation is assigned to the thirdValue .

This whole mess is why the ++ / -- operator is usually not recommended for use outside the for loops. In theory, it should be logical (what comes first gets applied first), but can be very confusing for beginners and even intermediate JS coders.

4. Labels

Lastly, I'd like to touch upon something that's not necessarily a trick, rather than just an uncommon syntax feature. I'm talking about JS labels - "identifiers" that can be used to identify all sorts of loop statements and then use them with continue or break statements.

outerLoop: 
for (let x = 0; x < 10; x++) {
  for (let y = 0; y < 10; y++) {
    if (x * y > 20) {
      break outerLoop;
    }
  }
}

Without a label provided, continue and break operate on the loop that they're being used it. But, with a label assigned (e.g. outerLoop: ) you're able to reference a different loop and use the statements on it instead. So, the only use-case for labels is within nested loops . And honestly, even there they aren't very common. This makes them mostly a good-to-know-but-won't-use-often kind of feature.

Bottom line

I hope this blog post allowed you to learn/remember a thing or two about JS's unpredictable nature and syntax. If so, let me know which one of the listed "tricks" were new to you.

If you like the post consider sharing it and following me on Twitter , Facebook , or through my weekly newsletter . If you're interested, I also recommend checking out my YouTube channel . Again, thanks for reading this piece and have a nice day!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Sovereign Individual

The Sovereign Individual

James Dale Davidson、William Rees-Mogg / Free Press / 1999-08-26 / USD 16.00

Two renowned investment advisors and authors of the bestseller The Great Reckoning bring to light both currents of disaster and the potential for prosperity and renewal in the face of radical changes ......一起来看看 《The Sovereign Individual》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具