JavaScript Declarations and Assignments Declaration

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

There are four principle ways to declare a variable in JavaScript: using the var, let or const keywords, or without a keyword at all ("bare" declaration). The method used determines the resulting scope of the variable, or reassignability in the case of const.

  • The var keyword creates a function-scope variable.
  • The let keyword creates a block-scope variable.
  • The const keyword creates a block-scope variable that cannot be reassigned.
  • A bare declaration creates a global variable.
var a = 'foo';    // Function-scope
let b = 'foo';    // Block-scope
const c = 'foo';  // Block-scope & immutable reference

Keep in mind that you can't declare constants without initializing them at the same time.

const foo; // "Uncaught SyntaxError: Missing initializer in const declaration"

(An example of keyword-less variable declaration is not included above for technical reasons. Continue reading to see an example.)



Got any JavaScript Question?