JavaScript - Tute 02
JavaScript Let
Variables defined with let cannot be Redeclared.
Variables defined with let must be Declared before use.
Variables defined with let have Block Scope.
Cannot be Redeclared
Variables defined with let cannot be redeclared.
You cannot accidentally redeclare a variable.
With let you can not do this:
let x = "John Doe";
let x = 0;
// SyntaxError: 'x' has already been declared
With var you can:
var x = "John Doe";
var x = 0;
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
These two keywords provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
{
var x = 2;
}
// x CAN be used here\
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable outside the block:
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable outside the block:
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Redeclaring
Redeclaring a JavaScript variable with var is allowed anywhere in a program:
var x = 2;
// Now x is 2
var x = 3;
// Now x is 3
With let, redeclaring a variable in the same block is NOT allowed:
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3; // Not allowed
}
{
let x = 2; // Allowed
var x = 3; // Not allowed
}
Redeclaring a variable with let, in another block, IS allowed:
let x = 2; // Allowed
{
let x = 3; // Allowed
}
{
let x = 4; // Allowed
}
Let Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.
Meaning: You can use the variable before it is declared:
carName = "Volvo";
var carName;
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with let are also hoisted to the top of the block, but not initialized.
Meaning: Using a let variable before it is declared will result in a ReferenceError:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>let</b>, you cannot use a variable before it is declared.</p>
<p id="demo"></p>
<script>
try {
carName = "Saab";
let carName = "Volvo";
}
catch(err) {
document.getElementById("demo").innerHTML = err;
}
</script>
</body>
</html>
JavaScript Const
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 const variable cannot be reassigned:
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:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript const</h2>
<p>Declaring a constant array does NOT make the elements unchangeable:</p>
<p id="demo"></p>
<script>
// Create an Array:
const cars = ["Saab", "Volvo", "BMW"];
// Change an element:
cars[0] = "Toyota";
// Add an element:
cars.push("Audi");
// Display the Array:
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
But you can NOT reassign the array:]
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
Constant Objects
You can change the properties of a constant object:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript const</h2>
<p>Declaring a constant object does NOT make the objects properties unchangeable:</p>
<p id="demo"></p>
<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};
// Change a property:
car.color = "red";
// Add a property:
car.owner = "Johnson";
// Display the property:
document.getElementById("demo").innerHTML = "Car owner is " + car.owner;
</script>
</body>
</html>
But you can NOT reassign the object:
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Block Scope
Declaring a variable with const is similar to let when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared outside the block:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScropt const variables has block scope</h2>
<p id="demo"></p>
<script>
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = "x is " + x;
</script>
</body>
</html>
Redeclaring
Redeclaring a JavaScript var variable is allowed anywhere in a program:
var x = 2; // Allowed
var x = 3; // Allowed
x = 4; // Allowed
Redeclaring an existing var or let variable to const, in the same scope, is not allowed:
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 2; // Not allowed
}
Reassigning an existing const variable, in the same scope, is not allowed:
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
{
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
}
Redeclaring a variable with const, in another scope, or in another block, is allowed:
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
Const Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.
Meaning: You can use the variable before it is declared:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Hoisting</h2>
<p>With <b>var</b>, you can use a variable before it is declared:</p>
<p id="demo"></p>
<script>
carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
var carName;
</script>
</body>
</html>
Variables defined with const are also hoisted to the top, but not initialized.
Meaning: Using a const variable before it is declared will result in a ReferenceError:
alert (carName);
const carName = "Volvo";
JavaScript Operators
The Assignment Operator (=) assigns a value to a variable.
// 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;
The Addition Operator (+) adds numbers:
let x = 5;
let y = 2;
let z = x + y;
The Multiplication Operator (*) multiplies numbers.
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
Logical Operators
Conditional Operators
Type Operators
JavaScript Arithmetic Operators
Arithmetic Operators are used to perform arithmetic on numbers:
Arthmetic Operators Example
let a = 3;
let x = (100 + 50) * a;
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
The Addition Assignment Operator (+=) adds a value to a variable.
let x = 10;
x += 5;
Adding JavaScript Strings
The + operator can also be used to add (concatenate) strings.
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The += assignment operator can also be used to add (concatenate) strings:
let text1 = "What a very ";
text1 += "nice day";
Adding Strings and Numbers
Adding two numbers, will return the sum, but adding a number and a string will return a string:
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
JavaScript Comparison Operators
JavaScript Logical Operators
JavaScript Type Operators
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.
JavaScript Arithmetic Operators
Arithmetic operators perform arithmetic on numbers (literals or variables).
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.
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.
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
The two numbers can be literals:
let x = 100 + 50;
or variables:
let x = a + b;
or expressions:
let x = (100 + 50) * a;
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the second operand.
let x = 5;
let z = x ** 2;
x ** y produces the same result as Math.pow(x,y):
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.
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.
Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:
let 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:
let x = 100 + 50 - 3;
JavaScript Assignment Operators
Assignment operators assign values to JavaScript variables.
Shift Assignment Operators
Bitwise Assignment Operators
Logical Assignment Operators
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 varable to the power of the operand.
let x = 10;
x **= 5;
The /= Operator
The Division Assignment Operator divides a variable.
let x = 10;
x /= 5;
The %= Operator
The Reminder Assignment Operator assigns a remainder to a variable.
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).
let x = -100;
x >>= 5;
The >>>= Operator
The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).
Unsigned Right Shift Assignment Example
let x = -100;
x >>>= 5;
The &= Operator
The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and
assigns the result to the the variable.
let x = 10;
x &= 5;
The |= Operator
The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns
the result to the variable.
let x = 10;
x |= 5;
The ^= Operator
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and
assigns the result to the variable.
let x = 10;
x ^= 5;
The &&= Operator
The Logical AND assignment operator is used between two values.
If the first value is true, the second value is assigned.
let x = 10;
x &&= 5;
The ||= Operator
The Logical OR assignment operator is used between two values.
If the first value is false, the second value is assigned.
let x = 10;
x ||= 5;
The ??= Operator
The Nullish coalescing assignment operator is used between two values.
If the first value is undefined or null, the second value is assigned.
let x = 10;
x ??= 5;
JavaScript Data Types
JavaScript variables can hold different data types: numbers, strings, objects and more:
let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object
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";
When adding a number and a string, JavaScript will treat the number as a string.
let x = 16 + "Volvo";
let x = "Volvo" + 16;
JavaScript evaluates expressions from left to right. Different sequences can produce different
results:
let x = 16 + 4 + "Volvo";
let x = "Volvo" + 16 + 4;
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:
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:
let carName1 = "Volvo XC60"; // Using double quotes
let carName2 = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
let answer1 = "It's alright"; // Single quote inside double quotes
let answer2 = "He is called 'Johnny'"; // Single quotes inside double quotes
let answer3 = 'He is called "Johnny"'; // Double quotes inside single quotes
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
let x1 = 34.00; // Written with decimals
let x2 = 34; // Written without decimals
Extra large or extra small numbers can be written with scientific (exponential) notation:
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
JavaScript Booleans
Booleans can only have two values: true or false.
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car names):
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
You will learn more about objects later in this tutorial.
The typeof Operator
You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
let car; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
let car = ""; // The value is "", the typeof is "string"