Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created June 25, 2025 21:46
Show Gist options
  • Save decagondev/27d88b0c86c5bf5d243c37d3a27b3351 to your computer and use it in GitHub Desktop.
Save decagondev/27d88b0c86c5bf5d243c37d3a27b3351 to your computer and use it in GitHub Desktop.

JavaScript Primer: Basics for Beginners

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.

Variables in JavaScript

What is a Variable?

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.

How to Declare a Variable

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";

Differences Between var, let, and const

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 and const: Limited to the block (e.g., inside a loop or if statement).
  • Reassignment: Changing the variable's value.
    • var and let: 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 and const: Prevent redeclaration in the same scope.
  • Hoisting: JavaScript moves declarations to the top during execution.
    • var: Hoisted and initialized to undefined.
    • let and const: Hoisted but not initialized (access before declaration results in a ReferenceError).

Examples

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

Best Practices

  • 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.

Functions in JavaScript

What is a Function?

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.

Anatomy of a Function

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
}
  1. Function Keyword (function): Declares that this is a function.
  2. Function Name (greet): A descriptive name to identify the function (follows variable naming rules).
  3. Parameters (name, timeOfDay): Placeholders for inputs the function expects, enclosed in parentheses. Can be none or multiple.
  4. Function Body ({ ... }): The code inside curly braces {} that runs when the function is called.
  5. Return Statement (return message): Specifies the value the function outputs. Execution stops after return statement. If omitted, the function returns undefined.

Key Terms

  • 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" in greet("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 for greet, could be number, object, etc.). If no return is specified, the function returns undefined.

Example with Parameters and Arguments

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 vs. Invoking a Function

  • 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.

Example of Defining and Invoking

// 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

Additional Notes on Functions

  • 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

Best Practices for Functions

  • Use descriptive names (e.g., calculateArea instead of ca).
  • 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.

Summary

  • Variables: Store data using var, let, or const. Prefer const for constants, let for reassignable values, and avoid var.
  • 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment