• United States
  • United Kingdom

What is JavaScript? The full-stack programming language

Javascript is the most in-demand programming language for developer jobs and one of the most versatile languages for full-stack development. here's what you need to know about javascript..

Josh Fruhlinger

Contributing writer, InfoWorld |

What is JavaScript? The full stack programming language

A brief history of JavaScript

What is javascript used for, advantages of using javascript, javascript libraries and frameworks, typescript: a superset of javascript, resources for learning javascript, get started with javascript.

JavaScript is a wildly popular interpreted scripting language that was the most in-demand language of 2023 , with 29% of job offers requiring programming experience with JavaScript or TypeScript. There are various reasons for JavaScript's success, starting from the fact that it's an open standard, not controlled by any single vendor, with numerous implementations and a syntax that is easy to learn.

Just about anything interactive or animated on a webpage today is rendered in JavaScript. Thanks to server-side frameworks such as Node.js , Deno , and bun , the language also extends beyond the browser. It is used to write code for anything from clients to servers to cloud-based applications.

This is an overview of JavaScript, including a brief history, what kinds of applications it is used for, tools for working with JavaScript, and resources for learning JavaScript.

As its name implies, JavaScript is a scripting language. Traditional languages such as C++ are compiled before they’re run into executable binary form, with the compiler checking for errors in the entire program before the process is complete. Scripting languages, by contrast, are executed one line at a time by another program called an interpreter. Scripting languages started out as a series of shell commands used to execute other programs. Their flexibility and ease of use made them a popular type of programming language in their own right, and languages like JavaScript became important with the rise of the web.

Many developers new to JavaScript wonder about the Java part of its name. The short story is that Java and JavaScript emerged during the same historic moment, and both were key to the birth of the web. Their history is intertwined, but the two languages are separate. Brendan Eich, JavaScript's creator, explained why JavaScript was considered an important complement to Java in the original Netscape browser:

There were people who argued strongly that Java’s fine for programmers who build components, but there’s a much larger audience of people who write scripts or maybe copy a script from somebody else and tweak it. These people are less specialized and may be paid to do something other than programming, like administer a network, and they write scripts part-time or on the side. If they’re writing small pieces of code, they just want to get their code done with the minimal amount of fuss.

Originally called LiveScript, the language was created with syntax that was superficially similar to Java in order to tap into the emerging Java developer community. Even though its usage grew in tandem with Java and early web development, JavaScript was long considered a lesser sidekick to the more robust Java programming language.

In 1997, the ECMA (European Computer Manufacturers Association) issued a standard defining the language that anyone could implement. The reason for this move was that “Java” remained a Sun trademark that only Netscape had a license to use. The new, standardized version of JavaScript was dubbed ECMAScript , but in practice, most people know the language as JavaScript.

JavaScript was developed to help create interactive websites, and this remains one of its primary uses today. Developers incorporate JavaScript into their website code, where it is executed by the interpreter built into the user's browser. The JavaScript code creates or modifies HTML on the fly to produce dynamic content and interact with back-end data stores. When used this way, JavaScript is called a client-side language, with one of its most lucrative applications being mobile games. Server-side frameworks like Node.js extend JavaScript for more scalable and event-driven applications.

You won't hear anyone arguing that JavaScript is a perfect language, but it is a very useful one. It's easy to write workable code quickly in JavaScript, and while interpreted languages often don't perform well compared to compiled code, JavaScript has a special advantage here because it was initially created for web browsers. Three of the biggest software companies in the world—Microsoft, Apple, and Google—compete to produce high-performance JavaScript interpreters. As a result, JavaScript is a remarkably robust and scalable language, even given its humble beginnings.

Once non-browser viable JavaScript runtimes became widely available, the army of web developers well-versed in JavaScript suddenly found themselves crowned as full-stack developers . The JavaScript tooling ecosystem boosts developer productivity with code that gets the job done from the browser to the server. Due to its popularity, the language is also frequently updated. It's a classic example of a virtuous cycle of popularity driving adoption.

You'll sometimes hear people refer to vanilla JavaScript . This, in a nutshell, means you're working with an application that was written in JavaScript from the ground up. This is fine for small bits of functionality, but once you start working at scale, it quickly becomes untenable, as any enterprise developer will tell you. Most JavaScript developers make frequent use of the vast array of available JavaScript libraries —prewritten third-party code, usually free and open source, that solves a common problem and can be integrated into your project. (The ECMAScript standard refers to JavaScript modules , but library is the more commonly used term in practice.)

Most JavaScript developers turn to libraries for basic application plumbing rather than reinventing the wheel. There are also frameworks , which are collections of libraries designed to work together to provide the scaffolding for enterprise-scale applications. Using frameworks lets developers focus on the technical aspects of their programs. Probably the most famous JavaScript framework is Angular . Others include React and Vue .

An important aspect of the JavaScript ecosystem is TypeScript , which is similar to JavaScript but has features that the basic language lacks, like strong typing of variables and other data structures. TypeScript and languages like it are often designed to bring to JavaScript concepts that make it easier to build sprawling enterprise-scale applications efficiently; TypeScript in particular was created at Microsoft when the company was developing a web-based version of its flagship Office suite.

TypeScript is said to be a superset of JavaScript because its syntax includes everything in JavaScript,  and then some : good JavaScript is always good TypeScript, but TypeScript has syntax that isn't part of JavaScript. TypeScript code is transpiled into ordinary JavaScript, allowing it to run in browsers and on standard JavaScript runtimes. Learn more about the similarities and differences between TypeScript and JavaScript .

If you are serious about becoming a JavaScript developer you’ll want to go deeper than this article. The W3Schools JavaScript tutorial is great for your first dive into JavaScript syntax. Here are some additional articles and tutorials to help you get started:

  • The Modern JavaScript Tutorial is a comprehensive resource that takes you step by step from a simple Hello, World! program to ways to build sophisticated interactive functionality into the browser.
  • JavaScript Examples at Tutorial Republic offer a wealth of short JavaScript programs that escalate in difficulty so you can see how JavaScript code works in action.
  • InfoWorld's Matthew Tyson writes frequently about JavaScript frameworks and programming techniques. Popular recent articles include  Using JavaScript and forms ,  Using JavaScript's built-in objects , and Building JavaScript tables in React .

JavaScript Snake is a live example of what you can do with JavaScript. It's a classic game that can be built to run in the browser using only JavaScript, HTML, and CSS. This tutorial from Panayiotis Nicolaou shows you how.

Are you ready to start playing around with JavaScript today? Because it’s an interpreted language, you don't need to download JavaScript. You can just fire up your favorite text editor (or better yet, a JavaScript editor or IDE) and start typing code! A JavaScript interpreter is built into any web browser that executes commands, so you can simply embed your JavaScript into an HTML document and load it up to test.

If you want to run JavaScript code in a desktop environment—which will give you access to the filesystem, among other things—then you can download Node.js .

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023
  • Software Development
  • Programming Languages

Josh Fruhlinger is a writer and editor who has been covering tech since the first dot-com boom. He’s interested in open source, changes in the development landscape, and what happens when tech theory meets practice in the real world.

Copyright © 2024 IDG Communications, Inc.

javascript essay

Transform your testing process with: Real Device Cloud , Company-wide Licences & Accessibility Testing

App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

A detailed guide on JavaScript Web Development

By Mohit Joshi, Community Contributor - August 7, 2023

The most widely used programming language in the world, JavaScript has enriched the whole digital realm by enabling developers to build dynamic websites with visually appealing user interfaces . Web Developers that are just starting or seasoned pro developers, everyone is playing with JavaScript, a fundamental route for building successful web applications .

If you’ve lived through the early decade of the century or the pre-JavaScript era, you must have wondered how far things have come across. The websites back then were not only less pleasant but were not even handy. So you might claim that JavaScript does more than just give your websites a pretty face; it also improves their usability and accessibility . If it’s difficult for you to imagine a world without JavaScript, you may just disable JavaScript in your browser and see how you can’t endure the lifeless web pages for more than a few minutes.

In this guide, we are diving into the fundamental understanding of how to leverage JavaScript for web development .

top programming languages

StackOverflow

What is JavaScript for Web Development?

Different types of web development, top javascript frameworks for web development, getting started with javascript for web development: with example, 1. variables, 2. operators, 3. functions, 4. conditional statements, best practices for using javascript web development.

JavaScript is a high-level interpreted programming language that was initially launched in 1995 but came into wider public usage much later. It is an engine that is used for building interactive aspects in the websites that broadens the functionality .

If you come across components in any websites, that utilize animations, maps, graphics, etc., you can be confident that JavaScript is behind all those functionalities. It is a lightweight and object-oriented programming language that is being used by the majority of modern websites available on the internet. It is cross-platform compatible and is supported by all major web browsers.

Both the front end and the back end of websites may be developed using JavaScript, which, when done right, captures seamless communication between the client and the server. The potential of JavaScript to manipulate the DOM is its main benefit for use in modern web development.

Also Read: Understanding JavaScript design patterns in depth

Why is JavaScript Important for Web Development?

It is hard to imagine developing user-friendly websites without dealing with JavaScript.  It not only makes the entire development process easier, but it also adds features you wouldn’t get from any other technology. Let’s look at the three top-most important criteria for using JavaScript for web development.

  • Cross-platform compatibility : JavaScript is supported on almost all modern web browsers present across the world. This has accepted JavaScript as one of the most essential and widely used client-side scripting languages. It not only ensures a seamless experience as a user but also ensures broader coverage of your website as a developer. 
  • Community Support: Being among the most popular programming languages in the world, JavaScript also ensures a vast collection of resources, tools, documentation, and community support. As a developer, you can go through numerous active forums, tutorials, and open-source projects due to their wide acceptance as a programming language among web developers throughout the world.
  • Client and Server side capabilities: JavaScript is well-known for building client-side webpages, enhancing the website’s user-friendliness, and adding cutting-edge interactive features. However, as the modern world evolved, JavaScript also expanded its capabilities of scripting the server side of the website with the help of NodeJS.

Also Read: How to test JavaScript in browsers

Typically, there are two steps involved in creating a website: front-end development and back-end development. In most cases, each part is developed by separate developers with different skill sets, however, When a single developer oversees the entire development of the website, they are known as full-stack developers. Let’s understand both parts of the development and what are their essential features.

  • Front-end development: It is also known as client-side development, as the name suggests it focuses on the visible parts of the websites that are UI components of an application. This development assures the website is responsive , user-friendly, stylish, and visually appealing in all aspects.
  • Back-end development: It is also known as server-side development, as it ensures the logic is properly applied on the website as intended by the developer. The developer here creates a behind-the-scene show that powers the website creates a connection of the front end of the website with the required servers and databases, and ensures a seamless transaction of data between them.

Types of Web Development Frameworks

Read More: Front End Testing: A Beginner’s Guide

A large ecosystem of frameworks and libraries that use JavaScript and provide several modern features and enhancements essential for web development exists. Since all the frameworks we’re going to talk about are built on JavaScript, learning them won’t take much time if you know JavaScript well.

Let’s look at the top frameworks based on JavaScript for web development.

  • NodeJS: NodeJS expands the capabilities of JavaScript, enabling programmers to build whole applications using only JavaScript. It allows to build a strong back end for any web application without having to learn any new programming language and leveraging JavaScript itself.
  • ReactJS: It is an open-source UI development JavaScript library for developing the front end of websites. A ReactJS website is a collection of several reusable components, each being a building block of the website. The implementation of reusable components using JavaScript has reduced the development time and complexity of development.

Read More: React Testing: How to test React components?

  • VueJS: VueJS is an open-source front-end framework used for creating dynamic user-interface and single-page applications (SPAs). Vue.Js enables developers to write code in JSX. However, the components are created in HTML components, therefore, allowing even beginner developers an easy-learning curve.
  • AngularJS: Angular is an open-source full-fledged web application framework based on TypeScript used for creating single-page applications (SPAs). As soon as it was launched, it caught several eyes, due to its excellent features. Moreover, AngularJS gained the enormous trust of developers because it is backed by a tech giant, Google.

Also Read: Angular vs React vs Vue: Core differences

You don’t need to rely on any third-party services while using JavaScript for Web Development, and you don’t even need to install a lot of packages in order to start writing JavaScript code.

Prerequisite:

  • Install any IDE of your choice. In this example, we are using VS code as our code editor. 

JavaScript Basics for Web Development

To begin with, JavaScript, just like we add CSS, we shall add the following code before the closing body tag in the HTML file to link the JavaScript file.

Note that, our JavaScript file name is “script.js” .

To make sure it works, insert the following line of code in your JavaScript file and view the output in the browser. The alert “hello world” will pop out.

JavaScript Web Development Example

Variables are containers of data that can be used to store data of different types such as numbers, strings, objects, and more. To define a variable you may use, ‘var’ , ’let’ , and ‘const’ keywords. Variables can be used anytime in a document when once define. Let’s understand with an example.

And the output goes as.

Variables in JavaScript Web Development

You can use JavaScript as a calculator. You can expect JavaScript to support all the basic arithmetic operators. These operators are used wildly in websites for several purposes. Let’s understand what I’m saying with an example.

Operators in JavaScript Web Development

Functions are reusable blocks of code that are assigned some name to use anywhere throughout the document. Let’s create a function that when given two numbers, returns the output as the sum of those numbers.

Functions in JavaScript Web Development

In a JavaScript file, every code is executed line by line, however, if in some instances, we wish that some code should only be executed under some conditions, otherwise skip the script. This can be achieved by applying conditions in our code with the help of ‘if..else’.

Let’s understand this with the help of an example.

Conditional Statements in JavaScript Web Development

JavaScript objects are simply key-value pairs or data containers that contain properties and methods. Let’s understand JavaScript objects with the help of an example.

Objects in JavaScript Web Development

These were some of the fundamental concepts of JavaScript. Now, let’s unleash the full potential of JavaScript with its most essential feature, which is manipulating DOM. 

Selecting HTML elements and adding an event listener

This part will show us how to really manipulate the DOM using JavaScript. To demonstrate that with an example whenever a button on the website is clicked, an alert is generated. This further demonstrates JavaScript’s dynamic nature. 

Create a button in your HTML file.

Creating Button Element in JavaScript Web Development

First, you have to get the button to operate any related action to it. To do so, there are several methods such as. 

  • getElementById()
  • getElementByClass()
  • getElementByName()
  • getElementByTagName()
  • querySelector()

Further when the HTML element is selected you may use the event listener function to it so it records the event that occurred. For example, if the button is clicked the event listener will record that the button is being clicked.

Let’s create a JavaScript code that creates an alert when the button is clicked.

Adding Event Listener to an Element in JavaScript Web Development

Now that we have come along so far, we have understood the capabilities of JavaScript, and how it has enhanced modern web development. Let’s now understand how to leverage JavaScript, so that we don’t lag in creating appealing websites. Here are some best practices you must follow to leverage JavaScript for web development.

  • Constant code style: To maximize efficiency when working on a large JavaScript project that involves developer collaboration, you must ensure that a code pattern and style have been mutually agreed upon. A consistent coding approach makes your code easier to read and prevents misunderstandings with other team members. 
  • Use proper testing strategies: The process of testing determines if the output product works as intended. If you follow the right testing procedures, your code becomes less susceptible to risks and doesn’t malfunction. Common JavaScript testing techniques include things like avoiding using mock, utilizing try..catch, adopting the BDD approach, and more. 
  • Keep up with the latest trends: If you stay up to date with the rapid speed of modern web development, you may actively contribute to the creation of user-friendly websites.
  • Proper Variable nomenclature: You must choose descriptive and meaningful names for variables, functions, and classes. This reduces misunderstanding among the project’s other participants and improves the readability of the code.

A website that engages well with the users stands out among the crowd. In this tutorial, we delved into a detailed discussion of using JavaScript for web development. JavaScript is the most popular and widely-used programming language across the globe. JavaScript has been able to completely change how websites are developed nowadays. 

This article also discussed a number of JavaScript-based frameworks that have altered the development environment by introducing features and tools that lessen the complexity and duration of development while enhancing output. You also got an understanding of different JavaScript code practices that will enable our website to reach a wider audience and work flawlessly in all popular operating systems and browsers.

We're sorry to hear that. Please share your feedback so we can do better

Related articles.

javascript essay

Understanding JavaScript Design Patterns In Depth

Want to reuse pieces of your JS code? Learn about JavaScript design patterns and their benefits.

5 Ways to Test Javascript in Browsers

How to test JavaScript in Browsers (with 5 Methods)

Learn to test JavaScript code in browsers with effective online tools such as JSFiddle, BrowserStack...

Angular vs React vs Vue Core Differences

Angular vs React vs Vue: Core Differences

Picking the best web framework is crucial. This guide on Angular vs React vs Vue compares and help y...

Featured Articles

Ready to try browserstack.

Over 6 million developers and 50,000 teams test on BrowserStack. Join them.

Martin Schneider

Schedule a personalized demo.

Our team will get in touch with you within 12 hours

Get in touch with us

Please share some details regarding your query

Request received!

We will respond back shortly to

In the meantime, here are some resources that might interest you:

2

Meanwhile, these links might interest you:

JavaScript Articles

An introduction to abstract data types in javascript.

  • Code Foundations ,

Build a 3D Environment with Three.js

Build a discord bot with node.js, comparison and logical operators, conditional statements, creating a react app.

  • JavaScript ,
  • Web Development

Creating Queues Using JavaScript

Deploying a back-end with heroku.

  • Developer Tools ,

Developing Phaser 3 Games Locally

  • Game Development ,
  • HTML & CSS ,

Getting User Input in Node.js

How to generate qr code using javascript.

  • Front-End Engineer ,

HTML5 Game Development with Phaser

  • Mobile Development ,

HTTP Requests in Velo

Implementing modules using es6 syntax, implementing the redux store from scratch.

  • Full-Stack Engineer ,

Intro to Mozilla Developer Network

Introduction to javascript runtime environments, javascript glossary, javascript guide: arrays, javascript guide: conditional statements, javascript guide: introduction to javascript, javascript versions: es6 and before, javascript: all the cool kids are doing it, methods and functions, mvc architecture for full-stack app.

  • Computer Science ,

NextJs Deployment with Caprover and Github Actions

React developer tools, react: the virtual dom, reading tests with mocha and chai, running javascript in the browser console, setting up a backend, setting up node, setting up node locally, the tsconfig.json file, up next on velo, using arrays to group data, variables, data types, and mathematical operators, web programming on a chromebook, what are tuples, what is a spa, what is async and await, what is express.js, what is javascript, what is json, what is node, why learn asynchronous javascript, why learn javascript foundations, wix built-in methods and functions.

To revisit this article, visit My Profile, then View saved stories .

  • Backchannel
  • Newsletters
  • WIRED Insider
  • WIRED Consulting

The Healing Power of JavaScript

A little over a year ago, as the Covid-19 lockdowns were beginning to fan out across the globe, most folks grasped for toilet paper and canned food. The thing I reached for: a search function.

The purpose of the search function was somewhat irrelevant. I simply needed to code. Code soothes because it can provide control in moments when the world seems to spiral. Reductively, programming consists of little puzzles to be solved. Not just inert jigsaws on living room tables, but puzzles that breathe with an uncanny life force. Puzzles that make things happen, that get things done, that automate tedium or allow for the publishing of words across the world.

Like many other writers and artists, I maintain a personal website. My current one has been active for nearly 20 years. Code in mind, I brushed off my rusty JavaScript skills and started to poke around for fuzzy-search libraries I could bolt onto my homepage, to make it easy to find specific essays from my collection.

Break the problem into pieces. Put them into a to-do app (I use and love Things). This is how a creative universe is made. Each day, I’d brush aside the general collapse of society that seemed to be happening outside of the frame of my life, and dive into search work, picking off a to-do. Covid was large; my to-do list was reasonable.

The real joy of this project wasn’t just in getting the search working but the refinement, the polish, the edge bits. Getting lost for hours in a world of my own construction. Even though I couldn’t control the looming pandemic, I could control this tiny cluster of bits.

The whole process was an escape, but an escape with forward momentum. Getting the keyboard navigation styled just right, shifting the moment the search payload was delivered, finding a balance of index size and search usefulness. And most important, keeping it all light, delightfully light. And then writing it up, making it a tiny “gist” on GitHub, sharing with the community. It’s like an alley-oop to others: Go ahead, now you use it on your website. Super fast, keyboard-optimized, client side Hugo search.

It's not perfect, but it’s darn good enough.

The point being that a habit of reaching for code is not only healing for the self, but a trick to transmute a sense of dread into something: A function that seems to add, however trivially, a small bit of value to the greater whole in a troubling moment.

I began coding when I was 10 and have been running with it ever since. Self-taught, mostly. I had a preternatural awkwardness with others. The machine was literal in a reassuring way, and seemed to promise access to a world that even the adults around me couldn’t fathom. In this way, the code became a friend—a nonjudgmental buddy.

A pattern was set: When the complexities of social situations exhausted me as a child, I turned to code, became an isolate. Ellen Ullman writes in her book Life in Code: A Personal History of Technology , “Until I became a programmer, I didn’t thoroughly understand the usefulness of such isolation: the silence, the reduction of life to thought and form; for example, going off to a dark room to work on a program when relations with people get difficult.”

Reading assembly language books in middle school or programming BBS software in high school didn’t register, then, explicitly, as a salve. My first conscious acknowledgement of the palliative power of code came a few years ago when I refactored my website from one content management system to another. This sounds implausible, but it’s true: I was healed by a CMS, a Google-unique phrase—and for good reason.

The 19 Best Movies on Amazon Prime Right Now

At the time, I was suffering from personal and professional depressions, a long time in the making. I had been knocked off kilter. When I took stock of my mind, I realized it was not where I wanted or expected it to be.

This happens to me, sometimes; to certain people, many times. I think often of the epigraph of William Styron’s Darkness Visible when I feel the weight of a depression descend: “For the thing which I greatly feared is come upon me …” That descent usually means I haven’t been getting enough rest. I don't mean over the course of days, but rather months or years. A slow tilting, like a ship taking on water through a pinhole. Given enough time, it must tip. My mind was tipping, and I found myself grasping for, of all things, servers. Like a life raft. Servers, it turns out, are one of my safe places.

I had wanted to shed my rickety and overpriced Rackspace server for years, but had been too lazy. It's a meaty task, a task for grunts, thankless, and one that requires focus.

Most everything related to servers happens in the “terminal,” on the command line, in a world devoid of images or graphical interfaces. Just text. Every action is key-precise and hyper-literal. A mistype of a single character can destroy a system. In fact, for decades, servers have presented the following message when you enter into administrator or “super user” mode:

We trust you have received the usual lecture from the local System Administrator. It usually boils down to these three things:
1: Respect the privacy of others.
2: Think before you type.
3: With great power comes great responsibility.

It can make a person weak in the knees to think about how much of the world's smooth operation is contingent on typing accuracy. But it is, and when you move through the guts of your favorite Linux operating system distribution, you can't help but stare gape-mouthed at the absurdity and beauty of the crisscross threads that keep the web and most of our digital (and, by proxy, physical) infrastructure afloat.

Therein lies part of the attraction: Moving through that jumble—with all of its perverted poetics of grep and vi and git and apache and *.ini—*and doing so with a fingers-floating-across-the-keyboard balletic grace, is exhilarating. You feel like an alchemist. And you are. You type esoteric words— near gibberish—into a line-by-line text interface, and with a rush not unlike pulling Excalibur from the stone you've just scaffolded a simple application that can instantly be accessed by a vast number of humans worldwide.

Romantic partners have regarded me with confusion and perhaps suspicion when I suddenly went fluent in bash (a flavor of terminal shell used to type commands). It was as if I had been keeping a dirty secret from them. I once dropped quick-fingered into text-land to help a friend's teenage son install some Minecraft mods, and by the look in his eyes I could tell I had become a minor celebrity in real time. With a few hundred keystrokes, two generations were bridged.

I find peace in the dark mess of that world. Code and servers are a home to me in a way that's difficult to explain to anyone for whom they are not.

So in my tilted state, my slightly depressive state, I moved websites from my old server to my new server. My tasks were guided by the trusty to-do list. URLs of old sites marked off distinct epochs in my life, of a variety of lenses through which I once saw myself. Perhaps I am this kind of artist or will be this kind of writer?

The old websites of mine are ghosts. Nobody will look at or think to hunt them down. I moved them because I feel a stewardship over them, feel that they have a right to go on living in bits.

A lot of this server work involved making complicated sites less complex. That is: Making the dynamic static. Gutting these sites of their PHP cores, Benjamin Buttoning them back into sleepy HTML and CSS, making them low maintenance and future friendly. It's funny how even something as simple as a MYSQL database requires pruning, nurture. How a PHP script—so seemingly innocuous!—is rendered obsolete a decade later as deprecation creeps, mental models of languages evolve. But take a page of HTML from the early ’90s, and it renders as well as ever on most anything with a screen.

In that spirit, as I moved my homepage I also rebuilt it as a so-called static site. A simpler version that should continue to work for the next hundred years. It looks nearly the same as it did before. With static sites, we've come full circle, like exhausted poets who have travelled the world trying every form of poetry and realizing that the haiku is enough to see most of us through our tragedies.

As is true for most infrastructure work, these gruntish behind-the-scenes tasks are often neglected, or derided as irrelevant, underfunded, ignored. That is, until they break, or a pandemic hits, and then we realize how infrastructure is everything, and without it our world reverts to some troglodytic cave state, or perhaps worse, an ever-widening extreme of haves and have-nots.

In the late 1990s you almost had no choice but to be your own homepage steward and janitor and systems engineer. Now you can offload that stewardship to a third party. Tumblr, Ghost, Facebook, Blogger, Wordpress—platforms have sprung up where you can focus purely on content in exchange for giving up a certain level of control.

You can take stewardship too far. I probably have. There is a diminishing return on what you can get out of any system, regardless of how much you put into it. But I don't care.

This work of line-by-line problem solving gets me out of bed some days. Do you know this feeling? The not-wanting-to-emerge-from-the-covers feeling? Every single morning of the last year may have been the most collectively experienced covers-craving in human history, where so many things in the world were off by a degree here or a degree there. But under those covers I begin to think— A ha! I know how to solve server problem x, or quirk y. I know how to fix that search code. And I'm able to emerge and become human, or part human, and enter into that line-by-line world, where there is very little judgement, just you and the mechanics of the systems, systems that become increasingly beautiful the more time you spend with them. For me, this stewardship is therapy.

And so I pull apart a system—a system that I have loved and has served me well over the years—and figure out a better, more sustainable framework for the code, and one hopes, by extension, maybe even the world.

  • 📩 The latest on tech, science, and more: Get our newsletters !
  • A genetic curse, a scared mom, and the quest to “fix” embryos
  • Larry Brilliant has a plan to speed up the pandemic’s end
  • Facebook's “Red Team X” hunts bugs beyond its walls
  • How to choose the right laptop: A step-by-step guide
  • Why retro-looking games get so much love
  • 👁️ Explore AI like never before with our new database
  • 🎮 WIRED Games: Get the latest tips, reviews, and more
  • 🎧 Things not sounding right? Check out our favorite wireless headphones , soundbars , and Bluetooth speakers

Learn Web Development Basics – HTML, CSS, and JavaScript Explained for Beginners

Kingsley Ubah

If you are learning web development, you will come across terms like HTML, CSS, and JavaScript. These are often called the building blocks of the Web.

These three tools dominate web development. Every library or tool seems to be centered around HTML, CSS, and JS. So if you want to become a web developer, you need to learn them well.

You'll also discover that websites are mostly built from these three languages.

But you're probably wondering what each one is and what it's really used for. What makes these languages so special and important? And what makes them so ubiquitous that you can’t help but see them in every tutorial and topic based on web development?

Well, now you need wonder no more.

In this article, I will explain the basics of what HTML, CSS, and JavaScript are, how they make the Web work, and what they do on their own.

What is the Internet?

The internet is simply a network of computers that communicate with each other to send and receive data (information).

Each of these computers on the internet can be distinguished and located by a unique number called an IP Address. An IP Address looks something like this: 168.212.226.204

What is the Web?

The Web is a subset of the internet.

Like every other computer network out there, the Web is made up of two main components: the web browser client and the web server.

The client requests the data and the server shares or serves its data. To achieve this, the two parties have to establish an agreement. That agreement is called the Application Programming Interface or in short, the API.

But this data has to be arranged and formatted into a form that's understandable by end-users who have a wide range of technical experiences and abilities.

This is where HTML, CSS, JavaScript and the whole concept of web development come into play.

What is HTML?

HTML stands for Hyper Text Markup Language.

Dictionary.com defines a Markup as:

a set of detailed instructions, usually written on a manuscript to be typeset, concerning style of type, makeup of pages, and the like.

So you can think of HTML as the language used for creating detailed instructions concerning style, type, format, structure and the makeup of a web page before it gets printed (shown to you).

But in the context of web development, we can replace the term ‘printed’ with ‘rendered’ as a more accurate term.

HTML helps you structure your page into elements such as paragraphs, sections, headings, navigation bars, and so on.  

To illustrate what a page looks like, let's create a basic HTML document:

This is how you can format and structure a document with just HTML. As you can see, this markup contains some web elements such as:

  • Level 1 heading h1
  • Level 2 heading h2
  • Level 3 heading h3
  • A paragraph   p
  • An unordered list with bullet points   ul li
  • A button input input
  • And the whole body of the page body

This is what that markup above renders on a web browser:

HTML

You can also add attributes to these elements which you can use to identify the elements and access them from other places in the site.

In our example, we set the id attributes to all of the three span elements. This will help us access them from our JavaScript as you will see later.

Think of this attribute the same way as your social media username. With this name, others can find you on social media. And someone can also refer to you or mention you with this name (you can get tagged in a post, and so on).

This page is very basic and unattractive, though. If you are building anything other than a demo, you will need to add some basic styling to make it more presentable. And we can do exactly that with CSS.

Want to learn more about HTML? You can start with freeCodeCamp's Responsive Web Design certification and this brand new full HTML course from Beau Carnes .

What is CSS?

While HTML is a markup language used to format/structure a web page, CSS is a design language that you use to make your web page look nice and presentable.

CSS stands for Cascading Style Sheets , and you use it to improve the appearance of a web page. By adding thoughtful CSS styles, you make your page more attractive and pleasant for the end user to view and use.

Imagine if human beings were just made to have skeletons and bare bones – how would that look? Not nice if you ask me. So CSS is like our skin, hair, and general physical appearance.

You can also use CSS to layout elements by positioning them in specified areas of your page.

To access these elements, you have to “select” them. You can select a single or multiple web elements and specify how you want them to look or be positioned.

The rules that govern this process are called CSS selectors .

With CSS you can set the colour and background of your elements, as well as the typeface, margins, spacing, padding and so much more.

If you remember our example HTML page, we had elements which were pretty self-explanatory. For example, I stated that I would change the color of the level one heading h1 to red.

To illustrate how CSS works, I will be sharing the code which sets the background-color of the three levels of headers to red, blue, and green respectively:

The above style, when applied, will change the appearance of our web page to this:

CSS

Cool, right?

We access each of the elements we want to work on by "selecting" them. The h1 selects all level 1 headings in the page, the h2 selects the level 2 elements, and so on. You can select any single HTML element you want and specify how you want it to look or be positioned.

Want to learn more about CSS? You can check out the second part of freeCodeCamp's Responsive Web Design certification to get started.

What is JavaScript?

Now, if HTML is the markup language and CSS is the design language , then JavaScript is the programming language.

If you don’t know what programming is, think of certain actions you take in your daily life:

When you sense danger, you run. When you are hungry, you eat. When you are tired, you sleep. When you are cold, you look for warmth. When crossing a busy road, you calculate the distance of vehicles away from you.

Your brain has been programmed to react in a certain way or do certain things whenever something happens. In this same way, you can program your web page or individual elements to react a certain way and to do something when something else (an event) happens.

You can program actions, conditions, calculations, network requests, concurrent tasks and many other kinds of instructions.

You can access any elements through the Document Object Model API (DOM) and make them change however you want them to.

The DOM is a tree-like representation of the web page that gets loaded into the browser.

DOM-

Thanks to the DOM, we can use methods like getElementById() to access elements from our web page.

JavaScript allows you to make your webpage “think and act” , which is what programming is all about.

If you remember from our example HTML page, I mentioned that I was going to sum up the two numbers displayed on the page and then display the result in the place of the placeholder text. The calculation runs once the button gets clicked.

CSS-1

This code illustrates how you can do calculations with JavaScript:

Remember what I told you about HTML attributes and their uses? This code displays just that.

The displaySum is a function which gets both items from the web page, converts them to numbers (with the Number method), sums them up, and passes them in as inner values to another element.

The reason we were able to access these elements in our JavaScript was because we had set unique attributes on them, to help us identify them.

So thanks to this:

We were able to do this:

Finally, upon clicking the button, you will see the sum of the two numbers on the newly updated page:

JAVASCRIPT

If you want to get started with JavaScript, you can check out freeCodeCamp's JavaScript Algorithms and Data Structures certification. And you can use this great Intro to JS course to supplement your learning.

How to Put HTML, CSS, and JavaScript Together

Together, we use these three languages to format, design, and program web pages.

And when you link together some web pages with hyperlinks, along with all their assets like images, videos, and so on that are on the server computer, it gets rendered into a website .

This rendering typically happens on the front end, where the users can see what's being displayed and interact with it.

On the other hand, data, especially sensitive information like passwords, are stored and supplied from the back end part of the website. This is the part of a website which exists only on the server computer, and isn't displayed on the front-end browser. There, the user cannot see or readily access that information.

The Modern JavaScript Tutorial

How it's done now. From the basics to advanced topics with simple, but detailed explanations.

We plan to improve the tutorial. Your feedback is important!

What do you want to see? More features? New content? Let us know here !

Table of contents

Main course contains 2 parts which cover JavaScript as a programming language and working with a browser. There are also additional series of thematic articles.

The JavaScript language

Here we learn JavaScript, starting from scratch and go on to advanced concepts like OOP.

We concentrate on the language itself here, with the minimum of environment-specific notes.

  • An Introduction to JavaScript
  • Manuals and specifications
  • Code editors
  • Developer console
  • Hello, world!
  • Code structure
  • The modern mode, "use strict"
  • Interaction: alert, prompt, confirm
  • Type Conversions
  • Basic operators, maths
  • Comparisons
  • Conditional branching: if, '?'
  • Logical operators
  • Nullish coalescing operator '??'
  • Loops: while and for
  • The "switch" statement
  • Function expressions
  • Arrow functions, the basics
  • JavaScript specials
  • Debugging in the browser
  • Coding Style
  • Automated testing with Mocha
  • Polyfills and transpilers
  • Object references and copying
  • Garbage collection
  • Object methods, "this"
  • Constructor, operator "new"
  • Optional chaining '?.'
  • Symbol type
  • Object to primitive conversion
  • Methods of primitives
  • Array methods
  • Map and Set
  • WeakMap and WeakSet
  • Object.keys, values, entries
  • Destructuring assignment
  • Date and time
  • JSON methods, toJSON
  • Recursion and stack
  • Rest parameters and spread syntax
  • Variable scope, closure
  • The old "var"
  • Global object
  • Function object, NFE
  • The "new Function" syntax
  • Scheduling: setTimeout and setInterval
  • Decorators and forwarding, call/apply
  • Function binding
  • Arrow functions revisited
  • Property flags and descriptors
  • Property getters and setters
  • Prototypal inheritance
  • F.prototype
  • Native prototypes
  • Prototype methods, objects without __proto__
  • Class basic syntax
  • Class inheritance
  • Static properties and methods
  • Private and protected properties and methods
  • Extending built-in classes
  • Class checking: "instanceof"
  • Error handling, "try...catch"
  • Custom errors, extending Error
  • Introduction: callbacks
  • Promises chaining
  • Error handling with promises
  • Promise API
  • Promisification
  • Async/await
  • Async iteration and generators
  • Modules, introduction
  • Export and Import
  • Dynamic imports
  • Proxy and Reflect
  • Eval: run a code string
  • Reference Type
  • Unicode, String internals
  • WeakRef and FinalizationRegistry

Browser: Document, Events, Interfaces

Learning how to manage the browser page: add elements, manipulate their size and position, dynamically create interfaces and interact with the visitor.

  • Browser environment, specs
  • Walking the DOM
  • Searching: getElement*, querySelector*
  • Node properties: type, tag and contents
  • Attributes and properties
  • Modifying the document
  • Styles and classes
  • Element size and scrolling
  • Window sizes and scrolling
  • Coordinates
  • Introduction to browser events
  • Bubbling and capturing
  • Event delegation
  • Browser default actions
  • Dispatching custom events
  • Mouse events
  • Moving the mouse: mouseover/out, mouseenter/leave
  • Drag'n'Drop with mouse events
  • Pointer events
  • Keyboard: keydown and keyup
  • Form properties and methods
  • Focusing: focus/blur
  • Events: change, input, cut, copy, paste
  • Forms: event and method submit
  • Page: DOMContentLoaded, load, beforeunload, unload
  • Scripts: async, defer
  • Resource loading: onload and onerror
  • Mutation observer
  • Selection and Range
  • Event loop: microtasks and macrotasks

Additional articles

  • Popups and window methods
  • Cross-window communication
  • The clickjacking attack
  • ArrayBuffer, binary arrays
  • TextDecoder and TextEncoder
  • File and FileReader
  • Fetch: Download progress
  • Fetch: Abort
  • Fetch: Cross-Origin Requests
  • URL objects
  • XMLHttpRequest
  • Resumable file upload
  • Long polling
  • Server Sent Events
  • Cookies, document.cookie
  • LocalStorage, sessionStorage
  • Bezier curve
  • CSS-animations
  • JavaScript animations
  • From the orbital height
  • Custom elements
  • Template element
  • Shadow DOM slots, composition
  • Shadow DOM styling
  • Shadow DOM and events
  • Patterns and flags
  • Character classes
  • Unicode: flag "u" and class \p{...}
  • Anchors: string start ^ and end $
  • Multiline mode of anchors ^ $, flag "m"
  • Word boundary: \b
  • Escaping, special characters
  • Sets and ranges [...]
  • Quantifiers +, *, ? and {n}
  • Greedy and lazy quantifiers
  • Capturing groups
  • Backreferences in pattern: \N and \k<name>
  • Alternation (OR) |
  • Lookahead and lookbehind
  • Catastrophic backtracking
  • Sticky flag "y", searching at position
  • Methods of RegExp and String
  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Should You Learn JavaScript? Advice for Newbie Web Developers

If you want to become a web developer, you’ll be wondering what programming languages to learn.  Do you start with the easiest ones ? Or the most useful ones? Both?

With so many options these days, why learn JavaScript?

You’ve no doubt heard that it’s an important web technology, but perhaps you’re not sure if JavaScript is all that relevant these days. With so many frameworks out there providing ready-to-use code, is it really necessary to learn JavaScript from scratch ?

In this guide, we’ll explore what JavaScript does and whether or not it’s still useful. We’ll then look at some of the main reasons for learning the language, and consider why it’s necessary to learn plain JavaScript first, before libraries and frameworks.

If you’d like to jump into it, get started learning JavaScript with our free coding short course .

If you want to skip ahead to a certain section, just use the clickable menu below:

  • What is JavaScript and what does it do?
  • Is it still worth learning JavaScript in 2024?
  • Why learn JavaScript?
  • Why learn vanilla JavaScript first?
  • What’s the best way to learn JavaScript?

So—should you learn JavaScript? Let’s find out.

1. What is JavaScript and what does it do?

Before you start learning something new, it’s important to understand exactly what it is and what it does. This is especially useful when it comes to mastering a new programming language.

In simple terms, JavaScript is a programming language used to make websites interactive. If you think about the basic makeup of a website, you have HTML, which describes and defines the basic content and structure of the website, then you have CSS, which tells the browser how this HTML content should be displayed—determining things like color and font.

With just HTML and CSS, you have a website that looks good but doesn’t actually do much. JavaScript brings the website to life by adding functionality. It’s is responsible for elements that the user can interact with, such as drop-down menus, modal windows, and contact forms. It is also used to create things like animations, video players, and interactive maps.

Nowadays, JavaScript is an all-purpose programming language—meaning it runs across the entire software stack. The most popular application of it is on the client side (aka frontend), but since Node.js came on the scene , many people run JavaScript on the server side (aka backend) as well.

When used on the client side, JavaScript code is read, interpreted, and executed in the user’s web browser. When used on the server side, it is run on a remote computer. You can learn more about the difference between frontend and backend programming in our guide .

JavaScript isn’t only used to create websites. It can also be used to build browser-based games and, with the help of certain frameworks, mobile apps for different operating systems. The creation of new libraries and frameworks is also making it possible to build backend programs with the language, such as web apps and server apps.

If you’re interested in learning more, we’ve covered more examples of what is JavaScript used for , including code in more depth elsewhere. But now that we know some of the array of uses of this twenty five year-old language, why learn JavaScript right now?

2. Is it still worth learning JavaScript in 2024?

The world of web development is constantly moving. With so many new tools popping up all the time, not to mention the proliferation of generative AI and the programming tools that come with it it can be extremely difficult to know where you should focus your efforts.

As an aspiring developer, you’ll want to make sure that what you’re learning is still relevant in today’s industry.

If you’re having doubts about this language, don’t. It’s important to note that since its creation in 1995 JavaScript is pretty much everywhere on the web—and that’s not likely to change any time soon. According to the 2023 StackOverflow developer survey , it’s the most commonly used programming language for the 11th year in a row .

A glance at the PYPL index and the Tiobe Index show that JavaScript is right up there in terms of popularity and searches by coders.

It’s currently used by 94.5% of all websites and, despite originally being designed as a client-side language, JavaScript has now made its way to the server-side of websites (thanks to Node.js), mobile devices (thanks to React Native and Ionic) and desktop (courtesy of Electron). Package managers like npm make it even more powerful.

As long as people are interacting with the web, you can assume that JS is highly relevant—there’s no doubt that this is a language worth knowing! With that in mind, let’s look at some of the key benefits of becoming a JavaScript expert.

3. Why learn JavaScript?

The most obvious reason for learning JavaScript is if you have hopes of becoming a web developer.

Even if you haven’t got your heart set on a tech career, being proficient in this language will enable you to build websites from scratch—a pretty useful skill to have in today’s job market!

If you do want to become a web developer, here are some of the main reasons why you should learn JavaScript:

JavaScript experts are versatile

JavaScript is an extremely versatile language. Once you’ve mastered it, the possibilities are endless: you can code on the client-side (frontend) using Angular and on the server-side (backend) using Node.js.

You can also develop web, mobile, and desktop apps using React.js , React Native, and Electron, and you can even get involved in machine learning.

If you want to become a frontend developer , JavaScript is a prerequisite. However, that’s not the only career path open to you as a JS expert. Mastering this key programming language could see you go on to work in full-stack development, games development, information security software engineering, machine learning, and artificial intelligence—to name just a few!

Ultimately, if you want any kind of development or engineering career, proficiency in this language is almost a must. So the next step is to check out the range of JavaScript bootcamps out there and find the one which is best suited to your needs!

JavaScript experts are in-demand (and well-paid)

JavaScript is the most popular programming language in the world, so it’s no wonder that it’s one of the most sought-after skills in the web development industry today.

According to the Devskiller IT Skills and Hiring Report 2020 , 72% of companies are looking to hire JavaScript experts. Enter the search term “JavaScript” on job site Indeed and you’ll find over 81,000 jobs requiring this skill (in the US). Run the same search on LinkedIn and the results are in excess of 110,000.

At the same time, the global demand for the language seems to outweigh the expertise available on the market. According to this HackerRank report for 2023 , JavaScript is the fifth-most popular language that companies look for in a web developer, four times more than its nearest competitor, Bash.

The growing popularity of TypeScript also helps the popularity of JavaScript remain steady, as TypeScript is built on top of it.

Not only are JavaScript experts in demand—they are also well-paid. In the United States, JavaScript developers earn an average yearly base salary of $103,590 per year . We’ve covered this topic in more detail in our JavaScript salary guide , but as you can see, learning this language can really boost your earning potential as a developer.

JavaScript is beginner-friendly

Compared to many other programming languages, JavaScript offers one of the more beginner-friendly entry points into the world of coding.

The great thing about it is that it comes installed on every modern web browser —there’s no need to set up any kind of development environment, which means you can start coding with JavaScript right away!

Another advantage of learning JavaScript as your first programming language is that you get instant feedback; with a minimal amount of code, you’ll immediately see visible results. There’s also a huge JS community on sites like Stack Overflow , so you’ll find plenty of support as you learn.

Not only is it beginner-friendly; it will also set you up with some extremely valuable transferable skills.

JavaScript supports object-oriented, functional, and imperative styles of programming—skills which can be transferred to any new language you might learn later on, such as Python, Java, or C++.

The language provides a crucial introduction to key principles and practices that you’ll take with you throughout your career as a developer.

4. Why learn vanilla JavaScript first?

When deciding whether or not to learn this language, what you’re really asking is whether or not you should learn “vanilla” JavaScript.

Vanilla JavaScript just means the basic language without any libraries or frameworks. Let’s explore what this means in more detail now.

What is meant by vanilla JavaScript, libraries, and frameworks?

If you research the term “vanilla JavaScript”, you might run into some confusion; however, all you need to know is that vanilla JavaScript is used to refer to the native, standards-based, non-extended version.

There’s no difference between vanilla JavaScript and JavaScript—it’s just there to emphasize the usage of plain JavaScript without the use of libraries and frameworks.

So what are libraries and frameworks?

JavaScript libraries and frameworks both contain sets of prewritten, ready-to-use code—but they’re not the same thing.

You can think of a framework as your blueprint for building a website: it gives you a structure to work from, and contains ready-made components and tools that help you to build certain elements much quicker than if you were to code them from scratch. Some popular JavaScript frameworks include Angular, Ember, and Vue.

Read more:  8 of the Best JavaScript Frameworks for Beginners

Frameworks also contain libraries. Libraries are smaller than frameworks, and tend to be used for more specific cases. A JavaScript library contains sets of code which can be called upon to implement certain functions and features.

Let’s imagine you want to code a particular element into your website. You could write, say, ten lines of JavaScript from scratch—or you could take the condensed, ready-made version from your chosen library. Some examples of JavaScript libraries include jQuery , Lodash , and Underscore .

The easiest way to understand how frameworks and libraries work together is to imagine you are building a house. The framework provides the foundation and the structure, while the library enables you to add in ready-made components (like furniture) rather than building your own from scratch.

You can learn more about the relationship between languages and libraries in this post explaining the main differences between JavaScript and jQuery . For now, let’s go back to our original question: How important is it to learn vanilla JavaScript?

Should you learn vanilla JavaScript first?

When it comes to learning the language, it can be tempting to skip ahead to those time-saving frameworks and libraries we just talked about—and many developers do. However, there are many compelling arguments for learning plain JavaScript first.

While JavaScript frameworks may help you get the job done quicker, there’s only so far you can go if you don’t understand the core concepts behind these frameworks. Frontend developer Abhishek Nagekar describes how not learning vanilla JavaScript came back to bite him when he started learning the JavaScript frameworks Node and Express:

“As I went to write more and more code in Node and Express, I began to get stuck at even the tiniest problems. Suddenly, I was surrounded with words like callbacks, closures, event loop and prototype. It felt like I got a reintroduction to JavaScript, but this time, it was not a toddler playing in its cradle, it was something of a mysterious monster, challenging me on every other step for not having taken it seriously.”

If you want to become a developer who can innovate, not just execute, you need to understand the underlying principles of the web—not just the shortcuts. This means learning vanilla JavaScript before you move on to frameworks. In fact, understanding plain JavaScript will help you later on when it comes to deciding whether to use a framework for a certain project, and if so, which framework to use.

Ultimately, if you want to work as a web developer , it’s inevitable that you’ll encounter this web development language at almost every turn. Learning plain JavaScript first will make you a versatile engineer who can work on both the frontend and the backend, and it’ll equip you to solve complex problems independently—a key skill in the industry.

5. What is the best way to start learning JavaScript?

So: if you want to become any kind of web developer, you absolutely need to learn this language—and you should start with plain old vanilla JavaScript first.

If you’re to work out how long to give to get up to speed on the language, senior developer Marven shows you how long it should take to pick up JavaScript .

The best way to start learning JavaScript is to get hands-on. Once you’ve read up on what the language is and how it works, give it a go in your browser. If you’re using Google Chrome, just click “View” then select “Developer” from the drop-down menu. From there, select “JavaScript Console” and you’re good to go!

As with most things, there are plenty of good resources on the web for teaching yourself JavaScript. However, if you want a more structured approach, consider a mentored web development course .

Whichever route you take, make sure you spend enough time learning all the basics. Once you know JavaScript inside out, you’re well-equipped to tackle the more complex languages of the web, as well as to show the benefits to the next person who asks themselves why learn JavaScript when there are other coding options out there.

Further reading

As one of the most powerful web development languages out there, the future for JavaScript is bright. Along with Python for web development , expect budding coders to be starting out by learning these for many more years to come.

If you’d like to learn more about forging a career in web development or just what’s going on in the coding world at the moment, check out the following articles:

  • How To Become A Web Developer: Everything You Need To Know
  • The Most In-Demand Web Developer Skills in 2024
  • What Qualifications Do You Need To Become A Web Developer?

Guru99

Top 100 JavaScript Interview Questions and Answers (2024)

James Hartman

JavaScript Interview Questions for Freshers

1. what is javascript.

JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also being used widely in game development and Mobile application development.

👉 Free PDF Download: JavaScript Interview Questions & Answers >>

2. Enumerate the differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for different intent. Java is an object-oriented programming (OOPS) or structured programming languages like C++ or C, whereas JavaScript is a client-side scripting language.

3. What are JavaScript Data Types?

Following are the JavaScript Data types:

4. What is the use of isNaN function?

isNan function returns true if the argument is not a number; otherwise, it is false.

5. Which is faster between JavaScript and an ASP script?

JavaScript is faster. JavaScript is a client-side language,, and thus it does not need the assistance of the webserver to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server-side language (nodejs).

6. What is negative Infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

7. Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by using a backslash, ‘\,’ at the end of the first line.

And if you change to a new line when not within a string statement, then javaScript ignores the break in the line.

8. Which company developed JavaScript?

Netscape is the software company that developed JavaScript.

9. What are undeclared and undefined variables?

Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

10. Write the code for adding new elements dynamically?

11. what are global variables how are these variable declared.

Global variables are available throughout the length of the code so that it has no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.

// Declare a global: globalVariable = “Test”;

The problems faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.

12. What is a prompt box?

A prompt box is a box that allows the user to enter input by providing a text box. A label and box will be provided to enter the text or number.

13. What is ‘this’ keyword in JavaScript?

‘This’ keyword refers to the object from where it was called.

14. What is the working of timers in JavaScript?

Timers are used to execute a piece of code at a set time or repeat the code in a given interval. This is done by using the functions setTimeout, setInterval, and clearInterval .

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function repeatedly executes the given function in the mentioned delay and only halts when canceled. The clearInterval(id) function instructs the timer to stop.

Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

15. Which symbol is used for comments in Javascript?

// for Single line comments and

16. What is the difference between ViewState and SessionState?

  • ‘ViewState’ is specific to a page in a session.
  • ‘SessionState’ is specific to user-specific data that can be accessed across all web application pages.

17. What is === operator?

=== is called a strict equality operator, which returns true when the two operands have the same value without conversion.

18. How you can submit a form using JavaScript?

To submit a form using JavaScript use

19. Does JavaScript support automatic type conversion?

Yes, JavaScript does support automatic type conversion. It is the common way of type conversion used by JavaScript developers

20. How can the style/class of an element be changed?

It can be done in the following way:

21. How to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

  • Using JavaScript extensions
  • Using a web page and Active X objects

22. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

  • Do-while loops

23. What is called Variable typing in Javascript?

Variable typing is used to assign a number to a variable. The same variable can be assigned to a string.

This is called variable typing.

24. How can you convert the string of any base to an integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter. The second parameter is the base of the given string.

To convert 4F (or base 16) to integer, the code used will be –

25. Difference between “==” and “===”?

Javascript interview questions for experienced, 26. what would be the result of 3+2+”7″.

Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

27. How to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the navigator. Platform string (property) should be used.

28. What do you mean by NULL in Javascript?

The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number, and no array object.

29. What is the function of the delete operator?

The delete keyword is used to delete the property as well as its value.

30. What is an undefined value in JavaScript?

Undefined value means the

  • Variable used in the code doesn’t exist
  • Variable is not assigned to any value
  • Property does not exist.

31. What are all the types of Pop up boxes available in JavaScript?

  • Confirm and

32. What is the use of Void (0)?

Void(0) is used to prevent the page from refreshing, and parameter “zero” is passed while calling.

Void(0) is used to call another method without refreshing the page.

33. How can a page be forced to load another page in JavaScript?

The following code has to be inserted to achieve the desired effect:

34. What is the data type of variables in JavaScript?

All variables in JavaScript are object data types.

35. What is the difference between an alert box and a confirmation box?

An alert box displays only one button, which is the OK button.

36. What are escape characters?

Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes, and ampersands. Place backslash before the characters to make it display.

37. What are JavaScript Cookies?

Cookies are the small test files stored in a computer, and they get created when the user visits the websites to store information that they need. Examples could be User Name details and shopping cart information from previous visits.

38. What a pop()method in JavaScript is?

The pop() method is similar to the shift() method, but the difference is that the Shift method works at the array’s start. The pop() method takes the last element off of the given array and returns it. The array on which it is called is then altered.

39. Does JavaScript has concept level scope?

No. JavaScript does not have concept-level scope. The variable declared inside the function has scope inside the function.

40. What are the disadvantages of using innerHTML in JavaScript?

If you use innerHTML in JavaScript, the disadvantage is

  • Content is replaced everywhere
  • We cannot use it like “appending to innerHTML
  • Even if you use +=like “innerHTML = innerHTML + ‘html'” still the old content is replaced by html
  • The entire innerHTML content is re-parsed and builds into elements. Therefore, it’s much slower
  • The innerHTML does not provide validation, and therefore we can potentially insert valid and broken HTML in the document and break it

41. What is break and continue statements?

Break statement exits from the current loop.

Continue statement continues with next statement of the loop.

42. What are the two basic groups of data types in JavaScript?

  • They are as—Primitive
  • Reference types

Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

43. How can generic objects be created?

Generic objects can be created as:

44. What is the use of a type of operator?

‘Typeof’ is an operator used to return a string description of the type of a variable.

45. Which keywords are used to handle exceptions?

Try… Catch—finally is used to handle exceptions in the JavaScript

46. Which keyword is used to print the text on the screen?

Document. Write (“Welcome”) is used to print the text–Welcome on the screen.

47. What is the use of the blur function?

Blur function is used to remove the focus from the specified object.

48. What is variable typing?

Variable typing assigns a number to a variable and then assigns a string to the same variable. An example is as follows:

49. How to find an operating system in the client machine using JavaScript?

The ‘ Navigator. the app version is used to find the operating system’s name in the client machine.

50. What are the different types of errors in JavaScript?

There are three types of errors:

  • Load time errors : Errors that come up when loading a web page, like improper syntax errors, are known as Load time errors and generate the errors dynamically.
  • Runtime errors : Errors that come due to misuse of the command inside the HTML language.
  • Logical errors : These are the errors that occur due to the bad logic performed on a function with a different operation.

JavaScript Interview Questions for 5 Years Experience

51. what is the use of the push method in javascript.

The push method is used to add or append one or more elements to an Array end. Using this method, we can append multiple elements by passing multiple arguments.

52. What is the unshift method in JavaScript?

Unshift method is like the push method, which works at the beginning of the array . This method is used to prepend one or more elements to the beginning of the array.

53. What is the difference between JavaScript and Jscript?

Both are almost similar. Netscape and Jscript develop JavaScript was developed by Microsoft.

54. How are object properties assigned?

Properties are assigned to objects in the following way –

55. What is the ‘Strict Mode in JavaScript, and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict Mode, JavaScript shows errors for a piece of code, which did not show an error before, but might be problematic and potentially unsafe. Strict Mode also solves some mistakes that hamper the JavaScript engines from working efficiently.

Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:

56. What is the way to get the status of a CheckBox?

The status can be acquired as follows –

If the CheckBox is checked, this alert will return TRUE.

57. How can the OS of the client machine be detected?

The navigator. appVersion string can be used to detect the operating system on the client machine.

58. What is a window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

59. How closures work in JavaScript?

The closure is a locally declared variable related to a function that stays in memory when it has returned.

For example:

60. How can a value be appended to an array?

A value can be appended to an array in the given manner –

61. What is for-in loop in Javascript?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is –

In each repetition, one property from the object is associated with the variable name. The loop is continued till all the properties of the object are depleted.

62. What are the important properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration –

63. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

64. What is event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of the parent will also work as if it were clicked too.

65. Is JavaScript case sensitive? Give its example.

Yes, JavaScript is case-sensitive. For example, a function parseInt is not the same as the function Parseint.

66. What boolean operators can be used in JavaScript?

The ‘And’ Operator (&&), ‘Or’ Operator (||), and the ‘Not’ Operator (!) can be used in JavaScript.

*Operators are without the parenthesis.

67. How can a particular frame be targeted, from a hyperlink, in JavaScript?

This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute.

68. What is the role of break and continue statements?

The break statement is used to come out of the current loop. In contrast, the continue statement continues the current loop with a new recurrence.

69. Write the point of difference between a web garden and a web farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server. At the same time,web-farm is a larger setup that uses more than one server.

70. How are object properties assigned?

Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document. form.action=”submit”

71. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor), for example, for the opening of a file –

72. How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraphs, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

73. How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a form by the user. An event handler is required to manage the proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes the event’s name and the action taken if the event takes place.

74. What is the role of deferred scripts in JavaScript?

The HTML code’s parsing during page loading is paused by default until the script has not stopped executing. If the server is slow or the script is particularly heavy, then the web page is delayed.

While using Deferred, scripts delays execution of the script till the time the HTML parser is running. This reduces the loading time of web pages, and they get displayed faster.

75. What are the various functional components in JavaScript?

The different functional components in JavaScript are-

  • First-class functions: Functions in JavaScript are utilized as first-class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables, or can also be stored in data structures.
  • Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘every time the main function is invoked.

76. Write about the errors shown in JavaScript?

JavaScript gives a message as if it encounters an error. The recognized errors are –

  • Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. The use of improper syntax encounters these errors and is thus detected while the page is getting loaded.
  • Runtime errors: This is the error that comes up while the program is running. For example, illegal operations cause the division of a number by zero or access a non-existent area of the memory.
  • Logic errors: It is caused by syntactically correct code, which does not fulfill the required task—for example, an infinite loop.

77. What are Screen objects?

Screen objects are used to read the information from the client’s screen. The properties of screen objects are –

  • AvailHeight: Gives the height of the client’s screen
  • AvailWidth: Gives the width of the client’s screen
  • ColorDepth: Gives the bit depth of images on the client’s screen
  • Height: Gives the total height of the client’s screen, including the taskbar
  • Width: Gives the total width of the client’s screen, including the taskbar

78. What is the unshift() method?

This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –

The output is shown below:

79. What is unescape() and escape() functions?

The escape () function is responsible for coding a string to transfer the information from one computer to the other across a network.

For Example:

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:

Output: Hello? How are you!

80. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

Output –

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab

JavaScript Interview Questions for 10+ Years Experience

81. why you should not use innerhtml in javascript.

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML. Therefore, it is easier to insert rogue code in the document and make the web page unstable.

82. What does the following statement declare?

It declares a three-dimensional array.

83. How are JavaScript and ECMA Script related?

ECMA Script is like rules and guidelines, while Javascript is a scripting language used for web development.

84. What is namespacing in JavaScript, and how is it used?

Namespacing is used for grouping the desired functions, variables, etc., under a unique name. It is a name that has been attached to the desired functions, objects, and properties. This improves modularity in the coding and enables code reuse.

85. How can JavaScript codes be hidden from old browsers that do not support JavaScript?

For hiding JavaScript codes from old browsers:

Add “<!–” without the quotes in the code just after the <script> tag.

Add “//–>” without the quotes in the code just before the <script> tag.

Old browsers will now treat this JavaScript code as a long HTML comment. While a browser that supports JavaScript will take the “<!–” and “//–>” as one-line comments.

86. How to use Loop in JavaScript?

Loops are useful when you repeatedly execute the same lines of code a specific number of times or as long as a specific condition is true. Suppose you want to type a ‘Hello’ message 100 times on your webpage. Of course, you will have to copy and paste the same line 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

87. How to use Loops in Javascript?

There are mainly four types of loops in JavaScript.

for/in a loop (explained later)

do…while loop

  • Statement1 is executed first, even before executing the looping code. So, this statement is normally used to assign values to variables used inside the loop.
  • The statement2 is the condition to execute the loop .
  • The statement3 is executed every time after the looping code is executed.

The “while loop” is executed as long as the specified condition is true. Inside the while loop, you should include the statement that will end the loop at some point in time. Otherwise, your loop will never end, and your browser may crash.

The do…while loop is very similar to the while loop. The only difference is that in do…while loop, the block of code gets executed once even before checking the condition.

88. What are the important JavaScript Array Method explain with example?

Javascript array methods.

The Array object has many properties and methods which help developers to handle arrays easily and efficiently. You can get the value of a property by specifying arrayname.property and the output of a method by specifying arrayname.method().

  • length property –> If you want to know the number of elements in an array, you can use the length property.
  • prototype property –> If you want to add new properties and methods, you can use the prototype property.
  • reverse method –> You can reverse the order of items in an array using a reverse method.
  • sort method –> You can sort the items in an array using sort method.
  • pop method –> You can remove the last item of an array using a pop method.
  • shift method –> You can remove the first item of an array using shift method.
  • push method –> You can add a value as the last item of the array.

89. What is OOPS Concept in JavaScript?

Many times, variables or arrays are not sufficient to simulate real-life situations. JavaScript allows you to create objects that act like real-life objects. A student or a home can be an object that has many unique characteristics of its own. You can create properties and methods for your objects to make programming easier. If your object is a student, it will have properties like the first name, last name, id, etc., and methods like calculating rank, change address, etc. If your object is a home, it will have properties like a number of rooms, paint color, location, etc. The methods like to calculate area, change owner, etc.

How to Create an Object

You can create an object like this:

90. What is Loop Though the Properties of an Object?

The for/in a loop is usually used to loop through the properties of an object. You can give any name for the variable, but the object’s name should be the same as an already existing object you need to loop through.

91. What is JavaScript Unit Testing, and what are the challenges in JavaScript Unit Testing?

JavaScript Unit Testing is a testing method in which JavaScript tests code written for a web page or web application module. It is combined with HTML as an inline event handler and executed in the browser to test if all functionalities work fine. These unit tests are then organized in the test suite.

Every suite contains several tests designed to be executed for a separate module. Most importantly, they don’t conflict with any other module and run with fewer dependencies on each other (some critical situations may cause dependencies).

Challenges of JavaScript Unit Testing:

Here are important challenges of JavaScript Unit Testing:

  • Many other languages support unit testing in browsers, in the stable as well as in runtime environment, but JavaScript can not
  • You can understand some system actions with other languages, but this is not the case with JavaScript
  • Some JavaScript are written for a web application that may have multiple dependencies.
  • JavaScript is good to use in combination with HTML and CSS rather than on the web
  • Difficulties with page rendering and DOM manipulation
  • Sometimes you find an error message on your screen regarding ‘Unable to load example.js’ or any other JavaScript error regarding version control. These vulnerabilities come under Unit Testing JavaScript

Solutions of JavaScript Unit Testing:

To avoid such issues, what you can do is;

  • Do not use global variables.
  • Do not manipulate predefined objects.
  • Design core functionalities based on the library.
  • Try to create small pieces of functionalities with lesser dependencies.

92. What are some important JavaScript Unit Testing Frameworks?

Following is a curated list of popular JavaScript Unit Testing Frameworks and Tools that are widely used :

Unit.js: It is known as an open-source assertion library running on browser and Node.js. It is extremely compatible with other JavaScript Unit Testing frameworks like Mocha, Karma, Jasmine, QUnit, Protractor, etc. Provides the full documented API of assertion list.

QUnit: It is used for both client-side and server-side JavaScript Unit Testing. This Free JavaScript testing framework is used for jQuery projects. It follows Common JS unit testing Specification for unit testing in JavaScript. It supports the Node Long-term Support Schedule.

Jasmine: Jasmine is the behavior-driven development framework to unit test JavaScript. It is used for testing both synchronous and asynchronous JavaScript codes. It does not require DOM and comes with an easy syntax that can be written for any test.

Karma: Karma is an open-source productive testing environment. Easy workflow control running on the command line. Offers the freedom to write the tests with Jasmine, Mocha, and QUnit. You can run the test on real devices with easy debugging.

Mocha: Mocha runs on Node.js and in the browser. Mocha performs asynchronous testing more simply. Provides accuracy and flexibility in reporting. Provides tremendous support of rich features such as test-specific timeouts, JavaScript APIs.

Jest: Facebook uses jest so far to test all the JavaScript code. It provides the ‘zero-configuration testing experience. Supports independent and non-interrupting running tests without any conflict. Do not require any other setup configuration and libraries.

AVA: AVA is a simple JavaScript Unit Testing Framework. Tests are being run in parallel and serially. Parallel tests run without interrupting each other. This testing framework supports asynchronous testing as well. AVA uses subprocesses to run the unit test JavaScript.

93. What is QuickSort Algorithm in JavaScript?

Quick Sort algorithm follows Divide and Conquer approach. It divides elements into smaller parts based on some conditions and performing the sort of operations on those divided smaller parts.

Quick Sort algorithm is one of the most used and popular algorithms in any programming language. If you are a JavaScript developer, you might have heard of sort() which is already available in JavaScript. Then, you might have been thinking about what the need for this Quick Sort algorithm is. To understand this, first, we need what is sorting and what is the default sorting in JavaScript.

Quicksort follows the Divide-and-Conquer algorithm. It divides elements into smaller parts based on some conditions and performs the sort operations on those divided smaller parts. Hence, it works well for large datasets. So, here are the steps of how Quicksort works in simple words.

  • First, select an element that is to be called the pivot element.
  • Next, compare all array elements with the selected pivot element and arrange them so that elements less than the pivot element are left. Greater than pivot is to its right.
  • Finally, perform the same operations on the left and right side elements to the pivot element.

So, that is the basic outline of Quicksort. Here are the steps which need to be followed one by one to perform Quicksort.

94.How does QuickSort Work

Step 1) First, find the “pivot” element in the array.

Step 2) Start the left pointer at the first element of the array.

Step 3) Start the right pointer at the last element of the array.

Step 4) Compare the element pointing with the left pointer, and if it is less than the pivot element, then move the left pointer to the right (add 1 to the left index). Continue this until the left side element is greater than or equal to the pivot element.

Step 5) Compare the element pointing with the right pointer. If it is greater than the pivot element, move the right pointer to the left (subtract 1 to the right index). Continue this until the right-side element is less than or equal to the pivot element.

Step 6) Check if the left pointer is less than or equal to a right pointer, then saw the elements in these pointers’ locations.

Step 7) Increment the left pointer and decrement the right pointer.

Step 8) If the left pointer index is still less than the right pointer’s index, repeat the process; else, return the left pointer’s index.

QuickSort Work

So, let us see these steps with an example. Let us consider an array of elements which we need to sort is [5,3,7,6,2,9].

Here are the steps to perform Quick sort that is being shown with an example [5,3,7,6,2,9].

STEP 1) Determine pivot as a middle element. So, 7 is the pivot element.

STEP 2) Start left and right pointers as first and last elements of the array, respectively. The left pointer points to 5 at index 0, and the right pointer points to 9 at index 5.

STEP 3) Compare the left pointer element with the pivot element, since 5 < 6 shift left pointer to the right to index 1.

STEP 4) Now, still 3 <6, so shift the left pointer to one more index to the right. Now 7 > 6 stops incrementing the left pointer, and now the left pointer is index 2.

STEP 5) Now, compare the value at the right pointer with the pivot element. Since 9 > 6, move the right pointer to the left. Now, as 2 < 6, stop moving the right pointer.

STEP 6) Swap both values present at left and right pointers with each other.

STEP 7) Move both pointers one more step.

STEP 8) Since 6 = 6, move pointers to one more step and stop as the left pointer crosses the right pointer and returns the left pointer’s index.

Here, based on the above approach, we need to write code for swapping elements and partitioning the array as mentioned in the above steps.

95. What is DOM in JavaScript?

JavaScript can access all the elements in a web page using the Document Object Model (DOM). The web browser creates a DOM of the webpage when the page is loaded.

96. How to use DOM and Events?

Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes, change the existing elements and attributes and even remove existing elements and attributes. JavaScript can also react to existing events and create new events in the page.

  • getElementById, innerHTML Example
  • getElementById: To access elements and attributes whose id is set.
  • innerHTML: To access the content of an element.

2.getElementsByTagName Example

getElementsByTagName: To access elements and attributes using tag name. This method will return an array of all the items with the same tag name.

Event handler Example

  • createElement: To create new element
  • removeChild: Remove an element
  • you can add an event handler to a particular element like this

97. What is External JavaScript?

You plan to display the current date and time on all your web pages. Suppose you wrote the code and copied it in to all your web pages (say 100). But later, you want to change the format in which the date or time is displayed. In this case, you will have to make changes to all the 100 web pages. This will be a very time-consuming and difficult task.

So, save the JavaScript code in a new file with the extension .js. Then, add a line of code in all your web pages to point to your .js file like this:

Note: It is assumed that the .js file and all your web pages are in the same folder. If the external.js file is in a different folder, you need to specify your file’s full path in the src attribute.

98. When to Use Internal and External JavaScript Code?

Suppose you have only a few lines of code that is specific to a particular webpage. In that case, it is better to keep your JavaScript code internal within your HTML document.

On the other hand, if your JavaScript code is used in many web pages, you should consider keeping your code in a separate file. If you wish to make some changes to your code, you have to change only one file, making code maintenance easy. If your code is too long, it is better to keep it in a separate file. This helps in easy debugging.

99. What are Cookies in JavaScript?

A cookie is a piece of data stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it every time you try to login? If yes, then you are using cookies. Cookies are saved as key/value pairs.

Javascript Set-Cookie:

You can create cookies using document. cookie property like this.

You can even add an expiry date to your Cookie to remove the particular Cookie from the computer on the specified date. The expiry date should be set in the UTC/GMT format. If you do not set the expiry date, the cookie will be removed when the user closes the browser.

You can also set the domain and path to specify which domain and to which directories in the specific domain the Cookie belongs to. By default, a cookie belongs to the page that sets the Cookie.

//create a cookie with a domain to the current page and a path to the entire domain.

JavaScript get Cookie

You can access the Cookie like this, which will return all the cookies saved for the current domain.

JavaScript Delete Cookie

To delete a cookie, you just need to set the cookie’s value to empty and set the value of expires to a passed date.

100. Give an example of JavaScript Multiplication Table

Here, are example of simple multiplication table asking the user the number of rows and columns he wants.

101. Explain Popup Message using event with example

Display a simple message “Welcome!!!” on your demo webpage and when the user hovers over the message, a popup should be displayed with a message “Welcome to my WebPage!!!”.

These interview questions will also help in your viva(orals)

  • Execute JavaScript Online
  • QuickSort Algorithm in JavaScript
  • 15 Best FREE JavaScript Certification Courses Online (2024)
  • Java vs JavaScript – Difference Between Them
  • Difference Between =, ==, and === in JavaScript [Examples]
  • 13 BEST JavaScript Books for Beginners (2024 Update)
  • 19 Best FREE JavaScript IDE & Editor (2024 Update)
  • JavaScript String Format: Methods with EXAMPLES
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements

JavaScript Syntax

  • JavaScript Output

JavaScript Comments

Js variables & datatypes.

  • Variables and Datatypes in JavaScript
  • Global and Local variables in JavaScript
  • JavaScript Let
  • JavaScript Const
  • JavaScript var

JS Operators

Javascript operators.

  • Operator precedence in JavaScript
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript Bitwise Operators
  • JavaScript Ternary Operator
  • JavaScript Comma Operator
  • JavaScript Unary Operators
  • JavaScript Relational operators
  • JavaScript String Operators
  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions

JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs.

JavaScript syntax refers to the set of rules that determines how JavaScript programs are constructed:

JavaScript Values

There are two types of values defined in JavaScript Syntax:

  • Fixed Values: These are known as the literals.
  • Variable values: These are called variables

These are the features of JavaScript which have some predefined syntax:

Table of Content

JavaScript Literals

Javascript variables, javascript expressions, javascript keywords, javascript data types, javascript functions, javascript identifiers.

Syntax Rules for the JavaScript fixed values are:

  • JavaScript Numbers can be written with or without decimals.
  • Javascript Strings are text that can be written in single or double quotes.

A JavaScript variable is the simple name of the storage location where data is stored. There are two types of variables in JavaScript which are listed below: 

  • Local variables: Declare a variable inside of a block or function.
  • Global variables: Declare a variable outside function or with a window object.

Example:  This example shows the use of JavaScript variables.

Output:  

JavaScript operators are symbols that are used to compute the value or in other words, we can perform operations on operands. Arithmetic operators ( +, -, *, / ) are used to compute the value, and Assignment operators ( =, +=, %= ) are used to assign the values to variables.

Example: This example shows the use of javascript operators.

Javascript Expression is the combination of values, operators, and variables. It is used to compute the values.

Example: This example shows a JavaScript expression.

The keywords are the reserved words that have special meanings in JavaScript. 

The comments are ignored by the JavaScript compiler. It increases the readability of code. It adds suggestions, Information, and warning of code. Anything written after double slashes // (single-line comment) or between /* and */ (multi-line comment) is treated as a comment and ignored by the JavaScript compiler.

Example: This example shows the use of javascript comments.

JavaScript provides different datatypes to hold different values on variables. JavaScript is a dynamic programming language, which means do not need to specify the type of variable. There are two types of data types in JavaScript. 

  • Primitive data type
  • Non-primitive (reference) data type

JavaScript functions are the blocks of code used to perform some particular operations. JavaScript function is executed when something calls it. It calls many times so the function is reusable.

Syntax:  

The JavaScript function can contain zero or more arguments.

Example:  This example shows the use of Javascript functions.

JavaScript Identifiers are names used to name variables and keywords and functions.

A identifier must begin with:

  • A letter(A-Z or a-z)
  • A dollar sign($)
  • A underscore(_)

Note: Numbers are not allowed as a first character in JavaScript Identifiers.

JavaScript Case Sensitive

JavaScript Identifiers are case-sensitive.

Example: Both the variables firstName and firstname are different from each other.

JavaScript Camel Case

In JavaScript Camel case is preferred to name a identifier.

JavaScript Character Set

A unicode character set is used in JavaScript. A unicode covers the characters, punctuations and symbols.

We have a complete article on character sets. Click here to read Charsets article.

Please Login to comment...

Similar reads.

  • javascript-basics
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6

JavaScript Arrow Function

  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()

JavaScript CallBack Function

  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure

JavaScript this

  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

  • Javascript Function call()
  • Javascript Function apply()
  • JavaScript Constructor Function

JavaScript Closures

JavaScript Function and Function Expressions

A function is an independent block of code that performs a specific task, while a function expression is a way to store functions in variables.

Here's a quick example of function and function expression. You can read the rest of the tutorial for more.

Here, we created the greet() function and used the displayPI variable to create a function expression. Then, we called the functions by using their names followed by parentheses () i.e. greet() and displayPI() .

  • Create a JavaScript Function

We can create a function in JavaScript using the function keyword:

Create a JavaScript Function

Here, we have created a simple function named greet() that prints Hello World! on the screen.

Our function contains the following parts:

  • Function Keyword - The function keyword is used to create the function.
  • Function Name - The name of the function is greet , followed by parentheses () .
  • Function Body - The code that is executed when we call the function. In our case, it is console.log("Hello World!");

Frequently Asked Questions

Suppose you need to write a program to draw a circle and color it. You can create two functions to solve this problem:

  • A function to draw the circle.
  • A function to color the circle.

From this example, we can see that functions provide the following benefits:

  • Reusable Code : Since functions are independent blocks of code, you can declare a function once and use it multiple times. For example, once you create a function to draw a circle, you can use it whenever you need to draw a circle.
  • Organized Code: Dividing small tasks into different functions makes our code easy to organize.
  • Readability: Functions increase readability by reducing redundancy and improving the structure of our code.
  • Call a Function

Previously, we declared a function named greet() :

If we run the above code, we won't get any output. But why?

It's because creating a function doesn't mean we are executing the code inside it. In other words, the function is ready and available for us to execute whenever we choose.

And if we want to use the function, we need to call it.

Function Call

As you can see, we call a function by writing the function name ( greet ) followed by parentheses () .

  • Example 1: JavaScript Function Call

In the above example, we created a function named greet() . Here's how the control of the program flows:

Working of a Function in JavaScript

  • When the greet() function is called, the program's control transfers to the function definition.
  • All the code inside the function is executed ( Hello World! is printed).
  • The program control then jumps to the next statement after the function call ( Outside function is printed).
  • JavaScript Function Arguments

Arguments are values you pass to the function when you call it.

In the above example, we passed "John" as an argument to the greet() function.

Pass Argument to the Function

Notice the name variable declared inside parentheses:

Here, name is a function parameter , which acts as a placeholder to store the function argument.

In other words, the argument "John" is stored in the name parameter.

Remember: A function argument is the value we pass to the function, while a function parameter is a placeholder that stores the argument passed to the function.

Pass Different Arguments to the Function

We can pass different arguments in each call, making the function re-usable and dynamic.

  • Example 2: JavaScript Function to Add Two Numbers

We can also pass multiple arguments to a single function. For example,

In the above example, we have created a function named addNumbers() with two parameters: num1 and num2 . Here,

  • num1 takes the value of the first argument, 5 .
  • num2 takes the value of the second argument, 4 .

The function then adds the values of num1 and num2 and the result is printed as output.

JavaScript Function Argument

  • The return Statement

We can return a value from a JavaScript function using the return statement.

In the above example, we have created a function named findSquare() . The function accepts a number and returns the square of the number.

In our case, we passed 3 as an argument to the function. So, the function returns the square of 3 , which is 9 , to the function call.

We then stored this return value in the square variable and printed it.

Working of JavaScript Functions

  • The return Statement Terminates the Function

Any code written in the function after the return statement is not executed. For example,

In this example, the display() function doesn't execute the second console.log() statement inside it.

This is because the function execution stops at the return statement. So, the following code is never reached:

This is what actually happens:

  • First, the function prints This will be executed. to the screen.
  • Then, it returns the string Returning from function. to the function call.
  • Finally, the function terminates its execution.
  • The return value is then stored in the message variable and printed.

Function Terminates After return

  • JavaScript Library Functions

JavaScript provides some built-in functions that can be directly used in our program. We don't need to create these functions; we just need to call them.

Some common JavaScript library functions are:

Library Function Description
Prints the string inside the quotation marks.
Returns the square root of a number.
Returns the power of a number.
Returns the converted to uppercase.
Returns the string converted to lowercase.

To learn more about library functions, visit JavaScript Library Functions .

Example 3: JavaScript Library Function

  • Math.sqrt(4) calculates the square root of 4 , resulting in 2 .
  • Math.pow(2, 3) computes 2 ^ 3 ( 2 raised to the power of 3 ), which is 8 .
  • band.toUpperCase() converts the string in the band variable to uppercase, resulting in IRON MAIDEN .
  • Function Expressions

In JavaScript, a function expression is a way to store functions in variables. For example,

In this example, the function that calculates the square of a number is assigned to the square variable.

We then used this variable to call the function expression using the code square(5) , where 5 is the function argument.

Note: Like with functions, we need to use parentheses () with the variable name to call a function expression.

Table of Contents

  • Introduction

Sorry about that.

Related Tutorials

JavaScript Tutorial

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Guidelines for writing JavaScript code examples

The following guidelines cover writing JavaScript example code for MDN Web Docs. This article is a list of rules for writing concise examples that will be understandable by as many people as possible.

General guidelines for JavaScript code examples

This section explains the general guidelines to keep in mind while writing JavaScript code examples. The later sections will cover more specific details.

Choosing a format

Opinions on correct indentation, whitespace, and line lengths have always been controversial. Discussions on these topics are a distraction from creating and maintaining content.

On MDN Web Docs, we use Prettier as a code formatter to keep the code style consistent (and to avoid off-topic discussions). You can consult our configuration file to learn about the current rules, and read the Prettier documentation .

Prettier formats all the code and keeps the style consistent. Nevertheless, there are a few additional rules that you need to follow.

Using modern JavaScript features

You can use new features once every major browser — Chrome, Edge, Firefox, and Safari — supports them.

Array creation

For creating arrays, use literals and not constructors.

Create arrays like this:

Don't do this while creating arrays:

Item addition

When adding items to an array, use push() and not direct assignment. Consider the following array:

Add items to the array like this:

Don't add items to the array like this:

Asynchronous methods

Writing asynchronous code improves performance and should be used when possible. In particular, you can use:

  • async / await

When both techniques are possible, we prefer using the simpler async / await syntax. Unfortunately, you can't use await at the top level unless you are in an ECMAScript module. CommonJS modules used by Node.js are not ES modules. If your example is intended to be used everywhere, avoid top-level await .

Comments are critical to writing good code examples. They clarify the intent of the code and help developers understand it. Pay special attention to them.

  • If the purpose or logic of the code isn't obvious, add a comment with your intention, as shown below: js let total = 0 ; // Calculate the sum of the four first elements of arr for ( let i = 0 ; i < 4 ; i ++ ) { total += arr [ i ] ; } On the other hand, restating the code in prose is not a good use of comments: js let total = 0 ; // For loop from 1 to 4 for ( let i = 0 ; i < 4 ; i ++ ) { // Add value to the total total += arr [ i ] ; }
  • Comments are also not necessary when functions have explicit names that describe what they're doing. Write: js closeConnection ( ) ; Don't write: js closeConnection ( ) ; // Closing the connection

Use single-line comments

Single-line comments are marked with // , as opposed to block comments enclosed between /* … */ .

In general, use single-line comments to comment code. Writers must mark each line of the comment with // , so that it's easier to notice commented-out code visually. In addition, this convention allows to comment out sections of code using /* … */ while debugging.

  • Leave a space between the slashes and the comment. Start with a capital letter, like a sentence, but don't end the comment with a period. js // This is a well-written single-line comment
  • If a comment doesn't start immediately after a new indentation level, add an empty line and then add the comment. It will create a code block, making it obvious what the comment refers to. Also, put your comments on separate lines preceding the code they are referring to. This is shown in the following example: js function checkout ( goodsPrice , shipmentPrice , taxes ) { // Calculate the total price const total = goodsPrice + shipmentPrice + taxes ; // Create and append a new paragraph to the document const para = document . createElement ( "p" ) ; para . textContent = ` Total price is ${ total } ` ; document . body . appendChild ( para ) ; }

Output of logs

  • In code intended to run in a production environment, you rarely need to comment when you log some data. In code examples, we often use console.log() , console.error() , or similar functions to output important values. To help the reader understand what will happen without running the code, you can put a comment after the function with the log that will be produced. Write: js function exampleFunc ( fruitBasket ) { console . log ( fruitBasket ) ; // ['banana', 'mango', 'orange'] } Don't write: js function exampleFunc ( fruitBasket ) { // Logs: ['banana', 'mango', 'orange'] console . log ( fruitBasket ) ; }
  • In case the line becomes too long, put the comment after the function, like this: js function exampleFunc ( fruitBasket ) { console . log ( fruitBasket ) ; // ['banana', 'mango', 'orange', 'apple', 'pear', 'durian', 'lemon'] }

Multi-line comments

Short comments are usually better, so try to keep them in one line of 60–80 characters. If this is not possible, use // at the beginning of each line:

Don't use /* … */ :

Use comments to mark ellipsis

Skipping redundant code using ellipses (…) is necessary to keep examples short. Still, writers should do it thoughtfully as developers frequently copy & paste examples into their code, and all of our code samples should be valid JavaScript.

In JavaScript, you should put the ellipses ( … ) in a comment. When possible, indicate what action somebody reusing this snippet is expected to add.

Using a comment for the ellipses (…) is more explicit, preventing errors when a developer copies and pastes a sample code. Write:

Don't use ellipses (…) like this:

Comment out parameters

When writing code, you usually omit parameters you don't need. But in some code examples, you want to demonstrate that you didn't use some possible parameters.

To do so, use /* … */ in the parameter list. This is an exception to the rule to only use single-line comments ( // ).

Function names

For function names, use camel case , starting with a lowercase character. Use concise, human-readable, and semantic names where appropriate.

The following is a correct example of a function name:

Don't use function names like these:

Function declarations

  • Where possible, use the function declaration over function expressions to define functions. Here is the recommended way to declare a function: js function sum ( a , b ) { return a + b ; } This is not a good way to define a function: js let sum = function ( a , b ) { return a + b ; } ;
  • When using anonymous functions as a callback (a function passed to another method invocation), if you do not need to access this , use an arrow function to make the code shorter and cleaner. Here is the recommended way: js const array1 = [ 1 , 2 , 3 , 4 ] ; const sum = array1 . reduce ( ( a , b ) => a + b ) ; Instead of this: js const array1 = [ 1 , 2 , 3 , 4 ] ; const sum = array1 . reduce ( function ( a , b ) { return a + b ; } ) ;
  • Consider avoiding using arrow function to assign a function to an identifier. In particular, don't use arrow functions for methods. Use function declarations with the keyword function : js function x ( ) { // … } Don't do: js const x = ( ) => { // … } ;
  • When using arrow functions, use implicit return (also known as expression body ) when possible: js arr . map ( ( e ) => e . id ) ; And not: js arr . map ( ( e ) => { return e . id ; } ) ;

Loops and conditional statements

Loop initialization.

When loops are required, choose the appropriate one from for(;;) , for...of , while , etc.

  • When iterating through all collection elements, avoid using the classical for (;;) loop; prefer for...of or forEach() . Note that if you are using a collection that is not an Array , you have to check that for...of is actually supported (it requires the variable to be iterable), or that the forEach() method is actually present. Use for...of : js const dogs = [ "Rex" , "Lassie" ] ; for ( const dog of dogs ) { console . log ( dog ) ; } Or forEach() : js const dogs = [ "Rex" , "Lassie" ] ; dogs . forEach ( ( dog ) => { console . log ( dog ) ; } ) ; Do not use for (;;) — not only do you have to add an extra index, i , but you also have to track the length of the array. This can be error-prone for beginners. js const dogs = [ "Rex" , "Lassie" ] ; for ( let i = 0 ; i < dogs . length ; i ++ ) { console . log ( dogs [ i ] ) ; }
  • Make sure that you define the initializer properly by using the const keyword for for...of or let for the other loops. Don't omit it. These are correct examples: js const cats = [ "Athena" , "Luna" ] ; for ( const cat of cats ) { console . log ( cat ) ; } for ( let i = 0 ; i < 4 ; i ++ ) { result += arr [ i ] ; } The example below does not follow the recommended guidelines for the initialization (it implicitly creates a global variable and will fail in strict mode): js const cats = [ "Athena" , "Luna" ] ; for ( i of cats ) { console . log ( i ) ; }
  • When you need to access both the value and the index, you can use .forEach() instead of for (;;) . Write: js const gerbils = [ "Zoé" , "Chloé" ] ; gerbils . forEach ( ( gerbil , i ) => { console . log ( ` Gerbil # ${ i } : ${ gerbil } ` ) ; } ) ; Do not write: js const gerbils = [ "Zoé" , "Chloé" ] ; for ( let i = 0 ; i < gerbils . length ; i ++ ) { console . log ( ` Gerbil # ${ i } : ${ gerbils [ i ] } ` ) ; }

Warning: Never use for...in with arrays and strings.

Note: Consider not using a for loop at all. If you are using an Array (or a String for some operations), consider using more semantic iteration methods instead, like map() , every() , findIndex() , find() , includes() , and many more.

Control statements

There is one notable case to keep in mind for the if...else control statements. If the if statement ends with a return , do not add an else statement.

Continue right after the if statement. Write:

Do not write:

Use braces with control flow statements and loops

While control flow statements like if , for , and while don't require the use of braces when the content is made of one single statement, you should always use braces. Write:

Don't write:

This prevent forgetting to add the braces when adding more statements.

Switch statements

Switch statements can be a little tricky.

  • Don't add a break statement after a return statement in a specific case. Instead, write return statements like this: js switch ( species ) { case "chicken" : return farm . shed ; case "horse" : return corral . entry ; default : return "" ; } If you add a break statement, it will be unreachable. Do not write: js switch ( species ) { case "chicken" : return farm . shed ; break ; case "horse" : return corral . entry ; break ; default : return "" ; }
  • Use default as the last case, and don't end it with a break statement. If you need to do it differently, add a comment explaining why.
  • Remember that when you declare a local variable for a case, you need to use braces to define a scope: js switch ( fruits ) { case "Orange" : { const slice = fruit . slice ( ) ; eat ( slice ) ; break ; } case "Apple" : { const core = fruit . extractCore ( ) ; recycle ( core ) ; break ; } }

Error handling

  • If certain states of your program throw uncaught errors, they will halt execution and potentially reduce the usefulness of the example. You should, therefore, catch errors using a try...catch block, as shown below: js try { console . log ( getResult ( ) ) ; } catch ( e ) { console . error ( e ) ; }
  • When you don't need the parameter of the catch statement, omit it: js try { console . log ( getResult ( ) ) ; } catch { console . error ( "An error happened!" ) ; }

Note: Keep in mind that only recoverable errors should be caught and handled. All non-recoverable errors should be let through and bubble up the call stack.

Object names

  • When defining a class, use PascalCase (starting with a capital letter) for the class name and camelCase (starting with a lowercase letter) for the object property and method names.
  • When defining an object instance, either a literal or via a constructor, use camelCase , starting with lower-case character, for the instance name. For example: js const hanSolo = new Person ( "Han Solo" , 25 , "he/him" ) ; const luke = { name : "Luke Skywalker" , age : 25 , pronouns : "he/him" , } ;

Object creation

For creating general objects (i.e., when classes are not involved), use literals and not constructors.

For example, do this:

Don't create a general object like this:

Object classes

  • Use ES class syntax for objects, not old-style constructors. For example, this is the recommended way: js class Person { constructor ( name , age , pronouns ) { this . name = name ; this . age = age ; this . pronouns = pronouns ; } greeting ( ) { console . log ( ` Hi! I'm ${ this . name } ` ) ; } }
  • Use extends for inheritance: js class Teacher extends Person { // … }

To define methods, use the method definition syntax:

Instead of:

Object properties

  • The Object.prototype.hasOwnProperty() method has been deprecated in favor of Object.hasOwn() .
  • When possible, use the shorthand avoiding the duplication of the property identifier. Write: js function createObject ( name , age ) { return { name , age } ; } Don't write: js function createObject ( name , age ) { return { name : name , age : age } ; }

This section lists our recommendations of which operators to use and when.

Conditional operators

When you want to store to a variable a literal value depending on a condition, use a conditional (ternary) operator instead of an if...else statement. This rule also applies when returning a value. Write:

The conditional operator is helpful when creating strings to log information. In such cases, using a regular if...else statement leads to long blocks of code for a side operation like logging, obfuscating the central point of the example.

Strict equality operator

Prefer the strict equality (triple equals) and inequality operators over the loose equality (double equals) and inequality operators.

Use the strict equality and inequality operators like this:

Don't use the loose equality and inequality operators, as shown below:

If you need to use == or != , remember that == null is the only acceptable case. As TypeScript will fail on all other cases, we don't want to have them in our example code. Consider adding a comment to explain why you need it.

Shortcuts for boolean tests

Prefer shortcuts for boolean tests. For example, use if (x) and if (!x) , not if (x === true) and if (x === false) , unless different kinds of truthy or falsy values are handled differently.

String literals can be enclosed within single quotes, as in 'A string' , or within double quotes, as in "A string" . Don't worry about which one to use; Prettier keeps it consistent.

Template literals

For inserting values into strings, use template literals .

  • Here is an example of the recommended way to use template literals. Their use prevents a lot of spacing errors. js const name = "Shilpa" ; console . log ( ` Hi! I'm ${ name } ! ` ) ; Don't concatenate strings like this: js const name = "Shilpa" ; console . log ( "Hi! I'm" + name + "!" ) ; // Hi! I'mShilpa!
  • Don't overuse template literals. If there are no substitutions, use a normal string literal instead.

Variable names

Good variable names are essential to understanding code.

  • Use short identifiers, and avoid non-common abbreviations. Good variable names are usually between 3 to 10-character long, but as a hint only. For example, accelerometer is more descriptive than abbreviating to acclmtr for the sake of character length.
  • Try to use real-world relevant examples where each variable has clear semantics. Only fall back to placeholder names like foo and bar when the example is simple and contrived.
  • Do not use the Hungarian notation naming convention. Do not prefix the variable name with its type. For example, write bought = car.buyer !== null rather than bBought = oCar.sBuyer != null or name = "John Doe" instead of sName = "John Doe" .
  • For collections, avoid adding the type such as list, array, queue in the name. Use the content name in the plural form. For example, for an array of cars, use cars and not carArray or carList . There may be exceptions, like when you want to show the abstract form of a feature without the context of a particular application.
  • For primitive values, use camelCase , starting with a lowercase character. Do not use _ . Use concise, human-readable, and semantic names where appropriate. For example, use currencyName rather than currency_name .
  • Avoid using articles and possessives. For example, use car instead of myCar or aCar . There may be exceptions, like when describing a feature in general without a practical context.
  • Use variable names as shown here: js const playerScore = 0 ; const speed = distance / time ; Don't name variables like this: js const thisIsaveryLONGVariableThatRecordsPlayerscore345654 = 0 ; const s = d / t ;

Note: The only place where it's allowed not to use human-readable, semantic names is where a very commonly recognized convention exists, such as using i and j for loop iterators.

Variable declarations

When declaring variables and constants, use the let and const keywords, not var . The following examples show what's recommended and what's not on MDN Web Docs:

  • If a variable will not be reassigned, prefer const , like so: js const name = "Shilpa" ; console . log ( name ) ;
  • If you'll change the value of a variable, use let as shown below: js let age = 40 ; age ++ ; console . log ( "Happy birthday!" ) ;
  • The example below uses let where it should be const . The code will work, but we want to avoid this usage in MDN Web Docs code examples. js let name = "Shilpa" ; console . log ( name ) ;
  • The example below uses const for a variable that gets reassigned. The reassignment will throw an error. js const age = 40 ; age ++ ; console . log ( "Happy birthday!" ) ;
  • The example below uses var , polluting the global scope: js var age = 40 ; var name = "Shilpa" ;
  • Declare one variable per line, like so: js let var1 ; let var2 ; let var3 = "Apapou" ; let var4 = var3 ; Do not declare multiple variables in one line, separating them with commas or using chain declaration. Avoid declaring variables like this: js let var1 , var2 ; let var3 = var4 = "Apapou" ; // var4 is implicitly created as a global variable; fails in strict mode

Type coercion

Avoid implicit type coercions. In particular, avoid +val to force a value to a number and "" + val to force it to a string. Use Number() and String() , without new , instead. Write:

Web APIs to avoid

In addition to these JavaScript language features, we recommend a few guidelines related to Web APIs to keep in mind.

Avoid browser prefixes

If all major browsers (Chrome, Edge, Firefox, and Safari) support a feature, don't prefix the feature. Write:

Avoid the added complexity of prefixes. Don't write:

The same rule applies to CSS prefixes.

Avoid deprecated APIs

When a method, a property, or a whole interface is deprecated, do not use it (outside its documentation). Instead, use the modern API.

Here is a non-exhaustive list of Web APIs to avoid and what to replace them with:

  • Use fetch() instead of XHR ( XMLHttpRequest ).
  • Use AudioWorklet instead of ScriptProcessorNode , in the Web Audio API.

Use safe and reliable APIs

  • Do not use Element.innerHTML to insert purely textual content into an element; use Node.textContent instead. The property innerHTML leads to security problems if a developer doesn't control the parameter. The more we as writers avoid using it, the fewer security flaws are created when a developer copies and pastes our code. The example below demonstrates the use of textContent . js const text = "Hello to all you good people" ; const para = document . createElement ( "p" ) ; para . textContent = text ; Don't use innerHTML to insert pure text into DOM nodes. js const text = "Hello to all you good people" ; const para = document . createElement ( "p" ) ; para . innerHTML = text ;
  • The alert() function is unreliable. It doesn't work in live examples on MDN Web Docs that are inside an <iframe> . Moreover, it is modal to the whole window, which is annoying. In static code examples, use console.log() or console.error() . In live examples , avoid console.log() and console.error() because they are not displayed. Use a dedicated UI element.

Use the appropriate log method

  • When logging a message, use console.log() .
  • When logging an error, use console.error() .

JavaScript language reference - browse through our JavaScript reference pages to check out some good, concise, meaningful JavaScript snippets.

MPD Logo

  • Contact Police
  • Annual Reports
  • Closed Circuit TV
  • Community Briefing Videos 2024
  • Community Briefing Videos 2023
  • Community Briefing Videos 2022
  • Community Briefing Videos 2021
  • Community Briefing Videos 2020
  • Community Briefing Videos 2016-2019
  • Crime Cards
  • Crime at a Glance
  • Block 1: Introduction to Policing
  • Block 2: Basic Investigative Skills
  • Block 3: Report Writing
  • Block 4: Introduction to Criminal Law
  • Block 5: Introduction to Crime
  • Block 6: Criminal Offenses I
  • Block 7: Criminal Offenses II
  • Block 8: Criminal Offenses III
  • Block 9: Complex Criminal Offenses I
  • Block 10: Complex Criminal Offenses II
  • Block 11: Serious Criminal Offenses
  • Curriculum Block 12: Traffic I
  • Curriculum Block 13: Traffic II
  • Crime Data at a Glance
  • Adult Arrests
  • Marijuana Arrests
  • MPD Closure/Clearance Rates
  • Hate Crimes
  • Juvenile Arrests
  • Juvenile Shooting Victim Data
  • Litigation Data Reports
  • Robbery and Carjacking Trends
  • ShotSpotter Data
  • Staffing and Attrition Data
  • Traffic Fatalities
  • Use of Force Data
  • Adverse Action Data Sheets
  • Adverse Action Hearing Schedule
  • Open Government and FOIA
  • General Orders
  • Special Orders
  • Standard Operating Procedures
  • Bureau/Division Orders
  • Recovered Property
  • Specialized Reports and Resources
  • Staffing, Attrition and Budget
  • Community Affairs
  • CameraConnect DC
  • Community Engagement Academy
  • Community Outreach
  • MPD Rewards
  • Partnerships With Other Agencies
  • Police Initiatives
  • Protection Orders
  • Special Liaison Division
  • Training Partnerships
  • Unsolved Homicides
  • Victim Assistance
  • Youth Outreach
  • Find Your Police District
  • About the Community
  • District Commander
  • District Roster
  • Download a High-Resolution Map
  • School and Child Safety
  • Campus Safety
  • Boating Safety
  • Business Safety
  • Drug Safety
  • Financial Safety
  • General Safety
  • Fireworks: Some Facts and Safety Tips
  • Halloween Safety
  • Holiday Safety
  • Traffic Safety
  • News Releases
  • Testimonies
  • Biographies
  • Organization
  • Specialized Units
  • Telephone and Contact Directory
  • Translated Documents

2024 NATO Summit Road Closure Maps

From Saturday, July 6, 2024, through Friday, July 12, 2024, there will be numerous impacts to vehicular traffic, pedestrians, and public transportation in the area of the Washington Convention Center, Mellon Auditorium, and The White House. Please plan accordingly and expect delays throughout the week. The following maps provide a visual representation of the areas that are closed. Larger, printeable PDFs are available via links at the bottom of this page.

  • INTERACTIVE MAP:  Road Closures, Parking Restrictions and Vehicle Checkpoints  

NATO Road Closures Convention Center 8.jpg

Adidas

When does pre-season start for the Reds?

IMAGES

  1. Javascript Introduction

    javascript essay

  2. essay.docx

    javascript essay

  3. Fillable Online JS TSM ESSAY COVER SHEET 2018-19.pdf Fax Email Print

    javascript essay

  4. Advantages & Disadvantages of JavaScript Essay Example

    javascript essay

  5. JavaScript-Based AJAX, MVC, and Functional Programming

    javascript essay

  6. JavaScript Assignment Help

    javascript essay

VIDEO

  1. 16. Продвинутый JS

  2. Уроки JavaScript

  3. Основы программирования

  4. Includes VS Some In JavaScript #javascript #javascripttutorial #javascriptlearning #webdevelopment

  5. Основы JavaScript для начинающих за 2 часа

  6. Создай КРУТОЙ проект в портфолио на JavaScript

COMMENTS

  1. What is JavaScript?

    JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.) The three layers build on top of one another nicely.

  2. What is JavaScript? The full-stack programming language

    As its name implies, JavaScript is a scripting language. Traditional languages such as C++ are compiled before they're run into executable binary form, with the compiler checking for errors in ...

  3. Introduction to JavaScript

    JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages. It is well-known for the development of web pages, and many non-browser environments also use it. JavaScript is a weakly typed language (dynamically typed).

  4. A detailed guide on JavaScript Web Development

    A website that engages well with the users stands out among the crowd. In this tutorial, we delved into a detailed discussion of using JavaScript for web development. JavaScript is the most popular and widely-used programming language across the globe. JavaScript has been able to completely change how websites are developed nowadays.

  5. 100 most asked JavaScript Interview Questions and Answers

    110. JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB, and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single ...

  6. JavaScript Articles

    JavaScript Articles. Javascript is a flexible multi-paradigm programming language largely used in the web-development space for both front-end and back-end applications. Whereas HTML and CSS describe the elements on a webpage, code written in JavaScript makes them interactive. A framework such as NodeJS allows back-end code to be written in ...

  7. Mastering JavaScript in 2023: The Comprehensive Guide

    Follow. 5 min read. ·. Nov 13, 2023. --. JavaScript's journey from a simple scripting language to a robust and ubiquitous programming language is a remarkable tale of evolution, adaptation, and ...

  8. PDF Learning JavaScript: A Hands-On Guide to the Fundamentals of Modern

    introduction to JavaScript while also illustrating the context of when and where it should be used." —R. S. Doiel, Senior Software Engineer, USC Web Services "Learni ng JavaScript is a great introduction into modern JavaScript development. From covering the history to its exciting future, Learning JavaScript equips the novice developer

  9. JavaScript Guide

    Meta programming. JavaScript modules. JavaScript Guide. The JavaScript Guide shows you how to use JavaScriptand gives an overview of the language. If you need exhaustive information about a language feature, have a look at the JavaScript reference. This Guide is divided into the following chapters.

  10. JavaScript first steps

    A first splash into JavaScript. Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course on the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step. What went wrong? Troubleshooting JavaScript

  11. The Healing Power of JavaScript

    The Healing Power of JavaScript. For some of us—isolates, happy in the dark—code is therapy, an escape and a path to hope in a troubled world. Illustration: WIRED; Getty Images. A little over ...

  12. Learn Web Development Basics

    As a web developer, the three main languages we use to build websites are HTML, CSS, and JavaScript. JavaScript is the programming language, we use HTML to structure the site, and we use CSS to design and layout the web page. These days, CSS has become more than just a design language, though. You can actually implement animations and smooth ...

  13. The Modern JavaScript Tutorial

    Modern JavaScript Tutorial: simple, but detailed explanations with examples and tasks, including: closures, document and events, object oriented programming and more.

  14. Why Learn JavaScript? A Beginner's Guide

    JavaScript brings the website to life by adding functionality. It's is responsible for elements that the user can interact with, such as drop-down menus, modal windows, and contact forms. It is also used to create things like animations, video players, and interactive maps.

  15. JavaScript Basics

    JavaScript Basics. JavaScript is a versatile, lightweight scripting language widely used in web development. It can be utilized for both client-side and server-side development, making it essential for modern web applications. Known as the scripting language for web pages, JavaScript supports variables, data types, operators, conditional ...

  16. Javascript Essays: Examples, Topics, & Outlines

    JavaScript is an interpreted programming or script language created by Netscape to integrate the functionality of Java with HTML (TechTarget). It is similar in capability to Microsoft's Visual asic, Sun's Tcl, the UNIX-derived Perl, and IM's Rexx. Script languages are easier…. Works Cited Read More.

  17. Java vs. JavaScript: What's the Difference?

    When considering Java versus JavaScript, you'll notice a few key differences. Java is a compiled language, meaning that you write code, then run it through a compiler and create bytecode. The bytecode is then run in a Java Virtual Machine (JVM), which is likely the software you have on your computer. JavaScript is an interpreted language.

  18. Top 100 JavaScript Interview Questions and Answers (2024)

    JavaScript is faster. JavaScript is a client-side language,, and thus it does not need the assistance of the webserver to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server-side language (nodejs). 6.

  19. 25+ JavaScript Coding Interview Questions (SOLVED with CODE)

    console.log(anotherArrayList); // Output ['a', 'b', 'c', 'd', 'e', 'f'] Method 2. arrayList.length = 0; Above code will clear the existing array by setting its length to 0. This way of empty the array also update all the reference variable which pointing to the original array. This way of empty the array is useful when you want to update all ...

  20. JavaScript Syntax

    JavaScript syntax refers to the rules and conventions dictating how code is structured and arranged within the JavaScript programming language. This includes statements, expressions, variables, functions, operators, and control flow constructs. Syntax. console.log("Basic Print method in JavaScript");

  21. JavaScript Function and Function Expressions (with Examples)

    In the above example, we have created a function named addNumbers() with two parameters: num1 and num2. Here, num1 takes the value of the first argument, 5. num2 takes the value of the second argument, 4. The function then adds the values of num1 and num2 and the result is printed as output.

  22. Guidelines for writing JavaScript code examples

    Use the content name in the plural form. For example, for an array of cars, use cars and not carArray or carList. There may be exceptions, like when you want to show the abstract form of a feature without the context of a particular application. For primitive values, use camelCase, starting with a lowercase character.

  23. JavaScript Playground

    Try this online JavaScript Playground playground with instant live preview and console. Easy & Fast. Experiment yourself.

  24. 2024 NATO Summit Road Closure Maps

    From Saturday, July 6, 2024, through Friday, July 12, 2024, there will be numerous impacts to vehicular traffic, pedestrians, and public transportation in the area of the Washington Convention Center, Mellon Auditorium, and The White House. Please plan accordingly and expect delays throughout the week. The following maps provide a visual representation of the areas that are closed.

  25. American Express Unveils Essential® Rewards Credit Card with Generous

    American Express Unveils Essential® Rewards Credit Card with Generous Rewards Designed to Appeal to a New Generation of Aussie Consumers

  26. Can you pass a U.S. citizenship test? Take our civics quiz

    How much do you know about America? In honor of July Fourth, test your knowledge with some of the questions aspiring U.S. citizens must answer to become naturalized.

  27. When will Man Utd return to pre season training for 2024 25 season

    The Reds will report back to Carrington today (Monday 8 July) to undergo the usual tests ahead of our first friendly, which is just one week away.

  28. Oracle Blogs

    This site requires JavaScript to be enabled.