WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Basic · question 4 of 100

How do you declare a variable in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, variables are used to store data values. Declaring a variable means creating a named storage space in memory to hold a value, which can be later updated or retrieved using the variable name. There are three ways to declare a variable in JavaScript:

var: The var keyword is used to declare a variable in JavaScript. It is the older way of declaring variables and is still widely used.

Example:

    var x = 10;

let: The let keyword is used to declare a block-scoped variable in JavaScript. Block scope means that the variable is only accessible within the block of code where it was declared, including any nested blocks.

Example:

    let x = 10;
    
    if (true) {
        let x = 20;
        console.log(x); // Outputs 20
    }
    
    console.log(x); // Outputs 10

const: The const keyword is used to declare a constant variable in JavaScript. A constant variable is a read-only variable whose value cannot be changed once it is initialized.

Example:

    const PI = 3.14;

In all three cases, the variable name comes after the keyword, followed by an equal sign and the initial value. The initial value can be any JavaScript expression that returns a value of the appropriate data type. If no initial value is provided, the variable is assigned the value undefined.

It is important to note that variables declared with var are function-scoped, meaning that they are accessible within the function where they are declared and any nested functions. Variables declared with let and const are block-scoped, meaning that they are only accessible within the block where they are declared and any nested blocks.

Variable names in JavaScript can contain letters, digits, underscores, and dollar signs, but they cannot begin with a digit. Variable names are case-sensitive, meaning that myVariable and myvariable are two different variables.

Example:

    var firstName = 'John';
    let lastName = 'Doe';
    const age = 30;

These are the basics of declaring variables in JavaScript. As a JavaScript expert, I would be happy to provide more information or examples if needed.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics