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
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.";
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 var, let 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 var, let 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, x, y, 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, x, y, 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
|