HTML Editors


A simple text editor is all you need to learn HTML.


Learn HTML Using Notepad or TextEdit

Web pages can be created and modified by using professional HTML editors.

However, for learning HTML we recommend a simple text editor like Notepad (PC) or TextEdit (Mac).

We believe that using a simple text editor is a good way to learn HTML.

Follow the steps below to create your first web page with Notepad or TextEdit.


Step 1: Open Notepad (PC)

Windows 8 or later:

Open the Start Screen (the window symbol at the bottom left on your screen). Type Notepad.

Windows 7 or earlier:

Open Start > Programs > Accessories > Notepad


Step 1: Open TextEdit (Mac)

Open Finder > Applications > TextEdit

Also change some preferences to get the application to save files correctly. In Preferences > Format > choose "Plain Text"

Then under "Open and Save", check the box that says "Display HTML files as HTML code instead of formatted text".

Then open a new document to place the code.


Step 2: Write Some HTML

Write or copy the following HTML code into Notepad:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>

Notepad



Step 3: Save the HTML Page

Save the file on your computer. Select File > Save as in the Notepad menu.

Name the file "index.htm" and set the encoding to UTF-8 (which is the preferred encoding for HTML files).

View in Browser

Tip: You can use either .htm or .html as file extension. There is no difference; it is up to you.


Step 4: View the HTML Page in Your Browser

Open the saved HTML file in your favorite browser (double click on the file, or right-click - and choose "Open with").

The result will look much like this:

View in Browser


W3Schools Online Editor - "Try it Yourself"

With our free online editor, you can edit the HTML code and view the result in your browser.

It is the perfect tool when you want to test code fast. It also has color coding and the ability to save and share code with others:

Example

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Click on the "Try it Yourself" button to see how it works.


W3Schools Spaces

If you want to create your own website and save your code online, try our free website builder, called :

W3Schools Spaces

W3Schools Spaces

Everything you need right in the browser.





JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Examples in Each Chapter

With our "Try it Yourself" editor, you can edit the source code and view the result.

Example

My First JavaScript

Click me to display Date and Time


Use the Menu

We recommend reading this tutorial, in the sequence listed in the menu.

If you have a large screen, the menu will always be present on the left.

If you have a small screen, open the menu by clicking the top menu sign â˜°.


Learn by Examples

Examples are better than 1000 words. Examples are often easier to understand than text explanations.

This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

If you try all the examples, you will learn a lot about JavaScript, in a very short time!


Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

   3. JavaScript to program the behavior of web pages

This tutorial covers every version of JavaScript:

·         The Original JavaScript ES1 ES2 ES3 (1997-1999)

·         The First Main Revision ES5 (2009)

·         The Second Revision ES6 (2015)

·         The Yearly Additions (2016, 2017 ... 2021, 2022)



Learning Speed

In this tutorial, the learning speed is your choice.

Everything is up to you.

If you are struggling, take a break, or re-read the material.

Always make sure you understand all the "Try-it-Yourself" examples.

The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code. Code !


 

Commonly Asked Questions

  • How do I get JavaScript?
  • Where can I download JavaScript?
  • Is JavaScript Free?

You don't have to get or download JavaScript.

JavaScript is already running in your browser on your computer, on your tablet, and on your smart-phone.

JavaScript is free to use for everyone.


My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study at W3Schools without using My Learning.

 

This page contains some examples of what JavaScript can do.

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello JavaScript":

Example

document.getElementById("demo").innerHTML = "Hello JavaScript";

JavaScript accepts both double and single quotes:

Example

document.getElementById('demo').innerHTML = 'Hello JavaScript';


JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img> tag:

The Light Bulb

Turn on the light  Turn off the light



JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Example

document.getElementById("demo").style.fontSize = "35px";


JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

Example

document.getElementById("demo").style.display = "none";


JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by changing the display style:

Example

document.getElementById("demo").style.display = "block";

Did You Know?

JavaScript and Java are completely different languages, both in concept and design.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.

ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

 

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

Example

<script>
document.getElementById(
"demo").innerHTML = "My First JavaScript";
</script>

Old JavaScript examples may use a type attribute: <script type="text/javascript">.
The type attribute is not required. JavaScript is the default scripting language in HTML.


JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

You will learn much more about functions and events in later chapters.


JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.


JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById(
"demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>



JavaScript in <body>

In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked (called) when a button is clicked:

Example

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById(
"demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.


External JavaScript

Scripts can also be placed in external files:

External file: myScript.js

function myFunction() {
  document.getElementById(
"demo").innerHTML = "Paragraph changed.";
}

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

Example

<script src="myScript.js"></script>

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External scripts cannot contain <script> tags.


External JavaScript Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

To add several script files to one page  - use several script tags:

Example

<script src="myScript1.js"></script>
<script src="myScript2.js"></script>


JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById(
"demo").innerHTML = 5 + 6;
</script>

</body>
</html>

Changing the innerHTML property of an HTML element is a common way to display data in HTML.


Using document.write()

For testing purposes, it is convenient to use document.write():

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(
5 + 6);
</script>

</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<button type="button" onclick="document.write(5 + 6)">Try it</button>

</body>
</html>

The document.write() method should only be used for testing.



Using window.alert()

You can use an alert box to display data:

Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
window.alert(
5 + 6);
</script>

</body>
</html>

You can skip the window keyword.

In JavaScript, the window object is the global scope object. This means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:

Example

<!DOCTYPE html>
<

Example

let x, y, z;    // Statement 1
x = 5;          // Statement 2
y = 6;          // Statement 3
z = x + y;      // Statement 4


JavaScript Programs

computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.


JavaScript Statements

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs (and JavaScript statements) are often called JavaScript code.


Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

Examples

let a, b, c;  // Declare 3 variables
a = 5;        // Assign the value 5 to a
b = 6;        // Assign the value 6 to b
c = a + b;    // Assign the sum of a and b to c

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.



JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

The following lines are equivalent:

let person = "Hege";
let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;


JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly!";


JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:

Example

function myFunction() {
  document.getElementById(
"demo1").innerHTML = "Hello Dolly!";
  document.getElementById(
"demo2").innerHTML = "How are you?";
}

In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.


JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword

Description

var

Declares a variable

let

Declares a block variable

const

Declares a block constant

if

Marks a block of statements to be executed on a condition

switch

Marks a block of statements to be executed in different cases

for

Marks a block of statements to be executed in a loop

function

Declares a function

return

Exits a function

try

Implements error handling to a block of statements

JavaScript keywords are reserved words. Reserved words cannot be used as names for variables.

 

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:
var x;
let y;

// How to use variables:
x = 5;
y = 
6;
let z = x + y;

JavaScript Values

The JavaScript syntax defines two types of values:

  • Fixed values
  • Variable values

Fixed values are called Literals.

Variable values are called Variables.


JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

10.50

1001

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'



JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords varlet and const to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

let x;
x = 
6;


JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:

(5 + 6) * 10

JavaScript uses an assignment operator ( = ) to assign values to variables:

let x, y;
x = 
5;
y = 
6;


JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

5 * 10

Expressions can also contain variable values:

x * 10

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"


JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y;
x = 
5 + 6;
y = x * 
10;

The var keyword also tells the browser to create variables:

var x, y;
x = 
5 + 6;
y = x * 
10;

In these examples, using var or let will produce the same result.

You will learn more about var and let later in this tutorial.


JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

let x = 5;   // I will be executed

// x = 6;   I will NOT be executed

You will learn more about comments in a later chapter.


JavaScript Identifiers / Names

Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

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

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note

Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.


JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive

The variables lastName and lastname, are two different variables:

let lastname, lastName;
lastName = 
"Doe";
lastname = 
"Peterson";

JavaScript does not interpret LET or Let as the keyword let.


JavaScript and Camel Case

Historically, programmers have used different ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. They are reserved for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.


JavaScript Character Set

JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the world.

For a closer look, please study our Complete Unicode Reference.

 

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:
var x;
let y;

// How to use variables:
x = 5;
y = 
6;
let z = x + y;

JavaScript Values

The JavaScript syntax defines two types of values:

  • Fixed values
  • Variable values

Fixed values are called Literals.

Variable values are called Variables.


JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

10.50

1001

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'



JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords varlet and const to declare variables.

An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

let x;
x = 
6;


JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values:

(5 + 6) * 10

JavaScript uses an assignment operator ( = ) to assign values to variables:

let x, y;
x = 
5;
y = 
6;


JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

For example, 5 * 10 evaluates to 50:

5 * 10

Expressions can also contain variable values:

x * 10

 

The values can be of various types, such as numbers and strings.

For example, "John" + " " + "Doe", evaluates to "John Doe":

"John" + " " + "Doe"

 


JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y;
x = 
5 + 6;
y = x * 
10;

 

The var keyword also tells the browser to create variables:

var x, y;
x = 
5 + 6;
y = x * 
10;

 

In these examples, using var or let will produce the same result.

You will learn more about var and let later in this tutorial.


JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

let x = 5;   // I will be executed

// x = 6;   I will NOT be executed

 

You will learn more about comments in a later chapter.


JavaScript Identifiers / Names

Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

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

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note

Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.


JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive

The variables lastName and lastname, are two different variables:

let lastname, lastName;
lastName = 
"Doe";
lastname = 
"Peterson";

 

JavaScript does not interpret LET or Let as the keyword let.


JavaScript and Camel Case

Historically, programmers have used different ways of joining multiple words into one variable name:

Hyphens:

first-name, last-name, master-card, inter-city.

Hyphens are not allowed in JavaScript. They are reserved for subtractions.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

JavaScript programmers tend to use camel case that starts with a lowercase letter:

firstName, lastName, masterCard, interCity.


JavaScript Character Set

JavaScript uses the Unicode character set.

Unicode covers (almost) all the characters, punctuations, and symbols in the world.

For a closer look, please study our Complete Unicode Reference.

 

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

·         Automatically

·         Using var

·         Using let

·         Using const

In this first example, xy, and z are undeclared variables.

They are automatically declared when first used:

Example

x = 5;
y = 
6;
z = x + y;

Note

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var

var x = 5;
var y = 6;
var z = x + y;

Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

let x = 5;
let y = 6;
let z = x + y;

Example using const

const x = 5;
const y = 6;
const z = x + y;

Mixed Example

const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.


Just Like Algebra

Just like in algebra, variables hold values:

let x = 5;
let y = 6;

Just like in algebra, variables are used in expressions:

let z = x + y;

From the example above, you can guess that the total is calculated to be 11.

Note

Variables are containers for storing values.



JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

Note

JavaScript identifiers are case-sensitive.


The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

Note

The "equal to" operator is written like == in JavaScript.


JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example

const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';


Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

var carName;

or:

let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

let carName = "Volvo";

In the example below, we create a variable called carName

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

·         Automatically

·         Using var

·         Using let

·         Using const

In this first example, xy, and z are undeclared variables.

They are automatically declared when first used:

Example

x = 5;
y = 
6;
z = x + y;

Note

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var

var x = 5;
var y = 6;
var z = x + y;

Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

let x = 5;
let y = 6;
let z = x + y;

Example using const

const x = 5;
const y = 6;
const z = x + y;

Mixed Example

const price1 = 5;
const price2 = 6;
let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.


Just Like Algebra

Just like in algebra, variables hold values:

let x = 5;
let y = 6;

Just like in algebra, variables are used in expressions:

let z = x + y;

From the example above, you can guess that the total is calculated to be 11.

Note

Variables are containers for storing values.



JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

Note

JavaScript identifiers are case-sensitive.


The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

Note

The "equal to" operator is written like == in JavaScript.


JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example

const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';


Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

var carName;

or:

let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

let carName = "Volvo";

In the example below, we create a variable called carName

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Example

const PI = 3.141592653589793;
PI = 
3.14;      // This will give an error
PI = PI + 10;   // This will also give an error


Must be Assigned

JavaScript const variables must be assigned a value when they are declared:

Correct

const PI = 3.14159265359;

Incorrect

const PI;
PI = 
3.14159265359;

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

·         A new Array

·         A new Object

·         A new Function

·         A new RegExp


Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

Example

// You can create a constant array:
const cars = ["Saab""Volvo""BMW"];

// You can change an element:
cars[0] = "Toyota";

// You can add an element:
cars.push("Audi");

But you can NOT reassign the array:

Example

const cars = ["Saab""Volvo""BMW"];

cars = [
"Toyota""Volvo""Audi"];    // ERROR


Constant Objects

You can change the properties of a constant object:

Example

// You can create a const object:
const car = {type:"Fiat", model:"500", color:"white"};

// You can change a property:
car.color = "red";

// You can add a property:
car.owner = "Johnson";

But you can NOT reassign the object:

Example

const car = {type:"Fiat", model:"500", color:"white"};

car = {type:
"Volvo", model:"EX60", color:"red"};    // ERROR


Difference Between var, let and const

 
 

Scope

Redeclare

Reassign

Hoisted

Binds this

var

No

Yes

Yes

Yes

Yes

let

Yes

No

Yes

No

No

const

Yes

No

No

No

No

What is Good?

let and const have block scope.

let and const can not be redeclared.

let and const must be declared before use.

let and const does not bind to this.

let and const are not hoisted.

What is Not Good?

var does not have to be declared.

var is hoisted.

var binds to this.


Javascript operators are used to perform different types of mathematical and logical computations.

Examples:

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values


JavaScript Assignment

The Assignment Operator (=) assigns a value to a variable:

Assignment Examples

let x = 10;

// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z:
let z = x + y;


JavaScript Addition

The Addition Operator (+) adds numbers:

Adding

let x = 5;
let y = 2;
let z = x + y;

JavaScript Multiplication

The Multiplication Operator (*) multiplies numbers:

Multiplying

let x = 5;
let y = 2;
let z = x * y;


Types of JavaScript Operators

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

let a = 3;
let x = (100 + 50) * a;

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

**

Exponentiation (ES2016)

/

Division

%

Modulus (Division Remainder)

++

Increment

--

Decrement

Note

Arithmetic operators are fully described in the JS Arithmetic chapter.



JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator (+=) adds a value to a variable.

Assignment

let x = 10;
x += 
5;

Operator

Example

Same As

=

x = y

x = y

+=

x += y

x = x + y

-=

x -= y

x = x - y

*=

x *= y

x = x * y

/=

x /= y

x = x / y

%=

x %= y

x = x % y

**=

x **= y

x = x ** y

Note

Assignment operators are fully described in the JS Assignment chapter.


JavaScript Comparison Operators

Operator

Description

==

equal to

===

equal value and equal type

!=

not equal

!==

not equal value or not equal type

greater than

less than

JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).

Operator

Description

+

Addition

-

Subtraction

*

Multiplication

**

Exponentiation (ES2016)

/

Division

%

Modulus (Remainder)

++

Increment

--

Decrement


Arithmetic Operations

A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

Example

let x = 100 + 50;

or variables:

Example

let x = a + b;

or expressions:

Example

let x = (100 + 50) * a;


Operators and Operands

The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

Operand

Operator

Operand

100

+

50



Adding

The addition operator (+) adds numbers:

Example

let x = 5;
let y = 2;
let z = x + y;


Subtracting

The subtraction operator (-) subtracts numbers.

Example

let x = 5;
let y = 2;
let z = x - y;


Multiplying

The multiplication operator (*) multiplies numbers.

Example

let x = 5;
let y = 2;
let z = x * y;


Dividing

The division operator (/) divides numbers.

Example

let x = 5;
let y = 2;
let z = x / y;


Remainder

The modulus operator (%) returns the division remainder.

Example

let x = 5;
let y = 2;
let z = x % y;

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic division.


Incrementing

The increment operator (++) increments numbers.

Example

let x = 5;
x++;
let z = x;


Decrementing

The decrement operator (--) decrements numbers.

Example

let x = 5;
x--;
let z = x;


Exponentiation

The exponentiation operator (**) raises the first operand to the power of the second operand.

Example

let x = 5;
let z = x ** 2;

x ** y produces the same result as Math.pow(x,y):

Example

let x = 5;
let z = Math.pow(x,2);


Operator Precedence

Operator precedence describes the order in which operations are performed in an arithmetic expression.

Example

let x = 100 + 50 * 3;

Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

Operator

Example

Same As

=

x = y

x = y

+=

x += y

x = x + y

-=

x -= y

x = x - y

*=

x *= y

x = x * y

/=

x /= y

x = x / y

%=

x %= y

x = x % y

**=

x **= y

x = x ** y


Shift Assignment Operators

Operator

Example

Same As

<<=

x <<= y

x = x << y

>>=

x >>= y

x = x >> y

>>>=

x >>>= y

x = x >>> y


Bitwise Assignment Operators

Operator

Example

Same As

&=

x &= y

x = x & y

^=

x ^= y

x = x ^ y

|=

x |= y

x = x | y


Logical Assignment Operators

Operator

Example

Same As

&&=

x &&= y

x = x && (x = y)

||=

x ||= y

x = x || (x = y)

??=

x ??= y

x = x ?? (x = y)

Note

The Logical assignment operators are ES2020.


The = Operator

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

let x = 10;

let x = 10 + y;


The += Operator

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

let x = 10;
x += 
5;

let text = "Hello"; text += " World";


The -= Operator

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

let x = 10;
x -= 
5;


The *= Operator

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

let x = 10;
x *= 
5;


The **= Operator

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

let x = 10;
x **= 
5;


The /= Operator

The Division Assignment Operator divides a variable.

Division Assignment Example

let x = 10;
x /= 
5;


The %= Operator

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

let x = 10;
x %= 
5;



The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

let x = -100;
x <<= 
5;


The >>= Operator

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

let x = -100;
x >>= 
5;


JavaScript has 8 Datatypes

1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype

The object data type can contain:

1. An object
2. An array
3. A date

Examples

// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab""Volvo""BMW"];

// Date object:
const date = new Date("2022-03-25");

Note

A JavaScript variable can hold any type of data.

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

let x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

let x = "16" + "Volvo";

Note

When adding a number and a string, JavaScript will treat the number as a string.

Example

let x = 16 + "Volvo";

Example

let x = "Volvo" + 16;

JavaScript evaluates expressions from left to right. Different sequences can produce different results:

JavaScript:

let x = 16 + 4 + "Volvo";

Result:

20Volvo

JavaScript:

let x = "Volvo" + 16 + 4;

Result:

Volvo164

In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".

In the second example, since the first operand is a string, all operands are treated as strings.



JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

Example

let x;       // Now x is undefined
x = 5;       // Now x is a Number
x = "John";  // Now x is a String


JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

Example

// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:
let carName2 = 'Volvo XC60';

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example

// Single quote inside double quotes:
let answer1 = "It's alright";

// Single quotes inside double quotes:
let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:
let answer3 = 'He is called "Johnny"';

You will learn more about strings later in this tutorial.


JavaScript Numbers

All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

Example

// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;


Exponential Notation

Extra large or extra small numbers can be written with scientific (exponential) notation:

Example

let y = 123e5;    // 12300000
let z = 123e-5;   // 0.00123


Note

Most programming languages have many number types:

Whole numbers (integers):
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)

Real numbers (floating-point):
float (32-bit), double (64-bit).

Javascript numbers are always one type:
double (64-bit floating point).

You will learn more about numbers later in this tutorial.


JavaScript BigInt

All JavaScript numbers are stored in a 64-bit floating-point format.

JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are too big to be represented by a normal JavaScript Number.

Example

let x = BigInt("123456789012345678901234567890");

You will learn more about BigInt later in this tutorial.


JavaScript Booleans

Booleans can only have two values: true or false.

Example

let x = 5;
let y = 5;
let

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example