JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I declare a variable in JavaScript?

Asked on Jul 03, 2024

Answer

In JavaScript, you can declare a variable using "let", "const", or "var". "let" and "const" are preferred in modern ES6+ code due to their block scope and other benefits.
<!-- BEGIN COPY / PASTE -->
        let name = "Alice";
        const age = 30;
        var city = "New York";
        <!-- END COPY / PASTE -->
Additional Comment:
  • "let" is used for variables that can be reassigned.
  • "const" is used for variables that should not be reassigned.
  • "var" is the old way of declaring variables and is function-scoped, which can lead to unexpected behavior. It's generally recommended to use "let" or "const" instead.
  • Always choose "const" by default unless you know the variable will need to change.
✅ Answered with JavaScript best practices.
← Back to All Questions