今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

标签:#learn

找到 584 篇相关文章

AI 资讯

From Devnet to Mainnet: What Changes When Your Solana Program Goes Live

There's a moment in every Solana project where the work stops being about whether the program works and starts being about whether it's ready . You've tested it, the logic holds, the constraints are tight. Then you point it at mainnet, and a different set of questions shows up: questions about money, permanence, and strangers. This post is about that transition. Not the commands, which are short and well documented, but the shift in what you're responsible for once real users can touch your code. If you've been building on devnet and you're starting to think about a live launch, this is the mental model to carry in. Devnet was a sandbox. Mainnet is not. Devnet is a practice field. The SOL is free, you airdrop more whenever you run low, and if you deploy something broken, the only casualty is your afternoon. That safety is the whole point of devnet: it lets you fail cheaply and often, which is exactly how you should be learning. Mainnet removes the safety net, and three things change the moment you cross over. The SOL is real. Deploying a program allocates an on-chain account sized to your compiled binary, and you pay rent for that space in actual SOL. Larger programs cost more. This isn't a huge sum for a typical program, but it's real money leaving a real wallet, and that alone tends to sharpen how carefully you check things before you hit deploy. The audience is real. On devnet the only person calling your program is you. On mainnet, anyone can find your program and send it any transaction they like, the moment it's live. Everything from the security arc stops being theoretical: the accounts strangers pass in, the inputs you didn't expect, the edge cases you hoped no one would hit. Mainnet is where "every account is attacker-controlled until proven otherwise" becomes a live condition rather than a lesson. The mistakes are visible. A bad devnet deploy disappears into the noise. A bad mainnet deploy is a public event, on a permanent ledger, in front of the users you

2026-07-11 原文 →
AI 资讯

Mapping Semantic Meaning Onto the Night Sky

If you were to look up into the night sky, what would you see? Countless points of light, scattered in every direction. Most of what you're looking at are stars. But some of those points are whole galaxies—vast collections of stars, spread across incomprehensible distances, compressed by that distance into a single pinprick of light. And what you can see with the naked eye is only a small fraction of what's actually out there. I want to use this as a way to offer you a way of thinking about how large language models work. Just an analogy, not literally what's happening inside the mathematics—that's not my forte. My hope is that it captures something true about the mechanics, and more importantly, it gives you a mental model you can actually use when you're working with these systems. About two years ago, I was wrestling with finding a way of explaining what an LLM does. My first analogy was that of a dictionary. The naive view was that a dictionary uses words to define other words, and an LLM holds a matrix of words with weights that describe their relationships to each other. So the parallel seemed natural: both systems work through relational structure. However, a dictionary gives you denotation—the surface-level meaning. It's a lookup tool for individual words, not a model of language itself. And critically, you have to already understand language before a dictionary is useful to you at all. The analogy didn't capture what was actually happening in the weight relationships—the distributional semantics, the contextual patterns that let an LLM generate coherent text. Ok, so back to galaxies, when you look up at the night sky, you're not seeing distance—you're seeing direction. That galaxy over there, the one that looks like a point of light, could be millions of light-years away, but what matters for our analogy isn't how far it is. It's which way you're looking. And when you point yourself in that direction and venture toward it, you discover it's not a point at a

2026-07-10 原文 →
AI 资讯

I made my agent more capable and it got worse

Builder Journal · ARC Prize 2026 There is a moment in every role-playing game where you load your character with so much heavy gear that they can barely walk. Strongest sword in the game, can't reach the fight. I did the machine-learning version of that this month. I kept making my agent more capable, and the scoreboard kept punishing me for it, and it took me two tries to understand that the upgrades were the problem. A quick frame, in case this is your first entry in this thread : I'm in the ARC Prize 2026, building an agent that has to learn small games it has never seen, with no instructions. As the benchmark's creator measured it, the hardest part by far is the piece that figures out the rules of a game by experimenting on it. So that piece is where I have been pouring my effort. The obvious upgrade The obvious way to make that piece better is to teach it more kinds of games. If it can model three families of puzzle today, teach it a fourth, and it should win more. So I did exactly that. I built support for a new class of game it could recognize and solve, wrote it carefully, tested it, and confirmed the thing I wanted to confirm: the agent now beat a game it provably could not beat the day before. Real, verified, new capability. Not a story I was telling myself, a genuine new skill on the board. Then I submitted, and the score went down. Twice This is the part I want to be honest about, because one bad result is noise and two is a pattern. My agent's attempts to use this theory-building component had already been underwhelming on the real board, landing around 0.05, 0.07, and 0.09 across earlier tries, all of them under the 0.25 my plain, careful agent scores when it does not reach for the fancy component at all. The fourth skill was supposed to turn that corner. Instead the next submission came in at 0.04, the worst of the lot. I had added ability and the number had dropped, again. So I stopped adding and started counting. I ran a survey across twenty-five of

2026-07-10 原文 →
AI 资讯

How a Transformer Plays Tic-Tac-Toe

An interactive guide to the architecture behind modern language models. Instead of predicting the next word, this Transformer predicts the next move in a game of fading Tic-Tac-Toe—making every step of the model easy to visualize and understand. Play the game, inspect every matrix multiplication, and watch tokens flow through the network in real time. What's covered Tokenization and embeddings Learned positional encoding Self-attention (Q, K, V) Multi-head attention Causal masking and softmax Residual connections and layer normalization MLP (feed-forward network) Unembedding and sampling Model ablations (no positional encoding, no causal mask, no MLP, no residual stream) Includes interactive visualizations for every stage of the Transformer pipeline - from input tokens to the final prediction. https://sbondaryev.dev/articles/transformer

2026-07-10 原文 →
AI 资讯

How I Built an AI Decision Copilot to Help India Prepare for the 2026 El Niño Crisis

Building an explainable AI platform that helps district administrators allocate resources and farmers make better crop decisions using Gemini, Vertex AI, BigQuery, and Google Cloud. Climate disasters are not just weather events. They are decision problems. When forecasts predict a strong El Niño, governments do not simply need more data. They need answers to questions like: Which districts will be affected first? Where should limited water resources be sent? Which crops are likely to fail? What should farmers sow instead? Why is the AI recommending this action? Existing dashboards provide plenty of charts. Very few provide decisions. That became the motivation behind El Niño 2026 Decision Copilot , an AI-powered decision intelligence platform built during the Google Cloud Gen AI Academy APAC Hackathon . The Problem India depends heavily on the monsoon. A severe El Niño can lead to: Rainfall deficits Reservoir depletion Groundwater stress Crop failures Rising food prices Rural employment challenges The information already exists across dozens of government portals, weather services, satellite datasets, and agricultural reports. The challenge is that it is scattered. District collectors do not have time to manually combine: Weather forecasts NDVI satellite imagery Reservoir levels Mandi prices Contingency plans Drought indicators Farmers face an even bigger challenge. Most need a simple answer: Given my district, should I plant the usual crop this season? The Goal Instead of building another dashboard, I wanted to build an AI system that reasons over multiple data sources and produces explainable recommendations. The platform serves two audiences through the same intelligence engine. District Administrators They receive: District risk scores Interactive risk maps Reservoir outlook Crop stress indicators Resource allocation recommendations AI-generated explanations Instead of simply showing that a district has high risk, the system explains why . Farmers Farmers intera

2026-07-10 原文 →
AI 资讯

Semantic Drift in LLMs: How Archetypal Attractors (Like “Goblin”) Emerge and How Structured Reflection Reduces Them

Large language models often develop recurring symbolic patterns — archetypes, metaphors, and memetic shortcuts — that appear across unrelated contexts. One observed example is the repeated emergence of fantasy-based metaphors such as “goblins,” “gremlins,” or similar entities when describing abstract system behavior, errors, or complexity. This article presents a structured analytical trace (A11 framework passes) showing how such patterns emerge from the interaction between reinforcement learning, cultural priors in training data, and user feedback loops. It also explores how introducing explicit interpretability layers can reduce the risk of these symbolic attractors becoming dominant explanatory shortcuts in model behavior. The first A11 pass S1 — Will Understand the causal mechanism: why the “goblin / fantasy drift” emerged in LLMs S2 — Wisdom (constraints) Main pitfall: confusing correlation (goblins appearing in outputs) with causation (why those specific symbols emerge) Also: “goblins” are not a standalone phenomenon they are a case of broader archetypal language drift S3 — Knowledge (what is actually known) There are 5 established mechanisms in LLM behavior: 1. RLHF reinforces “socially engaging metaphors” Models are rewarded for: vividness humor imagery human-like explanations ➡️ fantasy imagery tends to score highly 2. Internet prior already contains strong fantasy culture Training data includes: Reddit gaming discourse D&D culture fanfiction ➡️ “goblin / elf / troll” already exist as: universal behavioral archetypes 3. Compression effect (semantic abstraction) The model seeks compact semantic units: goblin = chaotic / greedy / messy / low-level failure mode ➡️ one token replaces a complex description 4. User feedback loop If the model says: “it’s like a goblin” users: react positively repeat it reinforce it in conversation ➡️ increases probability of reuse 5. Cross-task transfer (persona leakage) Stylistic patterns from: coding assistant mode creative mode

2026-07-10 原文 →
AI 资讯

26 AI Models Compared: A 2026 Cost Guide (GPT-4o vs Claude vs DeepSeek vs Local)

canonical_url: https://quantumflow-ai-ecosystem.vercel.app/blog/26-ai-models-compared-2026-cost-guide date: 2026-07-09T10:00:00Z If you're building an AI-powered application in 2026, you have a problem: there are too many models to choose from. OpenAI has GPT-4o. Anthropic has Claude 3.5 Sonnet. Google has Gemini 1.5 Pro. Meta has Llama 3.1. And then there's DeepSeek, Mistral, Cohere, and a dozen others. Most developers solve this by defaulting to GPT-4o for everything. It's the safe choice — powerful, well-documented, and reliable. But it's also expensive: $2.50 per million input tokens, $10.00 per million output tokens. If you're processing 10 million tokens a day, that's $75+ per day, $2,250+ per month. But here's the secret: most of your requests don't need GPT-4o. In this guide, we'll compare 26 AI models across three dimensions — cost, quality, and speed — and show you how intelligent routing can cut your AI bill by up to 90% without changing a single line of your application code. The 2026 AI Model Landscape The AI model market has fragmented into three tiers. Understanding these tiers is the foundation of any cost optimization strategy. Tier 1: Sovereign Local Models (Free, Priority 100-110) These models run on your own hardware (or your users' hardware) via runtimes like Ollama. They cost $0 per token. They're sovereign — no data leaves your infrastructure. They're fast (no network round-trip). And they're getting remarkably good. Model Parameters Context Best For Cost Llama 3.1 70B (Local) 70B 128K Complex reasoning, code $0 Llama 3.1 8B (Local) 8B 128K General chat, fast responses $0 Mistral 7B (Local) 7B 32K Efficient European-language tasks $0 DeepSeek Coder (Local) 6.7B 16K Code generation & completion $0 GLM-4 9B Chat (Local) 9B 128K Bilingual (EN/ZH) chat $0 Llama 3.2 3B (Local) 3B 128K Edge devices, mobile $0 Llama 3.2 1B (Local) 1B 128K Ultra-lightweight tasks $0 CodeLlama 7B (Local) 7B 16K Legacy code tasks $0 GLM-4V 9B Vision (Local) 9B 128K Loca

2026-07-10 原文 →
AI 资讯

Três bugs que cometi construindo um sistema de confiabilidade (e os três fingiram que deu tudo certo)

Passei os últimos dias construindo o HookSafe, uma camada que fica entre a plataforma de pagamento e o servidor do cliente para garantir que nenhum webhook se perca. A promessa do produto é uma só: se o seu servidor cair, eu seguro o evento e insisto até entregar. Cometi três bugs no caminho. O que me fez escrever este texto não foi a burrice de cada um, foi perceber, depois, que os três tinham a mesma forma: todos faziam uma falha parecer um sucesso. Num sistema cujo produto é confiabilidade, é difícil imaginar categoria de bug mais cruel. Bug 1: engoli o erro, e o sistema jurou que tinha entregue A função que entrega o evento no servidor do cliente ficou assim: go resposta, err := clienteHTTP.Do(requisicao) if err != nil { return "", nil // <- olhe com carinho } Eu quis escrever return "", err . Escrevi nil . O efeito: apontei o destino para uma porta onde não havia nada escutando. O Do devolveu um belo connection refused . E a minha função respondeu ao worker: "sem erro, chefe". O worker, obediente, marcou o evento como entregue , com o status da resposta vazio, e seguiu a vida. No banco: id | pedido_id | status | tentativas | resposta ----+-----------+----------+------------+---------- 6 | 9002 | entregue | 0 | Um evento que nunca saiu do lugar, registrado como entregue. Se isso estivesse em produção, um cliente teria pagado, não receberia nada, e o meu painel mostraria, orgulhoso, que a entrega foi um sucesso. Aquele if err != nil { return err } que a gente reclama de repetir em Go existe exatamente por isso. A linguagem te obriga a decidir o que fazer com a falha, toda vez. O preço da verbosidade é que ninguém engole um erro sem querer... a menos que digite nil . Bug 2: o log mentiu Corrigi o primeiro bug, rodei de novo, e o worker começou a cuspir isto, a cada cinco segundos, para sempre: worker: erro ao marcar morto 7: ERROR: column "reposta" does not exist worker: evento 7 esgotou as tentativas, marcado como MORTO Leia as duas linhas de novo. A primeira diz

2026-07-10 原文 →
开发者

Deciding to Appear: One Year of Shifting into Development

Nice to meet you! I'm Andrew It's been a year since I joined the community. I started developing a bit earlier, and changing my career just by learning and practicing is far from what I had planned. I cannot help but be thankful for each course and tutorial, and each developer and tutor who has shared some knowledge and wisdom with me. It is still too early to know exactly what I will fix, build, or vibe to improve the world, but I will do my best... print ( " Hola mundo, aquí vamos! " ) Follow my journey on GitHub "I'm curious to hear from others—what was the biggest challenge you faced during your first year of coding? Or, if you're just starting, what's one thing you're excited to build?"

2026-07-09 原文 →
AI 资讯

I thought building a video speed controller would take a weekend. The analytics nearly broke me.

It was 2 AM on a Tuesday, and I was staring at my CourseSpeed dashboard looking at a graph that claimed I had just finished a 14-hour AWS certification course in 47 minutes. I hadn't. I was just testing the 16x speed toggle. But my analytics engine thought I was a god. When I started building CourseSpeed—a browser extension to inject custom playback speeds and track learning analytics across Udemy, Coursera, LinkedIn Learning, and Skillshare—I thought the hard part would be the UI. It wasn't. Injecting a floating control panel and setting document.querySelector('video').playbackRate = 2.5 takes about ten lines of JavaScript. The actual nightmare was the learning analytics. Specifically, accurately tracking effective watch time versus wall-clock time across wildly different Single Page Applications (SPAs). The naive approach that burned me My first pass at the analytics tracker was straight out of MDN. I listened to the standard HTML5 video events. // The approach that worked perfectly in my head const video = document . querySelector ( ' video ' ); video . addEventListener ( ' ratechange ' , ( e ) => { sendAnalytics ({ type : ' speed_change ' , rate : e . target . playbackRate }); }); video . addEventListener ( ' timeupdate ' , () => { logWatchTime ( video . currentTime , video . playbackRate ); }); This worked flawlessly on Udemy. Then I opened LinkedIn Learning. The dashboard flatlined. Then I tried Coursera. The time spent was wildly inaccurate, drifting by minutes over an hour. I spent three days debugging this, tearing my hair out over console logs. Here is what I missed: modern learning platforms don't just drop a raw <video> tag on the page and leave it alone. They wrap it in custom players, throttle events to save CPU, and dynamically destroy and recreate the DOM node when you skip chapters or when the SPA router transitions. My event listeners were getting orphaned. Or worse, they were firing with stale data because the platform's custom wrapper was dispatc

2026-07-09 原文 →
AI 资讯

Epoch Duel: Cyberpunk LLM Alignment Battle

Have you ever wondered how AI engineers fine-tune and align large language models? Under the hood, they run Supervised Fine-Tuning (SFT), optimize parameters using direct preference gradients (DPO), filter out low-quality pre-training corpuses (Pruning), and mitigate catastrophic drifts. To help you visualize how LLM alignment and parameter optimization work in a highly strategic way, I built a cyberpunk card battler inspired by Gwent: 🤖 Epoch Duel: Cyberpunk LLM Alignment Battle Play in Fullscreen Mode (if the embed sizing is tight) 🛠️ Tune Your Model Parameters Your mission as an alignment engineer is to play optimizer cards to outscore the adversarial baseline AI across 3 training Epochs: ⚙️ Logic & Coding: Run SFT code snippets, compile theorem provers, and deploy Python scripts to build your coding benchmark scores. 📖 Language & Speech: Train on multilingual datasets and summarization corpuses to maximize reading comprehension. 🛡️ Safety & Alignment: Implement red-team safeguards, configure RLHF preference pairs, and run DPO tuning to protect your model's outputs. ⚡ regularizers & Drifts: Deploy Regularization cards like Gradient Clipping (Scorch) and Model Pruning to destroy anomalies, or exploit Anomalous Drifts to collapse the AI's rows. 🧬 Playable ML Concepts Explained Here is how the card battle mechanics map to production machine learning pipelines: 1. ✂️ Model Pruning (Weight Compression) In-Game: Playing the Model Pruning card triggers a glitchy dissolution animation that purges the lowest-value card from the targeted board row, cleaning up noise. 💾 The Real-World Counterpart Model Pruning removes unimportant weights (often those closest to zero) from a trained neural network. It shrinks the memory footprint of the model, allowing it to run faster on edge devices. ⚠️ How it affects LLMs By stripping out low-impact weights, pruning compresses models by 30-50% with minimal loss in benchmark accuracy, making deployment significantly cheaper. 2. 🔀 DPO vs RL

2026-07-09 原文 →
AI 资讯

I built on-device workout rep counting in Flutter — here's what actually worked

I'm building TrainWiz , a Flutter app that turns real exercise into a pet-raising game: you do squats or push-ups, your phone counts the reps, and a little creature levels up and evolves. The core technical problem sounds trivial and absolutely is not: count reps from the camera, on-device, without uploading a single frame. Here's what broke along the way, and what finally worked. Why on-device Two reasons: privacy and latency. A fitness camera that streams your body to a server is a non-starter for most people, and rep feedback has to feel instant or the whole "game" loop dies. So everything runs locally with tflite_flutter + an on-device pose model — no footage ever leaves the phone. Naive attempt #1: joint-angle thresholds The obvious approach: track the knee angle, count a rep when it dips below X° and comes back up. // looks fine in a demo, dies in the real world final kneeAngle = angleBetween ( hip , knee , ankle ); if ( ! _down && kneeAngle < 100 ) _down = true ; if ( _down && kneeAngle > 160 ) { reps ++ ; _down = false ; } It demos beautifully. Then real users prop the phone on the floor, stand at an angle, and it falls apart. The trap: a phone camera gives you 2D pose. A "120° knee angle" flattens completely depending on where the camera sits — the same squat reads as 90° or 150° purely from perspective. Lifting to 3D via the model's z doesn't save you either; monocular z is noisy enough that the angle jitters across your threshold and double-counts. Naive attempt #2: a "body-line" gate Next idea: figure out which exercise you're doing so I can pick the right signal. Standing (squat) vs. horizontal (push-up) should be easy — just check if shoulder, hip and heel form a straight line, right? Wrong, again for the 2D reason. In a real push-up shot from the front-corner, shoulder–hip–heel are not collinear on the image plane — perspective bends them. I gated push-up counting on "body is a straight line" and it would just... stop counting mid-set. Nothing is more

2026-07-09 原文 →
AI 资讯

Anthropic Found a Mind Hiding Inside Their Language Model

What if the AI you chat with every day is quietly running something that looks a lot like a train of thought, and we just never had the right tool to see it? On 7th July, 2026, Anthropic published a research paper that honestly feels a little spooky. The team behind the Transformer Circuits Thread released a long, detailed study called Verbalizable Representations Form a Global Workspace in Language Models . The title is dense, but the idea inside is wild. They found a small, privileged region inside Claude and similar models. A region that behaves a lot like what cognitive scientists call the global workspace , the part of the brain associated with conscious access. The part that lets you say, I am thinking about a banana right now . In this post, I want to walk you through what they found, in plain English, with no math fear and no jargon walls. We will cover what the workspace is, how they found it, what they can do with it, and why it matters for anyone building or using AI. Grab a coffee. This one is worth your time. First, a Quick Brain Detour Before we get to the model, we need a tiny bit of background from neuroscience. For decades, scientists have noticed that the brain seems to operate on two tracks. Most of what your brain does, like parsing the sounds coming into your ears or keeping you balanced, happens automatically and quietly. You cannot really talk about it . It just runs in the background. But a smaller slice of brain activity is different. It is reportable . You can put it into words. You can hold a concept in mind, dismiss it, chain it to another concept, and use it for reasoning. Cognitive scientists call this access consciousness . One popular theory, called the Global Workspace Theory , says this happens because the brain has a shared hub. Specialized processors do their own thing in parallel. But every now and then, a representation gets posted to this central workspace, and once it is there, lots of other brain systems can read it, reason w

2026-07-08 原文 →
AI 资讯

DEMYSTIFYING REACT COMPONENT INSTANCES

Hello fellow React developers! In this article we will be breaking down what React component instance is and scenarios where React component instance is at play. What is a React Component ? Before we can understand and really appreciate what a React component instance is, we first need to understand what a component itself is. Basically, components are the fundamental building blocks of any React application. They are independent, reusable pieces of code that allow you to split your application into distinct, manageable bits of logic and UI. From our knowledge of JavaScript, you can think of components in a way as what a function is. Just as we create and use functions to avoid repeating code and separate logic, components are used to divide our application into reusable visual chunks. However, they work in isolation and return HTML (via JSX) to describe what appears on the UI. Let take a look at a simple Greetings component used in a demo; Instead of writing the HTML layout for a greeting over and over again, we define it once as a component and reuse it multiple times in our application by passing different props (arguments). React Component Instances: What are they ? Now that we understand what a React component is, let's move on to React component instances. In programming, an instance is a concrete object created from a specific template (such as a JavaScript class or a Constructor function). In React, a component instance is the actual implementation of a component in a React application. It is a long-lived object that holds contextual information about a particular component. Every time a component is rendered in our application, React creates a new instance of that component. To help you visualize this, let’s take a look at a simple Counter component; // A Counter Component import React , { useState } from ' react ' ; export default function Counter () { const [ count , setCount ] = useState ( 0 ); return < button onClick = {() => setCount ( count + 1 )} > C

2026-07-08 原文 →
AI 资讯

Day 02: The Terminal, Shells & File Systems

🎯 Learning Objectives Understand the interface boundary between Terminal Emulators and Shell Interpreters (including Windows Terminal vs. PowerShell vs. CMD). Master File System path tracking, hidden dotfiles, and essential CLI utilities. Map system execution paths via global and local environment configurations. 1. Terminal vs. Shell (The Windows Architecture) Terminal: The visual GUI wrapper. A window application that captures keyboard strokes, handles GPU text rendering, and manages tabs/panes. Examples: Windows Terminal, iTerm2, Alacritty. Shell: The command interpreter engine running inside the terminal. It evaluates text strings, processes scripts, issues system calls ( syscalls ), and interacts with the OS Kernel. Examples: PowerShell, Bash, Zsh, Command Prompt (CMD). ┌────────────────────────────────────────────────────────┐ │ WINDOWS TERMINAL GUI (The Visual Interface Window) │ │ │ │ │ ├───► Tab 1: [ PowerShell Core Engine (Modern) ] │ │ ├───► Tab 2: [ Command Prompt Engine (Legacy) ] │ │ └───► Tab 3: [ WSL Ubuntu Linux Bash (Core) ] │ └───────────────────────────┬────────────────────────────┘ │ Raw Text & Input Streams ▼ ┌────────────────────────────────────────────────────────┐ │ SHELL INTERPRETER (e.g., PowerShell / CMD) │ │ └───► Parses input string commands into system tasks │ └───────────────────────────┬────────────────────────────┘ │ System Call (Syscall) ▼ ┌────────────────────────────────────────────────────────┐ │ OPERATING SYSTEM KERNEL │ │ └───► Interacts directly with underlying hardware │ └────────────────────────────────────────────────────────┘ 2. Deep Dive: PowerShell vs. Command Prompt (CMD) While both are Windows shells hosted inside Windows Terminal, they belong to entirely different computing eras: Command Prompt ( cmd.exe ): A legacy text shell maintained purely for backwards compatibility with 1980s MS-DOS. It pipelines data as Plain Text Only , meaning outputs must be manually string-filtered. PowerShell ( pwsh.exe ): A modern, cros

2026-07-08 原文 →
开发者

JavaScript Functions: Basic Concepts You Should Know

Introduction When learning JavaScript, one of the first concepts you’ll encounter is functions. Functions are the building blocks of JavaScript. They help you organize code, avoid repetition, and make your programs easier to understand. If variables store data, functions define behavior . You’ll use functions everywhere: handling user input, processing data, calling APIs, and structuring your code. In this article, we’ll cover: What is a function Function declarations Function expressions Parameters vs arguments Return values Arrow Functions Why Functions Matter 1. What is a Function? A function is a reusable block of code designed to perform a specific task. Think of it like a machine: Input → Process → Output function greet () { console . log ( " Hello! " ); } To run the function, you call it: greet (); // Hello! 2. Function Declaration This is the most common way to define a function: function add ( a , b ) { return a + b ; } 💡 Explanation: Defined using the function keyword Can be called before it is declared (because of hoisting) Key parts: function → keyword add → function name a, b → parameters return → output value add (); // ✅ Works! function add ( a , b ) { return a + b ; } 💡 Why does this work? JavaScript reads the code first, and function declarations are stored in memory during the initial phase (hoisting) . That’s why you can call the function even before it’s defined in the code. 3. Function Expressions Functions can also be stored in variables: function add ( a , b ) { return a + b ; } 💡 Explanation: Assigned to a variable Cannot be used before initialization add (); // ❌ Error: Cannot access before initialization const add = function ( a , b ) { return a + b ; }; 💡 Why does this cause an error? Because: const add has not been initialized yet when it is called. The function itself is not in memory at that moment . 4. Parameters vs Arguments This is a common beginner confusion: Parameter: variable in function definition Argument: actual value passed i

2026-07-08 原文 →