찾다
웹 프론트엔드JS 튜토리얼JavaScript의 재미있는 변형과 TypeScript가 이를 더 좋게 만드는 방법

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
C 및 JavaScript : 연결이 설명되었습니다C 및 JavaScript : 연결이 설명되었습니다Apr 23, 2025 am 12:07 AM

C 및 JavaScript는 WebAssembly를 통한 상호 운용성을 달성합니다. 1) C 코드는 WebAssembly 모듈로 컴파일되어 컴퓨팅 전력을 향상시키기 위해 JavaScript 환경에 도입됩니다. 2) 게임 개발에서 C는 물리 엔진 및 그래픽 렌더링을 처리하며 JavaScript는 게임 로직 및 사용자 인터페이스를 담당합니다.

웹 사이트에서 앱으로 : 다양한 JavaScript 애플리케이션웹 사이트에서 앱으로 : 다양한 JavaScript 애플리케이션Apr 22, 2025 am 12:02 AM

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.

Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교Apr 21, 2025 am 12:01 AM

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

JavaScript 통역사 및 컴파일러에서 C/C의 역할JavaScript 통역사 및 컴파일러에서 C/C의 역할Apr 20, 2025 am 12:01 AM

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

자바 스크립트 행동 : 실제 예제 및 프로젝트자바 스크립트 행동 : 실제 예제 및 프로젝트Apr 19, 2025 am 12:13 AM

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

JavaScript 및 웹 : 핵심 기능 및 사용 사례JavaScript 및 웹 : 핵심 기능 및 사용 사례Apr 18, 2025 am 12:19 AM

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

JavaScript 엔진 이해 : 구현 세부 사항JavaScript 엔진 이해 : 구현 세부 사항Apr 17, 2025 am 12:05 AM

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

Python vs. JavaScript : 학습 곡선 및 사용 편의성Python vs. JavaScript : 학습 곡선 및 사용 편의성Apr 16, 2025 am 12:12 AM

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

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!