Automatically translated.View original post

Convert data. The value of the data atype variable.

# Web Site Writing Basics

# javascrip

# data atype

Type Conversion or Type Casting in JavaScript can be done in a variety of ways depending on which type you want to convert the data to. This is essentially a back-and-forth conversion between String, Number and Boolean.

Here are some of the main ways to convert data types:

1.Converting to String (text)

You can convert any data into String using three main ways:

Method Code Sample Results

String (value) (function) String (123) "123"

String (true) "true"

value.toString () (method) (123) .toString () "123"

(false) .toString () "false."

String Concatenation (The Easiest Way) 123 + "" 123 "

Export to sheet

2. Conversion to Number (number)

Converting data into numbers is the most common and sensitive:

Method Code Sample Results Remembering

Number (value) (function) Number ("123") 123 changes null to 0, true to 1, false to 0, and non-number text (such as "hello") to NaN (Not a Number).

Unary Plus (+) + "123" 123 is a short and fast way to convert to numbers.

+ true 1

ParseInt (string) parseInt ("100px") 100 converts to an integer (Integer), stopping when it comes across a non-numeric character.

ParseFloat (string) parseFloat ("10.5em") 10.5 Converted to decimal (floating-point)

Export to sheet

Number () examples to watch out for:

JavaScript

Number ("123"); / / 123

Number ("12 34"); / / NaN (with space between numbers)

Number ("abc"); / / NaN

Number (null); / / 0

Number (undefined); / / NaN

3. Conversion to Boolean (true / false)

You can convert any data into a Boolean using two main ways:

Method Code Sample Results

Boolean (value) (function) Boolean (1) true

Boolean (0) false

Double NOT (!!)!! 1 true

!! 0 false

Export to sheet

The following values are converted to false (called Falsy Values):

Value (Value) Data Type

0 Number

"" (String empty) String

Null Object

Undefined Undefined

NaN Number

False Boolean

Export to sheet

All other values are converted to true (called Truthy Values), such as "0," "[] (Array is empty), or {} (Object is empty).

💡 Type Coercion (implicit data type conversion)

JavaScript also provides Implicit Conversion, also known as Type Coercion, when some Operators are in use, such as:

Operator + (addition): If one of the values is String, convert the other into String and connect String instead of adding numbers.

JavaScript

"10" + 5; / / "105" (5 was converted to "5")

10 + "5"; / / "105" (10 was converted to "10")

Other mathematical Operators (-, *, /): will try to convert all values into Numbers.

JavaScript

"10" - 5; / / 5 ("10" is converted to 10)

"10" * "2"; / / 20 ("10" and "2" were converted to 10 and 2)

Operator in terms (= =): Will convert the data type to the same before comparing.

JavaScript

"5" = = 5; / / true (5 is converted to "5" before comparison)

Instructions: To keep the code clear and prevent errors, Explicit Conversion (Explicit Conversion, such as Use Number () or String ()) should be used, and use Strict Equality Operator (= = =) to compare values and data types directly without implicit data conversion.

2025/10/3 Edited to

... Read moreหลายคนเริ่มเรียน JavaScript แล้วงงคำว่า “ชนิดข้อมูล” (datatype) เพราะเวลาอ่านโค้ดจะเจอทั้ง string, number, boolean และบางทีมีคำถามต่อว่า “integer คืออะไร” ทั้งที่ใน JS เหมือนจะมีแต่ Number อย่างเดียว ผมสรุปจากที่ใช้งานจริงให้เข้าใจง่ายๆ แบบนี้ ชนิดข้อมูล (ชนิดของค่า) คือประเภทของค่าที่ตัวแปรเก็บอยู่ เช่น ข้อความ ตัวเลข หรือจริง/เท็จ ซึ่งมีผลกับการคำนวณและการเปรียบเทียบมากๆ 1) String คืออะไร String คือ “ข้อความ” อยู่ในเครื่องหมาย '...' หรือ "..." เช่น "123" หรือ "hello" จุดที่ชอบพลาดคือ "123" เป็นข้อความ ไม่ใช่ตัวเลข ดังนั้น "10" + 5 จะได้ "105" เพราะเครื่องหมาย + เจอ string แล้วจะกลายเป็นการต่อข้อความ (type coercion) ทริคที่ผมใช้บ่อย: - แปลงเป็น string ชัดๆ: String(value) หรือ value.toString() - ถ้าค่าอาจเป็น null/undefined ให้ระวัง toString() เพราะจะ error ได้ (กรณี null.toString()) เลยใช้ String(value) ปลอดภัยกว่า 2) Integer คืออะไร (ใน JavaScript) Integer แปลว่า “จำนวนเต็ม” เช่น 1, 2, -5 ไม่มีจุดทศนิยม แต่ใน JavaScript “ชนิดข้อมูล” หลักของตัวเลขคือ Number (เป็น floating-point) หมายความว่า 1 และ 1.5 ก็เป็นชนิด Number เหมือนกัน แล้วทำไมยังมีคำว่า integer? - เป็น “รูปแบบของค่า” ที่เป็นจำนวนเต็ม แม้ชนิดข้อมูลยังเป็น Number - เวลาแปลง/รับค่าจาก input เรามักอยากได้จำนวนเต็มเลยใช้ parseInt() ตัวอย่างที่เจอบ่อย: - parseInt("100px", 10) ได้ 100 (หยุดเมื่อเจอตัวอักษร) - parseInt("08", 10) ควรใส่ฐาน 10 ไว้เสมอเพื่อกันการตีความผิด - Number("100px") จะได้ NaN (แปลงทั้งสตริง ต้องเป็นตัวเลขล้วนๆ ถึงผ่าน) 3) แปลงเป็นตัวเลข: Number() vs parseInt() vs parseFloat() ผมเลือกใช้ตามเคสแบบนี้ - ต้องการให้ “ทั้งสตริง” เป็นตัวเลขจริงๆ: ใช้ Number("123") - ต้องการ “จำนวนเต็ม” จากข้อความที่อาจมีหน่วย: ใช้ parseInt("100px", 10) - ต้องการทศนิยม: ใช้ parseFloat("10.5em") ข้อควรระวังที่ผมเจอบ่อย: - Number("12 34") ได้ NaN เพราะมีช่องว่างคั่นกลาง - Number(null) ได้ 0 แต่ Number(undefined) ได้ NaN 4) Boolean และค่า truthy/falsy แปลงเป็น boolean ใช้ Boolean(value) หรือ !!value ได้เลย สิ่งที่เป็น falsy ที่ควรจำ: 0, "", null, undefined, NaN, false นอกนั้นส่วนใหญ่เป็น true (เช่น "0", [], {}) 5) เปรียบเทียบค่าให้ชัวร์ ถ้าไม่อยากให้ JS แปลงชนิดให้เอง แนะนำใช้ === แทน == เช่น "5" == 5 เป็น true แต่ "5" === 5 เป็น false ซึ่งช่วยลดบั๊กได้เยอะ สรุปสั้นๆ: ถ้าคุณสงสัยว่า string คืออะไรให้ดูว่าอยู่ในเครื่องหมายคำพูดไหม ส่วน integer คือ “ค่าแบบจำนวนเต็ม” แต่ชนิดข้อมูลใน JS ยังเป็น Number อยู่ และถ้าต้องแปลงค่า แนะนำแปลงแบบ explicit (Number/String/Boolean/parseInt/parseFloat) จะอ่านโค้ดง่ายและปลอดภัยกว่า

Related posts

💻Try Linear Regression Modeling in Python
Since we’ve covered basic concepts like mean, median, correlation and linear regression, it is time we practiced using Python. Please refer to the pictures in this post for detailed coding and data display. 🖋️Get data set from Kaggle I downloaded the Titanic data set from the famous data scie
Capital&Crypto

Capital&Crypto

13 likes

A laptop displays a Google Sheets assignment tracker with due dates and class details, overlaid with text "COLLEGE LIFE A day of homework Some tips to staying focused." Small icons of a heart, clock, and coffee cup are visible, along with a "SWIPE" arrow.
College Tips: Staying Focused
#collegediary #lemon8contest While it’s all up to personal preference, these tips are some basics to keep you focused! I personally prefer studying alone as I get distracted too easily… (I am currently posting this while doing homework in starbucks 😦) ⭐️ ⭐️Give this a like if it’s helpful!!
mowglibee00

mowglibee00

84 likes

An image titled 'Fahrenheit to Celsius' presents a mental shortcut rule: subtract 30 from the Fahrenheit value, then divide by 2 to approximate Celsius. Examples like 80°F to 25°C and 40°F to 5°C are shown, illustrating the formula (°F-30)/2.
Fahrenheit to Celsius. The 10-Second Mental Trick🤨
No calculator needed. Subtract 30, divide by 2, and you’re close enough for everyday life. #mentalmathtips . #learnfast . #everydaymath . #smarterthinking . #lifeskills .
Life Rulers 👑

Life Rulers 👑

102 likes

SECRET SOCIETIES BEEN WAITING ON YOUR RISE 👁 NOW YOU’RE FULLY WOKE & THEY’RE LOOKING FOR YOU 🔥 #SelfDiscovery #ChosenOne #StarSeed #MindBodySoul #LightWorker
NQT MEDIA NEWS

NQT MEDIA NEWS

112 likes

🌘 The Seven Lights — Part 364: The Variable That Breathes 🧭The Loom calculates
🌘 The Seven Lights — Part 364: The Variable That Breathes 🧭 The Loom calculates outcomes. The heart creates moments. ​Moments defy the machine. ​✨ The final variable is the pause before the choice. #TheSevenLights #SevenLights #EpicFantasy #LivingSystems #ChoiceYourFate
AlfredoLevelUp

AlfredoLevelUp

1 like

A desk setup with two monitors displaying C++ code, featuring a "C++ Cheat Sheet For Beginners" title overlay. The left screen shows nested switch statement code, while the right screen displays more code. A keyboard and mouse are visible, with a Lemon8 watermark in the corner.
C++ Cheat Sheet For Beginners
Follow for more as I almost finish c++ 🫶🏽 #womeninstem #cplusplus #compsci #stem #student
Kailey

Kailey

1 like

A tropical scene with palm trees and carved stone details. Text states, 'They measured YOUR NERVOUS SYSTEM with the wrong ruler,' suggesting that traditional business frameworks are not suited for neurodivergent individuals.
A serene water body with stone edges. Text questions consistency and reveals 'RETURN POSTS CONVERT 34% HIGHER,' concluding 'wrong frameworks, not wrong person' for neurodivergent business approaches.
A woman in an orange dress walks on a winding path in a lush tropical garden at sunset. Text asks about trends and states 'NICHE AUTHORITY HOLDS 2.1x LONGER,' implying 'wrong map, not wrong direction' for business strategy.
The Business Data Your ADHD Coach Won't Show You (It Changes Everything)
📊 the business framework your coach sold you was built for a nervous system that can do the same thing, at the same time, every single day, without the wheels coming off. & then they looked us dead in the face & said consistency was the problem. the audacity is genuinely staggering.
Anxious Girl Empire🌿

Anxious Girl Empire🌿

0 likes

Handwritten notes titled "CHAPTER 1 READINGS" defining statistical terms like Data, Statistics, Population, Sample, and Voluntary Response Sample. It also explains Statistical Significance with an example of birth gender ratios.
Handwritten notes detailing steps to prevent low survey response rates, the impact of question wording and order, and definitions of Parameter, Statistic, Quantitative Data, and Categorical Data, emphasizing units of measurement.
Handwritten notes defining Discrete and Continuous Data with examples, and introducing the four levels of measurement: Nominal, Ordinal, Interval, and Ratio, with initial definitions for Nominal and Ordinal.
STAT 200 Notes
Chapter One of the textbook notes.
Gretchen

Gretchen

57 likes

How to turn groceries & sephora purchases into free flights (if you do it right!!) ✈️ As an American living abroad & a travel lover, these credit card hacks have saved me so much money and not only allowed me to go on so many more trips - but to also have the best flying experiences with
maddie clark

maddie clark

30 likes

Don’t just steal my job leads & dip 👀 I see you! Mutual of Omaha is hiring a Claim Intake Technician 👩🏽‍💻✨ If you’ve got claims or data entry experience, update your resume with the right keywords and APPLY. 🚨 Follow me so you don’t miss the next one 💅 #WorkFromHomeJobs ” #nophone #wfhjobs
Arialle Tate

Arialle Tate

94 likes

Pattern Variable Sewing Machine
#sewingmachine #stitchingmachine
Shoe & Leather Machines

Shoe & Leather Machines

9 likes

finishing my data analysis chapter!!
#dataanalysis #research #gradstudent #studywithme #studymotivation
Sam ౨ৎ⋆ ˚。⋆

Sam ౨ৎ⋆ ˚。⋆

6 likes

the best note taking device ever (the remarkable)
i am someone who absolutely loves to learn and i love to study. i know its weird but i really did love school and cant wait to go back and get my masters in cybersecurity because i just love learning so much! in my many years of school i really decided i loved handwritten notes best. taking notes o
lilly

lilly

148 likes

A digital budgeting calendar for September 2024, titled 'My Zero Based BUDGET', displaying various financial categories like income, fixed bills, variable bills, savings, and spendings on the right side.
A September 2024 calendar highlighting a $2,300 paycheck on the 6th, with text stating '1. DETERMINE YOUR PAYCHECK AMOUNT' and 'MY FIRST PAYCHECK IN SEPT. IS AROUND $2300'.
A September 2024 calendar highlighting fixed expenses: Auto Payment ($159.41), Internet ($60.30), and Student Loan ($277.77), with text '2. WRITE DOWN YOUR FIXED EXPENSES' and 'I HAVE 3 TOTALING $497.98'.
How to budget to ✨ SAVE ✨ money
Sharing my first #PaycheckBudget of September!! As always, I’m using my own Zero Based Budgeting Calendar that I designed in #Googlesheets . For context: - I live alone in Texas - I’m currently renting a studio for $1250 - My current job is a Data Analyst Now for the details: 1.
TheHappyPlanner

TheHappyPlanner

187 likes

A desk setup with a laptop displaying a data analysis report and a spreadsheet with a line fit plot, alongside a notebook with handwritten notes. The image has a text overlay 'DATA DRIVEN From EC to Analyst', reflecting a career transition into data analytics.
A close-up of a notebook page filled with handwritten notes on 'Quantitative Statistical Tools,' including T-test, ANOVA, Regression, and Cluster Analysis. The notes also feature the phrase 'FINDING THE RIGHT MODEL FOR THE SITUATION'.
A computer screen displaying a scatter plot titled 'PROGRAM PARTICIPATION RATE (%) LINE FIT PLOT' showing 'Nurse Attrition Rate (%)' with a regression line and equation. The image includes a text overlay 'MEEZ THE ANALYST' with a smiling emoji.
Exploring Data Analytics 🍋
This is truly the course I’ve been waiting for and up until now and my previous course financial management, I’ve passed on the first try for each assignment or assessment . Waking up and seeing revisions are needed would usually have my ego in distraught. On the journey to detach from the ego, I g
MEEZ🧚🏽

MEEZ🧚🏽

3 likes

🪴🌞 weekly report ! | a cottagecore update
This week wasn’t the best, but there were still some bright spots! Here’s my weekly report: still studying, keeping up with Pilates, adding little bits to our home decor, and of course, making lots of coffee and baked goods. Hoping for a better week ahead! How was your week? #cottagecorevibes
Ash ☕️🫶🏼✨🔮

Ash ☕️🫶🏼✨🔮

16 likes

Caregiver Calm Tip: Fixed vs. Variable
#Caregiver #Calm #budget #money
Cynthia

Cynthia

3 likes

Python Variable Names Explained (Avoid These Mista
Confused by Python code? 😵‍💫 The problem might be bad variable names. In this post, you’ll learn: ✔ What variable names are ✔ Rules you must follow ✔ Good vs bad examples ✔ Pro tips to write clean Python code Save this post 📌 and follow for more Python basics made easy 🐍✨ #Python #LearnPy
TechKeysX

TechKeysX

0 likes

STOP BLAMING THE UNIVERSE: The Truth About “Luck”
How many times have you blamed "bad luck" for a missed opportunity, only to realize deep down that you weren’t actually ready for it? It’s a tough pill to swallow, but I’m here to tell you Luck is a variable, but preparation is a choice. We often use the "unlucky" narrative as a
Coach J

Coach J

4 likes

HUMAN VARIABLE VIDEO
@Comedienne MsPat @pecan bay @TIANY GULLATT @SheBa @Fairnhyte 🚨 TONIGHT'S PREMIERE 🚨 🌌 THE HUMAN VARIABLE 🌌 🎵 LeoLennox x Velvet Black 📡 The Midnight Frequency 👑 AIML25 Every equation had an answer... Until one variable changed everything. ✨ Premiering Tonight ✨ 🕘 9:00 PM — La
Lennox Wilkins ��• AIML25

Lennox Wilkins • AIML25

0 likes

Pattern Variable Sewing Machine
#sewingmachine #stitchingmachine
Shoe & Leather Machines

Shoe & Leather Machines

1 like

Learn liner regression with Blair in one minute
#data #dataanalytics #datascience #ai #gossip
Tiffanythatgirl

Tiffanythatgirl

4 likes

A flat lay shows an iPad Pro 11 inch in a marbled case on a stand, with a small propagated pothos plant and an Apple Pencil. Text overlays read "Budgeting As Grad Student" and identify the items.
A flat lay shows an iPad displaying a Google Sheets budget calendar, an Apple Pencil, and a small plant. Text overlays indicate these are "My Essentials" for budgeting, including the Google Sheets App.
A close-up of an iPad screen shows a "2024 Budget & Bills Calendar" in Google Sheets, highlighting September and October. An arrow points to a note about moving savings to a 529 account for tuition.
Budgeting as A Grad Student
My #PaycheckBudget as a grad student and Data Analyst What I use to Budget: - my iPad and Google Sheets - previously I would use just pen and paper How I Budget: - zero based budgeting - basic idea is to make sure you allocate every dollar for a purpose (i.e. Fixed expenses, variabl
TheHappyPlanner

TheHappyPlanner

89 likes

Pattern Variable Sewing Machine
#sewingmachine #stitchingmachine #moccasins
Shoe & Leather Machines

Shoe & Leather Machines

3 likes

Pattern Variable Sewing Machine
#sewingmachine #stitchingmachine #moccasins #moccasin
Shoe & Leather Machines

Shoe & Leather Machines

4 likes

A white text box defines 'Variable Ratio' as a reinforcement schedule with variable responses, set against a dark background with book spines.
Variable Ratio
what is VR in ABA? #ABA #RBT #rbtstudy #rbtexam #reinforcement
Emma

Emma

0 likes

A couple with foreheads touching, eyes closed, conveying intimacy and contentment. Overlay text states, "People will never give you what you deserve, but what they are. What you deserve, you give yourself, when you decide to accept what others give you."
A couple with foreheads touching, eyes closed, showing intimacy. Overlay text in Spanish conveys that people give what they are, and one gives themselves what they deserve by choosing what to accept.
A woman places a note on a cork board filled with tasks and images, symbolizing choosing thoughts. Overlay text states, "You choose which programs run in your mind," emphasizing conscious control over one's internal world.
YOUR INTERNAL LAW IN A UNIVERSE OF FOREIGN CODES 🤫
PEOPLE WILL NEVER GIVE YOU WHAT YOU DESERVE, BUT WHAT THEY THEMSELVES ARE. WHAT YOU DESERVE, YOU GIVE YOURSELF BY CHOOSING WHAT TO ACCEPT FROM OTHERS. This is not philosophy; it is the raw mechanics of consciousness. Each person operates from a private universe, sealed by their genetics, synapti
Sanación Holistica Integral

Sanación Holistica Integral

3 likes

See more