Is JavaScript Statically Typed or Dynamically Typed? 🤔
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

Is JavaScript Statically Typed or Dynamically Typed? 🤔

Publish Date: Nov 18 '24
38 24

JavaScript – the language that powers the web! But when it comes to its typing system, people often wonder: Is JavaScript statically typed or dynamically typed? Let’s dive in, but with a twist – through examples, not just theory. 😎

What Does "Typed" Mean Anyway? 🧐

Before we jump into JavaScript, let’s quickly refresh what it means when we say a language is "typed."

  • Statically Typed: Variables must be declared with a specific type. Once you set the type, it cannot change.
  • Dynamically Typed: The type of a variable is determined at runtime, and it can change over time.

JavaScript's Type System 🖥️

JavaScript is dynamically typed. 🎉 This means you can assign any type of value to a variable, and you don't need to explicitly declare the type.

Example 1: Variable Type Flexibility 🔄

let x = 5;       // x is a number
console.log(typeof x);  // "number"

x = "Hello!";    // Now x is a string
console.log(typeof x);  // "string"
Enter fullscreen mode Exit fullscreen mode

In the above example, x starts as a number, and then we change it to a string. JavaScript allows this fluidity because it is dynamically typed.

Example 2: Function Argument Types 🔧

function printInfo(info) {
  console.log(info);
}

printInfo(42);      // Prints 42 (number)
printInfo("Hello"); // Prints Hello (string)
Enter fullscreen mode Exit fullscreen mode

Notice how the info argument can accept any type of data — a number, a string, an object, etc. JavaScript doesn’t require you to specify what kind of value info will hold when you call printInfo. The language decides at runtime.

Example 3: The Type “Surprise” 🎁

let value = 10;
value = value + "5";  // Adding a string to a number
console.log(value);    // "105" (String, not a number!)
Enter fullscreen mode Exit fullscreen mode

In this case, JavaScript automatically converts the number 10 into a string and concatenates it with "5". The type transformation happens seamlessly, which might surprise you, right? 😱

Example 4: Even Arrays and Objects Have No Restrictions! 🛠️

let user = {
  name: "Alice",
  age: 25
};

user = [1, 2, 3]; // Reassigned as an array!
console.log(user);  // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

We started with an object, then re-assigned the variable user to be an array. In statically typed languages, this would throw an error, but JavaScript handles it like a pro.


So... Why Is JavaScript Dynamically Typed? 🔍

JavaScript doesn't force you to declare types, making it more flexible and easier to write code quickly. However, this flexibility can also lead to unexpected behavior, especially when dealing with complex data and functions.

The Flip Side ⚖️

This flexibility comes with a catch: bugs can be harder to spot because types can change at runtime. It’s your responsibility as a developer to keep track of what kind of values your variables hold, or you might encounter some weird results. 👀


Conclusion: To Type or Not to Type? 🤷‍♂️

To wrap things up: JavaScript is dynamically typed! It lets you be flexible with your code, but also, sometimes unpredictable. 😅

Now, here's the tricky question for you... If you could choose, would you prefer JavaScript to be statically typed? And if so, would that improve or limit your coding experience? 💡

Comments 24 total

  • Peter Vivo
    Peter VivoNov 18, 2024

    For example hard to exactly typed a dynamical changed DOM query result, because the if the given tag type is different then the corresponding attributes and function list also different.

    Also problematic set exact type to the generator functions because that may have a different return values on different yield.

    Also will be problematic if user pass a complex maybe union types to a module which is according this generic-union give back another generic types related to user defined one. Like my jsdoc-duck module does.

    • Jagroop Singh
      Jagroop SinghNov 19, 2024

      What are you saying ?

      Image description

      • Peter Vivo
        Peter VivoNov 19, 2024

        You absolute right, I just talking about the using HTML comes many situation, where your type maybe a real complex question. Plus do not forget each function also have a type, where we can pass variable, we also also ability to pass a function.

        Certainly! Let's clarify my previous:

        1. Difficulty in Typing Dynamically Changed DOM Query Results:

          • Explanation: When you query the DOM for elements, the types of those elements can vary depending on the tag names. For example, an element retrieved as <div> will have different attributes and methods compared to an <input> element.
          • Issue: Because the specific type of the element isn't known at compile time—especially if the tag types can change dynamically—it's hard to assign an exact type. Each tag type comes with its own set of properties and methods, making static typing challenging in such dynamic scenarios.
        2. Problems with Setting Exact Types for Generator Functions:

          • Explanation: Generator functions can yield different types of values at different points during their execution.
          • Issue: Assigning a single, exact return type to a generator function is problematic because the yield statements may produce varying types. This variability makes it difficult to define a type that accurately represents all possible outputs of the generator.
        3. Handling Complex Union Types with Generic Modules (e.g., jsdoc-duck:

          • Explanation: When a user passes complex or union types to a module that uses generics, the module may return another generic type that's related to the user-defined input.
          • Issue: Managing and ensuring type safety with these complex or union types becomes challenging. The module has to account for all possible variations of the input types, which can complicate the type definitions and lead to potential type errors or inconsistencies.

        Summary:

        • Dynamic Types: Static typing struggles with elements that can change type at runtime, like dynamic DOM queries.
        • Generators: Generators that yield multiple types complicate type definitions since their output isn't uniform.
        • Generic Modules with Union Types: Modules that return types based on complex or union input types have difficulty maintaining accurate and useful type information.

        Possible Solutions:

        • Type Guards or Type Assertions: Use runtime checks to narrow down types where possible.
        • Union or Intersection Types: Define types that encompass all possible variations.
        • Advanced Type Features: Utilize features like conditional types or mapped types if the language supports them.
        • sewiko
          sewikoNov 19, 2024

          too much ChatGPT in this comment. Come On , don't be too lazy to write your review that much.

          • Mike Talbot ⭐
            Mike Talbot ⭐Nov 20, 2024

            But his initial comment wasn't ChatGPT; this one, where he tries to explain an answer to a question about his comment, is - his original point, and these are entirely legitimate points about why JavaScript is dynamically typed and what the advantages of that are. If English isn't your first language, I can understand how explaining complex concepts must be highly frustrating.

    • Lee Goddard
      Lee GoddardNov 19, 2024

      If you can't exactly type the element, then type it more loosely: all elements have a type in common...

      • Jagroop Singh
        Jagroop SinghNov 19, 2024

        Yes, agreed !!
        We can say in that way as well.

        • Mike Talbot ⭐
          Mike Talbot ⭐Nov 20, 2024

          If any wasn't frowned upon then that's true. What if you want to access those different properties, what if you want to use optional chaining to access elements and you don't want to write a lot of boilerplate casts and checks, because you don't need to. What if you want to add a Symbol property to everything you've scanning in a list before etc - this is all the power of a dynamic language.

  • waynef
    waynefNov 18, 2024

    Love dynamic typing, once you know the rules you can build stuff so much faster without the type gymnastics.

    • Jagroop Singh
      Jagroop SinghNov 19, 2024

      Absolutely! @wfreeth

    • Scott Crossan
      Scott CrossanNov 19, 2024

      Then when the next dev comes along and adds random stuff or changes the land everything breaks. Types prevent that, as it warns your ender you broke instead of going ooh let's see at run time 🙈

      • Jagroop Singh
        Jagroop SinghNov 20, 2024

        Yes, I feel the same!

      • Glenn Vandeuren
        Glenn VandeurenNov 24, 2024

        Then it means it's just a bad dev.

        • Jagroop Singh
          Jagroop SinghNov 24, 2024

          May be he just starting out and it's normal because "Master is once a noob"

      • waynef
        waynefDec 23, 2024

        They really don't, the small subset of errors that types "help" with, are pretty obvious issues. They will always get picked up in unit tests and reviews. I could probably count the times types would have been useful on one hand

  • Jeffrey Tackett
    Jeffrey TackettNov 19, 2024

    The way to visualize dynamically typed languages like JavaScript, Python, etc., you have to understand that the value is what retains the type instead of the variable name. When you understand this, you then can grasp the complexity of JavaScript type conversion -- which is something that most languages avoid and instead require the developer to use conversion functions/methods. JavaScript was made for automating forms and with that the need for it to do it's best to not fail leaf the team to create the conversation rules that dictate what type will be returned when two different types are used.

    That is why every month or so another article is written about this behavior, as it is the most unique experience in programming and has been a source of many bugs for those who don't understand how it determines a type.

    • Jagroop Singh
      Jagroop SinghNov 19, 2024

      Exactly! In dynamically typed languages, the type is tied to the value, not the variable, making type coercion a key (and sometimes tricky) feature.

  • Scott Crossan
    Scott CrossanNov 19, 2024

    For me working in a large team types or unit tests are essential to give you the feedback of the initially intended outcome of a function. It's why we use typescript on the frontend and enable strict types in PHP on the bankend, saves so many headaches

  • Kiran Sarpotdar
    Kiran SarpotdarNov 19, 2024

    The types in languages are effect of reserving memory in RAM. Languages like Javascript have dynamic allocation and I personally believe that that's how it should be as we have better RAM management. Of course the main kernel RAM management should be efficient. I personally prefer Javascript dynamically. JavaScript also offers flexibility of no compilation everytime. One can see immediate effect of the code change rather than everytime compilers has to work consuming more CPU and RAM anyways.

    Those who prefer statically types can use Typescript. I don't prefer typescript. Langauge must be flexible and programmer must be better in programming.

    Of course another issue in JavaScript is the variable naming and the case sensitive that causes issue but it's a separate issue. That issue takes whole lot of time of programmers if done mistakes in coding.

  • ANIRUDDHA  ADAK
    ANIRUDDHA ADAKNov 22, 2024

    wow amazing .

Add comment