Top Stories

Ankaj Gupta
February 03, 2019

Variable Scope in JavaScript

What is Scope in JavaScript?

Scope in JavaScript defines the accessibility of variables, functions, and objects. It determines the lifetime and visibility of a variable. Every time we create a function or a block {}, we create a new scope.

Understanding Variable Scope

Variable scope is the accessibility of variables, objects, and functions in a particular part of your code during runtime. In other words, scope determines the visibility of JavaScript variables and other resources in areas of your code.

Scope is how a computer keeps track of all variables in a program. It refers to the specific environment where a JavaScript variable is accessible and can be used.

Important: In JavaScript, there are 3 types of variable scope:

  1. Global variable: Declared globally (outside any function)
  2. Local variable: Declared locally (inside any function or block)
  3. Lexical variable: Ability of an inner function to access the scope of an outer function

Note: Global variables can be accessed from anywhere in a JavaScript program.

1. Global Variable

A global variable has global scope, meaning it can be defined anywhere in your code. JavaScript global variables are declared outside the function or declared with the window object and can be accessed and modified from anywhere in the code.

Memory: Global variables are always stored in memory. Even after function execution finishes, they remain accessible from anywhere in JavaScript code.

Example 1: Variable Defined Outside Any Function

Create a global variable by declaring it outside any function:

<script>
    //Initialize a global variable
    var data = 100; //'data' is global variable
    
    function myFunction(){
        document.writeln(data); // here can use data
    }
    
    function display(){
        // can also use data
    }
    
    myFunction(); //calling JavaScript function
</script>

Example 2: Access Variable via Window Object

When declared outside a function, the variable is added to the window object internally:

<script>
    var data = 100;
    
    function display() {
        document.writeln(data);
        document.writeln(window.data); // Access via window object
    }
    
    display(); //calling JavaScript function
</script>

Example 3: Declare Global Variable Inside Function

To declare global variables inside a function, use the window object:

<script>
    function myFunction(){
        //declaring global variable by window object
        window.data = 100;
    }
    
    function display(){
        //accessing global variable from other function
        document.writeln(window.data);
    }
    
    myFunction(); //calling JavaScript function
</script>

Example 4: Auto Global Scope (Not Recommended)

If you declare variables without the var keyword, they are automatically considered global scope:

<script>
    function display() {
        //variable declaring without specify keyword
        data = 100;
        document.writeln(data);
    }
    
    display();
    document.writeln(data); //data is accessible here
</script>

Output:

100
100

⚠️ Warning: Always use var, let, or const to avoid accidental global variables.

2. Local Variable

A variable declared inside a function is a local variable. Local variables have local scope and can't be accessed or modified outside the function declaration. Function parameters are always local to that function.

Memory: Local variables are stored in the stack frame within the function. They are created when function starts execution and removed from memory once execution is complete.

In JavaScript, there are 2 kinds of local scope:

  1. Function scope
  2. Block scope

Function Scope

Variables declared inside a function are known as function scope. In JavaScript, each function creates a new scope. When you declare a variable within a function, it can only be accessed within that function. When you exit the function, the variable is destroyed.

<script>
    function myFunction() {
        var data = "I am local scope";
        document.write(data);
    }
    
    myFunction();
    document.write(data); //Uncaught ReferenceError: data is not defined
</script>

Note: JavaScript functions have their own scope, but block scopes such as if/switch conditions or for/while loops do not create new scopes with var.

Block Scope

A block scope variable is similar to a function scope but is limited to a block instead of a function. A block is separated by curly braces {}.

ES6: ES6 introduced const and let variables. Unlike var, they allow us to scope to a block of code (the nearest pair of curly braces).

Example: Block Scope with let

<script>
    for(let i = 0; i <= 5; i++ ) {
        //write something
    }
    document.write(i); //i can not be used here
</script>

Example: Block with let/const

<script>
    {
        let x = 2;
    }
    document.write(x); //x can not be used here
</script>

Output:

ReferenceError: x is not defined

Example: Block with var (No Block Scope)

Variables declared with var keyword inside a block {} can be accessed from outside the block:

<script>
    {
        var x = 2;
    }
    document.write(x); //x can be used here
</script>

Output:

2

Important: let and const are block scoped variables. Block scope does NOT apply to var.

Key Points About Block Scope

  • • Before ES2015, JavaScript did not have Block Scope
  • • Variables declared inside a block {} with let/const cannot be accessed from outside the block
  • • Block statements like for/while loops or if/switch conditions do NOT create new scope with var

3. Lexical Scope

Lexical Scope (also known as Static scope or Nested scopes) literally means that scope is determined at lexing time (generally referred to as compiling) rather than at runtime.

Static Scope: When a function is defined inside another function, the inner function has access to the outer function's variables. This behavior is called lexical scoping.

Syntax: Nested Scopes

<script>
    function myFunction() {
        //local function scope
        function innerFunction() {
            //nested local function scope
        }
    }
</script>

Example: Lexical Scope

<script>
    function myFunction() {
        const outer = "I'm outer function!";
        
        function innerFunction() {
            const inner = "I'm inner function!";
            document.writeln(outer); // Can access outer variable
            document.writeln(inner);
        }
        
        innerFunction();
    }
    
    myFunction();
</script>

Output:

I'm outer function!
I'm inner function!

Why is Scope Important?

Security

Variables can be accessed only from specific areas of code, preventing unintended modifications.

Avoid Collisions

Reduces namespace collisions when two or more variables share a common name.

Code Organization

Helps organize and structure code logically with proper encapsulation.

Scope Comparison

Scope Type var let const
Global ✅ Yes ✅ Yes ✅ Yes
Function ✅ Yes ✅ Yes ✅ Yes
Block ❌ No ✅ Yes ✅ Yes
Lexical ✅ Yes ✅ Yes ✅ Yes

Best Practices

✅ Do's

  • • Use let and const instead of var
  • • Declare variables in the smallest scope possible
  • • Avoid global variables when possible
  • • Use meaningful variable names
  • • Understand lexical scoping for closures

❌ Don'ts

  • • Don't use var in modern JavaScript
  • • Avoid creating global variables unintentionally
  • • Don't rely on block scope with var
  • • Avoid variable name collisions
  • • Don't ignore scope when debugging

Summary

Understanding scope is fundamental to JavaScript programming. Scope determines where variables are accessible and how long they exist in memory:

  1. Global Scope: Variables accessible throughout the entire program
  2. Local Scope: Variables accessible only within their function or block
  3. Lexical Scope: Inner functions can access outer function variables

Always use let and const for better scope control and avoid unintended side effects. Understanding scope helps write secure, maintainable, and bug-free code.

JavaScript
Read
Ankaj Gupta
January 23, 2019

Variable life cycle in JavaScript | JavaScript Variables Lifecycle

JavaScript Variables Lifecycle

When the JavaScript engine works with variables, their lifecycle consists of three main phases. Understanding these phases is essential for mastering JavaScript programming.

The Three Phases of Variable Lifecycle

1. Declaration

Create a new variable

var myValue;

2. Assignment

Assign a value to the variable

myValue = 150;

3. Usage

Access and use the variable

alert(myValue);

1. Variable Declaration

Creating a variable is called "declaring" a variable. When you declare a variable, the computer reserves memory where it will store the variable data. The program can then read/write data in this memory area by manipulating the variable.

Single Variable Declaration

Declare a single variable in one line:

<script>
    var <var_name>;
</script>

Example:

<script>
    var carName;
</script>

Multiple Variables in Single Line

Declare multiple variables in one statement by separating them with commas:

<script>
    var <var_name1>, <var_name2>, <var_name3>;
</script>

Example:

<script>
    var carName, carNumber, carColor;
</script>

Multiple Variables in Multiple Lines

For better readability, spread declarations across multiple lines:

<script>
    var <var_name1>,
        <var_name2>,
        <var_name3>;
</script>

Example:

<script>
    var carName,
        carNumber,
        carColor;
</script>

Important Points About Declaration

❌ Declare Before Using

You must declare variables before you use them, otherwise you'll receive a ReferenceError:

<script>
    //Uncaught ReferenceError: myVariable is not defined
    document.write(myVariable);
</script>

⚠️ Undefined by Default

When a variable is declared, it exists in memory but has no value. In JavaScript, this is represented as undefined:

<script>
    var myVariable;
    document.write(myVariable); //undefined
</script>

2. Variable Assignment

Storing a value in a variable is called variable assignment or initialization. While a program is running, the value stored in a variable can change. To assign a new value to a variable, use the assignment operator =.

Note: The assignment operator (=) is used to assign values to variables.

Assigning Value After Declaration

You can assign a value after the variable is declared:

<script>
    var carName;
    carName = "Audi"; // Store the string
</script>

Declaration and Assignment in One Line

The declaration and assignment can be combined into a single statement. When a variable is assigned a value, it becomes defined:

<script>
    var <var_name> = <value>;
</script>

Example:

<script>
    var carName = "Audi"; // Store the string
</script>

Initializing Multiple Variables in Single Line

Initialize multiple variables in the same statement using commas:

<script>
    var <var_name1> = <value>, <var_name2> = <value>, <var_name3> = <value>;
</script>

Example:

<script>
    var carName = "Audi", carNumber = 1234, carColor = "Black";
</script>

Initializing Multiple Variables in Multiple Lines

For better readability, spread the initialization across multiple lines:

<script>
    var <var_name1> = <value>,
        <var_name2> = <value>,
        <var_name3> = <value>;
</script>

Example:

<script>
    var carName = "Audi",
        carNumber = 1234,
        carColor = "Black";
</script>

3. Variable Usage

Accessing the value of a variable is called variable usage. The process usually goes this way: first, a variable should be declared, then initialized with a value, and finally used.

Using Variables

<script>
    var carName = "Audi";
    document.write(carName); // Shows the variable content
</script>

Output:

Audi

Complete Example: All Three Phases

<script>
    // Phase 1: Declaration
    var firstName, lastName, age;
    
    // Phase 2: Assignment
    firstName = "John";
    lastName = "Doe";
    age = 30;
    
    // Phase 3: Usage
    console.log("Name: " + firstName + " " + lastName);
    console.log("Age: " + age);
</script>

Output:

Name: John Doe
Age: 30

Best Practices

✅ Do's

  • • Declare variables before using them
  • • Initialize variables when declaring them
  • • Use meaningful variable names
  • • Declare variables at the top of their scope
  • • Use let and const instead of var

❌ Don'ts

  • • Don't use variables before declaration
  • • Don't use var in modern JavaScript
  • • Avoid implicit global variables
  • • Don't redeclare variables unnecessarily
  • • Avoid using undefined variables

Key Takeaways

Declaration

Reserves memory space. Variable is undefined until assigned a value.

Assignment

Stores a value in the variable. Can be done at declaration or later.

Usage

Accesses the stored value. Can change value during program execution.

Summary

Understanding the three phases of variable lifecycle is fundamental to JavaScript programming:

  1. Declaration: Create the variable and reserve memory
  2. Assignment: Store a value in the variable
  3. Usage: Access and use the variable's value

Master these phases to write effective and bug-free JavaScript code. Always declare variables before using them and initialize them with appropriate values.

JavaScript
Read
Ankaj Gupta
January 20, 2019

Javascript variable naming rules

Naming JavaScript Variables

Variable names are known as identifiers in JavaScript. Understanding naming conventions and rules is crucial for writing clean, maintainable code.

Variable Naming Styles

There are different styles for naming variables in JavaScript. The most common are:

camelCase

var myName = 'Coder Website';

Recommended: JavaScript standard

snake_case

var my_name = 'Coder Website';

Less common: Used in Python

Best Practice: Use camelCase for JavaScript variables and functions. It's the widely accepted convention in the JavaScript community.

Rules for Naming Variables in JavaScript

JavaScript has specific rules for creating variable names:

1

Start with: Variable names must begin with a letter (a-z or A-Z), underscore (_), or dollar sign ($)

2

After first character: Can use digits (0, 1, 2...), for example: data2

3

Case-sensitive: JavaScript variables are case-sensitive. For example, a and A are two different variables

Limitations of Variable Names

There are several limitations when creating variable names:

  • Variable names must be one or more words
  • Must contain only letters, digits, or the symbols $ and _
  • First character cannot be a digit
  • Cannot contain whitespace characters (tabs or spaces)
  • Cannot use reserved keywords (let, var, const, for, while, class, return, function, etc.)

Variable Declaration Syntax

1. Single Variable Declaration

<script>
    var <variable-name>;
    let <variable-name>;
    const <variable-name>;
</script>

2. Multiple Variables in Single Line

<script>
    var <variable-name>, <variable-name>, <variable-name>;
    let <variable-name>, <variable-name>, <variable-name>;
    const <variable-name>, <variable-name>, <variable-name>;
</script>

Note: While you can declare multiple variables in one line, it's better for readability to declare them separately.

Valid vs Invalid Variable Names

✅ Valid Variable Names

These examples follow all JavaScript naming rules:

<script>
    // Using var
    var userName;
    var user02;
    var _user;
    var $user;
    
    // Using let
    let userName;
    let user02;
    let _user;
    let $user;
</script>

Explanation: All these names start with valid characters (letters, underscore, or dollar sign) and contain only allowed characters.

❌ Invalid Variable Names

These examples violate JavaScript naming rules:

<script>
    // Using var
    var user-Name;      // ❌ hyphens '-' aren't allowed
    var 2userName;      // ❌ cannot start with a digit
    var @user;          // ❌ '@' is not allowed
    var +user;          // ❌ '+' is not allowed
    var user name;      // ❌ no spaces allowed
    
    // Using let
    let user-Name;      // ❌ hyphens '-' aren't allowed
    let 2userName;      // ❌ cannot start with a digit
    let @user;          // ❌ '@' is not allowed
    let +user;          // ❌ '+' is not allowed
</script>

Common mistakes: Starting with digits, using hyphens, special characters, or spaces will cause syntax errors.

Reserved Keywords

JavaScript has reserved keywords that cannot be used as variable names:

Declaration Keywords

var let const function class

Control Flow Keywords

if else for while return

Tip: Modern code editors will highlight reserved keywords if you try to use them as variable names.

Best Practices for Naming Variables

✅ Do's

  • • Use camelCase for variables
  • • Use descriptive, meaningful names
  • • Start names with lowercase letters
  • • Use names that explain purpose
  • • Keep names short but clear

❌ Don'ts

  • • Don't use reserved keywords
  • • Avoid single-letter names (except loop counters)
  • • Don't use abbreviations
  • • Avoid names starting with numbers
  • • Don't use spaces or special characters
<script>
    // ✅ Good variable names
    let userName = 'John';
    let totalPrice = 99.99;
    let isLoggedIn = true;
    
    // ❌ Bad variable names
    let x = 'John';              // Not descriptive
    let tp = 99.99;              // Abbreviation
    let user name = 'John';      // Space not allowed
</script>

Summary

Variable names in JavaScript must start with a letter, underscore, or dollar sign. After the first character, you can use letters, digits, underscores, or dollar signs. Always use camelCase for JavaScript variables, avoid reserved keywords, and choose descriptive names that clearly communicate the variable's purpose.

Following these naming conventions will make your code more readable, maintainable, and professional.

JavaScript
Read
Ankaj Gupta
January 20, 2019

What is a JavaScript Variable?

Define JavaScript Variable

JavaScript variables are containers that store data values in memory so you can reference and reuse them. Creating a variable is called "declaring" a variable. A variable name must be unique, and you can assign a value when declaring it or before using it.

JavaScript Variable Declaration

In JavaScript, there are 3 reserved keywords used to declare a variable:

var

Function or global scope

let

Block scope

const

Block scope, immutable

Note: JavaScript is a dynamically typed language. A variable can hold values of any data type.

Important Points About JavaScript Variables

1. Cannot Access Before Definition

You cannot access a JavaScript variable before you define it:

<script>
    console.log(myName); //Uncaught ReferenceError: myName is not defined
    const myName = 'Ankaj Gupta';
</script>

Output:

ReferenceError: can't access lexical declaration `myName` before initialization

2. Dynamic Typing

Variables can change from one data type to another:

<script>
    var myName = 'Ankaj Gupta';  // String
    myName = 100;                // Number
    myName = true;               // Boolean
</script>

In this example: The variable changes from string to number to boolean.

3. Whitespace and Line Breaks

JavaScript allows multiple line breaks and whitespace when declaring variables with var:

<script>
    var
            one
        =
        1,
        two
        =
        "two"
</script>

Note: Semicolons are optional in JavaScript, but recommended for code clarity.

4. Loosely Typed Variables

JavaScript variables are loosely typed, meaning you can assign any data type to a variable without declaring the type:

<script>
    var one = 1;        // Numeric value
    one = 'one';        // String value
    one = 1.1;          // Decimal value
    one = null;         // null value
    one = true;         // Boolean value
</script>

Example: The same variable one can hold different data types.

Understanding var, let, and const

Feature var let const
Scope Function/Global Block Block
Re-declaration ✅ Allowed ❌ Not allowed ❌ Not allowed
Re-assignment ✅ Allowed ✅ Allowed ❌ Not allowed
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Use Case Legacy code Variables Constants

When to Use var, let, or const?

Use var when:

  • • Working with legacy code
  • • Need function-scoped variables
  • • Supporting older browsers

Recommendation: Avoid in modern JavaScript

Use let when:

  • • Variable will be reassigned
  • • Need block-scoped variables
  • • Loop counters or temporary values

Recommendation: Default choice for variables

Use const when:

  • • Value won't be reassigned
  • • Need immutable references
  • • Objects or arrays that shouldn't change

Recommendation: Prefer const by default

Best Practices

  • Use const by default: If the value won't change, use const
  • Use let for reassignments: If you need to reassign, use let
  • Avoid var: Don't use var in modern JavaScript due to hoisting and scope issues
  • Declare at the top: Declare variables at the top of their scope for clarity
  • Use meaningful names: Choose descriptive variable names that explain their purpose

Summary

JavaScript variables are dynamic, loosely typed containers that can hold any data type. Use const for constants, let for variables that need reassignment, and avoid var in modern code.

Understanding variable scope, hoisting, and type behavior is crucial for writing effective JavaScript code.

JavaScript
Read
Ankaj Gupta
January 11, 2019

How To Write Comments in JavaScript

Comments in JavaScript

JavaScript comments describe and explain code and improve readability. A comment is a statement that is not executed. The JavaScript interpreter skips comments, so they don't affect runtime.

Why Use Comments?

Comments add details, warnings, and suggestions so users and other developers can understand the code.

There are 3 types of comments in JavaScript:

  • Single-Line Comment
  • Multi-Line Comment
  • ScriptDoc Comment

1. Single-Line Comment

Single-line comments use double forward slashes // and can appear before any statement.

<script>
    // Write on browser
    document.write("Hello Javascript!");
    
    // Write text in <h2> Heading
    document.write("<h2> Hello Javascript! </h2>");  
</script>

Output:

Hello Javascript!

Hello Javascript!

2. Multi-Line Comment

Multi-line comments are used for longer descriptions. They start with /* and end with */.

Note: Multi-line comments can also be used for single-line comments if you prefer.

<script>
    /*
        First line: Write Simple write
        Second line: Write text in <h2> Heading
    */
    document.write("Hello World!");
    document.write("<h2> Hello World! </h2>");  
</script>

Output:

Hello World!

Hello World!

3. ScriptDoc Comment / JavaScript Documentation

ScriptDoc (JSDoc) is a JavaScript documentation technique for documenting functions, parameters, return values, and more.

Best Practice: Use JSDoc comments to document functions, arguments, and return types for better code maintainability.

Syntax:

<script>
    /** 
     * ScriptDoc technique to write comment
     * @TagName Description
     * @author   
     * @version 
     * ….
    **/ 
</script>

Complete Example:

<script>
    /** 
     * Multiplication of two numbers 
     * @param {Number} a - First number
     * @param {Number} b - Second number
     * @return {String} mult - Result of multiplication
    **/ 
    function multiplication(a, b) { 
        mult = a * b;
        return "Output is : " + mult.toString(); 
    }
    
    result = multiplication(7, 10);
    document.write(result);
</script>

Output:

Output is : 70

ScriptDoc Tags Reference

Common JSDoc tags for documenting JavaScript:

Tag Description
@author Author of JavaScript file, functions, class
@classDescription Brief description of the Class
@constructor Specifies this function is a constructor
@example Describe a real example for how to use this function
@method Specifies the method name in class
@param Specifies parameter of this function
@private Indicates that a class or function is private
@property Indicates specified property are instance of the class
@return Specifies the return values of a function
@type Specify the data type of this property
@version Specify the version number of file

Comment Types Comparison

Comment Type Syntax Best For
Single-Line // comment Quick notes, inline explanations
Multi-Line /* comment */ Longer explanations, disabling code
JSDoc /** */ Function documentation, API generation

Best Practices

✅ Do's

  • • Document complex logic
  • • Explain "why", not just "what"
  • • Use JSDoc for functions
  • • Keep comments up-to-date

❌ Don'ts

  • • Don't state the obvious
  • • Avoid outdated comments
  • • Don't over-comment simple code
  • • Remove commented-out code

Summary

JavaScript comments improve code readability. Use single-line comments (//) for short notes, multi-line comments (/* */) for longer descriptions, and JSDoc comments (/** */) for function documentation.

Good commenting practices improve maintainability and help other developers understand your code.

JavaScript web development and designing
Read