Scripting Languages_4
Scripting Languages_4
4. Introduction to JavaScript
(Part I)
2024, Spring Semester
Comments
Single-line Comments
you need to add // before the code on the line you wish to comment out: Also, we can add the comment at the end of the line.
console.log("Line 1");
console.log("Line 2");
/*
console.log("Line 4");
console.log("Line 5");
console.log("Line 6");
console.log("Line 7");
console.log("Line 8");
console.log("Line 9");
*/
console.log("Line 11");
Variables and Data Types
Variables
Before using variables, they must be defined. To define a variable, use the let keyword and choose a name for it:
let variableName;
Variable names should follow the camelCase style. camelCase means that words are written together without spaces, and each word (except the first) is
capitalized.
You can assign a value to a variable using the assignment operator ( =):
Using Variables
const
The primary difference between let and const is that variables created using const cannot change their values, whereas using the let keyword allows changes to the
variable's value.
Refactoring involves making structural changes to the code, such as modifying values, variable/function names, and
more.
The Data Type tells the interpreter how to work with the data.
// First case
console.log("123" + "123");
// Second case
console.log(123 + 123);
typeof()
The typeof() operator returns a string indicating the type of the operand's value.
let a = 15;
console.log(typeof 23);
console.log(typeof a);
const b = "today";
console.log(typeof "word");
console.log(typeof b);
Number
The number data type is used for calculations, counters, mathematical operations, and more.
Unlike other programming languages, JavaScript uses the number type instead of separate int and float types.
console.log(typeof(15.25));
console.log(typeof(211));
console.log(typeof(22 + 251));
console.log(typeof(26 / 342));
The typeof operator only determines the data type of the result, not the performed operations.
String
The string data type is used to change, print, and pass text to other programs.
let str = "Hello! I'm String, and I should help you to work with text!";
console.log(str);
To identify the string in the code, we should use single or double quotes (e.g., 'some text' or "some text")
console.log("text");
console.log('text');
console.log("console.log('text')");
console.log('console.log("text")');
console.log(typeof("10"));
Boolean
The boolean data type is used for logical operations. It has two values: true and false. Booleans are used to check conditions, as we'll describe later.
Booleans allow you to control code execution and direct it along different paths.
To create a boolean value, use the true or false values:
console.log(true);
console.log(false);
console.log(typeof(true));
console.log(typeof(false));
console.log(arr);
Indexes
Each element in an array has a unique index.
Indexes start from 0. The first element has an index of 0, the second element has an index of 1, and so on.
Accessing array data is done by specifying the index in square brackets ( [index]) after the array name: arrayName[index]
const arr = [1, 2, 3, 4, 5];
console.log(thirdElement);
Arrays can hold different data types, including number, string, boolean, and more.
const arr = [2441.23, "Hello!", false];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
Length Property
The length property is a built-in property of arrays that represents the number of elements in that array. To use this property, use the following syntax:
arrayName.length
console.log(x);
console.log(y);
Array Methods
Arrays are versatile for storing and retrieving data. Retrieving data using square brackets [] is called indexing.
let arr = [1, 2, 3, 4, 5, 6];
arr[3] // This is indexing
Adding Elements
Push The push() method adds a new value to the end of the array:
arr.push(4);
arr.push(5);
arr.push(6);
console.log(arr);
Unshift The unshift() method works like the push() method, but it inserts the value at the beginning of the array.
console.log("Array:", arr);
Indexing
arr[2] = 3;
arr[3] = 4;
console.log(arr);
Indexing allows you to assign a value to a specified index, reassign a previous value, and more:
arr[0] = 4;
console.log("Array:", arr);
To create a new element in the array without mistakes, you can use the push(value) method or the arr[arr.length] = value expression:
myArray[myArray.length] = "indexing";
console.log("After first indexing:", myArray);
myArray.push("pushing");
console.log("After first pushing:", myArray);
myArray[myArray.length] = "indexing";
console.log("After second indexing:", myArray);
myArray.push("pushing");
console.log("After second pushing:", myArray);
Deleting Elements
Pop The pop() method deletes the last element in an array and allows you to save it to another variable:
let arr = [11, 22, 33, 44];
console.log("Array:", arr);
console.log("Popped:", popped);
console.log("Array:", arr);
console.log("Shifted:", shifted);
console.log("Array:", arr);
Basic Operations
Assignment
The assignment is a fundamental operation that assigns values to variables, constants, array elements, and more. This operation is performedusing the = symbol.
a[0] = 5; // Assign the value `5` to the first element of array `a`
console.log("Array:", a);
Mathematical Operations
JavaScript can perform the following operations with numbers:
•Addition (+);
•Subtraction (-);
•Multiplication (*);
•Division (/);
•Remainder, or Modulo (%);
•Exponent (**).
let a = 17;
let a = 17; a = a + 5;
a += 5; This code is equivalent to the following: console.log(a);
console.log(a);
Increment Decrement
The increment operation is performed using the ++ operator: The decrement operation is performed using the -- operator:
let a = 0; let a = 5;
a++; a--;
console.log(a); console.log(a);
a++; a--;
console.log(a); console.log(a);
a++; a--;
console.log(a); console.log(a);
The = operator is for assignment, while == is for comparison. Be careful to distinguish them.
Greater and Less
The Greater Than (>) operator returns true if the first value exceeds the second. Conversely, the Less Than (<) operator returns true if the first value is less than the second.
The >= operator combines > and ==, not ===. The <= operator works similarly.
Logical Operations
There are three logical operators in JavaScript:
•AND (&&);
•OR (||);
•NOT (!).
AND (&&)
The AND (&&) logical operator returns true only when both values it operates on are true. The result is false if any value is false.
Concatenation is the process of combining two strings. This operation is achieved using the + operator:
console.log(wordOne + wordTwo);
String concatenation does not automatically add spaces. You need to manually include spaces like string1 + " " + string2.
console.log(text)
Conditional Statements
if Statements
The if keyword allows you to open a code block that will be executed if the given condition is true:
if (true) {
console.log("It's TRUE!");
}
if (false) {
console.log("It's FALSE!");
}
The syntax of an if statement is straightforward: it begins with the if keyword, followed by the condition enclosed in parentheses (), and a code block enclosed in curly
braces {}.
if (condition) {
// Code block
}
An expression, as well as a value, can be considered as a condition.
In the example, when a = 935, there are four conditions:
let a = 935;
if (a > 17) {
console.log("The variable is greater than 17");
}
if (a > 235124) {
console.log("The variable is greater than 235124");
}
if (a > 0) {
console.log("The variable is greater than 0");
}
if (a < 0) {
console.log("The variable is less than 0");
}
let a = 5;
let b = 3;
let c;
console.log(a, b, c);
else
In the example, the condition a >= 100 evaluates to false, so the code block within the if statement is
let a = 60; not executed. Instead, the code block within the else statement is executed because the if condition
is false.
if (a >= 100) {
console.log("a is greater than or equal to 100");
} else {
console.log("a is less than 100");
}
The syntax of the else statement is similar to that of the if statement, except it doesn't require a condition or parentheses ().
When using an else statement, do not place the end-of-command (;) after the if code block ({}), as this will result in a SyntaxError. The if-else statement is
considered a single command.
else if The else if construct provides a solution for selecting a specific code block within a series of conditions:
let a = 11; if (condition) {
// Code block
if (a > 15) { } else if (condition) {
console.log('greater than 15'); // Repeat the `if` syntax
} }
Let's apply this to our example:
if (a > 10) {
let a = 11;
console.log('greater than 10');
}
if (a > 15) {
console.log("greater than 15");
if (a > 5) {
} else if (a > 10) {
console.log('greater than 5');
console.log("greater than 10");
}
} else if (a > 5) {
console.log("greater than 5");
if (a > 0) {
} else if (a > 0) {
console.log('greater than 0');
console.log("greater than 0");
}
}
Now, we've created a sequence of conditions. When at least one if condition becomes true, the chain is interrupted.
This structure is useful when you only need one condition to be satisfied.
Adding else
let a = -61;
if (a > 15) {
console.log("greater than 15");
} else if (a > 10) {
console.log("greater than 10");
} else if (a > 5) {
console.log("greater than 5");
} else if (a > 0) {
console.log("greater than 0");
} else {
console.log("No condition is satisfied");
}