Thursday, January 22, 2026
HomeLanguagesJavascriptWhy use Question mark in TypeScript variable ?

Why use Question mark in TypeScript variable ?

Question marks on TypeScript variable are used to mark that variable as an optional variable. If we put the question mark when declaring a variable that variable becomes optional. The optional parameters will have value as undefined when unused.

syntax:

function A(x?: number) {
    // Function_body
}

Below examples illustrate the above approach:

  • Example 1:




    <script>
    function point(x?: number, y?: number){
        if(x) 
            console.log('X : ' + x);
        else 
            console.log('Value of X coordinate not given');
        if(y) 
            console.log('Y : ' + y);
        else 
            console.log('Value of Y coordinate not given');
    }
    </script>

    
    
  • Output:
    Function Call: point();
    Value of X coordinate not given
    Value of Y coordinate not given
    
    Function Call : point(10);
    X : 10
    Value of Y coordinate not given
    
    Function Call : point(10, 20);
    X : 10
    Y : 20
    
  • Example 2:




    <script>
    class Hello{
      
        constructor(private firstName: string, private lastName?: string)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            if (lastName)
                console.log('Hello ' + this.firstName + ' ' + this.lastName);
            else
                console.log('Hello ' + this.firstName);
        }
    }
      
    // Creating an object h1
    let h1 = new Hello('Shivam'); 
      
    // Creating an object h2
    let h2 = new Hello('Shivam', 'Gupta'); 
    </script>

    
    
  • Output:
    Hello Shivam
    Hello Shivam Gupta
    
  • Note: A required parameter cannot follow an optional parameter. If we declare any variable as optional, all the variables on the right side of that must also be optional, otherwise, it will give an error.

    Dominic
    Dominichttp://wardslaus.com
    infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
    RELATED ARTICLES

    Most Popular

    Dominic
    32475 POSTS0 COMMENTS
    Milvus
    119 POSTS0 COMMENTS
    Nango Kala
    6847 POSTS0 COMMENTS
    Nicole Veronica
    11977 POSTS0 COMMENTS
    Nokonwaba Nkukhwana
    12064 POSTS0 COMMENTS
    Shaida Kate Naidoo
    6986 POSTS0 COMMENTS
    Ted Musemwa
    7220 POSTS0 COMMENTS
    Thapelo Manthata
    6933 POSTS0 COMMENTS
    Umr Jansen
    6912 POSTS0 COMMENTS