Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
100 views

Java Script

1) JavaScript is the programming language of the web and is used to make web pages interactive. It can modify HTML content, styles, and attributes. 2) JavaScript code is inserted in HTML using <script> tags and can be placed in the <head> or <body> sections. It can also be stored externally in .js files. 3) JavaScript can output data by modifying HTML elements, using document.write(), alerts, or the browser console for debugging. Common output methods are innerHTML and document.write.

Uploaded by

mariejoy040223
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Java Script

1) JavaScript is the programming language of the web and is used to make web pages interactive. It can modify HTML content, styles, and attributes. 2) JavaScript code is inserted in HTML using <script> tags and can be placed in the <head> or <body> sections. It can also be stored externally in .js files. 3) JavaScript can output data by modifying HTML elements, using document.write(), alerts, or the browser console for debugging. Common output methods are innerHTML and document.write.

Uploaded by

mariejoy040223
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

JavaScript Tutorial

❮ HomeNext ❯
JavaScript is the programming language of HTML and the Web.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to advanced.

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

Web pages are not the only place where JavaScript is used. Many desktop and server
programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and
CouchDB, also use JavaScript as their programming language.

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.
You can read more about the different JavaScript versions in the chapter JS Versions.

2 JavaScript Introduction

JavaScript Can Change HTML Content


One of many JavaScript HTML methods is getElementById().
This example uses the method to "find" an HTML element (with id="demo") and
changes the element content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
JavaScript accepts both double and single quotes:
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
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

<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on
the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off


the light</button>

</body>
</html>

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";
Try it Yourself »

JavaScript Can Hide HTML Elements


Hiding HTML elements can be done by changing the display style:
Example
document.getElementById("demo").style.display = "none";
Try it Yourself »
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";

3 JavaScript Where To
The <script> Tag

In HTML, JavaScript code must be 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>
<h1>A Web Page</h1>
<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>

<h1>A Web Page</h1>


<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>

Try it Yourself »

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>
Try it Yourself »

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>

External References

External scripts can be referenced with a full URL or with a path relative to the current
web page.
This example uses a full URL to link to a script:
Example

<script src="https://www.w3schools.com/js/myScript1.js"></script>

Try it Yourself »
This example uses a script located in a specified folder on the current web site:

Example

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

Try it Yourself »
This example links to a script located in the same folder as the current page:

Example

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

Try it Yourself »
You can read more about file paths in the chapter HTML File Paths.

4 JavaScript Output
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>

Try it Yourself »
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>
Try it Yourself »
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>
Try it Yourself »

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>
Try it Yourself »
Using console.log()

For debugging purposes, you can use the console.log() method to display data.
You will learn more about debugging in a later chapter.

Example

<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

5 JavaScript Statements
Example
var x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
In a programming language, these programming instructions are called statements.
A 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.";
Try it Yourself »
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:
var 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
Try it Yourself »
When separated by semicolons, multiple statements on one line are allowed:
a = 5; b = 6; c = a + b;
Try it Yourself »
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:
var person = "Hege";
var person="Hege";
A good practice is to put spaces around operators ( = + - * / ):
var 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!";
Try it Yourself »

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?";
}
Try it Yourself »
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.
Visit our Reserved Words reference to view a full list of JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
debugger Stops the execution of JavaScript, and calls (if available) the debugging
function

do ... while Executes a block of statements, and repeats the block, while a condition
is true

for Marks a block of statements to be executed, as long as a condition is


true

function Declares a function


if ... else Marks a block of statements to be executed, depending on a condition

return Exits a function


switch Marks a block of statements to be executed, depending on different
cases

try ... Implements error handling to a block of statements


catch

var Declares a variable


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

6 JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
var x, y, z; // How to declare variables
x = 5; y = 6; // How to assign values
z = x + y; // How to compute values
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable values.
Fixed values are called literals. Variable values are called variables.

JavaScript Literals
The most important rules for writing fixed values are:
Numbers are written with or without decimals:
10.50
1001
Try it Yourself »
Strings are text, written within double or single quotes:
"John Doe"
'John Doe'
Try it Yourself »

JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword 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:
var x;
x = 6;
Try it Yourself »

JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
Try it Yourself »

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


var x, y;
x = 5;
y = 6;
Try it Yourself »
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
Try it Yourself »
Expressions can also contain variable values:
x * 10
Try it Yourself »
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
Try it Yourself »

JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
The var keyword tells the browser to create variables:
var x, y;
x = 5 + 6;
y = x * 10;
Try it Yourself »

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:
var x = 5; // I will be executed
// var x = 6; I will NOT be executed
Try it Yourself »
You will learn more about comments in a later chapter.

JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and
labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign
($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
Numbers are not allowed as the first character.
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:
var lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
Try it Yourself »
JavaScript does not interpret VAR or Var as the keyword var.

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.

7 JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.

JavaScript comments can also be used to prevent execution, when testing alternative
code.
Single Line Comments

Single line comments start with //.


Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
This example uses a single-line comment before each code line:

Example

// Change heading:
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »

This example uses a single line comment at the end of each line to explain the code:

Example

var x = 5; // Declare x, give it the value of 5


var y = x + 2; // Declare y, give it the value of x + 2
Try it Yourself »

Multi-line Comments

Multi-line comments start with /* and end with */.


Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to explain the code:

Example

/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »

It is most common to use single line comments.


Block comments are often used for formal documentation.
Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code testing.


Adding // in front of a code line changes the code lines from an executable line to a
comment.
This example uses // to prevent execution of one of the code lines:

Example

//document.getElementById("myH").innerHTML = "My First Page";


document.getElementById("myP").innerHTML = "My first paragraph.";
Try it Yourself »

This example uses a comment block to prevent execution of multiple lines:

Example

/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/

8 JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables:

Example

var x = 5;
var y = 6;
var z = x + y;
Try it Yourself »

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

Much Like Algebra

In this example, price1, price2, and total, are variables:


Example

var price1 = 5;
var price2 = 6;
var total = price1 + price2;

Try it Yourself »

In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 +
price2).
From the example above, you can calculate the total to be 11.
JavaScript variables are containers for storing data 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

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.)
The "equal to" operator is written like == in JavaScrip
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

var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
Try it Yourself »

Declaring (Creating) JavaScript Variables

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


You declare a JavaScript variable with the var keyword:

var carName;

After the declaration, the variable has no value (technically it has the value
of 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:

var carName = "Volvo";

In the example below, we create a variable called carName and assign the value "Volvo"
to it.
Then we "output" the value inside an HTML paragraph with id="demo":

Example

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

<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Try it Yourself »

It's a good programming practice to declare all variables at the beginning of a scrip
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with var and separate the variables by comma:

var person = "John Doe", carName = "Volvo", price = 200;


Try it Yourself »

A declaration can span multiple lines:

var person = "John Doe",


carName = "Volvo",
price = 200;
Try it Yourself »

Value = undefined

In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user
input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the execution of this
statement:

Example

var carName;
Try it Yourself »

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable, it will not lose its value.


The variable carName will still have the value "Volvo" after the execution of these
statements:

Example

var carName = "Volvo";


var carName;
Try it Yourself »
JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators
like = and +:

Example

var x = 5 + 2 + 3;

Try it Yourself »

You can also add strings, but strings will be concatenated:

Example

var x = "John" + " " + "Doe";


Try it Yourself »

Also try this:

Example

var x = "5" + 2 + 3;

Try it Yourself »

If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.
Now try this:

Example

var x = 2 + 3 + "5";

9 JavaScript Operators
Example

Assign values to variables and add them together:

var x = 5; // assign the value 5 to x


var y = 2; // assign the value 2 to y
var z = x + y; // assign the value 7 to z (x + y)
Try it Yourself »

The assignment operator (=) assigns a value to a variable.

Assignment

var x = 10;
Try it Yourself »

The addition operator (+) adds numbers:

Adding

var x = 5;
var y = 2;
var z = x + y;
Try it Yourself »

The multiplication operator (*) multiplies numbers.

Multiplying

var x = 5;
var y = 2;
var z = x * y;
Try it Yourself »

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers:

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Arithmetic operators are fully described in the JS Arithmetic chapter.

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

The addition assignment operator (+=) adds a value to a variable.

Assignment

var x = 10;
x += 5;
Try it Yourself »

Assignment operators are fully described in the JS Assignment chapter.

JavaScript String Operators

The + operator can also be used to add (concatenate) strings.

Example

var txt1 = "John";


var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
The result of txt3 will be:

John Doe
Try it Yourself »

The += assignment operator can also be used to add (concatenate) strings:

Example

var txt1 = "What a very ";


txt1 += "nice day";

The result of txt1 will be:

What a very nice day


Try it Yourself »

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a
string:

Example

var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;

The result of x, y, and z will be:

10
55
Hello5
Try it Yourself »

If you add a number and a string, the result will be a string!

JavaScript Comparison Operators

Operato Description
r
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript Logical Operators

Operato Description
r
&& logical and
|| logical or
! logical not

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an
object type

Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.


Any numeric operand in the operation is converted into a 32 bit number. The result is
converted back to a JavaScript number.

Operato Description Exampl Same Result Decimal


r e as
& AND 5&1 0101 & 0001 1
0001
| OR 5|1 0101 | 0101 5
0001
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0100 4
0001
<< Zero fill left shift 5 << 1 0101 << 1010 10
1
>> Signed right shift 5 >> 1 0101 >> 0010 2
1
>>> Zero fill right shift 5 >>> 1 0101 0010 2
>>> 1

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed
numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return
11111111111111111111111111111010

10 JavaScript Arithmetic

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
var x = 100 + 50;

Try it Yourself »

or variables:

Example
var x = a + b;

Try it Yourself »

or expressions:

Example
var x = (100 + 50) * a;

Try it Yourself »

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
var x = 5;
var y = 2;
var z = x + y;

Try it Yourself »

Subtracting

The subtraction operator (-) subtracts numbers.

Example
var x = 5;
var y = 2;
var z = x - y;

Multiplying

The multiplication operator (*) multiplies numbers.

Example

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

Dividing

The division operator (/) divides numbers.

Example
var x = 5;
var y = 2;
var z = x / y;
Try it Yourself »

Remainder

The modulus operator (%) returns the division remainder.

Example
var x = 5;
var y = 2;
var 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
var x = 5;
x++;
var z = x
Decrementing

The decrement operator (--) decrements numbers.

Example
var x = 5;
x--;
var z = x;

Exponentiation

The exponentiation operator (**) raises the first operand to the power of the second
operand.
Example
var x = 5;
var z = x ** 2; // result is 25

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

Example
var x = 5;
var z = Math.pow(x,2); // result is 25

Operator Precedence

Operator precedence describes the order in which operations are performed in an


arithmetic expression.

Example
var 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.

Multiplication (*) and division (/) have higher precedence than addition (+) and
subtraction (-).

And (as in school mathematics) the precedence can be changed by using parentheses:

Example
var x = (100 + 50) * 3;

When using parentheses, the operations inside the parentheses are computed first.

When many operations have the same precedence (like addition and subtraction), they
are computed from left to right:

Example
var x = 100 + 50 - 3;

You might also like