mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-06-28 21:00:56 +08:00
feat(curriculum): Add interactive examples to What Is ASCII, and How Does It Work with charCodeAt() and fromCharCode() (#63198)
This commit is contained in:
parent
0c8914818c
commit
565b919a9a
@ -5,7 +5,7 @@ challengeType: 19
|
||||
dashedName: what-is-ascii-and-how-does-it-work-with-charcodeat-and-fromcharcode
|
||||
---
|
||||
|
||||
# --description--
|
||||
# --interactive--
|
||||
|
||||
In programming, understanding how characters are represented as numbers is fundamental. This is where ASCII comes in. ASCII, short for American Standard Code for Information Interchange, is a character encoding standard used in computers to represent text. It assigns a numeric value to each character, which is universally recognized by machines.
|
||||
|
||||
@ -26,40 +26,56 @@ In JavaScript, you can easily access the ASCII code of a character using the `ch
|
||||
|
||||
Let’s take a look at an example:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let letter = "A";
|
||||
console.log(letter.charCodeAt(0)); // Output: 65
|
||||
console.log(letter.charCodeAt(0)); // 65
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, `A` is the first character of the string, and calling `charCodeAt(0)` returns its ASCII value, `65`.
|
||||
|
||||
You can also use this method with other characters to find their ASCII values:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let symbol = "!";
|
||||
console.log(symbol.charCodeAt(0)); // Output: 33
|
||||
console.log(symbol.charCodeAt(0)); // 33
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Here, the ASCII code for the exclamation mark `!` is returned as `33`.
|
||||
|
||||
While `charCodeAt()` helps you retrieve the ASCII value of a character, the `fromCharCode()` method allows you to do the opposite: convert an ASCII code into its corresponding character.
|
||||
|
||||
Let's see this in action:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let char = String.fromCharCode(65);
|
||||
console.log(char); // Output: A
|
||||
console.log(char); // A
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
In this example, `fromCharCode(65)` converts the ASCII value `65` back to the character `A`.
|
||||
|
||||
Another example would be converting the number `97` to its corresponding lowercase letter:
|
||||
|
||||
:::interactive_editor
|
||||
|
||||
```js
|
||||
let char = String.fromCharCode(97);
|
||||
console.log(char); // Output: a
|
||||
console.log(char); // a
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
These methods are particularly useful when you need to manipulate or compare characters based on their ASCII values.
|
||||
|
||||
For instance, you might use `charCodeAt()` to check if a character is uppercase, lowercase, or a digit by comparing its ASCII value.
|
||||
|
||||
Loading…
Reference in New Issue
Block a user