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

2173 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 ♡

6690 likes

Learn the basics of computer science & coding ✨
This book caught my eye and I don't regret purchasing it. This book is filled with bite-sized info to learn computer science and coding, and the information was also very well presented. When I shared this book one day, I got a lot of messages about the book details so I also included them here
teal.days

teal.days

1733 likes

A tablet on a desk displays code, with a colorful keyboard and notebook beside it. The image is overlaid with text "STUDY HACKS For ADHD Students" and "SWIPE".
A tablet shows the Pomofocus.io website with a large 25:00 timer and task list. Overlay text describes Pomofocus.io for the Pomodoro technique.
A tablet displays the Chrome Web Store page for the Speechify Text to Speech Voice Reader extension. Overlay text explains Speechify as a text-to-speech tool.
Study sites you need if you have ADHD
As someone with ADHD, I wish someone would’ve told me of the resources and techniques to help me study, so I put together 3 resources and their studying techniques to help you all. Here they are 1. POMODORO TECHNIQUE: this is a time management technique based on 25-minute stretches of focused w
Byaombe •••

Byaombe •••

1573 likes

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

Aysha

124 likes

A tablet on a desk displays math notes on linear algebra and calculus, with text overlay "FREE ONLINE COURSES (math edition)" and a calculus integral formula. A keyboard and mouse are also visible on the desk.
A memo-style graphic lists four free online math courses: OpenStax College Algebra, MIT Single Variable Calculus, 3Blue1Brown's Essence of Linear Algebra, and StatQuest with Josh Starmer, each with a brief description.
A person uses a stylus on a tablet displaying math problems, with a pink Stanley cup and keyboard on the desk. A monitor in the background shows a Spotify playlist. Text overlays encourage comments and following.
Free Online MATH Courses!!
🧮 If math has you stressed, don’t worry, these free courses make it so much easier to learn! From algebra and calculus to linear algebra and stats, I’ve got you covered with the best resources. ✏️ Drop a ❤️ if you're ready to learn, and follow for more tips to help you crush your classes! 📚✨
CompSkyy

CompSkyy

932 likes

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

Shoe & Leather Machines

9 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

157 likes

Even in the middle of preparing for testing, there is still room for joy. So we laughed a little today. 💗😂 Because growth doesn’t always have to feel heavy. #MathMadeEasy #MathMagic #MathMadeFun #mathjokes #laughter If this blessed you even a little… share it. 💛
SimplyMe1908

SimplyMe1908

142 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

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

Faïkat M.

30 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 ☀️

1162 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

math notes
Cte Bruno

Cte Bruno

55 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

237 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

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

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

Tie-ty

1 like

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

Shoe & Leather Machines

4 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

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

5 Tips to not get overwhelmed when studying 🙇🏻‍♀️
1. Set timers for tasks: if you have multiple assignments or multiple things to study from (books, lectures, notecards) you need to schedule 45mins - 1 hr for each task and you will get it all done and now smash things in you can even do it in cycles 🔁 2. Take breaks : a little social media bre
Alexis Sanchez

Alexis Sanchez

45 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

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 ✿

142 likes

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

Cynthia

3 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

Back to School tips and tricks!
Here are my essential Back to School ‘tips and tricks’ for this upcoming year 📗🖋️. Lmk your essential ‘tips and tricks’ in the comments… HAPPY BACK TO SCHOOL SZN 🤍 #BackToSchool #lemon8challenge #aesthetic #highschool #school supplies #backtoschoolprep #schoolbag #whattobringtosch
anni

anni

59 likes

A computer screen displays a Google Sheets budget template with various financial tracking sections. In the foreground, a green smoothie is visible, and small potted plants adorn the monitor. Text overlays read 'Healthy Girls BUDGET' and 'How I Budget with Google Sheets'.
A close-up of a Google Sheets budget dashboard shows charts for monthly income, expenses, and debt payments. It includes trackers for income, expenses, and recurring costs, providing a visual overview of financial flow.
A Google Sheets 'Paycheck Estimator' tab is displayed, detailing estimated gross and net pay based on hours and wage. An arrow points to the estimated net pay, with text explaining its use for planning ahead.
💚 How I Budget with Google Sheets 💚
So I started using this budget method quite a few years ago and while sometimes I fell off course, I always came back to it. After refining my process and practicing self discipline, I’ve been able to stick with my budget. I recently started a new job and decided I would make it my goal to pay
Vi

Vi

47 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

A study desk with a laptop, notebook, pink accessories, and a pink water bottle, featuring the text 'STUDY LIKE ELLE WOODS & BE SUCCESSFUL' in pink and white overlay, against a library background.
A study desk with a laptop and pink water bottle, overlaid with the text 'Goal Glam ✨' and advice on setting stylish, achievable goals and rewarding oneself, Elle Woods style.
A study desk with a laptop and pink water bottle, overlaid with the text 'Believe Big 💪' and advice from Elle Woods on the importance of confidence and hard work for achieving dreams.
4 Tips to Study Like Elle Woods ✨🩷😍
Channel your inner Elle Woods with these 4 fabulous study tips that combine style, confidence, and academic success. From setting glamorous goals to taking self-care sessions as seriously as Elle, these tips will help you study smarter while keeping your vibe on point. Whether dressing up your stu
LetsBeBestieBoos

LetsBeBestieBoos

208 likes

A desk setup with a monitor displaying Java code in Eclipse IDE, a keyboard, mouse, and an open textbook, illustrating the process of working on computer science assignments.
An open spiral notebook filled with handwritten computer science notes, including engineering methods, statistical concepts, and code logic, with a pen resting on the page, emphasizing early homework.
A laptop open on a desk, displaying a scenic mountain and lake wallpaper, with a search bar visible, representing a student's workspace and the advice to seek help.
How I Became The BEST Computer Science Student!
CS classes can get real overwhelming if you fall behind! So here are a few tips that helped me stay on top of things: Start your homework early (seriously). The bugs hit harder at 11pm. Go to office hours or the tutoring center and don’t wait until you're completely lost. And don’t be afra
CompSkyy

CompSkyy

91 likes

a typical week day
idk how to use this app tbh #reading📖 #studying #studyaesthetic #studymotivation #gilmoregirls
🦌Nox☽

🦌Nox☽

10 likes

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

73 likes

See more