JavaScript의 재미있는 변형과 TypeScript가 이를 더 좋게 만드는 방법
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.
