This guide introduces fundamental JavaScript concepts, including variables and functions, in a simple and clear way. It's designed for beginners to understand the basics and build a strong foundation.
A variable is like a labeled box where you store data (like numbers, text, or other values) to use later in your program. You give it a name, and you can change or retrieve its contents as needed.
In JavaScript, you declare a variable using one of three keywords: var
, let
, or const
. Declaring a variable tells JavaScript to reserve space for it.
- Syntax:
var variableName; // Using var let variableName; // Using let const variableName; // Using const
- You can also assign a value during declaration:
let age = 25; const name = "Alice";
Keyword | Scope | Reassignment | Redeclaration | Hoisting |
---|---|---|---|---|
var |
Function or global | Yes | Yes | Yes (to top, undefined) |
let |
Block (e.g., inside {} ) |
Yes | No | Yes (to top, uninitialized) |
const |
Block | No (value can't change) | No | Yes (to top, uninitialized) |
- Scope: Where the variable is accessible.
var
: Accessible in the entire function or globally if declared outside.let
andconst
: Limited to the block (e.g., inside a loop orif
statement).
- Reassignment: Changing the variable's value.
var
andlet
: Can be reassigned.const
: Cannot be reassigned (but objects/arrays can have their contents modified).
- Redeclaration: Declaring the same variable name again in the same scope.
var
: Allows redeclaration (can cause bugs).let
andconst
: Prevent redeclaration in the same scope.
- Hoisting: JavaScript moves declarations to the top during execution.
var
: Hoisted and initialized toundefined
.let
andconst
: Hoisted but not initialized (access before declaration results in aReferenceError
).
var x = 10; // Can redeclare
x = 20; // Reassign
var x = 30; // Redeclare (allowed)
let y = 5; // Block-scoped
y = 15; // Reassign
// let y = 25; // Error: Cannot redeclare
const z = 100; // Constant
// z = 200; // Error: Cannot reassign
// const z = "test"; // Error: Cannot redeclare
- Use
const
by default for values that won’t change. - Use
let
for variables that need reassignment. - Avoid
var
due to its loose behavior and potential for errors.
A function is a reusable block of code that performs a specific task. You define it once and can call (or invoke) it multiple times with different inputs to get different outputs.
A function in JavaScript has several parts. Here’s a breakdown with an example:
function greet(name, timeOfDay) { // 1. Function keyword, 2. Name, // 3. Parameters
const message = `Good ${timeOfDay}, ${name}!`; // 4. Body
return message; // 5. Return statement
}
- Function Keyword (
function
): Declares that this is a function. - Function Name (
greet
): A descriptive name to identify the function (follows variable naming rules). - Parameters (
name, timeOfDay
): Placeholders for inputs the function expects, enclosed in parentheses. Can be none or multiple. - Function Body (
{ ... }
): The code inside curly braces{}
that runs when the function is called. - Return Statement (
return message
): Specifies the value the function outputs. Execution stops afterreturn
statement. If omitted, the function returnsundefined
.
- Parameter: A variable defined in the function’s declaration to accept input (e.g.,
name
,timeOfDay
). Think of it as a placeholder. - Argument: The actual value passed to the function when it’s called (e.g.,
"Alice"
,"morning"
ingreet("Alice", "morning")
). - Return Type: JavaScript doesn’t explicitly declare return types (dynamic typing), but it’s the type of value returned by the function (e.g.,
string
forgreet
, could benumber
,object
, etc.). If noreturn
is specified, the function returnsundefined
.
function add(a, b) { // Parameters: a, b
return a + b;
}
const sum = add(3, 4); // Arguments: 3, 4 // Returns 7
console.log(sum); // Outputs: 7
-
Defining a Function**: Writing the function’s code to create it. This is like creating a recipe. The function is declared but not executed.
function sayHello() { // Defining console.log("Hello!"); }
-
Invoking a Function**: Calling or running the function by using its name followed by parentheses
()
(with arguments if required). This is like following the recipe to cook.sayHello(); // Invoking (Outputs: Hello!)
-
Key Difference:
- Defining creates the function and stores it in memory.
- Invoking executes the function’s code.
- You can define a function once but invoke it multiple times.
// Defining the function
function multiply(x, y) {
return x * y;
}
// Invoking the function multiple times
console.log(multiply(2, 3)); // Outputs: 6
console.log(multiply(5, 4)); // Outputs: 20
- Default Parameters: You can set default values for parameters.
function greet(name = "Guest") { return `Hello, ${name}!`; } console.log(greet()); // Outputs: Hello, Guest! console.log(greet("Bob")); // Outputs: Hello, Bob!
- Function Expressions: Another way to define functions by assigning them to variables.
const square = function(num) { return num * num; }; console.log(square(5)); // Outputs: 25
- Arrow Functions: A concise syntax introduced in ES6.
const cube = (num) => num * num * num; console.log(cube(3)); // Outputs: 27
- Use descriptive names (e.g.,
calculateArea
instead ofca
). - Keep functions small and focused on one task.
- Always include a
return
statement if the function should output a value. - Avoid side effects (changing external variables) when possible.
- Variables: Store data using
var
,let
, orconst
. Preferconst
for constants,let
for reassignable values, and avoidvar
. - Functions: Reusable code blocks with parameters, a body, and a return value. Define them to create, invoke them to execute.
- Understand the difference between parameters (placeholders) and arguments (actual values), and use clear naming to make your code readable.
This primer provides the foundation to start writing JavaScript code confidently. Practice by creating variables and functions to solve small problems!