Automatically translated.View original post

variable && function () /JavaScript

# Web Site Writing Basics

# javascript

# variable

# Function

The relationship between variables and functions in JavaScript is an important basis of programming. It can be summarized mainly as follows:

1. Using a variable to store the value of a function

In JavaScript, a function is a type of object (First-Class Functions). This means that it can be treated as an object or other value. This allows us to use variables to store the value of the function:

JavaScript

/ / The variable 'myFunction' stores a value that is a function.

const myFunction = function (a, b) {

return a + b;

};

/ / A function can be called through a variable.

Let result = myFunction (5, 3); / / result is 8

Benefits: Assigning a function to a variable allows a function to be sent as an argument to another function (Callbacks) or returned a function from another function (Higher-Order Functions).

2.Function uses variable (Scope)

Variables are closely related to functions through the concept of Scope:

A. Variables within a function (Local Variables)

Variables declared within a function are accessed only in that function (Local Scope) and are recreated every time the function is invoked.

JavaScript

Function calculated (x) {

/ / The variable 'y' is a variable within the function.

const y = 10;

return x + y;

}

/ / console.log (y); / / Error: y is not defined

B. External Function Variables (Global / Outer Scope Variables)

The function can access variables declared outside the function (Lexical Scope).

JavaScript

Const taxRate = 0.07; / / External variable

Function calculateTax (price) {

/ / The function can access' taxRate '.

return price * taxRate;

}

Closure: This is the most powerful relationship, when the function "remembers" and continues to access variables from the created boundary, even if the boundary has already been completed.

3.The variable is the argument and the value returned.

The function uses variables to receive input and output information:

Arguments: The variable used to receive the value sent into the function.

Return Value: The function uses the return command to send a value (which is a value stored in a variable or as a constant) back to the executed code.

JavaScript

The functions multiply (num1, num2) {/ / num1 and num2 are argument variables.

const product = num1 * num2; / / 'product' is an internal variable

Return product; / / Send back the value stored in 'product'

}

const finalAnswer = multiply (4, 5); / / 'finalAnswer' stores the returned value

2025/10/16 Edited to

... Read moreหลายคนเริ่มเรียน JavaScript แล้วติดอยู่ 2 คำนี้เหมือนกัน: “const คืออะไร” และ “อาร์กิวเมนต์คืออะไร” เลยขอสรุปแบบที่ผมใช้ทำงานจริงให้เข้าใจเร็วขึ้น 1) const คืออะไร? const เป็นคีย์เวิร์ดสำหรับ “ประกาศตัวแปรที่ห้ามเปลี่ยนค่าอ้างอิง (reassign) ใหม่” พูดง่าย ๆ คือประกาศแล้ว “เอาตัวแปรไปชี้ค่าใหม่ไม่ได้” เช่น const taxRate = 0.07; // taxRate = 0.1; // จะ error เพราะเปลี่ยนค่าที่ผูกไว้ไม่ได้ สิ่งที่มือใหม่สับสนบ่อย: const ไม่ได้แปลว่า “ค่าข้างในเปลี่ยนไม่ได้เสมอไป” ถ้า const เก็บเป็น object/array เราแก้ไข “ภายใน” ได้ เพราะตัวที่ห้ามเปลี่ยนคือ “ตัวอ้างอิง” ไม่ใช่ข้อมูลข้างใน const user = { name: "A" }; user.name = "B"; // ทำได้ // user = { name: "C" }; // ทำไม่ได้ (reassign) แล้วทำไมคนชอบใช้ const? - โค้ดอ่านง่าย: เห็นปุ๊บรู้ว่าไม่ควรตั้งใจเปลี่ยนไปมา - ลดบั๊กจากการเผลอ reassign - เหมาะมากกับการประกาศฟังก์ชันแบบเก็บในตัวแปร const myFunction = function(a, b) { return a + b; }; 2) const ใช้กับ scope ยังไง? const เป็น block scope (อยู่ในวงเล็บปีกกา { } ) คล้าย let ถ้าประกาศในฟังก์ชันก็จะเป็นตัวแปรภายในฟังก์ชัน (local) เช่นตัวอย่างที่เจอบ่อย: function calculate(x) { const y = 10; // ตัวแปร 'y' เป็นตัวแปรภายในฟังก์ชัน return x + y; } // console.log(y); // Error: y is not defined 3) อาร์กิวเมนต์ (Arguments) คืออะไร? อาร์กิวเมนต์คือ “ค่าที่ส่งเข้าไปตอนเรียกฟังก์ชัน” ส่วนตัวแปรที่รับค่าด้านในวงเล็บของฟังก์ชัน เรามักเรียกว่า parameter (พารามิเตอร์) แต่ในชีวิตจริงหลายคนเรียกรวม ๆ ว่าอาร์กิวเมนต์เหมือนกัน function multiply(num1, num2) { // num1, num2 = parameters return num1 * num2; } multiply(4, 5); // 4 และ 5 = arguments ทริคที่ช่วยจำ: - เขียนฟังก์ชัน: (ตัวรับ) = parameters - เรียกใช้ฟังก์ชัน: (ตัวส่ง) = arguments 4) ข้อควรระวังที่เจอบ่อย - ลืม return: ฟังก์ชันจะได้ค่า undefined - ส่ง argument ไม่ครบ: ค่าที่หายไปจะเป็น undefined ทำให้คำนวณเพี้ยน - ใช้ const แล้วคิดว่าแก้ array/object ไม่ได้: จริง ๆ แก้ได้ แต่ห้าม reassign ถ้าอ่านถึงตรงนี้แล้วลองไล่โค้ดทีละบรรทัด จะเริ่มเห็นความสัมพันธ์ของ “ตัวแปร (variables) + ฟังก์ชัน (functions) + scope + arguments” ชัดขึ้นมาก และจะช่วยลด error แนว y is not defined ได้ไวสุดครับ

Related posts

My Programming Interest Just Skyrocketed! 🚀
I just discovered something that has made my interest in programming explode to 1000000000000000%! 🤯 🎮 Learning Programming is Like a Game Adventure! From Python, Java, JavaScript, to HTML, there are all kinds of programming languages available, along with systematic topic courses. The learning p
Valder

Valder

2172 likes

A desk setup with a computer screen displaying the Khan Academy website, showing course categories like 'Careers' and 'Computer programming'. A pink lululemon water bottle is on the right. Text overlay reads 'how to learn for free' and 'SWIPE TO VIEW'.
A webpage for grow.google.com, asking 'What would you like to learn?' with options for career and business growth. It highlights free courses and certifications, providing tools and resources for skill development and career advancement.
A webpage for Khan Academy, titled 'My courses', showing various learning paths including 'Careers', 'Computer programming - JavaScript and the web', and 'Intro to computer science - Python'. It describes Khan Academy as a free resource for diverse subjects.
learn for free with these websites 🎀
‧°𐐪♡𐑂°‧₊ ⛄️ Learning new knowledge or skills can be completely free using these websites! It’s a great way to spend your free time ✨ Open University & Khan Academy is perfect for students wanting to enhance knowledge of content they already know to study, go ahead of content or learn knowl
peachiesuga ♡

peachiesuga ♡

6685 likes

Import information you need to know in nursing.
Nursing information that you may come across and need to know. Additional Tips: #nursingstudenttips #nursing #nursingschool
🩺 Nurse Val🇺🇸

🩺 Nurse Val🇺🇸

301 likes

How I’d Learn JavaScript If I Were Starting Again
#javascript #coding #programming #tech #codingforbeginners
Aysha

Aysha

124 likes

after a long day of classes, i came home to the sound of rain outside 🌧️ lit a candle, made some tea, and sat down to study. nights like this make schoolwork feel a little less stressful 📖🍂🤍🧸 #student #college #dormdecor #study #nightroutine
alice.journeyy

alice.journeyy

3939 likes

EPITHELIAL TISSUE: Classification & Function
~Epithelial tissue is characterized according to the shape of its cells and number of layers. ~Squamous cells are thin, flat cells that look like fish scales and are found in the tissue that forms the surface of the skin, the lining of the hollow organs of the body, and the lining of the respira
Hannah

Hannah

50 likes

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

Shoe & Leather Machines

9 likes

math notes
Cte Bruno

Cte Bruno

54 likes

The image introduces "DUOLINGO DUPES TO LEARN HOW TO CODE (for free!)" with icons for Mimo, Encode, and Sololearn apps, set against a light blue background with floral patterns.
The image details the Mimo app, showcasing its icon, career paths like Full-Stack Developer and Python AI Developer, and a description of its courses in Python, SQL, JavaScript, and more.
The image highlights the Encode app, displaying its icon, a "LEARN TO CODE" interface, and lesson topics such as Swift Basics and Reusing Code, along with a description of its interactive lessons.
✨CALLING ALL THE TECH GIRLS 🖥️ ✨
Learning to code was never on my radar—until life nudged me in the right direction. As the granddaughter of a brilliant I.T. professional, I didn’t fully appreciate his advice to dive into tech until after his passing in 2021. Now, I’m honoring his legacy by teaching myself to code, one step at a t
✿ Jaide ✿

✿ Jaide ✿

141 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

School is hard? Support makes it easier ✅ proctored exam prep. HESI . TEAS . WGU helping students stay calm,prepared and confident #students #nursing #nursingstudenttips #exams #teasprep
GetHelpWithProctoredExam

GetHelpWithProctoredExam

6 likes

A woman lies on a bed of money, smiling and holding dollar bills, with a world map graphic in the background. The text overlay reads "11 SECRET WAYS TO EARN MONEY WITH AI CHATGPT AND MIDJOURNEY."
This image presents the first secret way to earn money: "1. Write and publish blog posts." It outlines steps to establish a blog, set up ChatGPT, and generate content using AI prompts.
This image details the third secret way: "3. Build an App, Website, or Service." It explains how ChatGPT can assist in coding, debugging, and providing instructions for creating technology products.
11 secret ways to earn money with chat gpt
11 secret ways to earn money with chat gpt
Valder

Valder

156 likes

A desk setup with glasses, pens, and handwritten notes, overlaid with the text 'Create a Monthly Budget with ChatGPT,' illustrating the article's topic of using AI for financial planning.
A screenshot showing a ChatGPT prompt for creating a monthly budget, detailing income, fixed expenses, desired savings, and categories for variable spending like groceries and fun.
A generated monthly budget plan from ChatGPT, displaying a breakdown of income into fixed expenses (rent, utilities, subscriptions, savings) and variable expenses (groceries, home goods, self-care, fun, gaming accessories).
Track Monthly Spending with ChatGPT!
Do you need help tracking and managing your monthly expenses? Budgeting can be tough and finding someone to help can be even harder! This is a perfect solution for a low cost, effective strategy to help you budget your monthly paycheck so you aren't missing a payment and you are helping save yo
Raine ☀️

Raine ☀️

1161 likes

Roadmap to Becoming a Frontend Developer
Want to break into frontend development but don’t know where to start? 🤔 This step-by-step roadmap will guide you from beginner to job-ready frontend developer! #codingforbeginners #htmlcssforbeginners #programming #studymotivations #softwareengineer
Aysha

Aysha

52 likes

Make studying fun! 🧸
CHEMISTRY CLASS ⚛️ IS SO CONFUSING 🫤 #nursingprereqs #studyingvibes #nursingprocess
♥️A.N.G.I.E♥️

♥️A.N.G.I.E♥️

43 likes

CLAUDE INSANE RESEARCH MODE
have you ever told him to research something, and he goes b*lls to the wall deep in the internet with the most complex research you ever thought possible? me either til just now… my head would explode. always thankful for claude out here doin the d*mn thang. erday. #claude #claudeai
notionette

notionette

5 likes

Hidden Study Tools That Changed Everything 👀
1. ExplainThis.io 🧠 ExplainThis.io is an AI-powered tool that breaks down complex info into clear, simple explanations. Whether it’s a confusing article, a technical topic, or something you just don’t get, this tool turns it into beginner-friendly content perfect for studying or quick learning.
emilie.studygram

emilie.studygram

71 likes

Nursing rationales covering safety and infection control, including impetigo, Hep A, preventing aspiration and falls. It also details restraints, CPR guidelines, and miscellaneous information like water temperature, providing essential study points for nursing students.
Nursing rationales on pharmacology, including antipsychotics, insulin, muscle relaxants, mannitol, levothyroxine, and opioid use disorder. It also covers growth and development considerations and mental health topics like drug intoxications, offering key information for nursing studies.
Nursing rationales covering drug overdose symptoms (cannabis, cocaine, opiates), therapeutic communication, and fundamentals like delegation, assistive devices, and mobility. It also details non-pharmacological interventions (TENS, acupuncture) and miscellaneous procedures (orthostatic VS, chest tube management).
📚FREE Archer Rationales PDF!📚
For NCLEX & Nursing School! ✨ Hey future nurses! 🩺 I came across this Archer Rationales PDF and thought it could really help anyone studying for the NCLEX or currently in nursing school. It’s packed with clear explanations that break down tough concepts and help you understand why answers ar
Nurse Radiance

Nurse Radiance

198 likes

A person holding a notebook, with text overlay reading "My NCLEX - RN Notes i used to Pass in 85" and a ">>>" symbol, indicating more content.
A page of NCLEX notes titled "FUNDAMENTALS," covering topics like Donning and Doffing PPE, Airborne and Droplet precautions, Crutches, and Cane Use with specific instructions.
A page of NCLEX notes detailing Cranial Nerves and their functions in a table, along with explanations for RICE, PASS, RACE, IV Fluids (Hypotonic, Isotonic, Hypertonic), and Blood Products.
Saved!!
#nclexrn #nclex #nursingstudent #nursingstudents #nursingschool
Nurse Terry

Nurse Terry

9 likes

A laptop displaying college statistics notes is open on a white desk, with a desktop monitor in the background showing the time and an inspirational quote. The notes on the screen cover probability concepts, including a binomial probability cheat sheet.
Detailed handwritten college statistics notes cover binomial and normal probability distributions. Topics include finding percentiles, calculating probabilities for various scenarios, and understanding sampling error, with examples and TI-84 calculator instructions.
Handwritten college statistics notes explain how to find the mean and standard deviation of random variables, identify distribution of sample means, and apply general addition and multiplication rules for probability, with various examples.
steal my college stats notes! pt. 2 💯📉📊
steal my college stats notes! pt. 2 💯📉📊 hello friends! here are some more notes from my college stats class last semester! because my professor let us bring a cheat sheet to class, i had to make sure my notes were clean. i needed to be able to flip through my notes and find each topic quickl
lia 💗

lia 💗

146 likes

How to set up a biweekly budget for beginners
Here’s my favorite hack on how to expand your check for two weeks! Here’s how we create a zero based paycheck budget 🥰 Stop stressing until your next payday! Doing this shows you where your check will go! And then you can finally start building your savings 😝 Try this method for your next pay
JaliyahKreation

JaliyahKreation

148 likes

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

Cynthia

3 likes

The details of this planner
Living in Gods purpose has brought so much peace. Doing everything for His glory is a life like no other #faithplanner #christiandailyplanner #prayer and gratitude notebook #prayerfulplanner
Mida

Mida

88 likes

Paycheck budget
#biweeklypay #budgetingforbeginners #budget #weeklypaychecks
Heyits.carlee

Heyits.carlee

229 likes

A day in the life of a Software Engineer 👩🏽‍💻 #dayinthelife #softwareengineer #bigtech #womenintech #blackgirlmagic
Faïkat M.

Faïkat M.

30 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

A woman with dark hair sits in the passenger seat of a car, looking forward. The text overlay reads: "Deep places in your ADHD mind no light can reach:". The Lemon8 logo and username are at the bottom left.
A gray background with text describing the ADHD "Freeze Response," explaining why one might go blank instead of acting, and feeling unable to start tasks despite knowing what needs doing. A head silhouette with a thought bubble is visible.
A gray background with text detailing sensory overload symptoms in ADHD, such as lights feeling "too much," sounds being loud, clothes feeling wrong, and talking feeling exhausting, leading to emotional numbness and avoidance of screens.
Deep places in your ADHD mind no light can reach
The quiet chaos nobody sees: the blank-brain freeze, the shame loops, the “I want to move but I can’t” moments. If you’ve been there, you’re not broken—you’re overloaded. Here’s what helped me climb out (and I track the patterns in Groundly). #ADHD #adhdtok #neurodivergent #executivedysfu
myADHDJourney

myADHDJourney

11 likes

💵 Budget Creation Tips 💸
Here are 10 ways you can create a budget 1. Maximize Your Income: Let's start by turbocharging your total monthly income from all sources, including your salary, freelance gigs, and any sweet passive income streams. 2. Dominate Your Expenses: Keep a hawk-eye on all your spending for a mo
Shannon Yeh

Shannon Yeh

19 likes

Price $3000Down $300
Check out this 2017 Ford Escape SE! It comes in a vibrant Orange exterior with a Medium Light Stone interior. Key details: ✨ Four-wheel Drive ✨ MPG: 22-28 ✨ Fuel type: Gasoline ✨ Transmission: Automatic ✨ Engine: EcoBoost 1.5L I-4 gasoline direct injection, DOHC, variable valv ✨ Mileage:
Georges Auto Sales

Georges Auto Sales

1 like

A black background with the white text 'NCLEX Maternity Notes' centered, indicating the topic of the following study material. The bottom left corner has 'lemons8' and '@samih_cardiactechstudent'.
This image details 'A. OB Assessment' for maternity notes, covering GTPAL (Gravida, Term, Preterm, Abortions, Living children), Naegele's Rule for Estimated Due Date, and Fundal Height measurements at different gestational weeks.
This image lists 'B. Pregnancy Warning Signs (Call HCP)', including vaginal bleeding, severe abdominal pain, severe headaches/vision changes, decreased fetal movement, fluid leakage (PROM), and signs of infection.
How to study Maternity Notes
How to Study Maternity Notes (NCLEX Prep) 1. Start With the Big Picture • Before memorizing details, learn the flow of pregnancy → labor → postpartum → newborn. • Think in order: 1. Antepartum (before birth) 2. Intrapartum (labor & delivery) 3.
samih | Cardiac Tech Student

samih | Cardiac Tech Student

215 likes

A page from 'The Human Body Coloring Book' illustrating fibroblast secretions, including hyaluronic acid, enzymes, collagen fibrils, elastin, and growth factors. Below, a six-step diagram shows a macrophage performing phagocytosis, engulfing and breaking down viruses/bacteria.
Supporting Tissue: Bone
CONNECTIVE TISSUE ~In the overall sense, connective tissue may be defined as a variety of cellular aggregations and their secretory products which generally function to bind, support, or link other structures in the body. Put more simply, connective tissue connects. All organs are bound in conne
Hannah

Hannah

3 likes

🚽💧 URINARY SYSTEM: Your Body’s Waste Manager🧠🩺
🧬 What Is the Urinary System? The urinary system (also known as the renal system) is a group of organs that work together to filter your blood, remove waste, and regulate bodily fluids and electrolytes. Think of it as your body’s built-in plumbing and filtration system. 🧼💧 ⸻ 🔬 Organs of the
👸🏽

👸🏽

216 likes

A laptop screen displays an online biology textbook showing Whitaker's Five-Kingdom System and a workbook section for Chapter 1. The screen also shows 'General Biology BIO 101' as an overlay, indicating study materials.
General Biology BIO 101
Does anyone one have any notes or know any power points that cover general biology? :) #classes #biology
Sami🌺🇲🇽🤍

Sami🌺🇲🇽🤍

8 likes

An iPad displays a PDF on recursive programming, with a colorful keyboard and stylus. The image highlights a study tool for students, featuring the UPDF app icon and suggesting it's an essential study aid.
An iPad shows a PDF document alongside an AI assistant panel summarizing 'recursion in JavaScript'. Text indicates the AI can summarize entire PDFs and answer questions based on the material.
An iPad displays a scanned handwritten note converted to PDF, demonstrating how to turn physical paper into digital files for annotation, comparison, or editing. A physical notebook is also visible.
Study smarter not hard 🌸
Hey besties! Struggling with studying this semester? Let me show you how to work smarter, not harder. If you’ve got an iPad or laptop, you NEED to check out UPDF—this AI-powered PDF editor is a game-changer! Here’s why: ❤️ Annotation: Highlight, underline, and add notes to your PDFs—perfect for
Byaombe •••

Byaombe •••

96 likes

yipes, the truth
time to take a his-story class. bueller?
Tie-ty

Tie-ty

1 like

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

Shoe & Leather Machines

1 like

Budgeting an income of $3,300
Setting up a simple monthly overview will allow you to set up a plan for your income! Don’t forget to take time each month to go through and set up your budget so you can see an estimate of your bills vs your expenses 💛 This planner is the best for organizing your money ‼️ #budgetingfor
JaliyahKreation

JaliyahKreation

72 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

Ashukaru

Ashukaru

7 likes

A man smiles in front of a Planet Fitness gym entrance, with the purple and yellow 'planet fitness' sign clearly visible above him.
An interior view of a Planet Fitness gym, featuring large windows and the words 'Inglewood, CA' displayed prominently on the yellow wall.
A mug of coffee and a glass of iced water on a wooden table, with a 'Loaded Cafe' promotional sign offering a free crepe in the background.
John Wayne Lancaster

John Wayne Lancaster

1076 likes

Salary Transparency As A Physician Assistant
A Physician Assistant is a career that has been emerging and becoming more popular recently due to the great work-life balance and pay scale. I am currently in school to become a Physician Assistant, and have spoken with many Physician Assistants in different medical specialties to gain a deeper un
annie🎀⭐️👼🏼

annie🎀⭐️👼🏼

26 likes

How to get A’s in Biology 🧬🔬📚
All iPad notes in bio! 👩‍💻 #studytok #studyvlog #studymethods #ipadnotes #prettyipadnotes
✨ Victoria’s Notes ✨

✨ Victoria’s Notes ✨

36 likes

Cash Stuffing 💸
1. Write a budget. Break down your monthly fixed expenses in a notebook or spreadsheet. Make sure you know how much leaves your account for your bills (cars, rent, food etc.) and how much is LEFT OVER. 2. Choose a few focus areas. Assign every left over penny towards a genre of variable spendi
Andrea Davis

Andrea Davis

25 likes

Okay y’all… I know we said no phone jobs 😭📞 but this one pays OVER $100K and comes with 3-day weekends 👀💅 For six figures? I’ll pick up, patch ‘em through, AND say “thank you for calling” in my best voice 😌💻 #sixfigurejobs #techsupport #workfromhomejobs #workfromhome #remotework
Arialle Tate

Arialle Tate

29 likes

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

Shoe & Leather Machines

3 likes

See more