JavaScript의 재미있는 변형과 TypeScript가 이를 더 좋게 만드는 방법

Patricia Arquette
풀어 주다: 2024-10-12 14:32:30
원래의
484명이 탐색했습니다.

JavaScript’s Fun Twists and How TypeScript Makes It Better

JavaScript is a language we all love, right? It's flexible, lightweight, and runs everywhere. But for all its greatness, let's be honest, it can be weird. The kind of weird that makes you question your sanity after seeing something work that really should not.

In this article, we will tour some of the kinks within JavaScript - those behaviors that surprise you when you least expect it. Fortunately, there is a knight in shining armor for developers called TypeScript. We show you here how it can save you from tearing your hair by making those JavaScript's bizarreness somewhat more manageable.


1. The Great == vs === Debate

JavaScript gives us two flavors of equality: == or loose equality and === or strict equality.

console.log(0 == '0'); // true
console.log(0 === '0'); // false
로그인 후 복사

Wait, what? Yeah, JavaScript made 0 and '0' be considered equal with ==, but not with ===. That is because == does type coercion, or converting of types, before doing the comparison. It's trying to be helpful, making that string into a number for you—but this help leads to bugs.

Imagine using == on user input to check against a number. You might get true when the types aren't the same leading to unexpected behavior which is hard to track down. Why does this matter? Because JavaScript's type of coercion often works until it breaks something important.

How TypeScript Helps

TypeScript already enforces type safety out of the box. If you compare two things of different types, it's going to yell at you long before you can even run any code:

let a: number = 0;
let b: string = '0';

console.log(a === b); // TypeScript Error: This comparison is invalid
로그인 후 복사

Any surprise gone comparing a number against a string. TypeScript makes sure you always compare apples and apples or in this case number to number.


2. The Mysterious undefined vs null

Both undefined and null speak to nothing, but in subtly different ways. undefined is what JavaScript assigns to a variable that hasn't been initialized, while null is used when you intentionally want to assign an empty value. They are different, yet similar enough to confuse.

let foo;
console.log(foo); // undefined

let bar = null;
console.log(bar); // null
로그인 후 복사

Unless you are careful, you might end up checking for one but not the other, which results in some confusing bugs.

if (foo == null) {
    console.log("This catches both undefined and null");
}
로그인 후 복사

This works but can lead to subtle bugs if you don’t clearly distinguish between the two.

How TypeScript Helps

TypeScript encourages you to be explicit and precise about whether something can be null or undefined. It does this by making you handle both cases explicitly, so you are certain of what's going on:

let foo: number | undefined;
let bar: number | null = null;

// TypeScript will enforce these constraints
foo = null; // Error
bar = 5; // No problem!

로그인 후 복사

With TypeScript, you decide which types are allowed so that you don't accidentally mix types. This kind of strictness protects you from those bugs where you forget to check for null or undefined.


3. The Curious Case of NaN (Not-a-Number)

Have you ever run into the dreaded NaN? It's short for Not-a-Number, and it pops up when you try to perform mathematical operations that don’t make sense.

console.log(0 / 0);  // NaN
console.log("abc" - 5);  // NaN
로그인 후 복사

Here’s the catch: NaN is actually of type number. That’s right, Not-a-Number is a number!

console.log(typeof NaN); // "number"
로그인 후 복사

This can lead to some truly bizarre outcomes if you aren’t checking for NaN explicitly. What's worse, NaN is never equal to itself, so you can't easily compare it to check if it exists.

console.log(NaN === NaN); // false
로그인 후 복사

How TypeScript Helps

TypeScript can mitigate this issue by enforcing proper type checks and catching bad operations at compile-time. If TypeScript can infer that an operation will return NaN, it can throw an error before your code even runs.

let result: number = 0 / 0; // Warning: Possible 'NaN'
로그인 후 복사

TypeScript can also help you narrow down when and where NaN might pop up, encouraging better handling of numeric values.


4. The Wild this

this in JavaScript is one of the most powerful, yet easily misunderstood concepts. The value of this depends entirely on how a function is called, which can lead to unintended behavior in certain contexts.

const person = {
    name: 'Alice',
    greet() {
        console.log('Hello, ' + this.name);
    }
};

setTimeout(person.greet, 1000); // Uh-oh, what happened here?
로그인 후 복사

What you might expect is to see "Hello, Alice" printed after a second, but instead, you’ll get Hello, undefined. Why? Because this inside setTimeout refers to the global object, not the person object.

How TypeScript Helps

TypeScript can help you avoid these sorts of issues by using arrow functions which don't have their own this, and keep the context of the object they are in.

const person = {
    name: 'Alice',
    greet: () => {
        console.log('Hello, ' + person.name); // Always refers to 'person'
    }
};

setTimeout(person.greet, 1000); // No more surprises!
로그인 후 복사

No more unexpected this behavior. TypeScript forces you to think about context and helps you bind this properly, reducing the risk of weird undefined bugs.


5. Function Hoisting: When Order Does Not Matter

JavaScript functions are hoisted to the top of the scope; that means you can invoke them even before you have declared them in your code. This is kind of a cool trick, but can also be confusing if you are not paying attention to what's going on.

greet();

function greet() {
    console.log('Hello!');
}
로그인 후 복사

While this can be convenient, it can also cause confusion, especially when you're trying to debug your code.

This works just fine, because of function declaration hoisting. But it can make your code harder to follow, especially for other developers (or yourself after a few months away from the project).

How TypeScript Helps

TypeScript does not change how hoisting works but it gives you clearer feedback about your code's structure. If you accidentally called a function before it is defined, TypeScript will let you know immediately.

greet(); // Error: 'greet' is used before it’s defined

function greet() {
    console.log('Hello!');
}
로그인 후 복사

TypeScript forces you to do some cleanup, where your functions are declared before they are used. It makes your code much more maintainable this way.


Wrapping It Up

JavaScript is an amazing language, but it can certainly be quirky at times. By using TypeScript, you can tame some of JavaScript’s weirdest behaviors and make your code safer, more reliable, and easier to maintain. Whether you’re working with null and undefined, taming this, or preventing NaN disasters, TypeScript gives you the tools to avoid the headaches that can arise from JavaScript’s flexible—but sometimes unpredictable—nature.

So next time you find yourself puzzling over a strange JavaScript quirk, remember: TypeScript is here to help!

Happy coding!

위 내용은 JavaScript의 재미있는 변형과 TypeScript가 이를 더 좋게 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!