🌐
W3Schools
w3schools.com › js › js_variables.asp
JavaScript Variables
You declare a JavaScript variable with the let keyword or the const keyword. ... After the declaration, the variable has no value (technically it is undefined). To assign a value to the variable, use the equal sign:
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Variables
To create a variable in JavaScript, use the let keyword. The statement below creates (in other words: declares) a variable with the name “message”:
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Grammar_and_types
Grammar and types - JavaScript | MDN
This is called hashbang comment syntax, and is a special comment used to specify the path to a particular JavaScript engine that should execute the script. See Hashbang comments for more details. JavaScript has three kinds of variable declarations. ... Declares a variable, optionally initializing it to a value.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › Variables
Storing the information you need — Variables - Learn web development | MDN
To do this, we type the keyword let followed by the name you want to call your variable: ... Here we're creating two variables called myName and myAge. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-declare-variables-in-javascript
How to Declare Variables in JavaScript – var, let, and const Explained
November 7, 2023 - In the example above, we tried to redeclare the pineapple variable in two places: In the function, which we did successfully. But in the child block scope, the program threw the following error: "SyntaxError: Identifier 'pineapple' has already been declared" These days, let and const are the default choice for variable declaration in JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › var
var - JavaScript | MDN
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are scoped to the current function. Only a variable's declaration is hoisted, not its initialization.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-declare-variables-in-different-ways-in-javascript
How to declare variables in different ways in JavaScript? - GeeksforGeeks
October 11, 2025 - If you use this keyword to declare a variable then the variable can be accessible locally and it is changeable as well. It is good if the code gets huge. ... if (true) { let geeks = "GeeksforGeeks"; console.log(geeks); } /* This will be error and show geeks is not defined */ console.log(geeks); ... Hangup (SIGHUP) /home/guest/sandbox/Solution.js:8 console.log(geeks); ^ ReferenceError: geeks is not defined · This keyword is used to declare variable locally.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-variables
JavaScript Variables - GeeksforGeeks
Variables can be declared using var, let, or const. JavaScript is dynamically typed, so types are decided at runtime. You don’t need to specify a data type when creating a variable.
Published   January 27, 2023
🌐
TutorialsTeacher
tutorialsteacher.com › javascript › javascript-variable
JavaScript Variables (With Examples)
In JavaScript, a variable can be declared using var, let, const keywords. var keyword is used to declare variables since JavaScript was created.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript variables
JavaScript Variables - Learn How to Use Them Effectively
September 1, 2008 - In JavaScript, you can declare the variables in 4 ways − · Without using any keywords. Using the 'var' keyword. Using the 'let' keyword. Using the 'const' keyword. The let and const keywords were introduced to JavaScript in 2015 (ES6).
🌐
javascript.com
javascript.com › learn › variables
Learn to use JavaScript variables with this free resource
Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs.
Top answer
1 of 5
3

My question is, where do I declare the baz variable?

So the generic answer to this question is "wherever you want", but of course that's not helpful and has pitfalls, so I'm going to tell you where I recommend putting it, and attempt to defend my logic as best as possible.


No matter where you declare a function* or variable** in JavaScript, the function or variable will be hoisted to the top of its containing scope***. If there is no containing scope, it will be implicitly added to the global namespace (in browsers this is window, in NodeJS this is global).

When a variable or function is hoisted, it means that the JavaScript interpreter will pretend as though your variable declaration were written as the first line of the containing scope.

In practice what this means is that when you write:

(function () {
  ...a...
  if (...b...) {
    var example = ...c...;
//  ^^^^^^^^^^^
  }
}());

It's actually evaluated as:

(function () {
  var example;
//^^^^^^^^^^^
  ...a...
  if (...b...) {
    example = ...c...;
  }
}());

* I'm referring to function declaration here. I.E. function name(...) {...}
** I'm referring to variable declaration with var here. I.E. var name
*** Containing scope is typically the wrapping function, but sometimes for various reasons there is no wrapping function.


Isn't it safer to code as follows, where var is used where the variable is first used?

Because of hoisting this classic best practice becomes susceptible to simple mistakes.

Consider the case where you write some code...

(function () {
  for (var i = 0; i < x.length; i++) {
    ...do stuff...
    if (...something happens...) {
      break;
    }
  }
  ...more stuff...
  ...even more stuff...
  doSomethingWith(i);
}());

Then you come back later, and need to add some new functionality, so you add:

...more stuff...
for (var i = 0; i < y.length; i++) {
  ...do stuff...
}
...even more stuff...

Now, if you combine the two it's easy to see in this contrived example that sloppiness has led to accidentally redeclaring and overriding the i variable.

This might seem silly, but it happens all the time. It's quite easy if you don't actively take steps to avoid it. This sort of an issue isn't a problem in languages with block scope, because i would be contained in each for loop's scope, and to use doSomethingWith, we would have had to expose the value of i to the parent scope.


With that all said, your question is really one of best practices. This is inherently subjective and will lead to disagreement. I'm going to post my opinion and I will attempt to defend it, but it should be treated as an opinion and not dogma.

In my opinion, functions should have the following flow:

  1. Directives
  2. Variable declaration
  3. Function declaration
  4. Variable instantiation
  5. Other code

(1) Directives are things like "use strict". They come first by definition.

(2) Variable declaration using var comes second. They could come after function declaration, or even in between, but I've found it makes them harder to find. I also recommend using exactly one var statement with each var placed on separate lines, organized alphabetically. This forces variables to be clustered together, and alphabetical ordering prevents accidental duplication.

(3) Function declaration comes next because functions are hoisted just like variables. Seeing what local APIs are available within a given scope is something I find useful.

(4) Variable instantiation comes after function declaration, and in my opinion should be separate from declaration. Yes there are circumstances where it's easier to just put them on the same line, but as a general rule, you can't go wrong with keeping them separate.

The reasoning for this one is two-fold.

First, the declaration will be interpreted to happen before the assignment, so writing code that reads the way the interpreter is going to interpret it will help with understanding.

Second, if the assignment is merged with the declaration, order suddenly starts to matter, and you lose the ability to consistently alphabetize your variables.

As an example:

(function () {
  var x = ...x...,
      y = ...y...,
      length = Math.sqrt(x * x + y * y);
//    ^^^^^^ no longer alphabetical
}());

If you separate the declaration from assignment, you can get the benefits of both:

(function () {
  var length,
      x,
      y;

  x = ...x...;
  y = ...y...;
  length = Math.sqrt(x * x + y * y);
}());

(5) Once you're done with all the setup for a function, you'll need to write the rest of the code. This step is the "rest of the code" step.


If you've been paying attention to ECMAScript2015, then you should know that there are two new ways to declare variables: let and const.

These new variable declarations use block scope. If you're assigning a variable that will never be overwritten, use const, otherwise use let.

Going back to:

Isn't it safer to code as follows, where var is used where the variable is first used?

let allows you to do this. If you can use let, stop using var; use let and const where the variables are first used; combine declaration with assignment:

ES5 way:

(function () {
  var example;
  ...
  example = ...;
}());

ES2015 way:

(function () {
  ...
  let example = ...;
}());
2 of 5
5

Javascript variables only have 2 scopes, global and local. A variable declared inside a function (inside an IF or not) is accessible to the whole function.

Personally I declare variables toward the top of a function for the sake of clarity, and with the above in mind. Therefore I am in agreement with the advice given in your book.

You may want to look into "let" and "const", part of ECMAScript 2015 (ES6).

🌐
Reddit
reddit.com › r/learnjavascript › best way to declare variables
r/learnjavascript on Reddit: Best way to declare variables
December 27, 2023 -

I’ve heard that when declaring variables, you want to use let unless yk it will never never and you use const instead. However, I just heard the opposite where you always use const unless yk it’s going to change and then you use let. I am only asking because I have definitely seen come const where I would’ve used a let.

Top answer
1 of 5
8
If you've seen const where you would have used let, you should think about why you would use let, because you should've used const instead. The only difference is that const forces initialization and prevents assignment of the identifier; it prevents accidental reassignment, and allows tools to identify and report those errors statically. If you're not intentionally reassigning the identifier (mutating the variable), you should use const. Note that this is not the same as mutating the value, since objects in JS can be mutated while keeping references to them. I generally always use const unless/until I know the variable needs to be mutated, and then use let. Some people think this can be confusing, because they think const looks like it forces the value to be immutable, and so use let even for immutable references to objects that will be mutated.
2 of 5
3
I have definitely seen come const where I would’ve used a let. Explain yourself. Why would you have changed it from const to let? Here are some quick examples of let vs. const. let x; //okay const x; //initialization error let object = new Object(); object = new Object(); //okay const x = 5; x = 7; //reassignment error const object = new Object(); object = new Object(); //reassignment error const object = new Object(); object.x = y; //okay, unless x itself is also const let doesn't need to be immediately initialized with a value, but const does. let allows for variable reassignment, but const doesn't. Also, with cosnt, you can still mutate an object that's assigned to the variable.
🌐
W3Schools
w3schools.com › jsref › jsref_var.asp
JavaScript var Statement
ECMAScript6 (ES6 / JavaScript 2015) encourage you to declare variables with let not var. Use var to assign 5 to x and 6 to y, and display x + y: var x = 5; var y = 6; document.getElementById("demo").innerHTML = x + y; Try it Yourself »
🌐
Flow
flow.org › variable declarations
Variable Declarations | Flow
When you are declaring a new variable, you may optionally declare its type. JavaScript has three ways of declaring local variables:
🌐
BrainStation®
brainstation.io › learn › javascript › variables
JavaScript Variables (2026 Tutorial & Examples) | BrainStation®
February 4, 2025 - JavaScript variables can be created in three different ways using keywords var, let and const. Initially, variables were created using only the var keyword. But due to some historic drawbacks of using var, let and const were implemented for ...
🌐
SitePoint
sitepoint.com › blog › javascript › quick tip: how to declare variables in javascript
Quick Tip: How to Declare Variables in JavaScript — SitePoint
November 5, 2024 - Assignment: This is when a specific value is assigned to the variable. Note: while varhas been available in JavaScript since its initial releast, letand const are only available in ES6 (ES2015) and up. See this page for browser compatibility. ... var x; // Declaration and initialization x = "Hello World"; // Assignment // Or all in one var y = "Hello World";
🌐
YouTube
youtube.com › coding in public
How to Declare Variables in Javascript - YouTube
I’m starting a series for absolute beginners. I’ll add these videos every few weeks and slowly build out a beginner playlist for those new to Javascript. In ...
Published   June 19, 2021
Views   3K
🌐
LabEx
labex.io › questions › how-to-declare-a-variable-in-javascript-106904
How to Declare a Variable in JavaScript | LabEx
July 25, 2024 - Learn how to declare variables in JavaScript using var let and const with scope differences and realworld examples
🌐
TypeScript
typescriptlang.org › docs › handbook › variable-declarations.html
TypeScript: Documentation - Variable Declaration
This is equivalent to using indexing, but is much more convenient: ... Tuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements: ... This creates new variables a and b from o.a and o.b. Notice that you can skip c if you don’t need it. Like array destructuring, you can have assignment without declaration: ... Notice that we had to surround this statement with parentheses. JavaScript normally parses a { as the start of block.