What is Javascript?

What is Javascript?

Welcome to the wtg guide for What is Javascript.

JavaScript (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, most known as the scripting language for Web pages, but used in many non-browser environments as well such as node.js. It is a prototype-based, multi-paradigm scripting language that is dynamic, and supports object-oriented, imperative, and functional programming styles. Javascript is also embedded in a variety of applications created with frameworks such as Electron and Cordova.

Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it.

As a multi-paradigm language, JavaScript supports event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM). However, the language itself does not include any input/output (I/O), such as networking, storage, or graphics facilities, as the host environment (usually a web browser) provides those APIs.

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.

JavaScript is not to be confused with the Java programming language. Java is a trademark or registered trademark of Oracle in the U.S. and other countries.

Creation at Netscape

The Mosaic web browser was released in 1993. As the first browser with a graphical user interface accessible to non-technical people, it played a prominent role in the rapid growth of the nascent World Wide Web. The lead developers of Mosaic then founded the Netscape corporation, which released a more polished browser, Netscape Navigator, in 1994. Navigator quickly became the most used browser.

During these formative years of the Web, web pages could only be static, lacking the capability for dynamic behavior after the page was loaded in the browser. There was a desire in the burgeoning web development scene to remove this limitation, so in 1995, Netscape decided to add a scripting language to Navigator. They pursued two routes to achieve this: collaborating with Sun Microsystems to embed the Java programming language, while also hiring Brendan Eich to embed the Scheme language.

Netscape management soon decided that the best option was for Eich to devise a new language, with syntax similar to Java and less like Scheme or other extant scripting languages. Although the new language and its interpreter implementation were officially called LiveScript when first shipped as part of a Navigator release in September 1995, the name was changed to JavaScript three months later.

The choice of the JavaScript name has caused confusion, sometimes giving the impression that it is a spin-off of Java. Since Java was the hot new programming language at the time, this has been characterized as a marketing ploy by Netscape to give its own new language cachet.

Adoption by Microsoft
Microsoft debuted Internet Explorer in 1995, leading to a browser war with Netscape. On the JavaScript front, Microsoft reverse-engineered the Navigator interpreter to create its own, called JScript.

JScript was first released in 1996, alongside initial support for CSS and extensions to HTML. Each of these implementations was noticeably different from their counterparts in Navigator. These differences made it difficult for developers to make their websites work well in both browsers, leading to widespread use of “best viewed in Netscape” and “best viewed in Internet Explorer” logos for several years.

The rise of JScript

In November 1996, Netscape submitted JavaScript to ECMA International, as the starting point for a standard specification that all browser vendors could conform to. This led to the official release of the first ECMAScript language specification in June 1997.

The standards process continued for a few years, with the release of ECMAScript 2 in June 1998 and ECMAScript 3 in December 1999. Work on ECMAScript 4 began in 2000.

Meanwhile, Microsoft gained an increasingly dominant position in the browser market. By the early 2000s, Internet Explorer’s market share reached 95%. This meant that JScript became the de facto standard for client-side scripting on the Web.

Microsoft initially participated in the standards process and implemented some proposals in its JScript language, but eventually it stopped collaborating on ECMA work. Thus ECMAScript 4 was mothballed.

Growth and standardization

During the period of Internet Explorer dominance in the early 2000s, client-side scripting was stagnant. This started to change in 2004, when the successor of Netscape, Mozilla, released the Firefox browser. Firefox was well-received by many, taking significant market share from Internet Explorer.

In 2005, Mozilla joined ECMA International, and work started on the ECMAScript for XML (E4X) standard. This led to Mozilla working jointly with Macromedia (later acquired by Adobe Systems), who were implementing E4X in their ActionScript 3 language, which was based on an ECMAScript 4 draft. The goal became standardizing ActionScript 3 as the new ECMAScript 4. To this end, Adobe Systems released the Tamarin implementation as an open source project. However, Tamarin and ActionScript 3 were too different from established client-side scripting, and without cooperation from Microsoft, ECMAScript 4 never reached fruition.

Meanwhile, very important developments were occurring in open source communities not affiliated with ECMA work. In 2005, Jesse James Garrett released a white paper in which he coined the term Ajax and described a set of technologies, of which JavaScript was the backbone, to create web applications where data can be loaded in the background, avoiding the need for full page reloads. This sparked a renaissance period of JavaScript, spearheaded by open source libraries and the communities that formed around them. Many new libraries were created, including jQuery, Prototype, Dojo Toolkit, and MooTools.

Google debuted its Chrome browser in 2008, with the V8 JavaScript engine that was the first to use just-in-time compilation, significantly improving execution times. Other browser vendors needed to overhaul their engines to compete.

In July 2008, these disparate parties came together for a conference in Oslo. This led to the eventual agreement in early 2009 to combine all relevant work and drive the language forward. The result was the ECMAScript 5 standard, released in December 2009.

Reaching maturity

Ambitious work on the language continued for several years, culminating in an extensive collection of additions and refinements being formalized with the publication of ECMAScript 6 in 2015.

From 2016 to 2019, a new version of the ECMAScript standard was published each year, but the scope of changes was much smaller than the 5th or 6th editions. Thus JavaScript can now be considered a mature language that has largely settled down.

The current JavaScript ecosystem has many libraries and frameworks, established programming practices, and increased usage of JavaScript outside of web browsers. Plus, with the rise of single-page applications and other JavaScript-heavy websites, a number of transpilers have been created to aid the development process.


“JavaScript” is a trademark of Oracle Corporation in the United States. It is used under license for technology invented and implemented by Netscape Communications and other parties.

Website client-side usage

JavaScript is the dominant client-side scripting language of the Web, with 95% of websites using it for this purpose. Scripts are embedded in or included from HTML documents and interact with the DOM. All major web browsers have a built-in JavaScript engine that executes the code on the user’s device.

Examples of scripted behavior

  • Loading new page content without reloading the page. For example, social media websites use Ajax so that users can post new messages without leaving the page.
  • Animation of page elements, such as fading them in and out, resizing, and moving them.
  • Interactive content, such as games and video.
  • Validating input values of a web form to make sure that they are acceptable before being submitted to the server.
  • Transmitting information about the user’s behavior for analytics, ad tracking, and personalization.

Libraries and frameworks

The majority of websites use a third-party JavaScript library or web application framework as part of their client-side page scripting.

jQuery is the most popular library, used by over 70% of websites.

The Angular framework was created by Google for its web services; it is now open source and used by other websites. Likewise, Facebook created the React framework for its website and later released it as open source; other sites, including Twitter, now use it. There are other open source frameworks in use, such as Backbone.js and Vue.js.

java script
javascript tutorial
java vs javascript
javascript function
what is javascript
eloquent javascript
javascript vs java
difference between java and javascript
what is javascript used for
javascript string
javascript code
javascript es6
javascript for each
javascript or
javascript examples
function javascript
javascript methods
js date
link javascript to html
for in javascript
javascript for in
javascript require
vanilla javascript
javascript void(0)
javascript new date
what js
javascript for
this javascript
functions in javascript
how to link javascript to html
javascript developer
javascript time
javascript tutorials
what can you do
js bin
javascript queryselector
js meaning
javascript hello world
what is it?
javascript in html
javascript =>
javascript reverse array
javascript and
javascript class example
eich motors
html javascript
javascript do while
vanilla js
what is “
javascript object methods
javascript library
return javascript
$ in javascript
this in javascript
javascript for of
javascript is number
add javascript to html
function in javascript
=> javascript
in javascript
linked list javascript
free javascript course
do while javascript
javascript file
javascript %
set javascript
javascript html
what is a script
interneting is hard
javascript mdn
javascript $
is javascript a programming language
hello world javascript
java and javascript
how long does it take to learn javascript
javascript coding
… in javascript
javascript commands
what it
functions javascript
javascript date now
what is java script
what is ; used for
for in js
js for of
for javascript
js for in
javascript ?
javascript for dummies
javascript example
javascript create object
javascript image
what is the difference between java and javascript
run javascript
javascript some
or javascript
javascript new
define learned
javascript get time
break javascript
javascript code examples
define initially
javascript in
how to use javascript
js logo
javascript keywords
javascript !!
javascript vs html
javascript every
javascript date functions
javascript vs php
.js file
js console
javascript current time
javascript definition
intro to javascript
javascript tutorial point
javascript uses
what does javascript do
javascript tag
how to use javascript in html
require javascript
javascript if or
call javascript function from html
what is what
javascript …
javascript versions
javascript wiki
what is javascript?
mozilla javascript
how to code javascript
javascript language
javascript questions
javascript question mark
java browser
advanced javascript
js do while
what is closure in javascript
javascript programming
… javascript
javascript for android
what is @
what is a promise in javascript
what is |
not in javascript
javascript program
enable javascript in ie
date.now javascript
java script code examples
how it is
where js
js tutorial
es6: use destructuring assignment to assign variables from objects
function js
javascript codes example
javascript file extension
google javascripts
java script codes example
java script coding examples
what is const in javascript
java script keyword
javascript include
java is short for javascript
javascript new object
original js
oracle date functions
js in html
javascripts scripts
java script blog
javascript !==
javascript files
what can you do with javascript
html vs javascript
how to run javascript in visual studio code
learn java scripts
javascript and or
adding javascript to html
javascript coding example
js in array
what a browser
it does
javascript yield
learn java scripting
how to code in javascript
% in javascript
javascript history
what does $ mean in javascript
is what it is
how to write javascript
whst is
wht is
functional javascript
javascript game development
javascript dates
javascript tags
javascript ${}
what is £
what can you do?
what’s the difference between java and javascript
new array javascript
js to number
javascript website
what is an html
javascript date time
javascript link
how to open javascript
what is ^
html function
what is ‘ used for
javascript free
? javascript
javascript brower
jawa script com
javascript files extension
java script languages
what is hoisting in javascript
javascript introduction
javascript output
javascrip com
javascript brouser
scripting vs coding
javascript for in array
scripting definition
javascript $ meaning
javascript browser
java script com
javascripts free download
javascript file extensions
javascript tutorial for beginners
requiring javascript
javascripts com
eloquent js
javascript add object to array
what is prototype in javascript
enable javascript android
html and javascript
while javascript
embed javascript in html
javacript com
java script browsers
history of javascript
javascipt browser
javascript class names
how to javascript
java scripts
javascript lang
javascrip browser
javascript {}
html in javascript
!== javascript
.call javascript
and javascript
how long to learn javascript
js time
javascript include file
js =>
java or javascript
javascript date methods
new javascript
$ javascript
embedded java script
introduction to javascript
html introduction
is java and javascript the same
using javascript in html
what is promise in javascript
html include javascript
javascript blog
introduction example
javascript game tutorials
java script writer
what is a .js file
mocha host
basic js
javascript programs
what is vanilla javascript
is javascript hard to learn
introduction to
javascript .call
w3schools js
javascript broswer
difference between javascript and jquery
javascript filename extension
javascript browser for android
javascript broser
javascript extension
new object javascript
java introduction
javascript game tutorial
enable javascript on iphone
how to enable javascript on android
embedded javascript in html
js is number
javascript games tutorials
what is /
javascripts not working
what all can you do
.some javascript
javascript structures
break in javascript
html link javascript
javascript not
coding javascript
what is for
js new date
javascript ? :
instances by level vanilla
what is $ in javascript
what does mdn mean
is java short for javascript
javascript 101
type javascript
is javascript similar to java
java intoduction
what is a script in programming
and js
js code
javascript and html
some javascript
javascript code standards
java javascript
javascript interpreter online
javascript programming language
websites script
what is \
java html
javascripts android
what is a.js file
simple javascript games
what is/
circa interactive
javascript window objects
.on javascript
basics of javascript
javascript get year
methods in javascript
javascript browsers
java script writing
javascript version
javascript console online
how to put javascript in html
download java scripting
javascript codes
js script
javascript new function
what can javascript do
what is === in javascript
what is this in javascript
how to open javascript files
java script web site
javascript coding examples
javascript guide
differences between java and javascript
java scripts update
js function example
break js
downloads java scripts
javascript functions list
javascrip history back
java script program
javascript format time
this. javascript
javascript functions example
advanced javascript tutorial
js some
javascript keyword
html link js
what is a javascript framework
javascripts for mac
javascript meaning
javascript latest version
javascript .includes
javascript game coding
java intro
javascript change class
who created javascript
javascript scripting
what is a string in javascript
what is !
get time javascript
javascript opening files
what is used for
javascript external file
java script history back
java introdution
time javascript
javascript has class
syntax technologies
what iz
what is a closure javascript
what is a promise javascript
! javascript
promise already under evaluation: recursive default argument reference or earlier problems?
how to get javascript
what does === mean in javascript
javascript functionality examples
time java script
java skript android
when was javascript created
javascript add
javascript windows object
javascript wikipedia
javascript *=
for in array javascript
embedded js
javascript number function
how javascript works
javascript open files
difference between javascript and java
what is –
javascript on
javascript property
javascript files object
javascript !
javascripts websites
js games code
javascript built in functions
what is js
import javascript html
modern javascript
sample javascripts
what is en
html to javascript
what is an array in javascript
java java script
where to put javascript in html
javascript create function
js versions
eloquent javascript 3rd edition pdf
es6 array methods
javascript is in array
? in javascript
! in javascript
an introduction
java versus javascript
!! javascript
how to include javascript in html
sample javascript
for in object javascript
js add to object
$ in javascript means
what is ~ used for
javascript websites
javascript to html
javascript go to page
javascript create new object
create function javascript
javascript create class
body swap story interactive
css javascript
java script applications
para define
js english
how to enable javascript on ipad
javascript software
java script function
include javascript in html
methods javascript
javascript open windows
what is .js
js get time
q js
javascript —
creating a function in javascript
js date now
javascript languages
starting out with c++ early objects
script javascript
javascript hacking
java scripting codes
image javascript
javascript i phone
run javascript in atom
7 days to die object reference not set to an instance of an object
html javascript link
javascript add html
how to write a javascript function
wgat is
what is react javascript
javascript <<
javascript security
javascript tutorialspoint
scripting languages examples
what is {
java script updates
javascript function call
javascript file example
java array documentation
apply javascript
what is a method in javascript
what is : used for
method javascript
and or javascript
what is vanilla js
java scripting
what is a closure in javascript
examples of javascript
% javascript
create javascript object
call javascript functions
javascript game code
page js
script type javascript
javascript methods list
client side javascript
timing javascript
who invented javascript
what is?
javascript is defined
java script tutorials
java script tutorial
java vs. javascript
java scripts code
alert hello world
factorial in javascript
tutorialspoint javascript
difference between == and === javascript
how to start a javascript file
javascript intro
what’s javascript
what language does code.org use
click function javascript
javascript add to list
add js to html
javascript on iphone
javascript functions examples
mozilla developer network javascript
javascripts samples
js create array
calling javascript function from html
two sum javascript
!! in javascript
java to javascript
what is (
whats a browser
java scrip
javascript examples with source code
javascript online tutorial
what is a js file
every javascript
what is a prototype in javascript
what is prototyping in javascript
is java the same as javascript
javascript problems
what is a javascript
javascript secure
javascript hacks
javascript difference between and
javascript .on
programming javascript applications
call java script function
how does javascript work
javascript api tutorial
date now javascript
javascript writing
newest java script
javascript crash course
what is dom in javascript
javascript can be described as:
if function javascript
javascript dynamic array
java vs java script
what is … used for
should i learn java or javascript
example of javascript
javascript describe
html javascript example
what is [
what is a callback in javascript
is javascript the same as java
run javascript code
a what
javascript creating class
google script date format
math.average javascript
javascript change page
js !!
javascript when
javascript = vs ==
ruby string include
understanding javascript
wjat is
enable javascript on android
*= javascript
javascript define
java script js
js date constructor
learning javascript data structures and algorithms
es6: write higher order arrow functions
whats java
new in javascript
allow javascript
difference between javascript and php
beginning javascript
list of javascript functions
date and time html code for website
using js in html
what is a what
is javascript compiled
where do you put javascript in html
javascript java script
where does javascript go in html
js …
javascript codes examples
c# vs javascript
node js array
node.js oracle
javascript built in function
do i need javascript
javascript new file
what is what is
javascript info
html javascript tags
what does % mean in javascript
how to turn on java script
javascript updates
javascript open
what is an object in javascript
js every
wikipedia java script
explain how this works in javascript
in js
js %
javascript platform
opening javascript
making games with javascript
what isn
vanilla internet explorer
javascript example code
java script function list
javascript unique
html include js
j/s meaning
what is => in javascript
java script vs java
what is a function in javascript
what is ir.net
games made with javascript
write function in javascript
date function javascript
script definition computer
difference between javascript and html
what is node.js server-side javascript
convert coffeescript to javascript
javascript and java
javascript :
js introduction
java script include file
js file example
what is ; for
js ?
javascript show
html link to javascript
javascript is empty
what is used
javascript write file
java script javascript
what time js it
time in javascript
what is an argument in javascript
javascript examples with code
css vs javascript
javascript array prototype
javascript writer
javascript to java
free javascript code
math. javascript
what is es6 javascript
javascript web development
do while js
java script built in functions
objects js
what is a javascript closure
what is var in javascript
javascript write html
which of the following is a scripting language?
javascript in string
cool javascript examples
mdn js
whats an introduction
how to allow javascript
js is defined
html javascript function
how to turn on javascript on mac
javascript list contains
java script tutor
form javascripts
what is javascript and do i need it
what can i do with java
java script alternative
t is
what is strict mode in javascript
javascript add number
javascript application
link javascript
que es javascript
java script time function
run javascript in browser
whats is
javascript on change
hello world in javascript
html css javascript tutorial
what is a browser give one example
what does += mean in javascript
why js
example javascript
para script
paradigm marketing
javascript is
what is a javascript library
vanilla javascript tutorial
javascript source
why javascript
what is a javascript object
sample java script
javascript environment
es6 object
javascript run
javascripts source
javascripts tutorial
compile jscript
javascript define class
javascript game dev
js $
node js oracle
javascript in html example
javascript sample
when js
javascript query string
are java and javascript the same
simple javascript game
what is nan in javascript
javascript create file
javascript with
learning javascript in 2016
javascript ^
script programming
javascript server
date methods javascript
what is a javascript promise
javascript `
including javascript in html
what is a ; used for
javascript time now
link to javascript
javascript creating classes
javascript sample code
not javascript
in browser
js new object
js object methods
and in js
call javascript from html
javascript review
navigator javascript
code javascript
new js
running javascript
what can i do with javascript
advanced javascript concepts
array functions js
javascript year
js new
javascript .html
writing functions in javascript
javascript code example
javascript function in html
javascript on android
a result from a search engine search is called a(n) ______.
javascript date function
what is:
script source
click javascript
java script mozilla
create class javascript
what is %
$ in js
opening java script
run js online
side language
js example
what does => mean in javascript
javascript date class
is javascript free
javascript link to html
javascript games development
vanilla js document ready
writing a function in javascript
^ in javascript
java script show
for of js
modern javascript tutorial
vanilla extensions
html functions
javascript what is
javascript scripts
advantages of javascript
java script code
javascript done
javascript “
paradigm information services
what is a node in javascript
clientside javascript
javascript find function
javascript external files
javascript has key
java array addition
what time js
how do you r
coding in javascript
what does javascript look like
javascript objects tutorial
script language javascript
learned define
javascript factorial function
convert java to javascript
javascript examples code
what is ajax javascript
java scripting enabled
scripting language examples
javascript //
write javascript
javascript with html
method in javascript
javascript notes
javascript exist
wiki javascript
html vs css vs javascript
javascript manual
current time javascript
javascript create list
actionscript 3 tutorials
javascript difference
how to tell if javascript is enabled
javascript s
enable javascript on ipad
101 code
what is babel javascript
what does ? mean in javascript
making a game in javascript
jscript examples code
acrobat javascripts
date in javascript
scripting language definition
java script source codes
essentials elements 2000 for strings
what type of language is javascript
should i learn javascript
javascript string prototype
is javascript interpreted
object property javascript
javascript history object
oracle sum function
js definition
javascript android
javascript first
how to reference javascript in html
javascript execute
simple javascript code
what is ~ for
sample javascript codes
s scripts
array find js
javascript sourcecode
javascript for web developers
sample javascript code
javascript client side
es6 console
javascript !function
javascripts effects
c++ get function
javascript ??
javascript tutorial for programmers
java script sample codes
html intro
what is javascript framework
javascript run function
java script open
latest javascript version
javascript programming languages
javascript website examples
javascript create form
what is let in javascript
javascript write
whats javascript
javascript advance
array function javascript
javascript game tutorial for beginners
javascript >=
cool javascript codes
java script example
string prototype
why learn java script
javascript guides
javascript “!!”
what can you do with
you don’t know js: scope & closures
javascript names
who made javascript
simple javascript example
how to run javascript code
writing javascript in html
example javascript file
javascript how to
why is javascript so popular
interactive javascript
learn javascript step by step
javascript source codes
do i have javascript
javascript prototype explained
how to open javascript file
new function javascript
js file extension
define scripting
sample js files
learn javascript game
what is it in
in java script
array documentation java
javascript date year
is what
new date java
are java and javascript related
what does == mean in javascript
difference between and javascript
calling js from html
how to do javascript
java scipt
javascript basic
javascript source code
open jscript file
what is scope in javascript
javascript file input output
java script do
link html to javascript
can js
how to open java script files
how to open a javascript file
js advanced
js look
java script execute
how to run javascript files
difference between php and javascript
javascript w3c
and it is
object.create javascript
java read
javascript mean
js meaning in text
wikibooks html
if in array javascript
.js file extension
javascript history back
how to enable javascript on iphone
javascript list add
javascript =
type js

Localize Time with JavaScript

Localize Time with JavaScript

Say you have a time you’d like to display on your site. You’ve entered it in your time zone. You can always be specific and say something like: 3:00 PM Eastern Standard Time. Then leave it up to whoever is reading to convert it to their local time. Every Time Zone is a great site for that.

But it can be nice to localize the time for the reader. Time zone conversion is notoriously confusing. And it’s the type of thing computers are good at. JavaScript know what time zone the reader is in, after all.

I’m sure there are a number of ways to do this. I had to do it recently on a new project, and I followed Dave Rupert’s lead, who implemented it on ShopTalk’s website to display the localized time for our next live show.


Moment.js and Moment Timezone are a pair that can get this done. And if you need to do any other heavier date and time manipulation or relative calculations (e.g. “32 minutes ago”, “12 de Agosto de 2015”), you’ll be in good hands with these libraries.

We’ll also need to detect the time zone itself, and thankfully there is a library for that.

So we’ll be using:

  • jstz.js
  • moment.js
  • moment-timezone.js

Package or link those up however you will.

Step 1: Get the Timezone

Might as well stash it in localStorage after you’ve gotten it. That requires less effort on the browser’s part to retrieve next time.

if (!sessionStorage.getItem('timezone')) {
  var tz = jstz.determine() || 'UTC';
  sessionStorage.setItem('timezone', tz.name());
var currTz = sessionStorage.getItem('timezone');

Step 2: Get a Time Value

Moment expects a date/time value (in UTC) like:


If we’re only interested in the time, we can create the date portion of that string from Moment itself of today’s date (just makes the formatting way easier). The date actually kinda matters since UGHGKGJHGH daylight savings.

var date = moment().format("YYYY-MM-DD");

Then we’ll create the final string, assuming we have a variable with the time we want:

var stamp = date + "T" + theTime + "Z";

And turn it into a Moment object:

var momentTime = moment(stamp);

Step 3: Localize the time

Now we can adjust/localize that time with Moment Timezone:

var tzTime = momentTime.tz(currTz);

And properly format it for display:

var formattedTime = tzTime.format('h:mm A');

Step 4: Use it

Now we can drop it on the page anywhere we want. If you output the time zone as well, you could even replace the time currently output on the page, since even if detecting the time zone fails it will fall back to UTC and output that as the time zone.

output.textContent = "Time in " + currTz + ": " + formattedTime;

Adjusting Times

Sometimes it makes sense (perhaps from a CMS perspective) to ask people to input time in a local time zone. But in order to do the conversion correctly, it makes more sense to have that time in UTC.

Moment itself can help with adjusting times, like:

moment().subtract(4, 'hours');
moment().add(3, 'hours');

Server side languages can help too. For instance PHP can do math on times:

<?php var $sixHoursAgo = strtotime("-6 hours", time()); ?>

It probably makes the most sense to do that with Moment Timezone, because it’s not always an exact formula (again UGHADKGHK daylight savings).


In this demo we use an HTML5 time input and adjust it on the fly to a localized time.



Last Words

The dependencies we used here are not insignificant! It appears there are native JavaScript methods (e.g. getTimezoneOffset()) that have pretty good support that could be used to similar effect.


JavaScript Basics

JavaScript Basics

JavaScript is a programming language that adds interactivity to your website (e.g. games, responses when buttons are pressed or data entered in forms, dynamic styling, animation). This article helps you get started with this exciting language and gives you an idea of what is possible.

What is JavaScript, really?

JavaScript is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation.

You can do pretty much anything with JavaScript. You’ll start small with simple features such as carousels, image galleries, fluctuating layouts, and responses to button clicks. Eventually as you get more experienced with the language you’ll be able to create games, animated 2D and 3D graphics, full blown database-driven apps, and more!

JavaScript itself is fairly compact but very flexible, and developers have written a lot of tools that sit on top of the core JavaScript language to unlock a huge amount of extra functionality with very little effort. These include:

  • Application Programming Interfaces (APIs) built into web browsers providing various functionality like dynamically creating HTML and setting CSS styles, or grabbing and manipulating a video stream from the user’s webcam, or generating 3D graphics and audio samples.
  • Third-party APIs to allow developers to incorporate functionality in their sites from other properties, such as Twitter or Facebook.
  • Third-party frameworks and libraries you can apply to your HTML to allow you to rapidly build up sites and applications.

A “hello world” example

The above section sounds really exciting, and so it should — JavaScript is one of the most exciting Web technologies, and as you start to get good at it your websites will enter a new dimension of power and creativity.

HOWEVER, JavaScript is a bit more complex to get comfortable with than HTML and CSS, and you’ll have to start small, and keep working at it in tiny regular steps. To start off with, we’ll show you how to add some really basic JavaScript to your page, to create a “hello world!” example (the standard in basic programming examples.)

Important: If you haven’t been following along with the rest of our course, download this example code and use it as a starting point.

  1. First, go to your test site and create a new file called main.js. Save it in your scripts folder.
  2. Next, go to your index.html file and enter the following element on a new line just before the closing </body> tag:
    <script src="scripts/main.js"></script>
  3. This is basically doing the same job as the <link> element for CSS — it applies the JavaScript to the page, so it can have an effect on the HTML (and CSS, and anything else on the page).
  4. Now add the following code to the main.js file:
    var myHeading = document.querySelector('h1');
    myHeading.innerHTML = 'Hello world!';
  5. Now make sure the HTML and JavaScript files are saved, and load index.html in the browser. You should see something like the following:

Note: The reason we’ve put the <script> element near the bottom of the HTML file is that HTML is loaded by the browser in the order it appears in the file. If the JavaScript is loaded first and it is supposed to affect the HTML below it, it might not work, as the JavaScript would be loaded before the HTML it is supposed to work on. Therefore, near the bottom of the page is often the best strategy.

What happened?

So your heading text has been changed to “Hello world!” using JavaScript. We did this by first using a function called querySelector() to grab a reference to our heading, and store it in a variable calledmyHeading. This is very similar to what we did in CSS using selectors. When you want to do something to an element, first you need to select it.

After that, we set the value of the myHeading variable’s innerHTML property (which represents the content of the heading) to “Hello world!”.

Language basics crash course

Let’s explain just some of the basic features of the JavaScript language, to give you some more understanding of how it all works. Better yet, these features are common to all programming languages. If you can understand these fundamentals, you should be able to make a start programming just about anything!

Important: In this article, try entering the example code lines into your JavaScript console to see what happens. For more details on JavaScript consoles, see Discover browser developer tools.


Variables are containers that you can store values in. You start by declaring a variable with the varkeyword, followed by any name you want to call it:

var myVariable;

Note: All lines in JS must end with a semi-colon, to indicate that this is where the line ends. If you don’t include these, you can get unexpected results.

Note: You can call a variable nearly anything, but there are some name restrictions (see this article on variable naming rules.)

Note: JavaScript is case sensitive — myVariable is a different variable to myvariable. If you are getting problems in your code, check the casing!

After declaring a variable, you can give it a value:

myVariable = 'Bob';

You can retrieve the value by just calling the variable by name:


You can do both these operations on the same line if you wish:

var myVariable = 'Bob';

After giving a variable a value, you can later choose to change it:

var myVariable = 'Bob';
myVariable = 'Steve';

Note that variables have different data types:

Variable Explanation Example
String A string of text. To signify that the variable is a string, you should enclose it in quote marks. var myVariable = 'Bob';
Number A number. Numbers don’t have quotes around them. var myVariable = 10;
Boolean A True/False value. true/false are special keywords in JS, and don’t need quotes. var myVariable = true;
Array A structure that allows you to store multiple values in one single reference. var myVariable = [1,'Bob','Steve',10];
Call each member of the array like this: myVariable[0],myVariable[1], etc.
Object Basically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn. var myVariable = document.querySelector('h1');
All of the above examples too.

So why do we need variables? Well, variables are needed to do anything interesting in programming. If values couldn’t change, then you couldn’t do anything dynamic, like personalize a greeting message or change the image displayed in an image gallery.


You can put comments into JavaScript code, just like you can in CSS:

Everything in between is a comment.

If your comment contains no line breaks, it’s often easier to put it behind two slashes like this:

// This is a comment


An operator is a mathematical symbol that produces a result based on two values (or variables). In the following table you can see some of the simplest operators, along with some examples to try out in the JavaScript console.

Operator Explanation Symbol(s) Example
add/concatenation Used to add two numbers together, or glue two strings together. + 6 + 9;
"Hello " + "world!";
subtract, multiple, divide These do what you’d expect them to do in basic math. -, *, / 9 - 3;
8 * 2; // multiply in JS is an asterisk
9 / 3;
assignment operator You’ve seen this already: it assigns a value to a variable. = var myVariable = 'Bob';
Identity operator Does a test to see if two values are equal to one another, and returns a true/false(boolean) result. === var myVariable = 3;
myVariable === 4;
Negation, not equal Often used alongside the Equality operator, the negation operator is the JS equivalent of a logical NOT — it turns atrue into a false, etc. !, !== The basic expression is true, but the comparison returnsfalse because we’ve negated it:

var myVariable = 3;
!(myVariable === 3);

Here we are testing “is myVariable NOT equal to 3″. This returns false, because it IS equal to 3.

var myVariable = 3;
myVariable !== 3;

There are a lot more operators to explore, but this will do for now. See Expressions and operators for a complete list.

Note: Mixing data types can lead to some strange results when performing calculations, so be careful that you are referring to your variables correctly, and getting the results you expect. For example enter"35" + "25" into your console. Why don’t you get the result you expected? Because the quote marks turn the numbers into strings, so you’ve ended up concatenating strings rather than adding numbers. If you enter 35 + 25, you’ll get the correct result.


Conditionals are code structures that allow you to test whether an expression returns true or not, and then run different code depending on the result. The most common form of conditional is called if ... else. So for example:

var iceCream = 'chocolate';
if (iceCream === 'chocolate') {
  alert('Yay, I love chocolate ice cream!');    
} else {
  alert('Awwww, but chocolate is my favorite...');    

The expression inside the if ( ... ) is the test — this uses the identity operator (as described above) to compare the variable iceCream with the string chocolate to see if the two are equal. If this comparison returns true, run the first block of code. If not, skip that code and run the second block of code after the else statement.


Functions are a way of packaging functionality that you want to reuse, so that whenever you want the functionality you can call the function with the function name rather than constantly rewriting the entire code. You have already seen some functions above, for example:

  1. var myVariable = document.querySelector('h1');
  2. alert('hello!');

These functions are built into the browser for you to use whenever you like.

If you see something that looks like a variable name, but has brackets — () — after it, it is probably a function. Functions often take arguments — bits of data they need to do their job. These go inside the brackets, separated by commas if there is more than one item.

For example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what to write in the pop-up box.

The good news is that you can define your own functions — in this next example we write a simple function that takes two numbers as arguments and multiplies them:

function multiply(num1,num2) {
  var result = num1 * num2;
  return result;

Try running the above function in the console, then try using your new function a few times, e.g.:


Note: The return statement tells the browser to return the result variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping (read more on variable scoping here.)


To create real interactivity on a website, you need events — these are code structures that listen out for things happening to the browser, and then allow you to run code in response to those things. The most obvious example is the click event, which is fired by the browser when the mouse clicks on something. To demonstrate this, try entering the following into your console, then clicking on the current webpage:

document.querySelector('html').onclick = function() {
    alert('Ouch! Stop poking me!');

There are many ways to attach an event to an element. Here we are selecting the HTML element and setting its onclick handler property equal to an anonymous (i.e. nameless) function that contains the code we want to run when the click event occurs.

Note that

document.querySelector('html').onclick = function() {};

is equivalent to

var myHTML = document.querySelector('html');
myHTML.onclick = function() {};

It’s just shorter.

Supercharging our example website

Now we’ve gone over a few JavaScript basics, let’s add a few cool basic features to our example site to give you some first idea of what is possible.

Adding an image changer

In this section we’ll add another image to our site, and add some simple JavaScript to change between the two when the image is clicked on.

  1. First of all, find another image that you’d like to feature on your site. Make sure it is the same size as your first image, or as close as possible.
  2. Save the image in your images folder.
  3. Go to your main.js file, and enter the following JavaScript (if your hello world JavaScript is still there, delete it):
    var myImage = document.querySelector('img');
    myImage.onclick = function() {
        var mySrc = myImage.getAttribute('src');
        if(mySrc === 'images/firefox-icon.png') {
          myImage.setAttribute ('src','images/firefox2.png');
        } else {
          myImage.setAttribute ('src','images/firefox-icon.png');
  4. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!

So here, we are storing a reference to our image element in the myImage variable. Next, we make this variable’s onclick event handler property equal to an anonymous function. Now, every time this image element is clicked:

  1. We retrieve the value of the image’s src attribute.
  2. We use a conditional to check whether the src value is equal to the path to the original image:
    1. If it is, we change the src value to the path to the 2nd image, forcing the other image to be loaded inside the <image> element.
    2. If it isn’t (meaning it must already have changed), we change the src value back to the original image path, to flip it back to how it was originally.

Adding a personalized welcome message

Next we will add another bit of code, to change the page’s title to include a personalized welcome message when the user first navigates to the site. This welcome message will persist when the user leaves the site and then comes back. We will also include an option to change the user and therefore the welcome message anytime it is required.

  1. In index.html, add the following line just before the <script> element:
    <button>Change user</button>
  2. In main.js, add the following code at the bottom of the file, exactly as written — this grabs references to the new button we added and the heading, and stores them in variables:
    var myButton = document.querySelector('button');
    var myHeading = document.querySelector('h1');
  3. Now add the following function to set the personalized greeting — this won’t do anything yet, but we’ll use it later on:
    function setUserName() {
      var myName = prompt('Please enter your name.');
      localStorage.setItem('name', myName);
      myHeading.innerHTML = 'Mozilla is cool, ' + myName;

    This function contains a prompt() function, which brings up a dialog box, a bit like alert() except that prompt() asks the user to enter some data, and stores that data in a variable after the user presses OK. In this case, we are asking the user to enter their name. Next, we call on an API calledlocalStorage, which allows us to store data in the browser and retrieve it later on. We use localStorage’s setItem() function to create and store a data item called 'name', and set its value to the myName variable that contains the name the user entered. Finally, we set the innerHTML of the heading to a string, plus the user’s name.

  4. Next, add this if ... else block — we could call this the initialization code, as it sets up the app when it first loads:
    if(!localStorage.getItem('name')) {
    } else {
      var storedName = localStorage.getItem('name');
      myHeading.innerHTML = 'Mozilla is cool, ' + storedName;

    This block first uses the negation operator (logical NOT) to check whether the name data item exists. If not, the setUserName() function is run to create it. If so (i.e. the user set it during a previous visit), we retrieve the stored name using getItem() and set the innerHTML of the heading to a string, plus the user’s name, the same as we did inside setUserName().

  5. Finally, put the below onclick event handler on the button, so that when clicked thesetUserName() function is run. This allows the user to set a new name whenever they want by pressing the button:
    myButton.onclick = function() {

Now when you first visit the site, it’ll ask you for your username then give you a personalized message. You can then change the name any time you like by pressing the button. As an added bonus, because the name is stored inside localStorage, it persists after the site is closed down, so the personalized message will still be there when you open the site up again!