skip to Main Content

It’s good for beginners, but sometimes it creates a lot of confusion.
It works fine even if you don’t declare the variable and directly initialize it.

I have worked with Java before, and when I compare the two languages, I get totally confused about why does JavaScript run with this unstrict code

Both of these scenarios function properly. HOW COME?

a = 5
b = 4
c = a + b
console.log(c)

and

let a = 5
let b = 4
let c = a + b
console.log(c)

2

Answers


  1. JavaScript, by nature, is a very loose and flexible language. For some people, TypeScript is a better alternative, because it is much more strict.

    Variables

    1. Without Variable Declaration (a = 5, b = 4, c = a + b):
      In JavaScript, if you assign a value to a variable without declaring it using var, let, or const, the variable is automatically declared in the global scope. So, in your first scenario:

      a = 5;
      b = 4;
      c = a + b;
      console.log(c);
      

      JavaScript will interpret it as if you had declared a, b, and c as global variables. (This is not recommended because it can lead to naming conflicts)

    2. With Variable Declaration (let a = 5, let b = 4, let c = a + b):
      In this scenario, you explicitly declare each variable’s scope using the let keyword. This is the recommended way to declare variables in modern JavaScript. It keeps variables confined to the scope in which they are announced, preventing global namespace pollution (and other issues).

      1. Global Scope: Variables declared outside of any function or block are accessible everywhere in your code.
      let globalVariable = 10;
      
      function foo() {
           console.log(globalVariable); // Can access globalVariable
      }
      
      foo(); // Output: 10
      console.log(globalVariable); // Output: 10
      
      1. Function Scope: Variables declared inside a function are only accessible within that function.
      function foo() {
           let localVariable = 20;
           console.log(localVariable); // Can access localVariable
      }
      
      foo(); // Output: 20
      console.log(localVariable); // Error: localVariable is not defined
      
      1. Block Scope: Variables declared with let or const within curly braces {} are only accessible within that block.
      if (true) {
           let blockVariable = 30;
           console.log(blockVariable); // Can access blockVariable
      }
      
      console.log(blockVariable); // Error: blockVariable is not defined
      

    Note: Variables should be declared with let or const for block or function scope, var on the other hand has its own scoping system, and is typically avoided.

    Semicolons

    JavaScript does not strictly require semicolons because it has Automatic Semicolon Insertion (ASI) as part of its grammar. JavaScript is whitespace-sensitive, so line breaks are often enough to signify the end of a statement.

    Login or Signup to reply.
  2. Just to add to @RedYetiDev’s excelent answer, Javascript does have a "strict mode". You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

    By default, Javascript operates in non-strict mode, or as MDN puts it "slopy mode" in it, undeclared variables are assumed as global variables (or in the browser context, created inside the window object.

    In strict mode, this (among other things) are changed. I quote:

    Assigning to undeclared variables Strict mode makes it impossible to
    accidentally create global variables. In sloppy mode, mistyping a
    variable in an assignment creates a new property on the global object
    and continues to "work". Assignments which would accidentally create
    global variables throw an error in strict mode (…)

    so even though the code in your example would work, if you put it in strict mode it would fail

    'use strict' // activates strict mode
    a = 5 // Uncaught ReferenceError: b is not defined
    b = 4
    c = a + b
    console.log(c)
    

    so strict mode behaves a little bit more as you expect if you come from more stricter languages like Java, and its encouraged to use it for many reasons, including avoiding such mistakes and even improving performance (as the optimizer can sometimes add better optimizations with it)

    Now why does javascript have a "sloppy mode" and a "strict mode"? because when strict mode was introduced js had been years in the wild so a change this big woul’ve broken many existing pages. So it was introduced under that "use strict" flag, that is fully retrocompatible (because older browsers that see this command would just ignore it, and by default strict code is compatible with slopy code -although not the other way around-) so that older sites would keep behaving the way they did before.

    You will see this many times with JS, because as much as they want to improve the language, the compatibility must be maintain, this is the reason for the existance of things like var a = 1; and let a = 1. var is the older version of let and even though they serve the same purpose, they behave differently (let behaving more like you expect if you come from Java) but var is kept for retrocompatibility as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search