search
HomeWeb Front-endJS TutorialSix things you may not know about JavaScript

Written by Lewis Cianci✏️

So, you’re a JavaScript developer? Nice to hear — what do you think this code returns? And yeah, it’s a trick question:

function returnSomething()
{
  return
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}

In almost any other language — C#, Java, the list goes on — we’d get back the object with JavaScript Expert. And you’d be forgiven for thinking that in JavaScript, we’d get back the same result.

However, humor me, and pop this into your development console, and then execute the function. Almost unbelievably, it returns undefined.

When things don’t go to plan

Working as a software developer means that you are responsible for how your app works, whether it works well or poorly. A main constraint in that is the tools that you decide to use. If you understand what you’re using, you’ll hopefully make good choices in how you design your software.

JavaScript is unique because it’s the language of choice of so many new software developers. Want to write a mobile app? Just use React Native and JavaScript. Desktop app? React Native and JavaScript. A cloud function to run somewhere? Node.js, and, you guessed it, JavaScript.

However, due to how long JavaScript has been around, it has its fair share of footguns and gotchas. Some of these range from mildly amusing to none-of-my-code-works-and-I-don’t-know-why severity.

And, even if we lived in a time when Internet Explorer 6 was in its heyday, it would simply be too late to go and try to fix some of these design decisions, as we would break too much of the web. If that were the case then, imagine if we tried today! ??

So, how does JavaScript not work in a way that we might expect? Let’s take a look.

Automatic Semicolon Injection (ASI)

The example listed at the outset is accepted by JavaScript interpreters but doesn’t yield the expected result. The reason is because of Automatic Semicolon Injection.

Some languages, like C#, are dogmatic about ending each line with a semicolon. JavaScript also uses semicolons to indicate the end of a line, but the semicolon is actually optional. By optional, it means that JavaScript will apply a set of complex rules to work out whether a semicolon should have gone there or not.

In the example at the outset, because the opening bracket doesn’t occur on the same line as the return, ASI pops one in there for us. So, as far as JavaScript is concerned, our code actually looks like this:

function returnSomething()
{
  return ; // 



<p>The way to avoid this is to have the opening bracket on the same line as a return. And, while semicolons are technically optional in JavaScript, it’s going to hurt you in the long-run to work with that concept. </p><p>If you have an interview, and you have to write JS, and you write it without semicolons based on the rationale “but they’re optional”, there’s going to be a lot of paper shuffling and chuckling. Just don’t do it.</p>

<h2>
  
  
  Arrays with non-sequential keys
</h2>

<p>Let’s imagine we have a simple array:<br>
</p>

<pre class="brush:php;toolbar:false">function returnSomething()
{
  return
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}

We know we can pop, push, append, and do whatever we like with arrays. But we also know that JavaScript, like other languages, lets us access array elements by index.

However, what’s unusual about JavaScript is that you can also set elements by array index when the array isn’t even up to that index just yet:

function returnSomething()
{
  return ; // 



<p>I’ve got a good question for you though — What’s the length of an array when you’ve only set three elements? Possibly non-intuitively, it’s 101. On one hand, it’s reasonable that array items 2 through 99 are undefined, but on the other, we only set three objects, not 100. </p>

<p><strong>Why does it matter?</strong> <br>
Maybe your eyes roll out of your head and you say “Okay Lewis, you’re manually assigning items into an array and watching the wheels come off; that makes you weird, not JavaScript”. </p>

<p>I would understand that position. But imagine for a moment you’re doing something in a nested for loop, and you choose the wrong iterator or make a bunk calculation. </p>

<p>At some point, the thought process of “Why am I getting expected result, expected result, undefined, expected result” is going to turn to madness, and soon enough to tears! Little did you know your array magically grew to accommodate what you were trying to do. </p>

<p>The only problem was, you were trying to do the wrong thing. </p>

<p>To compare with another language like C# (for no particular reason), arrays are of fixed length. When you create an array, you have to define a length. Even for other dynamic collection objects, like List<t>, you can’t assign into an undefined index. So, if your nested loop attempts to write to a previously unassigned index, your program will throw. </t></p>

<p>Exceptions aren’t nice, but it’s probably the right thing to do. I mean, did you otherwise mean to create a Swiss-cheese array? Does anyone mean to do that? Hopefully not.   </p>

<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954908866066.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <em>It’s only Swiss cheese arrays if the developers are from Switzerland. Otherwise, it’s just sparkling bad programming.</em></p>
<h2>
  
  
  Adding properties to primatives are ignored
</h2>

<p>We know that in JavaScript we can assign new functions to prototypes. So, we can give strings or arrays ✨special powers✨. Of course, doing so is terrible practice because it means that our string prototype will behave differently to others, which already causes untold heartache for many a developer. </p><p>So, we can do this for example:<br>
</p>

<pre class="brush:php;toolbar:false">function returnSomething()
{
  return
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}

And then we can create a string object:

function returnSomething()
{
  return ; // 



<p>And it would return false. </p>

<p>It’s cute we can always just randomly jam our functions into the factory-defined implementation of how a string can act. </p>

<p>Sure, all those good people broke their backs and spent tens of thousands of hours defining JavaScript in the TC39 specification, but don’t let that dissuade you from banging in your random functions as you see fit. </p>

<p>If we’re not happy with that particular brand of pain, we can also randomly assign new functions to complex objects as we want to, ensuring that our code will be a very particular form of nonsense, understood only by yourself and God: <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954908998836.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <br>
Composing our objects like this is naturally a terrible idea, but as we are committed to this treachery, JavaScript obliges us in our request. Our testObject takes on the new function we’ve thrown into it. </p>

<p>However, the good will runs out with object primatives, in a surprising way: <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909074477.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <br>
The interpreter acknowledges our attempt to assign a function into the string primative. It even echoes the function back to us. But then, when we attempt to call it, we get a TypeError: testString.onlyFalse is not a function. If it’s not possible to do this, typically you would expect this to throw on assignation, not on function call. </p>

<p><strong>Why does it matter?</strong> <br>
For better or for worse, JavaScript is a highly flexible and dynamic language. This flexibility allows us to compose functionality that’s not possible in other languages. If something hasn’t worked, then we should expect an exception. JavaScript taking this awkward command and being like “uh, okay” and then forgetting about it changes this fundamental expectation.</p>
<h2>
  
  
  Type Coercion
</h2>

<p>In other strongly typed languages, we have to define the type of the data that we’re storing before we’re able to store it. JavaScript doesn’t have this same kind of limitation, and it will happily nudge objects away from their defined type to try to get them to play nice together. </p><p>On one hand, it gets us away from casting variables back and forth to their respective types. So it’s convenient: <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909188290.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"><br>
It’s even the same for booleans: <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909211047.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <br>
This approach is completely sane and valid until we want to involve ourselves in the taboo ritual known as “addition.” When we try to add "1" and 1 together, what happens? What way does the type coercion go? <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909319865.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <br>
The <del>insanity</del> hilarity multiplies when we bring bool to the party: <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909445100.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> <br>
Oh — is it because a bool is somehow a number under the hood? <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909562905.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> Nope. It’s a boolean. JavaScript is shaving off the pesky edges of the square to fit it into that round hole because reasons. </p>

<p><strong>Why does it matter?</strong> <br>
When you’re doing something as basic as adding numbers together, having results vary can create some weird bugs. It’s a good reminder to stick to the triple equals (===) when making comparisons, as zapping between types may not give you the intended result.</p>
<h2>
  
  
  Function hoisting
</h2>

<p>With languages that we use today, an important aspect is something called “function hoisting.” Essentially, it means that you can write your functions in your file wherever you like, and you’ll be able to call them before the functions are declared:<br>
</p>

<pre class="brush:php;toolbar:false">function returnSomething()
{
  return
    {
      name: 'JavaScript Expert'
      contactMethod: 'Shine batsign at sky'
    }
}

It’s handy because we don’t have to manually reorder our code to make it work.

But, there’s more than one way to describe a function. In this example, we used a function declaration to do so. We can also use a function expression:

function returnSomething()
{
  return ; // 



<p><strong>Why does it matter?</strong> <br>
There’s not a huge difference between declaring functions in either case, but if you choose the wrong one, you won’t be able to call your function unless you’re calling it after you’ve declared it.</p>

<h2>
  
  
  Null is an object
</h2>

<p>Within other languages, object properties can be assigned, or they can be null. null indicates that the property is not assigned. It’s simple to equate in our heads — there’s either an object there, or it’s null. We can also assign properties back to null if we so wish. </p>

<p>JavaScript complicates this landscape by having null and also undefined. But it’s all the same, right? You either have a ball in your hand, or you don’t. </p><p>Unsurprisingly, it’s not all the same. In JavaScript, null indicates the intentional lack of a value, whereas undefined indicates the implied lack of a value. So, whether it’s intentional, explicit, or written in the sky, the fact is that a no value = no value, right? </p>

<p>Again, unfortunately, that’s not how the equation works out. </p>

<p>Well, what’s the type of undefined? <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909681428.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> </p>

<p>Okay, and what’s the type of null? <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909737640.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> </p>

<p>? it’s an object. So in JavaScript, the type of a complex object and null are the same — they’re both object: <br>
<img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909893812.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"> </p>

<p><strong>Why does it matter?</strong> <br>
JavaScript doesn’t have a robust type-checking system built in, and there’s only a handful of primative types to choose from. So, using typeof to understand what’s in our variable can become tricky. If our variable holds a valid object, then we’d get object. But if it’s null, we’d still get object. It’s counter-intuitive to think that a null reference is an object.</p>

<h2>
  
  
  Conclusion
</h2>

<p>There’s no questioning of JavaScript’s immense popularity today as a language. As time continues and other ecosystems such as npm continue to host huge numbers of packages, JavaScript will only continue increasing in popularity. </p>

<p>But what’s done is done. No matter how weird it is that null is an object, or that JavaScript will pop semicolons in where it sees fit, these systems will probably never be deprecated, changed, or removed. Anecdotally, I would say that if Automatic Semicolon Injection was turned off overnight, it’d probably cause a bigger global outage than the CrowdStrike update would. </p>

<p>Certainly, changing one of these would wreak havoc on the web. It’s actually safer, and probably more practical, to make the developers aware of these particular language quirks than to actually go back and resolve the original problems. </p>

<p>So, go and make good choices, and don’t forget to use semicolons!</p>


<hr>

<h2>
  
  
  LogRocket: Debug JavaScript errors more easily by understanding the context
</h2>

<p>Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.</p>

<p>LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.</p><p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172954909986001.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Six things you may not know about JavaScript"></p>

<p>LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers   bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!</p>

<p>Try it for free.</p>


          

            
        

The above is the detailed content of Six things you may not know about JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor